diff --git a/software/calibration/requirements.txt b/software/calibration/requirements.txt index 2dbe347..f0b2593 100644 --- a/software/calibration/requirements.txt +++ b/software/calibration/requirements.txt @@ -1,3 +1,2 @@ -websocket-client matplotlib diff --git a/software/firmware/README.md b/software/firmware/README.md index 8df84ba..2092ae0 100644 --- a/software/firmware/README.md +++ b/software/firmware/README.md @@ -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. @@ -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 @@ -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. diff --git a/software/firmware/arduino_esp32/.clang-format b/software/firmware/arduino_esp32/.clang-format index ad9fd26..4e16f7c 100644 --- a/software/firmware/arduino_esp32/.clang-format +++ b/software/firmware/arduino_esp32/.clang-format @@ -13,7 +13,7 @@ AlignTrailingComments: false AllowAllArgumentsOnNextLine: false AllowAllConstructorInitializersOnNextLine: false AllowAllParametersOfDeclarationOnNextLine: false -AllowShortBlocksOnASingleLine: Always +AllowShortBlocksOnASingleLine: Never AllowShortCaseLabelsOnASingleLine: false AllowShortEnumsOnASingleLine: false AllowShortFunctionsOnASingleLine: Inline @@ -35,7 +35,7 @@ BreakConstructorInitializers: BeforeColon BreakInheritanceList: BeforeColon BreakStringLiterals: true ColumnLimit: 120 -CompactNamespaces: false +CompactNamespaces: true ConstructorInitializerAllOnOneLineOrOnePerLine: true ConstructorInitializerIndentWidth: 4 ContinuationIndentWidth: 4 @@ -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 diff --git a/software/firmware/arduino_esp32/.vscode/extensions.json b/software/firmware/arduino_esp32/.vscode/extensions.json index 080e70d..a91ca8f 100644 --- a/software/firmware/arduino_esp32/.vscode/extensions.json +++ b/software/firmware/arduino_esp32/.vscode/extensions.json @@ -5,6 +5,7 @@ "platformio.platformio-ide" ], "unwantedRecommendations": [ - "ms-vscode.cpptools-extension-pack" + "ms-vscode.cpptools-extension-pack", + "pioarduino.pioarduino-ide" ] } diff --git a/software/firmware/arduino_esp32/lib/NextWheel/src/NextWheel.h b/software/firmware/arduino_esp32/lib/NextWheel/src/NextWheel.h index 1b64144..0c2ab64 100644 --- a/software/firmware/arduino_esp32/lib/NextWheel/src/NextWheel.h +++ b/software/firmware/arduino_esp32/lib/NextWheel/src/NextWheel.h @@ -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 diff --git a/software/firmware/arduino_esp32/lib/NextWheel/src/RTC.cpp b/software/firmware/arduino_esp32/lib/NextWheel/src/RTC.cpp index ad93a32..e56a92a 100644 --- a/software/firmware/arduino_esp32/lib/NextWheel/src/RTC.cpp +++ b/software/firmware/arduino_esp32/lib/NextWheel/src/RTC.cpp @@ -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}; @@ -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 : "); @@ -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 +} diff --git a/software/firmware/arduino_esp32/lib/NextWheel/src/RTC.h b/software/firmware/arduino_esp32/lib/NextWheel/src/RTC.h index 8d61012..a6022d6 100644 --- a/software/firmware/arduino_esp32/lib/NextWheel/src/RTC.h +++ b/software/firmware/arduino_esp32/lib/NextWheel/src/RTC.h @@ -5,6 +5,11 @@ #include #include +// 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: @@ -12,7 +17,9 @@ class 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; diff --git a/software/firmware/arduino_esp32/lib/NextWheel/src/config/GlobalConfig.cpp b/software/firmware/arduino_esp32/lib/NextWheel/src/config/GlobalConfig.cpp index 5b64dac..cf00bb3 100644 --- a/software/firmware/arduino_esp32/lib/NextWheel/src/config/GlobalConfig.cpp +++ b/software/firmware/arduino_esp32/lib/NextWheel/src/config/GlobalConfig.cpp @@ -2,6 +2,7 @@ #include #include "IMU.h" +#include const std::vector GlobalConfig::m_accel_ranges = {IMU::IMU_ACC_RANGE_2G, IMU::IMU_ACC_RANGE_4G, IMU::IMU_ACC_RANGE_8G, IMU::IMU_ACC_RANGE_16G}; @@ -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() @@ -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"); @@ -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(); } @@ -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; } diff --git a/software/firmware/arduino_esp32/lib/NextWheel/src/config/GlobalConfig.h b/software/firmware/arduino_esp32/lib/NextWheel/src/config/GlobalConfig.h index d1187d9..8a8385e 100644 --- a/software/firmware/arduino_esp32/lib/NextWheel/src/config/GlobalConfig.h +++ b/software/firmware/arduino_esp32/lib/NextWheel/src/config/GlobalConfig.h @@ -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; @@ -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 diff --git a/software/firmware/arduino_esp32/lib/NextWheel/src/data/ConfigDataFrame.h b/software/firmware/arduino_esp32/lib/NextWheel/src/data/ConfigDataFrame.h index f9ce1fa..9791c3f 100644 --- a/software/firmware/arduino_esp32/lib/NextWheel/src/data/ConfigDataFrame.h +++ b/software/firmware/arduino_esp32/lib/NextWheel/src/data/ConfigDataFrame.h @@ -3,11 +3,14 @@ #include #include +#include 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()); diff --git a/software/firmware/arduino_esp32/lib/NextWheel/src/drivers/DPEng_BMX160.h b/software/firmware/arduino_esp32/lib/NextWheel/src/drivers/DPEng_BMX160.h index 020bcc0..144b6a2 100644 --- a/software/firmware/arduino_esp32/lib/NextWheel/src/drivers/DPEng_BMX160.h +++ b/software/firmware/arduino_esp32/lib/NextWheel/src/drivers/DPEng_BMX160.h @@ -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) */ diff --git a/software/firmware/arduino_esp32/platformio.ini b/software/firmware/arduino_esp32/platformio.ini index e0251f5..6585d63 100644 --- a/software/firmware/arduino_esp32/platformio.ini +++ b/software/firmware/arduino_esp32/platformio.ini @@ -31,9 +31,6 @@ lib_deps = Wire EEPROM@2.0.0 Adafruit Unified Sensor@1.1.13 sv-zanshin/MCP7940@1.2.0 - #esphome/ESPAsyncWebServer-esphome@^3.1.0 - # https://github.com/yubox-node-org/ESPAsyncWebServer - links2004/WebSockets@^2.4.1 ESP32Encoder@0.10.2 ; Serial Monitor @@ -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 diff --git a/software/firmware/arduino_esp32/src/NextWheelApp.cpp b/software/firmware/arduino_esp32/src/NextWheelApp.cpp index 123fbc6..fcf2f55 100644 --- a/software/firmware/arduino_esp32/src/NextWheelApp.cpp +++ b/software/firmware/arduino_esp32/src/NextWheelApp.cpp @@ -20,8 +20,8 @@ void NextWheelApp::begin() m_sdCardWorkerTask.setPriority(TASK_PRIORITY_HIGH); // SAME CORE AS WiFi, BLE - m_webSocketServerTask.setCore(0); - m_webSocketServerTask.setPriority(TASK_PRIORITY_LOW); + m_webServerTask.setCore(0); + m_webServerTask.setPriority(TASK_PRIORITY_LOW); m_adcTask.setCore(1); m_adcTask.setPriority(TASK_PRIORITY_HIGHEST); @@ -46,9 +46,9 @@ void NextWheelApp::start() #ifndef NEXTWHEEL_DISABLE_WIFI - m_webSocketServerTask.start(this); + m_webServerTask.start(this); #else - Serial.println("WiFi + WebSocketServerTask disabled"); + Serial.println("WiFi + WebServerTask disabled"); #endif @@ -67,7 +67,7 @@ bool NextWheelApp::isRecording() bool NextWheelApp::isStreaming() { - return m_webSocketServerTask.isWebSocketConnected(); + return m_webServerTask.isUDPStreaming(); } LEDS& NextWheelApp::getLEDS() @@ -138,25 +138,25 @@ void NextWheelApp::unregisterSensorTasksFromSDCardWorker() xSemaphoreGive(m_queueMutex); } -void NextWheelApp::registerSensorTasksToWebSocketServer() +void NextWheelApp::registerSensorTasksToWebServer() { - Serial.println("Registering sensor tasks to WebSocketServerTask"); + Serial.println("Registering sensor tasks to WebServerTask"); xSemaphoreTake(m_queueMutex, portMAX_DELAY); - m_adcTask.registerDataQueue(m_webSocketServerTask.getQueue()); - m_imuTask.registerDataQueue(m_webSocketServerTask.getQueue()); - m_powerTask.registerDataQueue(m_webSocketServerTask.getQueue()); - m_quadEncoderTask.registerDataQueue(m_webSocketServerTask.getQueue()); + m_adcTask.registerDataQueue(m_webServerTask.getQueue()); + m_imuTask.registerDataQueue(m_webServerTask.getQueue()); + m_powerTask.registerDataQueue(m_webServerTask.getQueue()); + m_quadEncoderTask.registerDataQueue(m_webServerTask.getQueue()); xSemaphoreGive(m_queueMutex); } -void NextWheelApp::unregisterSensorTasksFromWebSocketServer() +void NextWheelApp::unregisterSensorTasksFromWebServer() { - Serial.println("Unregistering sensor tasks from WebSocketServerTask"); + Serial.println("Unregistering sensor tasks from WebServerTask"); xSemaphoreTake(m_queueMutex, portMAX_DELAY); - m_adcTask.unregisterDataQueue(m_webSocketServerTask.getQueue()); - m_imuTask.unregisterDataQueue(m_webSocketServerTask.getQueue()); - m_powerTask.unregisterDataQueue(m_webSocketServerTask.getQueue()); - m_quadEncoderTask.unregisterDataQueue(m_webSocketServerTask.getQueue()); + m_adcTask.unregisterDataQueue(m_webServerTask.getQueue()); + m_imuTask.unregisterDataQueue(m_webServerTask.getQueue()); + m_powerTask.unregisterDataQueue(m_webServerTask.getQueue()); + m_quadEncoderTask.unregisterDataQueue(m_webServerTask.getQueue()); xSemaphoreGive(m_queueMutex); } @@ -213,7 +213,7 @@ void NextWheelApp::sendConfigUpdateEvent(bool from_isr) m_quadEncoderTask.sendBaseCommandEvent(Task::BASE_TASK_CONFIG_UPDATED, from_isr); // Workers m_sdCardWorkerTask.sendBaseCommandEvent(Task::BASE_TASK_CONFIG_UPDATED, from_isr); - m_webSocketServerTask.sendBaseCommandEvent(Task::BASE_TASK_CONFIG_UPDATED, from_isr); + m_webServerTask.sendBaseCommandEvent(Task::BASE_TASK_CONFIG_UPDATED, from_isr); } diff --git a/software/firmware/arduino_esp32/src/NextWheelApp.h b/software/firmware/arduino_esp32/src/NextWheelApp.h index feffb1c..7cf2c58 100644 --- a/software/firmware/arduino_esp32/src/NextWheelApp.h +++ b/software/firmware/arduino_esp32/src/NextWheelApp.h @@ -12,7 +12,7 @@ #include "tasks/ADCSensorTask.h" #include "tasks/IMUSensorTask.h" #include "tasks/PowerSensorTask.h" -#include "tasks/WebSocketServerTask.h" +#include "tasks/WebServerTask.h" #include "tasks/SDCardWorkerTask.h" #include "tasks/DACActuatorTask.h" #include "tasks/QuadEncoderSensorTask.h" @@ -46,8 +46,8 @@ class NextWheelApp void registerSensorTasksToSDCardWorker(); void unregisterSensorTasksFromSDCardWorker(); - void registerSensorTasksToWebSocketServer(); - void unregisterSensorTasksFromWebSocketServer(); + void registerSensorTasksToWebServer(); + void unregisterSensorTasksFromWebServer(); bool button1Pressed(); bool button2Pressed(); @@ -83,8 +83,7 @@ class NextWheelApp // Workers SDCardWorkerTask m_sdCardWorkerTask; - // WebSocketServerTask m_webSocketServerTask; - WebSocketServerTask m_webSocketServerTask; + WebServerTask m_webServerTask; SemaphoreHandle_t m_queueMutex; }; diff --git a/software/firmware/arduino_esp32/src/main.cpp b/software/firmware/arduino_esp32/src/main.cpp index 15930b1..c3ec31f 100644 --- a/software/firmware/arduino_esp32/src/main.cpp +++ b/software/firmware/arduino_esp32/src/main.cpp @@ -148,7 +148,7 @@ void loop() NextWheelApp::instance()->getLEDS().setLED1(false); } - // LED 2 - Streaming (WebSocket) + // LED 2 - Streaming (UDP) if (NextWheelApp::instance()->isStreaming()) { NextWheelApp::instance()->getLEDS().toggleLED2(); diff --git a/software/firmware/arduino_esp32/src/tasks/DACActuatorTask.cpp b/software/firmware/arduino_esp32/src/tasks/DACActuatorTask.cpp index 5a2a1ee..ce0b488 100644 --- a/software/firmware/arduino_esp32/src/tasks/DACActuatorTask.cpp +++ b/software/firmware/arduino_esp32/src/tasks/DACActuatorTask.cpp @@ -147,7 +147,7 @@ void DACActuatorTask::run(void*) // DAC will only use the MSB // Right channel stereo_buffer[0] = 0; - stereo_buffer[1] = (sample)&0xFF; + stereo_buffer[1] = (sample) & 0xFF; // Left channel // stereo_buffer[2] = 0; diff --git a/software/firmware/arduino_esp32/src/tasks/PowerSensorTask.cpp b/software/firmware/arduino_esp32/src/tasks/PowerSensorTask.cpp index 2f5457d..c0af23f 100644 --- a/software/firmware/arduino_esp32/src/tasks/PowerSensorTask.cpp +++ b/software/firmware/arduino_esp32/src/tasks/PowerSensorTask.cpp @@ -1,7 +1,7 @@ #include "PowerSensorTask.h" #include "NextWheelApp.h" -PowerSensorTask::PowerSensorTask() : SensorTask("PowerSensorTask") {} +PowerSensorTask::PowerSensorTask() : SensorTask("PowerSensorTask", POWER_SENSOR_TASK_STACK_SIZE) {} void PowerSensorTask::run(void* app) { diff --git a/software/firmware/arduino_esp32/src/tasks/PowerSensorTask.h b/software/firmware/arduino_esp32/src/tasks/PowerSensorTask.h index ad9de6f..0e6c180 100644 --- a/software/firmware/arduino_esp32/src/tasks/PowerSensorTask.h +++ b/software/firmware/arduino_esp32/src/tasks/PowerSensorTask.h @@ -9,6 +9,9 @@ class PowerSensorTask : public SensorTask { + // Larger than default, Serial.printf with %f needs a lot of stack + static const size_t POWER_SENSOR_TASK_STACK_SIZE = 4096; + public: PowerSensorTask(); virtual void run(void* app) override; diff --git a/software/firmware/arduino_esp32/src/tasks/QuadEncoderSensorTask.cpp b/software/firmware/arduino_esp32/src/tasks/QuadEncoderSensorTask.cpp index cb5547e..eee3833 100644 --- a/software/firmware/arduino_esp32/src/tasks/QuadEncoderSensorTask.cpp +++ b/software/firmware/arduino_esp32/src/tasks/QuadEncoderSensorTask.cpp @@ -33,7 +33,10 @@ void QuadEncoderSensorTask::run(void* app) encoder_timer, &NextWheelInterrupts::quad_encoder_sensor_task_timer_interrupt, false); // Attach interrupt function - timerAlarmWrite(encoder_timer, 1000000 / GlobalConfig::instance().get_encoder_sample_rate(), true); // us timer calculation + timerAlarmWrite( + encoder_timer, + 1000000 / GlobalConfig::instance().get_encoder_sample_rate(), + true); // us timer calculation timerAlarmEnable(encoder_timer); @@ -77,8 +80,8 @@ void QuadEncoderSensorTask::run(void* app) // Reset counter // m_encoder.clearCount(); - //Serial.print("encoder counts: "); - //Serial.println(count); + // Serial.print("encoder counts: "); + // Serial.println(count); // Update timestamp and value frame.setTimestamp(DataFrame::getCurrentTimeStamp()); diff --git a/software/firmware/arduino_esp32/src/tasks/UDPStreamer.cpp b/software/firmware/arduino_esp32/src/tasks/UDPStreamer.cpp new file mode 100644 index 0000000..ce6e458 --- /dev/null +++ b/software/firmware/arduino_esp32/src/tasks/UDPStreamer.cpp @@ -0,0 +1,82 @@ +#include "UDPStreamer.h" +#include +#include + + +UDPStreamer::UDPStreamer() : m_socket(-1), m_streaming(false), m_droppedPackets(0) {} + +UDPStreamer::~UDPStreamer() +{ + stop(); +} + +bool UDPStreamer::start() +{ + if (m_socket < 0) + { + m_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP); + if (m_socket < 0) + { + Serial.printf("UDPStreamer::start: socket() failed, errno: %i\n", errno); + return false; + } + + // Allow sending to broadcast addresses (default is 255.255.255.255) + int broadcast = 1; + setsockopt(m_socket, SOL_SOCKET, SO_BROADCAST, &broadcast, sizeof(broadcast)); + } + + m_droppedPackets = 0; + m_streaming = true; + return true; +} + +void UDPStreamer::stop() +{ + m_streaming = false; + if (m_socket >= 0) + { + close(m_socket); + m_socket = -1; + } +} + +bool UDPStreamer::isStreaming() const +{ + return m_streaming; +} + +bool UDPStreamer::send(const uint8_t* data, size_t size) +{ + if (!m_streaming || m_socket < 0) + { + return false; + } + + // Address is stored in network byte order (IPAddress raw value) + struct sockaddr_in dest = {}; + dest.sin_family = AF_INET; + dest.sin_port = htons(GlobalConfig::instance().get_udp_broadcast_port()); + dest.sin_addr.s_addr = GlobalConfig::instance().get_udp_broadcast_address(); + + // Non blocking, if the WiFi stack is out of buffers, drop the packet + int sent = sendto(m_socket, data, size, MSG_DONTWAIT, (struct sockaddr*)&dest, sizeof(dest)); + if (sent != (int)size) + { + m_droppedPackets++; + return false; + } + return true; +} + +bool UDPStreamer::sendFrame(const DataFrame& frame) +{ + uint8_t buffer[frame.getTotalSize()]; + frame.serialize(buffer, frame.getTotalSize()); + return send(buffer, frame.getTotalSize()); +} + +uint32_t UDPStreamer::getDroppedPackets() const +{ + return m_droppedPackets; +} diff --git a/software/firmware/arduino_esp32/src/tasks/UDPStreamer.h b/software/firmware/arduino_esp32/src/tasks/UDPStreamer.h new file mode 100644 index 0000000..a9bb3eb --- /dev/null +++ b/software/firmware/arduino_esp32/src/tasks/UDPStreamer.h @@ -0,0 +1,33 @@ +#ifndef _UDP_STREAMER_H_ +#define _UDP_STREAMER_H_ + +#include +#include + +/** + * Sends binary frames (see "UDP Binary Message Format" in README) to the UDP + * address / port stored in GlobalConfig. The destination is read from + * GlobalConfig on every send so configuration changes apply immediately. + */ +class UDPStreamer +{ +public: + UDPStreamer(); + ~UDPStreamer(); + + bool start(); + void stop(); + bool isStreaming() const; + + bool send(const uint8_t* data, size_t size); + bool sendFrame(const DataFrame& frame); + + uint32_t getDroppedPackets() const; + +private: + int m_socket; + bool m_streaming; + uint32_t m_droppedPackets; +}; + +#endif // _UDP_STREAMER_H_ diff --git a/software/firmware/arduino_esp32/src/tasks/WebSocketServerTask.cpp b/software/firmware/arduino_esp32/src/tasks/WebServerTask.cpp similarity index 59% rename from software/firmware/arduino_esp32/src/tasks/WebSocketServerTask.cpp rename to software/firmware/arduino_esp32/src/tasks/WebServerTask.cpp index a36b577..2f8d7f5 100644 --- a/software/firmware/arduino_esp32/src/tasks/WebSocketServerTask.cpp +++ b/software/firmware/arduino_esp32/src/tasks/WebServerTask.cpp @@ -1,4 +1,4 @@ -#include "WebSocketServerTask.h" +#include "WebServerTask.h" #include "config/GlobalConfig.h" #include "NextWheelApp.h" #include @@ -7,19 +7,22 @@ #include #include #include +#include +volatile bool WebServerTask::s_ntpSynced = false; +volatile bool WebServerTask::s_ntpRTCUpdatePending = false; +volatile time_t WebServerTask::s_ntpLastSyncTime = 0; +volatile int64_t WebServerTask::s_ntpLastSyncTimerUs = 0; -WebSocketServerTask::WebSocketServerTask() - : WorkerTask("WebSocketServerTask", WEBSOCKET_SERVER_STACK_SIZE), - m_webSocketServer(81), - m_webServer(80) -{ -} +WebServerTask::WebServerTask() : WorkerTask("WebServerTask", WEB_SERVER_STACK_SIZE), m_webServer(80) {} -void WebSocketServerTask::run(void* app) +void WebServerTask::run(void* app) { - Serial.printf("WebSocketServerTask::run Priority: %li Core: %li \n", uxTaskPriorityGet(NULL), xPortGetCoreID()); + Serial.printf("WebServerTask::run Priority: %li Core: %li \n", uxTaskPriorityGet(NULL), xPortGetCoreID()); + + // NTP will be started when an IP address is obtained, until the first sync + setupNTP(); WiFi.begin(WIFI_DEFAULT_SSID, WIFI_DEFAULT_PASSWORD); // put your setup code here, to run once: @@ -33,19 +36,26 @@ void WebSocketServerTask::run(void* app) TickType_t lastGeneration = xTaskGetTickCount(); - m_webSocketServer.begin(); - m_webSocketServer.onEvent([this](uint8_t num, WStype_t type, uint8_t* payload, size_t length) - { this->webSocketEvent(num, type, payload, length); }); - setupRESTAPI(); m_webServer.begin(); while (1) { - // Serial.println("WebSocketServerTask::run: m_webSocketServer.loop()"); - m_webSocketServer.loop(); + // Serial.println("WebServerTask::run: m_webServer.loop()"); m_webServer.handleClient(); + // Store NTP time in the RTC (done here to avoid I2C access from the lwIP task) + if (s_ntpRTCUpdatePending) + { + s_ntpRTCUpdatePending = false; + // NTP is only needed once at startup, stop it here (not from the lwIP callback) + stopNTP(); + // With smooth sync, system time is still converging, use NTP time + elapsed time instead + int64_t elapsed_us = esp_timer_get_time() - s_ntpLastSyncTimerUs; + NextWheelApp::instance()->getRTC().adjustRTCTime(s_ntpLastSyncTime + elapsed_us / 1000000); + NextWheelApp::instance()->getRTC().printTime(); + } + // First empty the command queue (timeout=0, not waiting) // Loop while we have BASE_TASK_COMMAND_NONE --> 0 while (Task::BaseTaskCommand command = dequeueBaseCommand(0)) @@ -53,20 +63,17 @@ void WebSocketServerTask::run(void* app) switch (command) { case Task::BASE_TASK_COMMAND_NONE: - Serial.println("WebSocketServerTask::run: BASE_TASK_COMMAND_NONE"); + Serial.println("WebServerTask::run: BASE_TASK_COMMAND_NONE"); break; case Task::BASE_TASK_CONFIG_UPDATED: { - Serial.println("WebSocketServerTask::run: BASE_TASK_CONFIG_UPDATED"); + Serial.println("WebServerTask::run: BASE_TASK_CONFIG_UPDATED"); // We should update the configuration info from now ConfigDataFrame configDataFrame(GlobalConfig::instance().get()); - for (auto id = 0; id < m_webSocketServer.connectedClients(); id++) - { - uint8_t config_data[configDataFrame.getTotalSize()]; - configDataFrame.serialize(config_data, configDataFrame.getTotalSize()); - m_webSocketServer.sendBIN(id, config_data, configDataFrame.getTotalSize()); - } + + // Send to UDP destination (does nothing if not streaming) + m_udpStreamer.sendFrame(configDataFrame); // Empty the queue (with old config!) while (DataFramePtr dataPtr = dequeue(0)) @@ -77,13 +84,13 @@ void WebSocketServerTask::run(void* app) break; default: - Serial.print("WebSocketServerTask::run: Unknown command: "); + Serial.print("WebServerTask::run: Unknown command: "); Serial.println(command); break; } } - // Then dequeue all data frames and send them to the websocket + // Then dequeue all data frames and send them as a UDP superframe size_t total_payload_size = 0; std::list dataPtrs; @@ -122,67 +129,127 @@ void WebSocketServerTask::run(void* app) delete dataPtr; } - // Send to all websockets - for (auto id = 0; id < m_webSocketServer.connectedClients(); id++) - { - m_webSocketServer.sendBIN(id, super_frame, total_payload_size + DataFrame::HEADER_SIZE); - } + // Send to UDP destination (does nothing if not streaming) + m_udpStreamer.send(super_frame, total_payload_size + DataFrame::HEADER_SIZE); } } // while(1) } -bool WebSocketServerTask::isWebSocketConnected() +bool WebServerTask::isUDPStreaming() { - return m_webSocketServer.connectedClients() > 0; + return m_udpStreamer.isStreaming(); } -void WebSocketServerTask::webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length) +bool WebServerTask::startUDPStreaming(uint32_t address, uint16_t port) { - switch (type) + if (m_udpStreamer.isStreaming()) { - case WStype_DISCONNECTED: - Serial.printf("[%u] Disconnected!\n", num); - SystemState::instance().getState().streaming = false; - NextWheelApp::instance()->playStopStreamingSound(); - NextWheelApp::instance()->unregisterSensorTasksFromWebSocketServer(); - break; - case WStype_CONNECTED: + //return false; + stopUDPStreaming(); + } + + // Destination is stored in the config, UDPStreamer reads it when sending + GlobalConfig::instance().set_udp_broadcast_address(address); + GlobalConfig::instance().set_udp_broadcast_port(port); + + if (!m_udpStreamer.start()) + { + return false; + } + + Serial.printf( + "UDP streaming to %s:%u\n", + IPAddress(GlobalConfig::instance().get_udp_broadcast_address()).toString().c_str(), + GlobalConfig::instance().get_udp_broadcast_port()); + + SystemState::instance().getState().streaming = true; + NextWheelApp::instance()->playStartStreamingSound(); + + // Send the current configuration first, clients need it to decode data frames + ConfigDataFrame configDataFrame(GlobalConfig::instance().get()); + m_udpStreamer.sendFrame(configDataFrame); + + NextWheelApp::instance()->registerSensorTasksToWebServer(); + return true; +} + +bool WebServerTask::stopUDPStreaming() +{ + if (!m_udpStreamer.isStreaming()) + { + return false; + } + + NextWheelApp::instance()->unregisterSensorTasksFromWebServer(); + Serial.printf("UDP streaming stopped, dropped packets: %u\n", m_udpStreamer.getDroppedPackets()); + m_udpStreamer.stop(); + + SystemState::instance().getState().streaming = false; + NextWheelApp::instance()->playStopStreamingSound(); + return true; +} + +void WebServerTask::setupNTP() +{ + WiFi.onEvent( + [this](arduino_event_id_t event, arduino_event_info_t info) { - IPAddress ip = m_webSocketServer.remoteIP(num); - Serial.printf("[%u] Connected from %d.%d.%d.%d url: %s\n", num, ip[0], ip[1], ip[2], ip[3], payload); - SystemState::instance().getState().streaming = true; - NextWheelApp::instance()->playStartStreamingSound(); - - // Send the current configuration - ConfigDataFrame configDataFrame(GlobalConfig::instance().get()); - uint8_t config_data[configDataFrame.getTotalSize()]; - configDataFrame.serialize(config_data, configDataFrame.getTotalSize()); - m_webSocketServer.sendBIN(num, config_data, configDataFrame.getTotalSize()); - - NextWheelApp::instance()->registerSensorTasksToWebSocketServer(); - } - break; - case WStype_TEXT: - Serial.printf("[%u] get Text: %s\n", num, payload); - break; - case WStype_BIN: - Serial.printf("[%u] get binary length: %u\n", num, length); - break; - case WStype_ERROR: - case WStype_FRAGMENT_TEXT_START: - case WStype_FRAGMENT_BIN_START: - case WStype_FRAGMENT: - case WStype_FRAGMENT_FIN: - break; + Serial.print("WebServerTask: Got IP: "); + Serial.println(IPAddress(info.got_ip.ip_info.ip.addr)); + // Only sync once at startup, do not restart NTP on reconnect + if (!s_ntpSynced) + { + startNTP(); + } + }, + ARDUINO_EVENT_WIFI_STA_GOT_IP); +} + +void WebServerTask::startNTP() +{ + // Restart SNTP if already running (IP changed / reconnected) + if (sntp_enabled()) + { + sntp_stop(); + } + + // Not using configTime() since it overrides the TZ, make sure local time is Eastern + RTC::setTimeZone(); + + sntp_setoperatingmode(SNTP_OPMODE_POLL); + // Gradual correction (adjtime) to avoid timestamp jumps while recording / streaming + // Note: error > 35 minutes (e.g. RTC never set) is still corrected immediately + sntp_set_sync_mode(SNTP_SYNC_MODE_SMOOTH); + sntp_setservername(0, NTP_DEFAULT_SERVER); + sntp_set_time_sync_notification_cb(&WebServerTask::onNTPTimeSync); + sntp_init(); + Serial.printf("WebServerTask: NTP started with server %s\n", NTP_DEFAULT_SERVER); +} + +void WebServerTask::stopNTP() +{ + if (sntp_enabled()) + { + sntp_stop(); + Serial.println("WebServerTask: NTP stopped"); } } -void WebSocketServerTask::setupRESTAPI() +void WebServerTask::onNTPTimeSync(struct timeval* tv) +{ + s_ntpLastSyncTime = tv->tv_sec; + s_ntpLastSyncTimerUs = esp_timer_get_time(); + s_ntpSynced = true; + s_ntpRTCUpdatePending = true; + Serial.printf("WebServerTask: NTP time synchronized: %li\n", (long)tv->tv_sec); +} + +void WebServerTask::setupRESTAPI() { m_webServer.onNotFound( [this]() { - Serial.println("WebSocketServerTask::setupRESTAPI: onNotFound"); + Serial.println("WebServerTask::setupRESTAPI: onNotFound"); String message = "Not Found\n\n"; message += "URI: "; message += m_webServer.uri(); @@ -204,7 +271,7 @@ void WebSocketServerTask::setupRESTAPI() HTTP_GET, [this]() { - Serial.println("WebSocketServerTask::setupRESTAPI: /"); + Serial.println("WebServerTask::setupRESTAPI: /"); String message = "Hello from NextWheel REST API Server !"; m_webServer.send(200, "text/plain", message); }); @@ -236,6 +303,55 @@ void WebSocketServerTask::setupRESTAPI() } }); + m_webServer.on( + "/ntp_time", + HTTP_GET, + [this]() + { + Serial.println("get: /ntp_time"); + + struct timeval current_time; + gettimeofday(¤t_time, NULL); + + char iso_time[32]; + strftime(iso_time, sizeof(iso_time), "%Y-%m-%dT%H:%M:%S%z", localtime(¤t_time.tv_sec)); + + cJSON* root = cJSON_CreateObject(); + cJSON_AddBoolToObject(root, "synced", s_ntpSynced); + cJSON_AddStringToObject(root, "server", NTP_DEFAULT_SERVER); + cJSON_AddNumberToObject(root, "time", (double)current_time.tv_sec + current_time.tv_usec / 1e6); + cJSON_AddStringToObject(root, "local_time", iso_time); + cJSON_AddNumberToObject(root, "last_sync", (double)s_ntpLastSyncTime); + + // Remaining correction (seconds) being applied gradually, 0 when system time is in sync + struct timeval remaining = {0, 0}; + adjtime(NULL, &remaining); + cJSON_AddNumberToObject(root, "adjusting", (double)remaining.tv_sec + remaining.tv_usec / 1e6); + String json(cJSON_Print(root)); + + // Free memory + cJSON_free(root); + + Serial.println(json); + m_webServer.send(200, "application/json", json); + }); + + m_webServer.on( + "/ntp_resync", + HTTP_GET, + [this]() + { + Serial.println("get: /ntp_resync"); + if (WiFi.status() != WL_CONNECTED) + { + m_webServer.send(400, "text/plain", "Not connected"); + return; + } + // NTP will be stopped again after the next synchronization + startNTP(); + m_webServer.send(200, "text/plain", "OK"); + }); + m_webServer.on( "/config_update", HTTP_POST, @@ -253,6 +369,9 @@ void WebSocketServerTask::setupRESTAPI() GlobalConfig::instance().set_adc_sample_rate(m_webServer.arg("adc_sampling_rate").toInt()); GlobalConfig::instance().set_encoder_sample_rate(m_webServer.arg("encoder_sampling_rate").toInt()); + // Apply the new configuration to all tasks (sensor rates, IMU ranges, CONFIG frame to SD card / UDP) + NextWheelApp::instance()->sendConfigUpdateEvent(); + // Print current config Serial.println("Current config:"); Serial.printf("Accelerometer precision: %d\n", GlobalConfig::instance().get_accel_range()); @@ -287,6 +406,12 @@ void WebSocketServerTask::setupRESTAPI() cJSON_AddNumberToObject(root, "imu_sampling_rate", GlobalConfig::instance().get_imu_sample_rate()); cJSON_AddNumberToObject(root, "adc_sampling_rate", GlobalConfig::instance().get_adc_sample_rate()); cJSON_AddNumberToObject(root, "encoder_sampling_rate", GlobalConfig::instance().get_encoder_sample_rate()); + /* + cJSON_AddStringToObject( + root, "udp_broadcast_address", + IPAddress(GlobalConfig::instance().get_udp_broadcast_address()).toString().c_str()); + cJSON_AddNumberToObject(root, "udp_broadcast_port", GlobalConfig::instance().get_udp_broadcast_port()); + */ String json(cJSON_Print(root)); // Free memory @@ -355,6 +480,57 @@ void WebSocketServerTask::setupRESTAPI() }); + m_webServer.on( + "/start_streaming", + HTTP_GET, + [this]() + { + Serial.println("get: /start_streaming"); + if (!m_webServer.hasArg("address") || !m_webServer.hasArg("port")) + { + m_webServer.send(400, "text/plain", "Missing arguments (address, port)"); + return; + } + IPAddress udp_address; + if (!udp_address.fromString(m_webServer.arg("address"))) + { + m_webServer.send(400, "text/plain", "Invalid address (expected x.x.x.x)"); + return; + } + long udp_port = m_webServer.arg("port").toInt(); + if (udp_port <= 0 || udp_port >= 0xFFFF) + { + m_webServer.send(400, "text/plain", "Invalid port"); + return; + } + + if (startUDPStreaming(uint32_t(udp_address), udp_port)) + { + m_webServer.send(200, "text/plain", "OK"); + } + else + { + m_webServer.send(400, "text/plain", "Already streaming"); + } + }); + + m_webServer.on( + "/stop_streaming", + HTTP_GET, + [this]() + { + Serial.println("get: /stop_streaming"); + if (stopUDPStreaming()) + { + m_webServer.send(200, "text/plain", "OK"); + } + else + { + m_webServer.send(400, "text/plain", "Not streaming"); + } + }); + + m_webServer.on( "/file_list", HTTP_GET, diff --git a/software/firmware/arduino_esp32/src/tasks/WebServerTask.h b/software/firmware/arduino_esp32/src/tasks/WebServerTask.h new file mode 100644 index 0000000..f5cc4ff --- /dev/null +++ b/software/firmware/arduino_esp32/src/tasks/WebServerTask.h @@ -0,0 +1,47 @@ +#ifndef _WEB_SERVER_TASK_H_ +#define _WEB_SERVER_TASK_H_ + +#include "config/WiFiConfig.h" +#include "tasks/WorkerTask.h" +#include +#include +#include +#include +#include +#include +#include "tasks/UDPStreamer.h" + +#ifndef NTP_DEFAULT_SERVER +#define NTP_DEFAULT_SERVER "pool.ntp.org" +#endif + +class WebServerTask : public WorkerTask +{ + static const size_t WEB_SERVER_STACK_SIZE = 12000; + +public: + WebServerTask(); + virtual void run(void* app) override; + bool isUDPStreaming(); + + +protected: + void setupRESTAPI(); + bool startUDPStreaming(uint32_t address, uint16_t port); + bool stopUDPStreaming(); + void setupNTP(); + void startNTP(); + void stopNTP(); + static void onNTPTimeSync(struct timeval* tv); + + // Written from the SNTP callback (lwIP task), read from this task + static volatile bool s_ntpSynced; + static volatile bool s_ntpRTCUpdatePending; + static volatile time_t s_ntpLastSyncTime; + static volatile int64_t s_ntpLastSyncTimerUs; + + WebServer m_webServer; + UDPStreamer m_udpStreamer; +}; + +#endif // _WEB_SERVER_TASK_H_ diff --git a/software/firmware/arduino_esp32/src/tasks/WebSocketServerTask.h b/software/firmware/arduino_esp32/src/tasks/WebSocketServerTask.h deleted file mode 100644 index 6a296ed..0000000 --- a/software/firmware/arduino_esp32/src/tasks/WebSocketServerTask.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef _WEBSOCKET_SERVER_TASK_H_ -#define _WEBSOCKET_SERVER_TASK_H_ - -#include "config/WiFiConfig.h" -#include "tasks/WorkerTask.h" -#include -#include -#include -#include -#include -#include -#include - - -class WebSocketServerTask : public WorkerTask -{ - static const size_t WEBSOCKET_SERVER_STACK_SIZE = 12000; - -public: - WebSocketServerTask(); - virtual void run(void* app) override; - bool isWebSocketConnected(); - - -protected: - void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length); - void setupRESTAPI(); - - WebSocketsServer m_webSocketServer; - WebServer m_webServer; -}; - -#endif // _WEBSOCKET_SERVER_TASK_H_ diff --git a/software/python/.vscode/settings.json b/software/python/.vscode/settings.json new file mode 100644 index 0000000..c820b9a --- /dev/null +++ b/software/python/.vscode/settings.json @@ -0,0 +1,4 @@ +{ + "python-envs.defaultEnvManager": "ms-python.python:conda", + "python-envs.defaultPackageManager": "ms-python.python:conda" +} diff --git a/software/python/README.md b/software/python/README.md index 4f6df8f..a5f0b86 100644 --- a/software/python/README.md +++ b/software/python/README.md @@ -25,6 +25,15 @@ To use the module: >>> nw.stop_streaming() ``` +Streamed data is sent by the wheel over UDP (by default, broadcast on port +12345). Make sure your firewall accepts incoming UDP datagrams on this port. +To change where the wheel sends its data (e.g., a different port for each +wheel, or this computer's IP address instead of broadcast): + +```python +>>> nw.start_streaming("255.255.255.255", 12346) +``` + To see the list of recorded data files: ```python diff --git a/software/python/nextwheel/__init__.py b/software/python/nextwheel/__init__.py index bef1edd..95a5109 100644 --- a/software/python/nextwheel/__init__.py +++ b/software/python/nextwheel/__init__.py @@ -16,6 +16,7 @@ import json import os +import socket import struct import threading from enum import IntEnum @@ -24,7 +25,6 @@ import numpy as np import requests -import websocket from requests.exceptions import ConnectTimeout try: @@ -56,11 +56,15 @@ def __repr__(self): GRAVITY = 9.80665 STANDARD_MAG_RANGE = 2500 HTTP_RESPONSE_CODE_OK = 200 +HTTP_RESPONSE_CODE_BAD_REQUEST = 400 +DEFAULT_UDP_PORT = 12345 +UDP_RECEIVE_BUFFER_SIZE = 65535 +UDP_SOCKET_TIMEOUT = 0.2 # s, delay to notice that streaming was stopped ENCODER_RESOLUTION = 0.087890625 / 180 * np.pi # rad per tick class FrameType(IntEnum): - """Identify frame type from websocket message.""" + """Identify frame type from a UDP datagram or a dat file.""" CONFIG = 1 ADC = 2 @@ -230,13 +234,19 @@ class NextWheel: Communicate with the instrumented wheel. The class permit to communicate with the instrumented wheel with 3 methods: - - NextWheel.connect() allows to start a connection with the server via - the WebSocketApp. + - NextWheel.start_streaming() asks the wheel to stream its data over + UDP and starts receiving it in a background thread. - NextWheel.fetch() return the streamed data in a nested dictionary - with all the usefull informations. Also clear the buffer. - - NextWheel.close() close the connection with the instrumented wheel. + with all the usefull informations. + - NextWheel.stop_streaming() stops the stream. It needs an IP address like in the example below. + The wheel sends its data to the UDP address and port given to + NextWheel.start_streaming() (by default, broadcast 255.255.255.255 on + port 12345). Use a different port for each wheel to reduce network load + on each receiver. The local firewall must accept incoming UDP datagrams + on this port. + Raises ------ TimeoutError @@ -247,10 +257,11 @@ class NextWheel: ------- >>> from nextwheel import NextWheel >>> nw = NextWheel("196.168.1.254") + >>> nw.start_streaming() >>> print(nw.fetch()) - >>> nw.close() + >>> nw.stop_streaming() """ @@ -258,6 +269,7 @@ def __init__( self, ip: str = "", *, + port: int = 80, debug: bool = False, ): # General configuration @@ -271,9 +283,12 @@ def __init__( self.calibration_matrix: np.ndarray = np.eye(6) self.calibration_offset: np.ndarray = np.zeros(6) - # Communication stuff + # Communication stuff (port must be set before ip, which connects) + self.port = port self.ip = ip - self.ws: None | websocket.WebSocketApp = None + self._udp_socket: None | socket.socket = None + self._udp_thread: None | threading.Thread = None + self._stop_event = threading.Event() self._mutex = threading.Lock() self._thread_is_running = False @@ -452,42 +467,75 @@ def _parse_message(self, stream: bytes, offset: int = 0) -> int: # noqa PLR0911 raise ValueError(f"Received an unknown frame type: {frame_type}") - def _on_message(self, ws: websocket.WebSocketApp, message: bytes) -> None: + def _parse_datagram(self, datagram: bytes) -> None: """ - React to WebSocketApp message received. - - Simply a wrapper to the more generic _parse_messages function. + Parse all messages contained in a received UDP datagram. Parameters ---------- - ws - Unused. - message + datagram Information containing data in bytes. """ - if self._debug: - print("Received data: ", ws) + offset = 0 with self._mutex: - self._parse_message(message) + while ( + new_offset := self._parse_message(datagram, offset) + ) > offset: + offset = new_offset - def _on_open(self, ws): - """Reaction of the WebSocketApp when the connection is open.""" - if self._debug: - print("Connected: ", ws) + def _receive_loop(self, udp_socket: socket.socket, wheel_ip: str) -> None: + """ + Receive UDP datagrams from the wheel until streaming is stopped. - def _on_error(self, ws, error): - """Reaction of the WebSocketApp when there is an error.""" - print(ws, error) - self.stop_streaming() + Parameters + ---------- + udp_socket + Bound UDP socket with a timeout. + wheel_ip + Datagrams not coming from this address (e.g., from another wheel + broadcasting on the same port) are ignored. - def _on_close(self, ws, close_status_code, close_msg): - """Reaction of the WebSocketApp when the connection is close.""" - if self._debug: - print("Closed: ", ws, close_status_code, close_msg) + """ + while not self._stop_event.is_set(): + try: + datagram, (sender_ip, _) = udp_socket.recvfrom( + UDP_RECEIVE_BUFFER_SIZE + ) + except TimeoutError: + continue + except OSError: + # Socket closed by stop_streaming + break - def start_streaming( + if sender_ip != wheel_ip: + continue + + if self._debug: + print(f"Received {len(datagram)} bytes from {sender_ip}") + + try: + self._parse_datagram(datagram) + except (ValueError, struct.error) as e: + # A corrupted datagram should not stop the stream + print("Invalid datagram received: ", e) + + def _update_config_from_params(self, params: dict) -> None: + """Update the conversion configuration from get_sensors_params().""" + with self._mutex: + self._config.accel_range = params["accelerometer_precision"] + self._config.gyro_range = params["gyrometer_precision"] + self._config.imu_sampling_rate = params["imu_sampling_rate"] + self._config.adc_sampling_rate = params["adc_sampling_rate"] + self._config.encoder_sampling_rate = params[ + "encoder_sampling_rate" + ] + + def start_streaming( # noqa: PLR0913 self, + address: str = "255.255.255.255", + port: int = DEFAULT_UDP_PORT, + *, max_imu_samples: int = 1000, max_analog_samples: int = 1000, max_encoder_samples: int = 100, @@ -498,6 +546,13 @@ def start_streaming( Parameters ---------- + address : str, optional + IP address (x.x.x.x) where the wheel sends the streamed data. The + default 255.255.255.255 broadcasts to the whole local network. + Using the IP address of this computer avoids broadcasting. + port : int, optional + UDP port where the wheel sends the streamed data, and where this + computer listens. The default is 12345. max_imu_samples : int, optional Maximum IMU data to keep in memory. The default is 1000. max_analog_samples : int, optional @@ -520,49 +575,98 @@ def start_streaming( self.max_encoder_samples = max_encoder_samples self.max_power_samples = max_power_samples - self.ws = websocket.WebSocketApp( - f"ws://{self.ip}:81/", - on_open=self._on_open, - on_message=self._on_message, - on_error=self._on_error, - on_close=self._on_close, + # The config frame is only sent when streaming starts, which may have + # been done by another client. Get the current config from the REST + # API so that the data can be converted in any case. + params = self.get_sensors_params() + self._update_config_from_params(params) + + udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) + if hasattr(socket, "SO_REUSEPORT"): + # Allows several NextWheel instances to receive broadcasts on the + # same port. + udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEPORT, 1) + udp_socket.bind(("", port)) + udp_socket.settimeout(UDP_SOCKET_TIMEOUT) + self._udp_socket = udp_socket + + self._stop_event.clear() + self._udp_thread = threading.Thread( + target=self._receive_loop, + args=(udp_socket, socket.gethostbyname(self.ip)), + daemon=True, ) - - t = threading.Thread(target=self.ws.run_forever) # type: ignore - t.start() + self._udp_thread.start() self._thread_is_running = True + if self._debug: + print( + "Listening on UDP port", + port, + "for data sent to", + address, + ) + + # Ask the wheel to start streaming. "Already streaming" means that + # another client started it (possibly to another destination), which + # is fine. + response = requests.get( + f"http://{self.ip}:{self.port}/start_streaming", + params={"address": address, "port": str(port)}, + ) + already_streaming = ( + response.status_code == HTTP_RESPONSE_CODE_BAD_REQUEST + and "Already streaming" in response.text + ) + if ( + response.status_code != HTTP_RESPONSE_CODE_OK + and not already_streaming + ): + self.stop_streaming() + raise RuntimeError( + f"Could not start streaming: {response.status_code} " + f"{response.text}" + ) + def stop_streaming(self): """ - Stop streaming via websocket. + Stop streaming. Returns ------- None. """ - self.ws.close() - self._thread_is_running = False - try: - # If something has crashed somewhere, release the mutex for the - # next connection. - self._mutex.release() - except RuntimeError: - # No mutex was locked. That's fine. - pass + if not self._thread_is_running: + return - def monitor(self) -> None: + try: + requests.get(f"http://{self.ip}:{self.port}/stop_streaming") + finally: + self._stop_event.set() + if self._udp_thread is not None: + self._udp_thread.join() + self._udp_thread = None + if self._udp_socket is not None: + self._udp_socket.close() + self._udp_socket = None + self._thread_is_running = False + + def monitor( + self, address: str = "255.255.255.255", port: int = DEFAULT_UDP_PORT + ) -> None: """ Blocking function that monitors the sensors measurements. This function shows the current sensor states in a simple GUI for testing and monitoring. To log data, use NextWheel.fetch() - instead. + instead. See start_streaming() for address and port. """ # Don't import until needed. import nextwheel.monitor as nwm # noqa - self.start_streaming() + self.start_streaming(address, port) nwm.monitor(self) self.stop_streaming() @@ -836,10 +940,11 @@ def set_time(self, unix_time: int) -> None: """ requests.post( - f"http://{self.ip}/config_set_time", params={"time": unix_time} + f"http://{self.ip}:{self.port}/config_set_time", + params={"time": unix_time}, ) - def set_sensors_params( + def set_sensors_params( # noqa: PLR0913 self, adc_sampling_rate: int, imu_sampling_rate: int, @@ -871,15 +976,16 @@ def set_sensors_params( requests.Response """ + params = { + "adc_sampling_rate": adc_sampling_rate, + "imu_sampling_rate": imu_sampling_rate, + "encoder_sampling_rate": encoder_sampling_rate, + "accelerometer_precision": accelerometer_precision, + "gyrometer_precision": gyrometer_precision, + } + response = requests.post( - f"http://{self.ip}/config_update", - params={ - "adc_sampling_rate": adc_sampling_rate, - "imu_sampling_rate": imu_sampling_rate, - "encoder_sampling_rate": encoder_sampling_rate, - "accelerometer_precision": accelerometer_precision, - "gyrometer_precision": gyrometer_precision, - }, + f"http://{self.ip}:{self.port}/config_update", params=params ) return response @@ -893,7 +999,7 @@ def get_sensors_params(self) -> dict: A dictionary in the form parameter:value. """ - response = requests.get(f"http://{self.ip}/config") + response = requests.get(f"http://{self.ip}:{self.port}/config") return json.loads(response.content) def get_system_state(self) -> dict: @@ -906,9 +1012,38 @@ def get_system_state(self) -> dict: A dictionary in the form parameter:value """ - response = requests.get(f"http://{self.ip}/system_state") + response = requests.get(f"http://{self.ip}:{self.port}/system_state") + return json.loads(response.content) + + def get_ntp_time(self) -> dict: + """ + Get the NTP time status of the instrumented wheel. + + Returns + ------- + dict + A dictionary with keys synced, server, time (epoch seconds), + local_time (ISO 8601), last_sync (epoch seconds) and + adjusting (remaining gradual correction in seconds). + + """ + response = requests.get(f"http://{self.ip}:{self.port}/ntp_time") return json.loads(response.content) + def resync_ntp(self) -> None: + """ + Request a new NTP synchronization on the instrumented wheel. + + NTP is stopped after the next synchronization. Use get_ntp_time() + to check when last_sync is updated. + + Returns + ------- + None + + """ + requests.get(f"http://{self.ip}:{self.port}/ntp_resync") + def start_recording(self) -> None: """ Start recording data on the instrumented wheel. @@ -918,7 +1053,7 @@ def start_recording(self) -> None: None """ - requests.get(f"http://{self.ip}/start_recording") + requests.get(f"http://{self.ip}:{self.port}/start_recording") def stop_recording(self) -> None: """ @@ -929,7 +1064,7 @@ def stop_recording(self) -> None: None """ - requests.get(f"http://{self.ip}/stop_recording") + requests.get(f"http://{self.ip}:{self.port}/stop_recording") def file_list(self) -> dict: """ @@ -940,7 +1075,7 @@ def file_list(self) -> dict: dict """ - response = requests.get(f"http://{self.ip}/file_list") + response = requests.get(f"http://{self.ip}:{self.port}/file_list") return json.loads(response.content) def file_download(self, filename: str, save_path: str = ".") -> int: @@ -963,7 +1098,9 @@ def file_download(self, filename: str, save_path: str = ".") -> int: """ param = {"file": filename} response = requests.get( - f"http://{self.ip}/file_download", params=param, stream=True + f"http://{self.ip}:{self.port}/file_download", + params=param, + stream=True, ) if response.status_code == HTTP_RESPONSE_CODE_OK: with open(os.path.join(save_path, filename), "wb") as f: @@ -989,7 +1126,8 @@ def file_delete(self, filename: str) -> None: """ requests.get( - f"http://{self.ip}/file_delete", params={"file": filename} + f"http://{self.ip}:{self.port}/file_delete", + params={"file": filename}, ) diff --git a/software/python/requirements.txt b/software/python/requirements.txt index 5bba0db..74599f5 100644 --- a/software/python/requirements.txt +++ b/software/python/requirements.txt @@ -1,4 +1,3 @@ -websocket-client matplotlib requests -numpy \ No newline at end of file +numpy diff --git a/software/python/run_monitor.py b/software/python/run_monitor.py index e921c41..2f75d83 100755 --- a/software/python/run_monitor.py +++ b/software/python/run_monitor.py @@ -1,13 +1,35 @@ #!/usr/bin/env python3 """Connect to a wheel and run the monitor from command line.""" -import sys +import argparse import nextwheel if __name__ == "__main__": - ip = sys.argv[-1] - nw = nextwheel.NextWheel(ip) - nw.start_streaming() - nw.monitor() - nw.stop_streaming() + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--ip", required=True, help="IP address of the wheel") + parser.add_argument( + "--port", + type=int, + default=80, + help="HTTP (REST API) port of the wheel (default: 80)", + ) + parser.add_argument( + "--udp_address", + default="255.255.255.255", + help="IP address where the wheel sends streamed data, e.g. " + "255.255.255.255 or this computer's IP (default: 255.255.255.255)", + ) + parser.add_argument( + "--udp_port", + type=int, + default=nextwheel.DEFAULT_UDP_PORT, + help="UDP port where the wheel sends streamed data " + f"(default: {nextwheel.DEFAULT_UDP_PORT})", + ) + args = parser.parse_args() + + nw = nextwheel.NextWheel(args.ip, port=args.port) + + # monitor() starts and stops streaming + nw.monitor(args.udp_address, args.udp_port) diff --git a/software/python/setup.py b/software/python/setup.py index 3eda358..ef2e540 100644 --- a/software/python/setup.py +++ b/software/python/setup.py @@ -5,7 +5,7 @@ with open("README.md") as fh: long_description = fh.read() -version = "0.1.8" +version = "0.2.0" setuptools.setup( name="nextwheel", @@ -13,7 +13,7 @@ description="Python module for NextWheel instrumented wheels", long_description=long_description, long_description_content_type="text/markdown", - url="https://github.com/felixchenier/NextWheel", + url="https://github.com/LabMOSA/NextWheel", author="NextWheel collaborators", author_email="chenier.felix@uqam.ca", license="Apache", @@ -23,11 +23,11 @@ "nextwheel": [], }, project_urls={ - "Documentation": "https://github.com/felixchenier/NextWheel/tree/master/python", - "Source": "https://github.com/felixchenier/NextWheel", - "Tracker": "https://github.com/felixchenier/NextWheel/issues", + "Documentation": "https://github.com/LabMOSA/NextWheel/tree/master/python", + "Source": "https://github.com/LabMOSA/NextWheel", + "Tracker": "https://github.com/LabMOSA/NextWheel/issues", }, - install_requires=["numpy", "websocket-client", "matplotlib", "requests"], + install_requires=["numpy", "matplotlib", "requests"], classifiers=[ "Development Status :: 2 - Pre-Alpha", "Intended Audience :: Science/Research",