From d5dbf5d2eff10ae0181c83432104ebcffb1f0759 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominic=20Le=CC=81tourneau?= Date: Fri, 16 Oct 2026 16:45:48 -0400 Subject: [PATCH 01/14] UDPStreamer First Implementation. Removed Websocket. To be verified. Python API needs to be updated. --- .../arduino_esp32/.vscode/extensions.json | 3 +- .../lib/NextWheel/src/config/GlobalConfig.cpp | 35 +++++ .../lib/NextWheel/src/config/GlobalConfig.h | 10 ++ .../lib/NextWheel/src/data/ConfigDataFrame.h | 5 +- .../firmware/arduino_esp32/platformio.ini | 7 +- .../arduino_esp32/src/NextWheelApp.cpp | 2 +- .../arduino_esp32/src/tasks/UDPStreamer.cpp | 82 +++++++++++ .../arduino_esp32/src/tasks/UDPStreamer.h | 33 +++++ .../src/tasks/WebSocketServerTask.cpp | 134 +++++++++++++++++- .../src/tasks/WebSocketServerTask.h | 14 +- 10 files changed, 317 insertions(+), 8 deletions(-) create mode 100644 software/firmware/arduino_esp32/src/tasks/UDPStreamer.cpp create mode 100644 software/firmware/arduino_esp32/src/tasks/UDPStreamer.h 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/config/GlobalConfig.cpp b/software/firmware/arduino_esp32/lib/NextWheel/src/config/GlobalConfig.cpp index 5b64dac..6f79004 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,28 @@ 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; + 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; + 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 +168,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(); } @@ -187,5 +216,11 @@ bool GlobalConfig::validate() return false; } + // Config saved by older firmware does not contain UDP settings + if (m_config.udp_broadcast_port == 0 || m_config.udp_broadcast_port == 0xFFFF) + { + return false; + } + return true; } 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..dfc370c 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/platformio.ini b/software/firmware/arduino_esp32/platformio.ini index e0251f5..fbd5ffb 100644 --- a/software/firmware/arduino_esp32/platformio.ini +++ b/software/firmware/arduino_esp32/platformio.ini @@ -33,7 +33,7 @@ lib_deps = Wire sv-zanshin/MCP7940@1.2.0 #esphome/ESPAsyncWebServer-esphome@^3.1.0 # https://github.com/yubox-node-org/ESPAsyncWebServer - links2004/WebSockets@^2.4.1 + # links2004/WebSockets@^2.4.1 ESP32Encoder@0.10.2 ; Serial Monitor @@ -45,13 +45,14 @@ monitor_filters = esp32_exception_decoder, colorize, time upload_speed = 921600 ; Add -DNEXTWHEEL_DISABLE_WIFI=1 to build_flags to disable wifi +; Add -D_WEBSOCKET_SERVER_ENABLED=1 to build_flags to enable the WebSocket server ; None -;build_flags = -DCORE_DEBUG_LEVEL=0 -DNEXTWHEEL_DISABLE_WIFI=1 +;build_flags = -DCORE_DEBUG_LEVEL=0 -DNEXTWHEEL_DISABLE_WIFI=1 -D_WEBSOCKET_SERVER_ENABLED=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..1302b0b 100644 --- a/software/firmware/arduino_esp32/src/NextWheelApp.cpp +++ b/software/firmware/arduino_esp32/src/NextWheelApp.cpp @@ -67,7 +67,7 @@ bool NextWheelApp::isRecording() bool NextWheelApp::isStreaming() { - return m_webSocketServerTask.isWebSocketConnected(); + return m_webSocketServerTask.isWebSocketConnected() || m_webSocketServerTask.isUDPStreaming(); } LEDS& NextWheelApp::getLEDS() 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..3abf84e --- /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..3db719e --- /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 (same format as the WebSocket stream) 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/WebSocketServerTask.cpp index a36b577..8ee0995 100644 --- a/software/firmware/arduino_esp32/src/tasks/WebSocketServerTask.cpp +++ b/software/firmware/arduino_esp32/src/tasks/WebSocketServerTask.cpp @@ -11,7 +11,9 @@ WebSocketServerTask::WebSocketServerTask() : WorkerTask("WebSocketServerTask", WEBSOCKET_SERVER_STACK_SIZE), +#ifdef _WEBSOCKET_SERVER_ENABLED m_webSocketServer(81), +#endif m_webServer(80) { } @@ -33,9 +35,11 @@ void WebSocketServerTask::run(void* app) TickType_t lastGeneration = xTaskGetTickCount(); +#ifdef _WEBSOCKET_SERVER_ENABLED 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); }); +#endif setupRESTAPI(); m_webServer.begin(); @@ -43,7 +47,9 @@ void WebSocketServerTask::run(void* app) while (1) { // Serial.println("WebSocketServerTask::run: m_webSocketServer.loop()"); +#ifdef _WEBSOCKET_SERVER_ENABLED m_webSocketServer.loop(); +#endif m_webServer.handleClient(); // First empty the command queue (timeout=0, not waiting) @@ -61,12 +67,18 @@ void WebSocketServerTask::run(void* app) // We should update the configuration info from now ConfigDataFrame configDataFrame(GlobalConfig::instance().get()); + + // Send to UDP destination (does nothing if not streaming) + m_udpStreamer.sendFrame(configDataFrame); + +#ifdef _WEBSOCKET_SERVER_ENABLED 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()); } +#endif // Empty the queue (with old config!) while (DataFramePtr dataPtr = dequeue(0)) @@ -122,20 +134,78 @@ void WebSocketServerTask::run(void* app) delete dataPtr; } + // Send to UDP destination (does nothing if not streaming) + m_udpStreamer.send(super_frame, total_payload_size + DataFrame::HEADER_SIZE); + +#ifdef _WEBSOCKET_SERVER_ENABLED // 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); } +#endif } } // while(1) } bool WebSocketServerTask::isWebSocketConnected() { +#ifdef _WEBSOCKET_SERVER_ENABLED return m_webSocketServer.connectedClients() > 0; +#else + return false; +#endif +} + +bool WebSocketServerTask::isUDPStreaming() +{ + return m_udpStreamer.isStreaming(); +} + +bool WebSocketServerTask::startUDPStreaming() +{ + if (m_udpStreamer.isStreaming()) + { + return false; + } + + 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()->registerSensorTasksToWebSocketServer(); + return true; +} + +bool WebSocketServerTask::stopUDPStreaming() +{ + if (!m_udpStreamer.isStreaming()) + { + return false; + } + + NextWheelApp::instance()->unregisterSensorTasksFromWebSocketServer(); + 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; } +#ifdef _WEBSOCKET_SERVER_ENABLED void WebSocketServerTask::webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length) { switch (type) @@ -176,6 +246,7 @@ void WebSocketServerTask::webSocketEvent(uint8_t num, WStype_t type, uint8_t* pa break; } } +#endif void WebSocketServerTask::setupRESTAPI() { @@ -247,11 +318,32 @@ void WebSocketServerTask::setupRESTAPI() m_webServer.hasArg("imu_sampling_rate") && m_webServer.hasArg("adc_sampling_rate") && m_webServer.hasArg("encoder_sampling_rate")) { + // UDP settings are optional, validate them before changing anything + IPAddress udp_address(GlobalConfig::instance().get_udp_broadcast_address()); + if (m_webServer.hasArg("udp_broadcast_address") && + !udp_address.fromString(m_webServer.arg("udp_broadcast_address"))) + { + m_webServer.send(400, "text/plain", "Invalid udp_broadcast_address (expected x.x.x.x)"); + return; + } + long udp_port = GlobalConfig::instance().get_udp_broadcast_port(); + if (m_webServer.hasArg("udp_broadcast_port")) + { + udp_port = m_webServer.arg("udp_broadcast_port").toInt(); + if (udp_port <= 0 || udp_port >= 0xFFFF) + { + m_webServer.send(400, "text/plain", "Invalid udp_broadcast_port"); + return; + } + } + GlobalConfig::instance().set_accel_range(m_webServer.arg("accelerometer_precision").toInt()); GlobalConfig::instance().set_gyro_range(m_webServer.arg("gyrometer_precision").toInt()); GlobalConfig::instance().set_imu_sample_rate(m_webServer.arg("imu_sampling_rate").toInt()); 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()); + GlobalConfig::instance().set_udp_broadcast_address(uint32_t(udp_address)); + GlobalConfig::instance().set_udp_broadcast_port(udp_port); // Print current config Serial.println("Current config:"); @@ -260,6 +352,9 @@ void WebSocketServerTask::setupRESTAPI() Serial.printf("IMU sampling rate: %d\n", GlobalConfig::instance().get_imu_sample_rate()); Serial.printf("ADC sampling rate: %d\n", GlobalConfig::instance().get_adc_sample_rate()); Serial.printf("Encoder sampling rate: %d\n", GlobalConfig::instance().get_encoder_sample_rate()); + Serial.printf("UDP broadcast address: %s\n", + IPAddress(GlobalConfig::instance().get_udp_broadcast_address()).toString().c_str()); + Serial.printf("UDP broadcast port: %d\n", GlobalConfig::instance().get_udp_broadcast_port()); m_webServer.send(200, "text/plain", "OK"); } @@ -269,7 +364,7 @@ void WebSocketServerTask::setupRESTAPI() 400, "text/plain", "Missing arguments (accelerometer_precision, gyrometer_precision, imu_sampling_rate, " - "adc_sampling_rate, encoder_sampling_rate)"); + "adc_sampling_rate, encoder_sampling_rate), optional (udp_broadcast_address, udp_broadcast_port)"); } }); @@ -287,6 +382,10 @@ 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 +454,39 @@ void WebSocketServerTask::setupRESTAPI() }); + m_webServer.on( + "/start_streaming", + HTTP_GET, + [this]() + { + Serial.println("get: /start_streaming"); + if (startUDPStreaming()) + { + 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/WebSocketServerTask.h b/software/firmware/arduino_esp32/src/tasks/WebSocketServerTask.h index 6a296ed..5e10679 100644 --- a/software/firmware/arduino_esp32/src/tasks/WebSocketServerTask.h +++ b/software/firmware/arduino_esp32/src/tasks/WebSocketServerTask.h @@ -8,8 +8,11 @@ #include #include #include +#if defined(_WEBSOCKET_SERVER_ENABLED) #include +#endif #include +#include "tasks/UDPStreamer.h" class WebSocketServerTask : public WorkerTask @@ -20,14 +23,23 @@ class WebSocketServerTask : public WorkerTask WebSocketServerTask(); virtual void run(void* app) override; bool isWebSocketConnected(); + bool isUDPStreaming(); protected: - void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length); + void setupRESTAPI(); + bool startUDPStreaming(); + bool stopUDPStreaming(); + + #ifdef _WEBSOCKET_SERVER_ENABLED + void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length); WebSocketsServer m_webSocketServer; + #endif + WebServer m_webServer; + UDPStreamer m_udpStreamer; }; #endif // _WEBSOCKET_SERVER_TASK_H_ From 19c6f482c06385711db013c48b7c7c5e0360973c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominic=20Le=CC=81tourneau?= Date: Mon, 19 Oct 2026 09:13:54 -0400 Subject: [PATCH 02/14] Updated with new firmware to send UDP messages. --- .../lib/NextWheel/src/NextWheel.h | 2 +- .../src/tasks/PowerSensorTask.cpp | 2 +- .../arduino_esp32/src/tasks/PowerSensorTask.h | 3 + software/python/.vscode/settings.json | 4 + software/python/README.md | 9 + software/python/nextwheel/__init__.py | 275 +++++++++++++----- software/python/requirements.txt | 1 - software/python/run_monitor.py | 40 ++- software/python/setup.py | 2 +- 9 files changed, 263 insertions(+), 75 deletions(-) create mode 100644 software/python/.vscode/settings.json diff --git a/software/firmware/arduino_esp32/lib/NextWheel/src/NextWheel.h b/software/firmware/arduino_esp32/lib/NextWheel/src/NextWheel.h index 1b64144..e015ce0 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.1.1" #define NEXT_WHEEL_DEBUG_LEVEL 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/python/.vscode/settings.json b/software/python/.vscode/settings.json new file mode 100644 index 0000000..4b5a294 --- /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" +} \ No newline at end of file diff --git a/software/python/README.md b/software/python/README.md index 4f6df8f..86546f3 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.set_udp_destination("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..05f1b6b 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 stored in its + configuration (by default, broadcast 255.255.255.255 on port 12345). Use + NextWheel.set_udp_destination() to change them, for instance to use a + different port for each wheel. 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,39 +467,69 @@ 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 + + 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( self, @@ -520,36 +565,78 @@ 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) + port = int(params.get("udp_broadcast_port", DEFAULT_UDP_PORT)) + + 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", + params.get("udp_broadcast_address"), + ) + + # Ask the wheel to start streaming. Error 400 means that the wheel is + # already streaming, which is fine. + response = requests.get( + f"http://{self.ip}:{self.port}/start_streaming" + ) + if response.status_code not in ( + HTTP_RESPONSE_CODE_OK, + HTTP_RESPONSE_CODE_BAD_REQUEST, + ): + 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 + if not self._thread_is_running: + return + 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 + 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) -> None: """ @@ -836,16 +923,20 @@ 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, encoder_sampling_rate: int, accelerometer_precision: int, gyrometer_precision: int, + *, + udp_broadcast_address: str | None = None, + udp_broadcast_port: int | None = None, ) -> requests.Response: """ Set the parameters of the instrumented wheel. @@ -865,24 +956,73 @@ def set_sensors_params( gyrometer_precision Gyrometer range, in degrees per second. Valid values are 250, 500, 1000, 2000. + udp_broadcast_address + Optional. IP address (x.x.x.x) where the wheel sends the streamed + data. Use 255.255.255.255 to broadcast, or the IP address of this + computer. Unchanged if not provided. + udp_broadcast_port + Optional. UDP port where the wheel sends the streamed data. + Unchanged if not provided. Returns ------- requests.Response """ + params: dict[str, int | str] = { + "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, + } + if udp_broadcast_address is not None: + params["udp_broadcast_address"] = udp_broadcast_address + if udp_broadcast_port is not None: + params["udp_broadcast_port"] = udp_broadcast_port + 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 + def set_udp_destination( + self, address: str = "255.255.255.255", port: int = DEFAULT_UDP_PORT + ) -> requests.Response: + """ + Set where the instrumented wheel sends the streamed data. + + The sensor parameters are kept unchanged. If the wheel is currently + streaming, call stop_streaming() and start_streaming() again to + receive on the new port. + + Parameters + ---------- + address + 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 + UDP port where the wheel sends the streamed data. The default is + 12345. When using several wheels, using a different port for each + wheel reduces network load on each receiver. + + Returns + ------- + requests.Response + + """ + params = self.get_sensors_params() + return self.set_sensors_params( + adc_sampling_rate=params["adc_sampling_rate"], + imu_sampling_rate=params["imu_sampling_rate"], + encoder_sampling_rate=params["encoder_sampling_rate"], + accelerometer_precision=params["accelerometer_precision"], + gyrometer_precision=params["gyrometer_precision"], + udp_broadcast_address=address, + udp_broadcast_port=port, + ) + def get_sensors_params(self) -> dict: """ Get the parameters of the instrumented wheel sensors. @@ -893,7 +1033,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,7 +1046,7 @@ 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 start_recording(self) -> None: @@ -918,7 +1058,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 +1069,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 +1080,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 +1103,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 +1131,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..36c11f1 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 diff --git a/software/python/run_monitor.py b/software/python/run_monitor.py index e921c41..c8fbbe1 100755 --- a/software/python/run_monitor.py +++ b/software/python/run_monitor.py @@ -1,13 +1,43 @@ #!/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() + 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( + "--broadcast_ip", + required=False, + 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: unchanged)", + ) + parser.add_argument( + "--broadcast_port", + type=int, + help="UDP port where the wheel sends streamed data " + "(default: unchanged)", + default=12345, + ) + args = parser.parse_args() + + nw = nextwheel.NextWheel(args.ip, port=args.port) + + if args.broadcast_ip is not None or args.broadcast_port is not None: + params = nw.get_sensors_params() + nw.set_udp_destination( + args.broadcast_ip or params["udp_broadcast_address"], + args.broadcast_port or params["udp_broadcast_port"], + ) + + # monitor() starts and stops streaming nw.monitor() - nw.stop_streaming() diff --git a/software/python/setup.py b/software/python/setup.py index 3eda358..6581a0c 100644 --- a/software/python/setup.py +++ b/software/python/setup.py @@ -27,7 +27,7 @@ "Source": "https://github.com/felixchenier/NextWheel", "Tracker": "https://github.com/felixchenier/NextWheel/issues", }, - install_requires=["numpy", "websocket-client", "matplotlib", "requests"], + install_requires=["numpy", "matplotlib", "requests"], classifiers=[ "Development Status :: 2 - Pre-Alpha", "Intended Audience :: Science/Research", From 0d682bfc98948a58c95a1d82ec2b5a40da5caf2c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominic=20Le=CC=81tourneau?= Date: Mon, 19 Oct 2026 13:27:10 -0400 Subject: [PATCH 03/14] Updating API to send IP/Port on streaming only. --- .../lib/NextWheel/src/config/GlobalConfig.cpp | 12 +- .../src/tasks/WebSocketServerTask.cpp | 54 ++++----- .../src/tasks/WebSocketServerTask.h | 2 +- software/python/README.md | 2 +- software/python/nextwheel/__init__.py | 103 ++++++------------ software/python/run_monitor.py | 20 +--- 6 files changed, 73 insertions(+), 120 deletions(-) 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 6f79004..2f93cc4 100644 --- a/software/firmware/arduino_esp32/lib/NextWheel/src/config/GlobalConfig.cpp +++ b/software/firmware/arduino_esp32/lib/NextWheel/src/config/GlobalConfig.cpp @@ -140,7 +140,8 @@ uint32_t GlobalConfig::get_encoder_sample_rate() const void GlobalConfig::set_udp_broadcast_address(uint32_t address) { m_config.udp_broadcast_address = address; - save(); + //Not saved, configured at runtime, not persisted to EEPROM + //save(); } uint32_t GlobalConfig::get_udp_broadcast_address() const @@ -151,7 +152,8 @@ uint32_t GlobalConfig::get_udp_broadcast_address() const void GlobalConfig::set_udp_broadcast_port(uint16_t port) { m_config.udp_broadcast_port = port; - save(); + //Not saved, configured at runtime, not persisted to EEPROM + //save(); } uint16_t GlobalConfig::get_udp_broadcast_port() const @@ -216,11 +218,5 @@ bool GlobalConfig::validate() return false; } - // Config saved by older firmware does not contain UDP settings - if (m_config.udp_broadcast_port == 0 || m_config.udp_broadcast_port == 0xFFFF) - { - return false; - } - return true; } diff --git a/software/firmware/arduino_esp32/src/tasks/WebSocketServerTask.cpp b/software/firmware/arduino_esp32/src/tasks/WebSocketServerTask.cpp index 8ee0995..3ab6944 100644 --- a/software/firmware/arduino_esp32/src/tasks/WebSocketServerTask.cpp +++ b/software/firmware/arduino_esp32/src/tasks/WebSocketServerTask.cpp @@ -162,13 +162,17 @@ bool WebSocketServerTask::isUDPStreaming() return m_udpStreamer.isStreaming(); } -bool WebSocketServerTask::startUDPStreaming() +bool WebSocketServerTask::startUDPStreaming(uint32_t address, uint16_t port) { if (m_udpStreamer.isStreaming()) { return false; } + // 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; @@ -318,32 +322,11 @@ void WebSocketServerTask::setupRESTAPI() m_webServer.hasArg("imu_sampling_rate") && m_webServer.hasArg("adc_sampling_rate") && m_webServer.hasArg("encoder_sampling_rate")) { - // UDP settings are optional, validate them before changing anything - IPAddress udp_address(GlobalConfig::instance().get_udp_broadcast_address()); - if (m_webServer.hasArg("udp_broadcast_address") && - !udp_address.fromString(m_webServer.arg("udp_broadcast_address"))) - { - m_webServer.send(400, "text/plain", "Invalid udp_broadcast_address (expected x.x.x.x)"); - return; - } - long udp_port = GlobalConfig::instance().get_udp_broadcast_port(); - if (m_webServer.hasArg("udp_broadcast_port")) - { - udp_port = m_webServer.arg("udp_broadcast_port").toInt(); - if (udp_port <= 0 || udp_port >= 0xFFFF) - { - m_webServer.send(400, "text/plain", "Invalid udp_broadcast_port"); - return; - } - } - GlobalConfig::instance().set_accel_range(m_webServer.arg("accelerometer_precision").toInt()); GlobalConfig::instance().set_gyro_range(m_webServer.arg("gyrometer_precision").toInt()); GlobalConfig::instance().set_imu_sample_rate(m_webServer.arg("imu_sampling_rate").toInt()); 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()); - GlobalConfig::instance().set_udp_broadcast_address(uint32_t(udp_address)); - GlobalConfig::instance().set_udp_broadcast_port(udp_port); // Print current config Serial.println("Current config:"); @@ -352,9 +335,6 @@ void WebSocketServerTask::setupRESTAPI() Serial.printf("IMU sampling rate: %d\n", GlobalConfig::instance().get_imu_sample_rate()); Serial.printf("ADC sampling rate: %d\n", GlobalConfig::instance().get_adc_sample_rate()); Serial.printf("Encoder sampling rate: %d\n", GlobalConfig::instance().get_encoder_sample_rate()); - Serial.printf("UDP broadcast address: %s\n", - IPAddress(GlobalConfig::instance().get_udp_broadcast_address()).toString().c_str()); - Serial.printf("UDP broadcast port: %d\n", GlobalConfig::instance().get_udp_broadcast_port()); m_webServer.send(200, "text/plain", "OK"); } @@ -364,7 +344,7 @@ void WebSocketServerTask::setupRESTAPI() 400, "text/plain", "Missing arguments (accelerometer_precision, gyrometer_precision, imu_sampling_rate, " - "adc_sampling_rate, encoder_sampling_rate), optional (udp_broadcast_address, udp_broadcast_port)"); + "adc_sampling_rate, encoder_sampling_rate)"); } }); @@ -382,10 +362,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 @@ -460,7 +442,25 @@ void WebSocketServerTask::setupRESTAPI() [this]() { Serial.println("get: /start_streaming"); - if (startUDPStreaming()) + 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"); } diff --git a/software/firmware/arduino_esp32/src/tasks/WebSocketServerTask.h b/software/firmware/arduino_esp32/src/tasks/WebSocketServerTask.h index 5e10679..ea8a5e0 100644 --- a/software/firmware/arduino_esp32/src/tasks/WebSocketServerTask.h +++ b/software/firmware/arduino_esp32/src/tasks/WebSocketServerTask.h @@ -29,7 +29,7 @@ class WebSocketServerTask : public WorkerTask protected: void setupRESTAPI(); - bool startUDPStreaming(); + bool startUDPStreaming(uint32_t address, uint16_t port); bool stopUDPStreaming(); #ifdef _WEBSOCKET_SERVER_ENABLED diff --git a/software/python/README.md b/software/python/README.md index 86546f3..a5f0b86 100644 --- a/software/python/README.md +++ b/software/python/README.md @@ -31,7 +31,7 @@ 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.set_udp_destination("255.255.255.255", 12346) +>>> nw.start_streaming("255.255.255.255", 12346) ``` To see the list of recorded data files: diff --git a/software/python/nextwheel/__init__.py b/software/python/nextwheel/__init__.py index 05f1b6b..1e5eeb5 100644 --- a/software/python/nextwheel/__init__.py +++ b/software/python/nextwheel/__init__.py @@ -241,11 +241,11 @@ class NextWheel: - 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 stored in its - configuration (by default, broadcast 255.255.255.255 on port 12345). Use - NextWheel.set_udp_destination() to change them, for instance to use a - different port for each wheel. The local firewall must accept incoming - UDP datagrams on this port. + 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 ------ @@ -531,8 +531,10 @@ def _update_config_from_params(self, params: dict) -> None: "encoder_sampling_rate" ] - def start_streaming( + 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, @@ -543,6 +545,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 @@ -570,7 +579,6 @@ def start_streaming( # API so that the data can be converted in any case. params = self.get_sensors_params() self._update_config_from_params(params) - port = int(params.get("udp_broadcast_port", DEFAULT_UDP_PORT)) udp_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) udp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) @@ -596,17 +604,23 @@ def start_streaming( "Listening on UDP port", port, "for data sent to", - params.get("udp_broadcast_address"), + address, ) - # Ask the wheel to start streaming. Error 400 means that the wheel is - # already streaming, which is fine. + # 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" + f"http://{self.ip}:{self.port}/start_streaming", + params={"address": address, "port": port}, + ) + already_streaming = ( + response.status_code == HTTP_RESPONSE_CODE_BAD_REQUEST + and "Already streaming" in response.text ) - if response.status_code not in ( - HTTP_RESPONSE_CODE_OK, - HTTP_RESPONSE_CODE_BAD_REQUEST, + if ( + response.status_code != HTTP_RESPONSE_CODE_OK + and not already_streaming ): self.stop_streaming() raise RuntimeError( @@ -638,18 +652,20 @@ def stop_streaming(self): self._udp_socket = None self._thread_is_running = False - def monitor(self) -> None: + 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() @@ -934,9 +950,6 @@ def set_sensors_params( # noqa: PLR0913 encoder_sampling_rate: int, accelerometer_precision: int, gyrometer_precision: int, - *, - udp_broadcast_address: str | None = None, - udp_broadcast_port: int | None = None, ) -> requests.Response: """ Set the parameters of the instrumented wheel. @@ -956,73 +969,25 @@ def set_sensors_params( # noqa: PLR0913 gyrometer_precision Gyrometer range, in degrees per second. Valid values are 250, 500, 1000, 2000. - udp_broadcast_address - Optional. IP address (x.x.x.x) where the wheel sends the streamed - data. Use 255.255.255.255 to broadcast, or the IP address of this - computer. Unchanged if not provided. - udp_broadcast_port - Optional. UDP port where the wheel sends the streamed data. - Unchanged if not provided. Returns ------- requests.Response """ - params: dict[str, int | str] = { + 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, } - if udp_broadcast_address is not None: - params["udp_broadcast_address"] = udp_broadcast_address - if udp_broadcast_port is not None: - params["udp_broadcast_port"] = udp_broadcast_port response = requests.post( f"http://{self.ip}:{self.port}/config_update", params=params ) return response - def set_udp_destination( - self, address: str = "255.255.255.255", port: int = DEFAULT_UDP_PORT - ) -> requests.Response: - """ - Set where the instrumented wheel sends the streamed data. - - The sensor parameters are kept unchanged. If the wheel is currently - streaming, call stop_streaming() and start_streaming() again to - receive on the new port. - - Parameters - ---------- - address - 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 - UDP port where the wheel sends the streamed data. The default is - 12345. When using several wheels, using a different port for each - wheel reduces network load on each receiver. - - Returns - ------- - requests.Response - - """ - params = self.get_sensors_params() - return self.set_sensors_params( - adc_sampling_rate=params["adc_sampling_rate"], - imu_sampling_rate=params["imu_sampling_rate"], - encoder_sampling_rate=params["encoder_sampling_rate"], - accelerometer_precision=params["accelerometer_precision"], - gyrometer_precision=params["gyrometer_precision"], - udp_broadcast_address=address, - udp_broadcast_port=port, - ) - def get_sensors_params(self) -> dict: """ Get the parameters of the instrumented wheel sensors. diff --git a/software/python/run_monitor.py b/software/python/run_monitor.py index c8fbbe1..2f75d83 100755 --- a/software/python/run_monitor.py +++ b/software/python/run_monitor.py @@ -15,29 +15,21 @@ help="HTTP (REST API) port of the wheel (default: 80)", ) parser.add_argument( - "--broadcast_ip", - required=False, + "--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: unchanged)", + "255.255.255.255 or this computer's IP (default: 255.255.255.255)", ) parser.add_argument( - "--broadcast_port", + "--udp_port", type=int, + default=nextwheel.DEFAULT_UDP_PORT, help="UDP port where the wheel sends streamed data " - "(default: unchanged)", - default=12345, + f"(default: {nextwheel.DEFAULT_UDP_PORT})", ) args = parser.parse_args() nw = nextwheel.NextWheel(args.ip, port=args.port) - if args.broadcast_ip is not None or args.broadcast_port is not None: - params = nw.get_sensors_params() - nw.set_udp_destination( - args.broadcast_ip or params["udp_broadcast_address"], - args.broadcast_port or params["udp_broadcast_port"], - ) - # monitor() starts and stops streaming - nw.monitor() + nw.monitor(args.udp_address, args.udp_port) From e3bf1d0084d7da7227bcb7055d62d82316fda423 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominic=20Le=CC=81tourneau?= Date: Tue, 20 Oct 2026 16:21:01 -0400 Subject: [PATCH 04/14] Refs #58. Remove old WebSocket code and rename task to WebServerTask. --- .../src/tasks/{WebSocketServerTask.cpp => WebServerTask.cpp} | 0 .../src/tasks/{WebSocketServerTask.h => WebServerTask.h} | 0 2 files changed, 0 insertions(+), 0 deletions(-) rename software/firmware/arduino_esp32/src/tasks/{WebSocketServerTask.cpp => WebServerTask.cpp} (100%) rename software/firmware/arduino_esp32/src/tasks/{WebSocketServerTask.h => WebServerTask.h} (100%) diff --git a/software/firmware/arduino_esp32/src/tasks/WebSocketServerTask.cpp b/software/firmware/arduino_esp32/src/tasks/WebServerTask.cpp similarity index 100% rename from software/firmware/arduino_esp32/src/tasks/WebSocketServerTask.cpp rename to software/firmware/arduino_esp32/src/tasks/WebServerTask.cpp diff --git a/software/firmware/arduino_esp32/src/tasks/WebSocketServerTask.h b/software/firmware/arduino_esp32/src/tasks/WebServerTask.h similarity index 100% rename from software/firmware/arduino_esp32/src/tasks/WebSocketServerTask.h rename to software/firmware/arduino_esp32/src/tasks/WebServerTask.h From 16f113f2075aab9af74f1ca78a09134d107ddf7d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominic=20Le=CC=81tourneau?= Date: Tue, 20 Oct 2026 16:21:45 -0400 Subject: [PATCH 05/14] Refs #58. Remove WebSocket code and create WebServerTask. --- software/firmware/README.md | 2 +- .../firmware/arduino_esp32/platformio.ini | 8 +- .../arduino_esp32/src/NextWheelApp.cpp | 36 +++--- .../firmware/arduino_esp32/src/NextWheelApp.h | 10 +- .../arduino_esp32/src/tasks/WebServerTask.cpp | 115 +++--------------- .../arduino_esp32/src/tasks/WebServerTask.h | 23 +--- 6 files changed, 49 insertions(+), 145 deletions(-) diff --git a/software/firmware/README.md b/software/firmware/README.md index 8df84ba..7751df1 100644 --- a/software/firmware/README.md +++ b/software/firmware/README.md @@ -72,7 +72,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 2: To avoid sending small packets with high overhead ratio (data size small vs websocket overhead), the [WebServerTask](arduino_esp32/src/tasks/WebServerTask.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. ### ADC and IMU VALUE CONVERSION diff --git a/software/firmware/arduino_esp32/platformio.ini b/software/firmware/arduino_esp32/platformio.ini index fbd5ffb..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 @@ -45,12 +42,11 @@ monitor_filters = esp32_exception_decoder, colorize, time upload_speed = 921600 ; Add -DNEXTWHEEL_DISABLE_WIFI=1 to build_flags to disable wifi -; Add -D_WEBSOCKET_SERVER_ENABLED=1 to build_flags to enable the WebSocket server + ; None -;build_flags = -DCORE_DEBUG_LEVEL=0 -DNEXTWHEEL_DISABLE_WIFI=1 -D_WEBSOCKET_SERVER_ENABLED=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 diff --git a/software/firmware/arduino_esp32/src/NextWheelApp.cpp b/software/firmware/arduino_esp32/src/NextWheelApp.cpp index 1302b0b..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() || m_webSocketServerTask.isUDPStreaming(); + 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..0c256b3 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,8 @@ class NextWheelApp // Workers SDCardWorkerTask m_sdCardWorkerTask; - // WebSocketServerTask m_webSocketServerTask; - WebSocketServerTask m_webSocketServerTask; + // WebServerTask m_webServerTask; + WebServerTask m_webServerTask; SemaphoreHandle_t m_queueMutex; }; diff --git a/software/firmware/arduino_esp32/src/tasks/WebServerTask.cpp b/software/firmware/arduino_esp32/src/tasks/WebServerTask.cpp index 3ab6944..2f6d75b 100644 --- a/software/firmware/arduino_esp32/src/tasks/WebServerTask.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 @@ -9,19 +9,16 @@ #include -WebSocketServerTask::WebSocketServerTask() - : WorkerTask("WebSocketServerTask", WEBSOCKET_SERVER_STACK_SIZE), -#ifdef _WEBSOCKET_SERVER_ENABLED - m_webSocketServer(81), -#endif +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()); WiFi.begin(WIFI_DEFAULT_SSID, WIFI_DEFAULT_PASSWORD); // put your setup code here, to run once: @@ -35,21 +32,12 @@ void WebSocketServerTask::run(void* app) TickType_t lastGeneration = xTaskGetTickCount(); -#ifdef _WEBSOCKET_SERVER_ENABLED - 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); }); -#endif - setupRESTAPI(); m_webServer.begin(); while (1) { - // Serial.println("WebSocketServerTask::run: m_webSocketServer.loop()"); -#ifdef _WEBSOCKET_SERVER_ENABLED - m_webSocketServer.loop(); -#endif + // Serial.println("WebServerTask::run: m_webServer.loop()"); m_webServer.handleClient(); // First empty the command queue (timeout=0, not waiting) @@ -59,26 +47,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()); // Send to UDP destination (does nothing if not streaming) m_udpStreamer.sendFrame(configDataFrame); - -#ifdef _WEBSOCKET_SERVER_ENABLED - 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()); - } -#endif // Empty the queue (with old config!) while (DataFramePtr dataPtr = dequeue(0)) @@ -89,7 +68,7 @@ void WebSocketServerTask::run(void* app) break; default: - Serial.print("WebSocketServerTask::run: Unknown command: "); + Serial.print("WebServerTask::run: Unknown command: "); Serial.println(command); break; } @@ -136,33 +115,16 @@ void WebSocketServerTask::run(void* app) // Send to UDP destination (does nothing if not streaming) m_udpStreamer.send(super_frame, total_payload_size + DataFrame::HEADER_SIZE); - -#ifdef _WEBSOCKET_SERVER_ENABLED - // 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); - } -#endif } } // while(1) } -bool WebSocketServerTask::isWebSocketConnected() -{ -#ifdef _WEBSOCKET_SERVER_ENABLED - return m_webSocketServer.connectedClients() > 0; -#else - return false; -#endif -} - -bool WebSocketServerTask::isUDPStreaming() +bool WebServerTask::isUDPStreaming() { return m_udpStreamer.isStreaming(); } -bool WebSocketServerTask::startUDPStreaming(uint32_t address, uint16_t port) +bool WebServerTask::startUDPStreaming(uint32_t address, uint16_t port) { if (m_udpStreamer.isStreaming()) { @@ -189,18 +151,18 @@ bool WebSocketServerTask::startUDPStreaming(uint32_t address, uint16_t port) ConfigDataFrame configDataFrame(GlobalConfig::instance().get()); m_udpStreamer.sendFrame(configDataFrame); - NextWheelApp::instance()->registerSensorTasksToWebSocketServer(); + NextWheelApp::instance()->registerSensorTasksToWebServer(); return true; } -bool WebSocketServerTask::stopUDPStreaming() +bool WebServerTask::stopUDPStreaming() { if (!m_udpStreamer.isStreaming()) { return false; } - NextWheelApp::instance()->unregisterSensorTasksFromWebSocketServer(); + NextWheelApp::instance()->unregisterSensorTasksFromWebServer(); Serial.printf("UDP streaming stopped, dropped packets: %u\n", m_udpStreamer.getDroppedPackets()); m_udpStreamer.stop(); @@ -209,55 +171,12 @@ bool WebSocketServerTask::stopUDPStreaming() return true; } -#ifdef _WEBSOCKET_SERVER_ENABLED -void WebSocketServerTask::webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length) -{ - switch (type) - { - case WStype_DISCONNECTED: - Serial.printf("[%u] Disconnected!\n", num); - SystemState::instance().getState().streaming = false; - NextWheelApp::instance()->playStopStreamingSound(); - NextWheelApp::instance()->unregisterSensorTasksFromWebSocketServer(); - break; - case WStype_CONNECTED: - { - 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; - } -} -#endif - -void WebSocketServerTask::setupRESTAPI() +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(); @@ -279,7 +198,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); }); diff --git a/software/firmware/arduino_esp32/src/tasks/WebServerTask.h b/software/firmware/arduino_esp32/src/tasks/WebServerTask.h index ea8a5e0..02f60f4 100644 --- a/software/firmware/arduino_esp32/src/tasks/WebServerTask.h +++ b/software/firmware/arduino_esp32/src/tasks/WebServerTask.h @@ -1,5 +1,5 @@ -#ifndef _WEBSOCKET_SERVER_TASK_H_ -#define _WEBSOCKET_SERVER_TASK_H_ +#ifndef _WEB_SERVER_TASK_H_ +#define _WEB_SERVER_TASK_H_ #include "config/WiFiConfig.h" #include "tasks/WorkerTask.h" @@ -8,21 +8,17 @@ #include #include #include -#if defined(_WEBSOCKET_SERVER_ENABLED) -#include -#endif #include #include "tasks/UDPStreamer.h" -class WebSocketServerTask : public WorkerTask +class WebServerTask : public WorkerTask { - static const size_t WEBSOCKET_SERVER_STACK_SIZE = 12000; + static const size_t WEB_SERVER_STACK_SIZE = 12000; public: - WebSocketServerTask(); + WebServerTask(); virtual void run(void* app) override; - bool isWebSocketConnected(); bool isUDPStreaming(); @@ -31,15 +27,8 @@ class WebSocketServerTask : public WorkerTask void setupRESTAPI(); bool startUDPStreaming(uint32_t address, uint16_t port); bool stopUDPStreaming(); - - #ifdef _WEBSOCKET_SERVER_ENABLED - void webSocketEvent(uint8_t num, WStype_t type, uint8_t* payload, size_t length); - - WebSocketsServer m_webSocketServer; - #endif - WebServer m_webServer; UDPStreamer m_udpStreamer; }; -#endif // _WEBSOCKET_SERVER_TASK_H_ +#endif // _WEB_SERVER_TASK_H_ From 33c3c40d0e9d507dada3d97905e37c7b9914192e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominic=20Le=CC=81tourneau?= Date: Wed, 21 Oct 2026 09:12:30 -0400 Subject: [PATCH 06/14] Refs #38, #58. Aded NTP Time, Fixed documentation, code cleanup using .clang-format rules. Fixing config update. --- software/calibration/requirements.txt | 1 - software/firmware/README.md | 68 ++++++++--- software/firmware/arduino_esp32/.clang-format | 6 +- .../arduino_esp32/lib/NextWheel/src/RTC.cpp | 35 +++--- .../arduino_esp32/lib/NextWheel/src/RTC.h | 7 ++ .../lib/NextWheel/src/config/GlobalConfig.cpp | 18 +-- .../lib/NextWheel/src/config/GlobalConfig.h | 6 +- .../lib/NextWheel/src/drivers/DPEng_BMX160.h | 6 +- .../firmware/arduino_esp32/src/NextWheelApp.h | 1 - software/firmware/arduino_esp32/src/main.cpp | 2 +- .../src/tasks/DACActuatorTask.cpp | 2 +- .../src/tasks/QuadEncoderSensorTask.cpp | 9 +- .../arduino_esp32/src/tasks/UDPStreamer.cpp | 4 +- .../arduino_esp32/src/tasks/UDPStreamer.h | 2 +- .../arduino_esp32/src/tasks/WebServerTask.cpp | 114 ++++++++++++++++-- .../arduino_esp32/src/tasks/WebServerTask.h | 14 ++- software/python/nextwheel/__init__.py | 15 +++ 17 files changed, 243 insertions(+), 67 deletions(-) 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 7751df1..6377784 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 [WebServerTask](arduino_esp32/src/tasks/WebServerTask.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,45 @@ 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. +* Each time an IP address is obtained (connection, reconnection or IP change), SNTP is (re)started by the [WebServerTask](arduino_esp32/src/tasks/WebServerTask.cpp). +* Time is then resynchronized every 3 hours (Arduino-ESP32 default `CONFIG_LWIP_SNTP_UPDATE_DELAY`). The interval can be changed with `sntp_set_sync_interval()` (minimum 15 seconds). +* 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 at the next NTP synchronization. + +| **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 at the next NTP synchronization, 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. +/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/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 2f93cc4..cf00bb3 100644 --- a/software/firmware/arduino_esp32/lib/NextWheel/src/config/GlobalConfig.cpp +++ b/software/firmware/arduino_esp32/lib/NextWheel/src/config/GlobalConfig.cpp @@ -140,8 +140,8 @@ uint32_t GlobalConfig::get_encoder_sample_rate() const 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(); + // Not saved, configured at runtime, not persisted to EEPROM + // save(); } uint32_t GlobalConfig::get_udp_broadcast_address() const @@ -152,8 +152,8 @@ uint32_t GlobalConfig::get_udp_broadcast_address() const 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(); + // Not saved, configured at runtime, not persisted to EEPROM + // save(); } uint16_t GlobalConfig::get_udp_broadcast_port() const @@ -170,8 +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 + m_config.udp_broadcast_address = 0xFFFFFFFF; // Default to broadcast address + m_config.udp_broadcast_port = 12345; // Default port save(); } @@ -212,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 dfc370c..8a8385e 100644 --- a/software/firmware/arduino_esp32/lib/NextWheel/src/config/GlobalConfig.h +++ b/software/firmware/arduino_esp32/lib/NextWheel/src/config/GlobalConfig.h @@ -62,11 +62,11 @@ 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(); 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/src/NextWheelApp.h b/software/firmware/arduino_esp32/src/NextWheelApp.h index 0c256b3..7cf2c58 100644 --- a/software/firmware/arduino_esp32/src/NextWheelApp.h +++ b/software/firmware/arduino_esp32/src/NextWheelApp.h @@ -83,7 +83,6 @@ class NextWheelApp // Workers SDCardWorkerTask m_sdCardWorkerTask; - // WebServerTask m_webServerTask; 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/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 index 3abf84e..ce6e458 100644 --- a/software/firmware/arduino_esp32/src/tasks/UDPStreamer.cpp +++ b/software/firmware/arduino_esp32/src/tasks/UDPStreamer.cpp @@ -60,8 +60,8 @@ bool UDPStreamer::send(const uint8_t* data, size_t size) 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) + int sent = sendto(m_socket, data, size, MSG_DONTWAIT, (struct sockaddr*)&dest, sizeof(dest)); + if (sent != (int)size) { m_droppedPackets++; return false; diff --git a/software/firmware/arduino_esp32/src/tasks/UDPStreamer.h b/software/firmware/arduino_esp32/src/tasks/UDPStreamer.h index 3db719e..a9bb3eb 100644 --- a/software/firmware/arduino_esp32/src/tasks/UDPStreamer.h +++ b/software/firmware/arduino_esp32/src/tasks/UDPStreamer.h @@ -5,7 +5,7 @@ #include /** - * Sends binary frames (same format as the WebSocket stream) to the UDP + * 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. */ diff --git a/software/firmware/arduino_esp32/src/tasks/WebServerTask.cpp b/software/firmware/arduino_esp32/src/tasks/WebServerTask.cpp index 2f6d75b..959b84a 100644 --- a/software/firmware/arduino_esp32/src/tasks/WebServerTask.cpp +++ b/software/firmware/arduino_esp32/src/tasks/WebServerTask.cpp @@ -7,19 +7,23 @@ #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; -WebServerTask::WebServerTask() - : WorkerTask("WebServerTask", WEB_SERVER_STACK_SIZE), - m_webServer(80) -{ -} +WebServerTask::WebServerTask() : WorkerTask("WebServerTask", WEB_SERVER_STACK_SIZE), m_webServer(80) {} void WebServerTask::run(void* app) { Serial.printf("WebServerTask::run Priority: %li Core: %li \n", uxTaskPriorityGet(NULL), xPortGetCoreID()); + // NTP will be started each time an IP address is obtained + setupNTP(); + WiFi.begin(WIFI_DEFAULT_SSID, WIFI_DEFAULT_PASSWORD); // put your setup code here, to run once: while (WiFi.status() != WL_CONNECTED) @@ -40,6 +44,16 @@ void WebServerTask::run(void* app) // 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; + // 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)) @@ -74,7 +88,7 @@ void WebServerTask::run(void* app) } } - // 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; @@ -128,7 +142,8 @@ bool WebServerTask::startUDPStreaming(uint32_t address, uint16_t port) { if (m_udpStreamer.isStreaming()) { - return false; + //return false; + stopUDPStreaming(); } // Destination is stored in the config, UDPStreamer reads it when sending @@ -140,9 +155,10 @@ bool WebServerTask::startUDPStreaming(uint32_t address, uint16_t port) 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()); + 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(); @@ -171,6 +187,48 @@ bool WebServerTask::stopUDPStreaming() return true; } +void WebServerTask::setupNTP() +{ + WiFi.onEvent( + [this](arduino_event_id_t event, arduino_event_info_t info) + { + Serial.print("WebServerTask: Got IP: "); + Serial.println(IPAddress(info.got_ip.ip_info.ip.addr)); + 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::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( @@ -230,6 +288,39 @@ void WebServerTask::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( "/config_update", HTTP_POST, @@ -247,6 +338,9 @@ void WebServerTask::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()); diff --git a/software/firmware/arduino_esp32/src/tasks/WebServerTask.h b/software/firmware/arduino_esp32/src/tasks/WebServerTask.h index 02f60f4..76f984b 100644 --- a/software/firmware/arduino_esp32/src/tasks/WebServerTask.h +++ b/software/firmware/arduino_esp32/src/tasks/WebServerTask.h @@ -11,6 +11,9 @@ #include #include "tasks/UDPStreamer.h" +#ifndef NTP_DEFAULT_SERVER +#define NTP_DEFAULT_SERVER "pool.ntp.org" +#endif class WebServerTask : public WorkerTask { @@ -23,10 +26,19 @@ class WebServerTask : public WorkerTask protected: - void setupRESTAPI(); bool startUDPStreaming(uint32_t address, uint16_t port); bool stopUDPStreaming(); + void setupNTP(); + void startNTP(); + 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; }; diff --git a/software/python/nextwheel/__init__.py b/software/python/nextwheel/__init__.py index 1e5eeb5..04cdf9d 100644 --- a/software/python/nextwheel/__init__.py +++ b/software/python/nextwheel/__init__.py @@ -1014,6 +1014,21 @@ def get_system_state(self) -> dict: 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 start_recording(self) -> None: """ Start recording data on the instrumented wheel. From 908cb4b6aae6de68a0e4c38107c3a4f6d9c903c2 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominic=20Le=CC=81tourneau?= Date: Thu, 22 Oct 2026 08:36:29 -0400 Subject: [PATCH 07/14] NTP sync only at startup and on manual REST command. --- software/firmware/README.md | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/software/firmware/README.md b/software/firmware/README.md index 6377784..2092ae0 100644 --- a/software/firmware/README.md +++ b/software/firmware/README.md @@ -196,12 +196,12 @@ Values are already converted on device. Size optimization of the binary stream w 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. -* Each time an IP address is obtained (connection, reconnection or IP change), SNTP is (re)started by the [WebServerTask](arduino_esp32/src/tasks/WebServerTask.cpp). -* Time is then resynchronized every 3 hours (Arduino-ESP32 default `CONFIG_LWIP_SNTP_UPDATE_DELAY`). The interval can be changed with `sntp_set_sync_interval()` (minimum 15 seconds). +* 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 at the next NTP synchronization. +* `/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** | |------------|-------------|-----------------| @@ -221,8 +221,9 @@ All endpoints are served on HTTP port 80. Text responses are `text/plain`, JSON |**Url** | **HTTP Method** | **Param(s)** | **Return** | **Description** | |-----|-----------|----|-----------|---| / | 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 at the next NTP synchronization, see [Time Synchronization](#time-synchronization-ntp). +/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. From ffedfa6e034f470bf042d8afcd76afebdba410a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominic=20Le=CC=81tourneau?= Date: Thu, 22 Oct 2026 08:39:48 -0400 Subject: [PATCH 08/14] Added NTP synchronization management: starts when an IP address is obtained, stops after the first synchronization, and adds a REST API to force resynchronization. --- .../arduino_esp32/src/tasks/WebServerTask.cpp | 35 +++++++++++++++++-- .../arduino_esp32/src/tasks/WebServerTask.h | 1 + software/python/nextwheel/__init__.py | 14 ++++++++ 3 files changed, 48 insertions(+), 2 deletions(-) diff --git a/software/firmware/arduino_esp32/src/tasks/WebServerTask.cpp b/software/firmware/arduino_esp32/src/tasks/WebServerTask.cpp index 959b84a..2f8d7f5 100644 --- a/software/firmware/arduino_esp32/src/tasks/WebServerTask.cpp +++ b/software/firmware/arduino_esp32/src/tasks/WebServerTask.cpp @@ -21,7 +21,7 @@ void WebServerTask::run(void* app) { Serial.printf("WebServerTask::run Priority: %li Core: %li \n", uxTaskPriorityGet(NULL), xPortGetCoreID()); - // NTP will be started each time an IP address is obtained + // NTP will be started when an IP address is obtained, until the first sync setupNTP(); WiFi.begin(WIFI_DEFAULT_SSID, WIFI_DEFAULT_PASSWORD); @@ -48,6 +48,8 @@ void WebServerTask::run(void* app) 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); @@ -194,7 +196,11 @@ void WebServerTask::setupNTP() { Serial.print("WebServerTask: Got IP: "); Serial.println(IPAddress(info.got_ip.ip_info.ip.addr)); - startNTP(); + // Only sync once at startup, do not restart NTP on reconnect + if (!s_ntpSynced) + { + startNTP(); + } }, ARDUINO_EVENT_WIFI_STA_GOT_IP); } @@ -220,6 +226,15 @@ void WebServerTask::startNTP() 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 WebServerTask::onNTPTimeSync(struct timeval* tv) { s_ntpLastSyncTime = tv->tv_sec; @@ -321,6 +336,22 @@ void WebServerTask::setupRESTAPI() 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, diff --git a/software/firmware/arduino_esp32/src/tasks/WebServerTask.h b/software/firmware/arduino_esp32/src/tasks/WebServerTask.h index 76f984b..f5cc4ff 100644 --- a/software/firmware/arduino_esp32/src/tasks/WebServerTask.h +++ b/software/firmware/arduino_esp32/src/tasks/WebServerTask.h @@ -31,6 +31,7 @@ class WebServerTask : public WorkerTask 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 diff --git a/software/python/nextwheel/__init__.py b/software/python/nextwheel/__init__.py index 04cdf9d..af99d7f 100644 --- a/software/python/nextwheel/__init__.py +++ b/software/python/nextwheel/__init__.py @@ -1029,6 +1029,20 @@ def get_ntp_time(self) -> dict: 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. From 425084d8606194da9dd261019d066dda15216d99 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?F=C3=A9lix=20Ch=C3=A9nier?= <34967663+felixchenier@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:51:50 -0400 Subject: [PATCH 09/14] Update setup.py --- software/python/setup.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/software/python/setup.py b/software/python/setup.py index 6581a0c..75103ad 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", From cb00a16dcf5a58b8f21ad3e228629972770c69ca Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominic=20Le=CC=81tourneau?= Date: Wed, 28 Oct 2026 08:48:50 -0400 Subject: [PATCH 10/14] Fixing code quality and bump minor version --- software/python/nextwheel/__init__.py | 1 + software/python/setup.py | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/software/python/nextwheel/__init__.py b/software/python/nextwheel/__init__.py index af99d7f..3c49863 100644 --- a/software/python/nextwheel/__init__.py +++ b/software/python/nextwheel/__init__.py @@ -535,6 +535,7 @@ 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, diff --git a/software/python/setup.py b/software/python/setup.py index 6581a0c..89ca744 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.1.9" setuptools.setup( name="nextwheel", From 8d65caa15ebb7536eecec7697fb93805e15524c6 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominic=20Le=CC=81tourneau?= Date: Wed, 28 Oct 2026 08:55:24 -0400 Subject: [PATCH 11/14] Fixing type --- software/python/nextwheel/__init__.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/software/python/nextwheel/__init__.py b/software/python/nextwheel/__init__.py index 3c49863..95a5109 100644 --- a/software/python/nextwheel/__init__.py +++ b/software/python/nextwheel/__init__.py @@ -613,7 +613,7 @@ def start_streaming( # noqa: PLR0913 # is fine. response = requests.get( f"http://{self.ip}:{self.port}/start_streaming", - params={"address": address, "port": port}, + params={"address": address, "port": str(port)}, ) already_streaming = ( response.status_code == HTTP_RESPONSE_CODE_BAD_REQUEST From 829b6e063e21063042ba2b35cc72826e16c1ff78 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominic=20L=C3=A9tourneau?= Date: Wed, 28 Oct 2026 09:00:46 -0400 Subject: [PATCH 12/14] Add numpy to requirements.txt --- software/python/requirements.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/software/python/requirements.txt b/software/python/requirements.txt index 36c11f1..74599f5 100644 --- a/software/python/requirements.txt +++ b/software/python/requirements.txt @@ -1,3 +1,3 @@ matplotlib requests -numpy \ No newline at end of file +numpy From 51a2485ef8c9d39f36f1c45794958dfee59bdf66 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Dominic=20L=C3=A9tourneau?= Date: Wed, 28 Oct 2026 09:01:45 -0400 Subject: [PATCH 13/14] Fix JSON formatting in settings.json --- software/python/.vscode/settings.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/software/python/.vscode/settings.json b/software/python/.vscode/settings.json index 4b5a294..c820b9a 100644 --- a/software/python/.vscode/settings.json +++ b/software/python/.vscode/settings.json @@ -1,4 +1,4 @@ { "python-envs.defaultEnvManager": "ms-python.python:conda", "python-envs.defaultPackageManager": "ms-python.python:conda" -} \ No newline at end of file +} From 34046a9c4e99c05f6abd8c30b3c8862543b93ede Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Fe=CC=81lix=20Che=CC=81nier?= Date: Fri, 30 Oct 2026 11:41:29 -0400 Subject: [PATCH 14/14] Version and URL changes --- .../firmware/arduino_esp32/lib/NextWheel/src/NextWheel.h | 2 +- software/python/setup.py | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/software/firmware/arduino_esp32/lib/NextWheel/src/NextWheel.h b/software/firmware/arduino_esp32/lib/NextWheel/src/NextWheel.h index e015ce0..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.1" +#define NEXT_WHEEL_VERSION "0.2" #define NEXT_WHEEL_DEBUG_LEVEL 0 diff --git a/software/python/setup.py b/software/python/setup.py index 75103ad..ef2e540 100644 --- a/software/python/setup.py +++ b/software/python/setup.py @@ -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,9 +23,9 @@ "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", "matplotlib", "requests"], classifiers=[