Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion software/calibration/requirements.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,2 @@
websocket-client
matplotlib

69 changes: 55 additions & 14 deletions software/firmware/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,11 +51,22 @@ Default address : 0x40

ADS8688 IDBTR

## WiFi / WebSocket Protocol
## WiFi / UDP Streaming Protocol

Once a WebSocket connection is established, the client and server exchange data via the WebSocket protocol in binary format : application messages, using the HTTP protocol, are split into one or more frames, adding a little overhead that needs to be considered, especially if we send small amount of data at once.
Sensor data is streamed over UDP by the [UDPStreamer](arduino_esp32/src/tasks/UDPStreamer.cpp), while control is done with the [REST API](#rest-api) over HTTP (port 80).

### WebSocket Binary Message Format
1. The client opens a UDP socket bound to a port of its choice (Python API default: 12345).
2. The client calls `/start_streaming?address=x.x.x.x&port=n` to give the destination of the stream. The address can be the IP of the client (unicast, recommended) or a broadcast address such as `255.255.255.255` (default of the Python API), which reaches every host on the local network.
3. The wheel first sends a CONFIG frame (type 1), required to convert raw values, then data superframes (type 255). A new CONFIG frame is sent every time the configuration changes (`/config_update`). Data frames still queued with the previous configuration are discarded.
4. The client calls `/stop_streaming` to stop the stream.

Since UDP is connectionless:

* There is no retransmission and no ordering guarantee. Datagrams are sent non-blocking and are dropped (counted as dropped packets) if the WiFi stack is out of buffers. Clients must tolerate lost datagrams.
* Each datagram is self-contained: it holds one or more complete frames, never a partial frame, so it can be decoded independently of the others.
* Streaming continues until `/stop_streaming` is called, even if the client goes away.

### UDP Binary Message Format

> Note 1: Bytes are ordered little endian (lsb first)
> Note 2: Protocol optimized for more efficiency using raw data when possible. Conversions need to occur in client code.
Expand All @@ -72,7 +83,7 @@ Once a WebSocket connection is established, the client and server exchange data
| 7=QUADENCODER | UNIX MICROSECONDS | 8 BYTES | 1 INT64 (See [QuadEncoderDataFrame](lib/NextWheel/src/data/QuadEncoderDataFrame.h))|
| 255=SUPERFRAME | UNIX MICROSECONDS | NB INCLUDED FRAMES | VARIABLE NUMBER OF FULL FRAMES |

> Note 2: To avoid sending small packets with high overhead ratio (data size small vs websocket overhead), the [WebSocketServerTask](src/tasks/WebSocketServerTask.h) sends periodic superframes of type 255 at a rate of 20Hz, wich is the aggregation of all accumulated frames in a 50 ms period. This allows to maximize the bandwidth and minimize the TCP/IP embedded stack overhead. Every data frame is timstamped, so we can recover all data chronologically.
> Note 3: To avoid sending small packets with a high overhead ratio (small data size vs UDP/IP headers), the [WebServerTask](arduino_esp32/src/tasks/WebServerTask.cpp) aggregates all queued frames into a superframe of type 255, sent as a single UDP datagram. A superframe is sent when its payload reaches approximately 1400 bytes (to stay below the WiFi MTU and avoid IP fragmentation) or when no new frame arrives for 50 ms. Every data frame is timestamped, so all data can be recovered chronologically.

### ADC and IMU VALUE CONVERSION

Expand Down Expand Up @@ -180,16 +191,46 @@ class GlobalConfig:
Values are already converted on device. Size optimization of the binary stream was not very practical and useful for those low bandwidth values.


## Time Synchronization (NTP)

The system time is used to timestamp every data frame (UNIX microseconds) and to generate recording file names.

* At boot, the system time is initialized from the [RTC](arduino_esp32/lib/NextWheel/src/RTC.cpp) (MCP7940M with battery backup). The RTC stores UTC time.
* When an IP address is obtained at startup, SNTP is started by the [WebServerTask](arduino_esp32/src/tasks/WebServerTask.cpp). If the connection is lost before the first synchronization, SNTP is restarted on reconnection.
* After the first synchronization, SNTP is stopped. There is no periodic resynchronization, so the system time drifts until the next boot or until a resynchronization is requested with `/ntp_resync`. SNTP is stopped again after that synchronization.
* Corrections are applied gradually (`SNTP_SYNC_MODE_SMOOTH`, using `adjtime`) to avoid timestamp jumps while recording or streaming. If the error is larger than 35 minutes (e.g. RTC never set), the time is set immediately.
* After each synchronization, the NTP time is written back to the RTC so the next boot starts with a corrected time, even without WiFi.
* The NTP server requires Internet access from the WiFi network. Without it, the system keeps running on RTC time.
* `/config_set_time` still sets the time manually, but it will be overridden by the startup NTP synchronization or by `/ntp_resync`.

| **Define** | **Default** | **Description** |
|------------|-------------|-----------------|
| `NTP_DEFAULT_SERVER` | `"pool.ntp.org"` | NTP server ([WebServerTask.h](arduino_esp32/src/tasks/WebServerTask.h)) |
| `NEXTWHEEL_TIMEZONE` | `"EST5EDT,M3.2.0,M11.1.0"` | POSIX TZ string for local time, America/Toronto ([RTC.h](arduino_esp32/lib/NextWheel/src/RTC.h)) |

Both can be overridden with `build_flags` in [platformio.ini](arduino_esp32/platformio.ini), for example:

```ini
build_flags = -DNTP_DEFAULT_SERVER=\"ca.pool.ntp.org\"
```

## REST API

|**Url** | **HTTP Method** | **Param(s)** | **Return** | **Description** |
All endpoints are served on HTTP port 80. Text responses are `text/plain`, JSON responses are `application/json`. Unknown URLs return 404 with the request details.

|**Url** | **HTTP Method** | **Param(s)** | **Return** | **Description** |
|-----|-----------|----|-----------|---|
/config_set_time | POST | *time* (int) = unix timestamp | 200 (OK) |Set system time from unix timestamp
/config_update | POST | accelerometer_precision (int)[], gyrometer_precision (int) [], imu_sampling_rate(int) [], adc_sampling_rate (int)[], encoder_sampling_rate (int)[]| 200 (OK), 400 (Unknown parameter)| Set the sensor configuration
/config | GET | None | 200, JSON={"accelerometer_precision": value, "gyrometer_precision": value, "imu_sampling_rate": value, "adc_sampling_rate": value, "encoder_sampling_rate": value} | Get the current sensor configuration.
/system_state | GET | None | 200, JSON = {"recording": (bool) recording_flag, "streaming": (bool) streaming_flag, "filename": (string) recording_filename } | Return the current state of the system.
/start_recording | GET | None | 200, "OK", 400, "Already recording." | Start recording on SDCard. File name will be automatically generated with current time.
/stop_recording | GET | None | 200, "0K", 400, "Not recording." | Stop recording to SD Card.
/file_list | GET | None | 200, JSON Dict containing {"files": [{"name": file_size(string), "size": file_size(int)}, ...], "download_url": url_for_file_download(string), "delete_url": url_for_file_delete(string)} | Get all the file information stored in the SD Card.
/file_delete | GET | file (string) The name of the file | 200 (OK), 400 (Bad Parameter) | Delete the file from the SD CARD.
/file_download | GET | file (string) The name of the file | The file in binary format or 404 not found. | The file is is transfered from the SDCARD.
/ | GET | None | 200, "Hello from NextWheel REST API Server !" | Check that the server is running.
/config_set_time | POST | time (int) unix timestamp in seconds | 200 (OK), 400 (Missing time argument) | Set the system time and the RTC from a unix timestamp. Overridden by the startup NTP synchronization or `/ntp_resync`, see [Time Synchronization](#time-synchronization-ntp).
/ntp_time | GET | None | 200, JSON = {"synced": (bool) ntp_response_received, "server": (string) ntp_server, "time": (float) current_unix_time_seconds, "local_time": (string) ISO 8601 local time with UTC offset, "last_sync": (int) unix_time_of_last_sync, "adjusting": (float) remaining_gradual_correction_seconds} | Get the current time and NTP synchronization status. `adjusting` is 0 when the system time is fully synchronized.
/ntp_resync | GET | None | 200 (OK), 400 (Not connected) | Restart SNTP for a single synchronization. It is stopped again once the time is received and written to the RTC. Check `last_sync` in `/ntp_time` to know when it is done.
/config_update | POST | accelerometer_precision (int), gyrometer_precision (int), imu_sampling_rate (int), adc_sampling_rate (int), encoder_sampling_rate (int). All are required. | 200 (OK), 400 (Missing arguments) | Set and save the sensor configuration. It is applied immediately to all sensors, and a new CONFIG frame is written to the current recording and sent on the UDP stream.
/config | GET | None | 200, JSON = {"accelerometer_precision": (int), "gyrometer_precision": (int), "imu_sampling_rate": (int), "adc_sampling_rate": (int), "encoder_sampling_rate": (int)} | Get the current sensor configuration.
/system_state | GET | None | 200, JSON = {"recording": (int 0/1) recording_flag, "streaming": (int 0/1) streaming_flag, "filename": (string) recording_filename} | Get the current state of the system.
/start_streaming | GET | address (string) destination IP (x.x.x.x, unicast or broadcast), port (int) destination UDP port (1-65534) | 200 (OK), 400 (Missing arguments, Invalid address, Invalid port, Already streaming) | Start streaming data over UDP to address:port. See [UDP Streaming Protocol](#wifi--udp-streaming-protocol).
/stop_streaming | GET | None | 200 (OK), 400 (Not streaming) | Stop UDP streaming.
/start_recording | GET | None | 200 (OK), 400 (Already recording) | Start recording on the SD card. The file name is generated from the current local time (`log_YYYY-MM-DD_HH-MM-SS.dat`).
/stop_recording | GET | None | 200 (OK), 400 (Not recording) | Stop recording on the SD card.
/file_list | GET | None | 200, JSON = {"files": [{"name": (string) file_name, "size": (int) file_size_bytes}, ...], "download_url": "/file_download", "delete_url": "/file_delete"} | List the recording files (`.dat`) stored on the SD card.
/file_delete | GET | file (string) file name | 200 (OK), 400 (File not found, Missing file argument) | Delete a file from the SD card.
/file_download | GET | file (string) file name | 200, file content (`application/octet-stream`, with `Content-Disposition` and `Content-Length`), 400 (File not found, Missing file argument) | Download a file from the SD card.
6 changes: 3 additions & 3 deletions software/firmware/arduino_esp32/.clang-format
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ AlignTrailingComments: false
AllowAllArgumentsOnNextLine: false
AllowAllConstructorInitializersOnNextLine: false
AllowAllParametersOfDeclarationOnNextLine: false
AllowShortBlocksOnASingleLine: Always
AllowShortBlocksOnASingleLine: Never
AllowShortCaseLabelsOnASingleLine: false
AllowShortEnumsOnASingleLine: false
AllowShortFunctionsOnASingleLine: Inline
Expand All @@ -35,7 +35,7 @@ BreakConstructorInitializers: BeforeColon
BreakInheritanceList: BeforeColon
BreakStringLiterals: true
ColumnLimit: 120
CompactNamespaces: false
CompactNamespaces: true
ConstructorInitializerAllOnOneLineOrOnePerLine: true
ConstructorInitializerIndentWidth: 4
ContinuationIndentWidth: 4
Expand Down Expand Up @@ -82,7 +82,7 @@ SpacesInConditionalStatement: false
SpacesInContainerLiterals: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
Standard: c++14
Standard: Latest
StatementAttributeLikeMacros: [emit]
StatementMacros: [Q_UNUSED, Q_OBJECT]
TabWidth: 4
Expand Down
3 changes: 2 additions & 1 deletion software/firmware/arduino_esp32/.vscode/extensions.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"platformio.platformio-ide"
],
"unwantedRecommendations": [
"ms-vscode.cpptools-extension-pack"
"ms-vscode.cpptools-extension-pack",
"pioarduino.pioarduino-ide"
]
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
/*
NextWheel - Global definitions and macros
*/
#define NEXT_WHEEL_VERSION "0.1.0"
#define NEXT_WHEEL_VERSION "0.2"
#define NEXT_WHEEL_DEBUG_LEVEL 0


Expand Down
35 changes: 20 additions & 15 deletions software/firmware/arduino_esp32/lib/NextWheel/src/RTC.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,8 @@ void RTC::begin()
// Initialize the RTC
m_mcp7940.begin(I2C_FAST_MODE);

// Set the system timezone
// TODO Hardcoded for now...
setenv("TZ", "EST+5EDT,M3.2.0/2,M11.1.0/2", 1);
tzset();
// Set the system timezone, RTC stores UTC
setTimeZone();

DateTime now = m_mcp7940.now(); // get the current time from RTC
struct timeval my_time = {(time_t)now.unixtime(), 0};
Expand Down Expand Up @@ -40,21 +38,20 @@ void RTC::update()

void RTC::printTime()
{
char inputBuffer[SPRINTF_BUFFER_SIZE]; // Buffer for sprintf()/sscanf()
DateTime now = m_mcp7940.now(); // get the current time
char inputBuffer[SPRINTF_BUFFER_SIZE]; // Buffer for strftime()
time_t now = (time_t)m_mcp7940.now().unixtime(); // get the current time (UTC)

sprintf(
inputBuffer,
"%04d-%02d-%02d %02d:%02d:%02d",
now.year(), // Use sprintf() to pretty print
now.month(),
now.day(),
now.hour(),
now.minute(),
now.second()); // date/time with leading zeros
// Display in local time
strftime(inputBuffer, SPRINTF_BUFFER_SIZE, "%Y-%m-%d %H:%M:%S %Z", localtime(&now));
Serial.printf("Current time: %s \n", inputBuffer); // Display the current date/time
}

void RTC::setTimeZone()
{
setenv("TZ", NEXTWHEEL_TIMEZONE, 1);
tzset();
}

bool RTC::setTime(String time)
{
Serial.print("RTC::setTime : ");
Expand All @@ -70,3 +67,11 @@ bool RTC::setTime(String time)
settimeofday(&my_time, NULL);
return true;
}

void RTC::adjustRTCTime(time_t unix_time)
{
// Store the time (e.g. obtained from NTP) in the RTC only
// System time is not modified
m_mcp7940.adjust(DateTime((uint32_t)unix_time));
m_mcp7940.setBattery(true); // enable battery
}
7 changes: 7 additions & 0 deletions software/firmware/arduino_esp32/lib/NextWheel/src/RTC.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,21 @@
#include <NextWheel.h>
#include <MCP7940.h>

// POSIX TZ string for America/Toronto (Eastern, DST from 2nd Sunday of March to 1st Sunday of November)
#ifndef NEXTWHEEL_TIMEZONE
#define NEXTWHEEL_TIMEZONE "EST5EDT,M3.2.0,M11.1.0"
#endif

class RTC
{
public:
RTC();
void begin();
void update();
bool setTime(String time);
void adjustRTCTime(time_t unix_time);
void printTime();
static void setTimeZone();

private:
MCP7940_Class m_mcp7940;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

#include <algorithm>
#include "IMU.h"
#include <IPAddress.h>

const std::vector<uint32_t> GlobalConfig::m_accel_ranges =
{IMU::IMU_ACC_RANGE_2G, IMU::IMU_ACC_RANGE_4G, IMU::IMU_ACC_RANGE_8G, IMU::IMU_ACC_RANGE_16G};
Expand Down Expand Up @@ -46,6 +47,10 @@ void GlobalConfig::print()
Serial.println(m_config.adc_sample_rate);
Serial.print("encoder_sample_rate: ");
Serial.println(m_config.encoder_sample_rate);
Serial.print("udp_broadcast_address: ");
Serial.println(IPAddress(m_config.udp_broadcast_address));
Serial.print("udp_broadcast_port: ");
Serial.println(m_config.udp_broadcast_port);
}

void GlobalConfig::save()
Expand Down Expand Up @@ -132,6 +137,30 @@ uint32_t GlobalConfig::get_encoder_sample_rate() const
return m_config.encoder_sample_rate;
}

void GlobalConfig::set_udp_broadcast_address(uint32_t address)
{
m_config.udp_broadcast_address = address;
// Not saved, configured at runtime, not persisted to EEPROM
// save();
}

uint32_t GlobalConfig::get_udp_broadcast_address() const
{
return m_config.udp_broadcast_address;
}

void GlobalConfig::set_udp_broadcast_port(uint16_t port)
{
m_config.udp_broadcast_port = port;
// Not saved, configured at runtime, not persisted to EEPROM
// save();
}

uint16_t GlobalConfig::get_udp_broadcast_port() const
{
return m_config.udp_broadcast_port;
}

void GlobalConfig::setDefault()
{
Serial.println("GlobalConfig : Setting default config");
Expand All @@ -141,6 +170,8 @@ void GlobalConfig::setDefault()
m_config.imu_sample_rate = m_imu_sampling_rate_ranges[0];
m_config.adc_sample_rate = m_adc_sampling_rate_ranges[0];
m_config.encoder_sample_rate = m_encoder_sampling_rate_ranges[0];
m_config.udp_broadcast_address = 0xFFFFFFFF; // Default to broadcast address
m_config.udp_broadcast_port = 12345; // Default port
save();
}

Expand Down Expand Up @@ -181,8 +212,10 @@ bool GlobalConfig::validate()
return false;
}

if (std::find(m_encoder_sampling_rate_ranges.begin(), m_encoder_sampling_rate_ranges.end(),
m_config.encoder_sample_rate) == m_encoder_sampling_rate_ranges.end())
if (std::find(
m_encoder_sampling_rate_ranges.begin(),
m_encoder_sampling_rate_ranges.end(),
m_config.encoder_sample_rate) == m_encoder_sampling_rate_ranges.end())
{
return false;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,8 @@ class GlobalConfig
uint32_t imu_sample_rate;
uint32_t adc_sample_rate;
uint32_t encoder_sample_rate;
uint32_t udp_broadcast_address;
uint16_t udp_broadcast_port;
} ConfigData;


Expand Down Expand Up @@ -59,6 +61,14 @@ class GlobalConfig

uint32_t get_encoder_sample_rate() const;

void set_udp_broadcast_address(uint32_t address);

uint32_t get_udp_broadcast_address() const;

void set_udp_broadcast_port(uint16_t port);

uint16_t get_udp_broadcast_port() const;

void setDefault();

// Singleton instance
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,14 @@

#include <data/DataFrame.h>
#include <config/GlobalConfig.h>
#include <cstddef>

class ConfigDataFrame : public DataFrame
{
public:
const static size_t CONFIG_DATA_FRAME_SIZE = sizeof(GlobalConfig::ConfigData);
// Only the sensor configuration is serialized (network settings are excluded)
// to keep the frame format compatible with existing clients and recordings.
const static size_t CONFIG_DATA_FRAME_SIZE = offsetof(GlobalConfig::ConfigData, udp_broadcast_address);

ConfigDataFrame(const GlobalConfig::ConfigData& configData, uint64_t timestamp = DataFrame::getCurrentTimeStamp());

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,9 @@
namespace DPEng
{

/*=========================================================================
I2C ADDRESS/BITS AND SETTINGS
-----------------------------------------------------------------------*/
/*=========================================================================
I2C ADDRESS/BITS AND SETTINGS
-----------------------------------------------------------------------*/
/** 7-bit I2C address for this sensor */
#define BMX160_ADDRESS (0x68) // 0110 1001
/** Device ID for this sensor (used as sanity check during init) */
Expand Down
9 changes: 3 additions & 6 deletions software/firmware/arduino_esp32/platformio.ini
Original file line number Diff line number Diff line change
Expand Up @@ -31,9 +31,6 @@ lib_deps = Wire
[email protected]
Adafruit Unified [email protected]
sv-zanshin/[email protected]
#esphome/ESPAsyncWebServer-esphome@^3.1.0
# https://github.com/yubox-node-org/ESPAsyncWebServer
links2004/WebSockets@^2.4.1
[email protected]

; Serial Monitor
Expand All @@ -46,12 +43,12 @@ upload_speed = 921600

; Add -DNEXTWHEEL_DISABLE_WIFI=1 to build_flags to disable wifi


; None
;build_flags = -DCORE_DEBUG_LEVEL=0 -DNEXTWHEEL_DISABLE_WIFI=1
;build_flags = -DCORE_DEBUG_LEVEL=0 -DNEXTWHEEL_DISABLE_WIFI=1
;build_unflags = -std=gnu++11
;-DWS_MAX_QUEUED_MESSAGES=24
;-std=gnu++17
build_flags = -DCORE_DEBUG_LEVEL=1
build_flags = -DCORE_DEBUG_LEVEL=1

; Error
;build_flags = -DCORE_DEBUG_LEVEL=1
Expand Down
Loading
Loading