mirror of
https://github.com/legop3/MultiRoombaRover.git
synced 2026-09-16 09:31:20 -04:00
Compare commits
11
Commits
5ab62c3633
...
esp32io
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
a3c13f3dd3 | ||
|
|
b0389b5ddc | ||
|
|
9ca039229a | ||
|
|
8895ed6bd8 | ||
|
|
6ca7cc0cf0 | ||
|
|
d3fd3946e6 | ||
|
|
038ae0f45a | ||
|
|
3859806fca | ||
|
|
f654394636 | ||
|
|
c8836f7d65 | ||
|
|
f77a969098 |
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
Vendored
BIN
Binary file not shown.
+402
-319
@@ -1,6 +1,6 @@
|
|||||||
# Boot-discovered rover peripherals
|
# Boot-discovered rover peripherals
|
||||||
|
|
||||||
This document defines the planned system for attaching self-describing ESP32 peripherals to a rover over USB. A peripheral advertises a small ordered set of controls, the web UI renders those controls automatically, and the current driver can use them without adding device-specific configuration to the rover or server.
|
This document defines the system for attaching self-describing ESP32 peripherals to a rover over USB. A peripheral advertises a small ordered set of controls, the web UI renders those controls automatically, and the current driver can use them without adding device-specific configuration to the rover or server.
|
||||||
|
|
||||||
The design deliberately stays small:
|
The design deliberately stays small:
|
||||||
|
|
||||||
@@ -11,10 +11,12 @@ The design deliberately stays small:
|
|||||||
- Controls appear in one vertical column in the order registered by the ESP32 program.
|
- Controls appear in one vertical column in the order registered by the ESP32 program.
|
||||||
- Anyone who can currently drive the rover can use its peripheral controls.
|
- Anyone who can currently drive the rover can use its peripheral controls.
|
||||||
- Peripherals are discovered once when `roverd` starts; changing one requires restarting the rover.
|
- Peripherals are discovered once when `roverd` starts; changing one requires restarting the rover.
|
||||||
|
- ESP32 firmware is built and uploaded with PlatformIO.
|
||||||
|
- The same firmware supports CH340/CP210x USB-to-UART boards and native USB CDC boards.
|
||||||
- There is no peripheral configuration in the rover configuration file.
|
- There is no peripheral configuration in the rover configuration file.
|
||||||
- There is no separate rover-peripheral protocol version.
|
- There is no separate rover-peripheral protocol version.
|
||||||
|
|
||||||
This is a design document. The names of proposed Go, JavaScript, and Arduino APIs describe the intended implementation and do not refer to code that already exists.
|
This document is both the design contract and implementation guide. The PlatformIO firmware library, reference sketch, focused Go Firmata client, hardware probe, boot-time daemon discovery, fixed inventory, generic output dispatch, built-in hardware backend selection, rover WebSocket message shapes, server roster forwarding, and shared HUD renderer now exist.
|
||||||
|
|
||||||
## System boundary
|
## System boundary
|
||||||
|
|
||||||
@@ -75,9 +77,12 @@ Custom functions can do anything the ESP32 program can do, including:
|
|||||||
- Send text to a display.
|
- Send text to a display.
|
||||||
- Operate hardware through an ESP32-specific library.
|
- Operate hardware through an ESP32-specific library.
|
||||||
- Change several outputs as one operation.
|
- Change several outputs as one operation.
|
||||||
- Update state used by non-blocking work in `loop()`.
|
- Update state used by non-blocking work in `updateRoverPeripheral()`.
|
||||||
|
|
||||||
Application authors use string IDs such as `specialAction` or `animationSpeed`. They do not assign numeric action IDs. Firmata necessarily uses a numeric SysEx feature byte internally, but that is an implementation detail hidden by the peripheral library.
|
The visible control name is also its string wire identifier, so authors provide
|
||||||
|
one meaningful name instead of maintaining a second hidden ID. They do not
|
||||||
|
assign numeric action IDs. Firmata necessarily uses a numeric SysEx feature byte
|
||||||
|
internally, but that is an implementation detail hidden by the package.
|
||||||
|
|
||||||
## Firmata user feature
|
## Firmata user feature
|
||||||
|
|
||||||
@@ -124,11 +129,13 @@ The receiver combines each pair:
|
|||||||
source byte = encoded byte 1 | (encoded byte 2 << 7)
|
source byte = encoded byte 1 | (encoded byte 2 << 7)
|
||||||
```
|
```
|
||||||
|
|
||||||
Peripheral authors never perform this encoding themselves. It belongs in the ESP32 `RoverPeripheralFirmata` library and the Go Firmata client used by `roverd`.
|
Peripheral authors never perform this encoding themselves. It belongs inside the ESP32 `RoverPeripheral` package and the Go Firmata client used by `roverd`.
|
||||||
|
|
||||||
|
ConfigurableFirmata's ESP32 parser accepts 252 bytes inside one incoming SysEx frame, including the feature and operation bytes. `CONTROL` values are not chunked in this deliberately simple design. The Go client checks the fully encoded message before writing it and returns an error if a particular control value cannot fit, rather than sending a frame the ESP32 would discard. Normal numeric, boolean, and short text controls fit comfortably; a text control's configured length should reflect this transport constraint.
|
||||||
|
|
||||||
## Peripheral description
|
## Peripheral description
|
||||||
|
|
||||||
The ESP32 library builds this description from the controls registered during `setup()`. The order of the `controls` array is the registration order and is also the UI order.
|
The ESP32 library builds this description from the controls registered in `configureRoverPeripheral()`. The order of the `controls` array is the registration order and is also the UI order.
|
||||||
|
|
||||||
An example description is:
|
An example description is:
|
||||||
|
|
||||||
@@ -137,7 +144,7 @@ An example description is:
|
|||||||
"name": "Example peripheral",
|
"name": "Example peripheral",
|
||||||
"controls": [
|
"controls": [
|
||||||
{
|
{
|
||||||
"id": "servoPosition",
|
"id": "Servo position",
|
||||||
"type": "slider",
|
"type": "slider",
|
||||||
"name": "Servo position",
|
"name": "Servo position",
|
||||||
"min": 0,
|
"min": 0,
|
||||||
@@ -148,20 +155,20 @@ An example description is:
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "lightBrightness",
|
"id": "Light brightness",
|
||||||
"type": "slider",
|
"type": "slider",
|
||||||
"name": "Light brightness",
|
"name": "Light brightness",
|
||||||
"min": 0,
|
"min": 0,
|
||||||
"max": 255,
|
"max": 255,
|
||||||
"output": {
|
"output": {
|
||||||
"type": "pwm",
|
"type": "pwm",
|
||||||
"pin": 18
|
"pin": 17
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"id": "specialAction",
|
"id": "Special action",
|
||||||
"type": "button",
|
"type": "button",
|
||||||
"name": "Run special action",
|
"name": "Special action",
|
||||||
"mode": "momentary",
|
"mode": "momentary",
|
||||||
"output": {
|
"output": {
|
||||||
"type": "custom"
|
"type": "custom"
|
||||||
@@ -324,44 +331,35 @@ An ESP32 that supplies all three roles describes:
|
|||||||
|
|
||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"name": "Laptop rover GPIO",
|
"name": "Rover GPIO",
|
||||||
"roverControls": {
|
"roverControls": {
|
||||||
"cameraServo": {
|
"cameraServo": {
|
||||||
"output": {
|
"pin": 14,
|
||||||
"type": "servo",
|
"minimumAngleDegrees": -15,
|
||||||
"pin": 14
|
"maximumAngleDegrees": 30,
|
||||||
},
|
"homeAngleDegrees": 0,
|
||||||
"minAngle": -15,
|
|
||||||
"maxAngle": 30,
|
|
||||||
"homeAngle": 0,
|
|
||||||
"nudgeDegrees": 2,
|
"nudgeDegrees": 2,
|
||||||
"minPulseUs": 900,
|
"minimumPulseMicroseconds": 900,
|
||||||
"maxPulseUs": 2100,
|
"maximumPulseMicroseconds": 2100,
|
||||||
"allowRawPulse": false,
|
"allowRawPulse": false,
|
||||||
"invert": false
|
"inverted": false
|
||||||
},
|
},
|
||||||
"headlight": {
|
"headlight": {
|
||||||
"output": {
|
"pin": 18,
|
||||||
"type": "digital",
|
"activeLow": false,
|
||||||
"pin": 18
|
"initiallyOn": false
|
||||||
},
|
|
||||||
"initialOn": false,
|
|
||||||
"activeLow": false
|
|
||||||
},
|
},
|
||||||
"laser": {
|
"laser": {
|
||||||
"output": {
|
"pin": 16,
|
||||||
"type": "digital",
|
"activeLow": false,
|
||||||
"pin": 19
|
"initiallyOn": false
|
||||||
},
|
|
||||||
"initialOn": false,
|
|
||||||
"activeLow": false
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
"controls": []
|
"controls": []
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
The ESP32 description owns the calibration for hardware attached to that ESP32. Laptop rover YAML does not repeat the ESP32 pin numbers or servo calibration.
|
The ESP32 description owns the calibration for hardware attached to that ESP32. Rover YAML does not repeat the ESP32 pin numbers or servo calibration.
|
||||||
|
|
||||||
### Optional backend-selection rule
|
### Optional backend-selection rule
|
||||||
|
|
||||||
@@ -373,7 +371,7 @@ The ESP32 description owns the calibration for hardware attached to that ESP32.
|
|||||||
|
|
||||||
Native configuration deliberately wins. A Pi rover can attach an ESP32 for unrelated generic controls without unexpectedly moving its existing camera servo, headlight, or laser to the ESP32. To deliberately use the ESP32 for one of those features, disable only that native feature in rover YAML.
|
Native configuration deliberately wins. A Pi rover can attach an ESP32 for unrelated generic controls without unexpectedly moving its existing camera servo, headlight, or laser to the ESP32. To deliberately use the ESP32 for one of those features, disable only that native feature in rover YAML.
|
||||||
|
|
||||||
The normal laptop configuration keeps the unavailable native GPIO features disabled:
|
Any rover configuration that should use the ESP32 for these roles keeps the corresponding native GPIO features disabled:
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
cameraServo:
|
cameraServo:
|
||||||
@@ -386,7 +384,7 @@ laser:
|
|||||||
enabled: false
|
enabled: false
|
||||||
```
|
```
|
||||||
|
|
||||||
An attached ESP32 can then fill any or all of those roles automatically at the next `roverd` start. No USB path or backend name is added to YAML.
|
An attached ESP32 can then fill any or all of those roles automatically at the next `roverd` start. This works identically on Raspberry Pi and laptop rover hosts; no USB path or backend name is added to YAML.
|
||||||
|
|
||||||
Conflict behavior is fixed and simple:
|
Conflict behavior is fixed and simple:
|
||||||
|
|
||||||
@@ -493,221 +491,44 @@ The Firmata toggle backend converts the logical value using `activeLow` before s
|
|||||||
|
|
||||||
## ESP32 authoring API
|
## ESP32 authoring API
|
||||||
|
|
||||||
Peripheral authors should not write JSON, construct SysEx messages, or manually dispatch control IDs. The proposed `RoverPeripheralFirmata` Arduino library owns those tasks.
|
Peripheral programs include `RoverPeripheral.h` and define
|
||||||
|
`configureRoverPeripheral()`. The library provides serial setup, Firmata setup,
|
||||||
|
`setup()`, and `loop()`.
|
||||||
|
|
||||||
A long positional call such as `addRoverCameraServo(14, -15, 30, 0, 2, 900, 2100, false, false)` is deliberately not part of the API. Several adjacent numbers and booleans are too difficult to understand or review without repeatedly consulting the function signature.
|
Configurations use structs. Programs assign one named field per line and then
|
||||||
|
register the completed configuration. This avoids positional lists for settings
|
||||||
|
such as angles, pulse widths, polarity, and ranges.
|
||||||
|
|
||||||
The public API uses named configuration structs. Field names include units where a bare number would otherwise be ambiguous, and enums replace booleans whose meaning would be unclear at the call site.
|
### Complete firmware
|
||||||
|
|
||||||
### Proposed configuration types
|
This program defines the standard camera tilt, headlight, and laser roles. It
|
||||||
|
also defines slider, button, number, and text accessory controls.
|
||||||
The core public types are:
|
|
||||||
|
|
||||||
```cpp
|
```cpp
|
||||||
enum class OutputPolarity {
|
#include <RoverPeripheral.h>
|
||||||
ActiveHigh,
|
|
||||||
ActiveLow
|
|
||||||
};
|
|
||||||
|
|
||||||
enum class ButtonMode {
|
namespace {
|
||||||
Toggle,
|
constexpr uint8_t specialActionPin = 21;
|
||||||
Momentary
|
|
||||||
};
|
|
||||||
|
|
||||||
struct FirmataServoOutput {
|
int repeatCount = 1;
|
||||||
uint8_t pin;
|
String displayMessage;
|
||||||
};
|
|
||||||
|
|
||||||
struct FirmataPwmOutput {
|
void runSpecialAction(bool pressed) {
|
||||||
uint8_t pin;
|
digitalWrite(specialActionPin, pressed ? HIGH : LOW);
|
||||||
};
|
|
||||||
|
|
||||||
struct FirmataDigitalOutput {
|
|
||||||
uint8_t pin;
|
|
||||||
OutputPolarity polarity = OutputPolarity::ActiveHigh;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct RoverCameraServoConfig {
|
|
||||||
uint8_t pin;
|
|
||||||
|
|
||||||
float minimumAngleDegrees;
|
|
||||||
float maximumAngleDegrees;
|
|
||||||
float homeAngleDegrees = 0;
|
|
||||||
float nudgeDegrees = 2;
|
|
||||||
|
|
||||||
uint16_t minimumPulseMicroseconds = 900;
|
|
||||||
uint16_t maximumPulseMicroseconds = 2100;
|
|
||||||
|
|
||||||
bool allowRawPulse = false;
|
|
||||||
bool inverted = false;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct RoverDigitalOutputConfig {
|
|
||||||
uint8_t pin;
|
|
||||||
OutputPolarity polarity = OutputPolarity::ActiveHigh;
|
|
||||||
bool initiallyOn = false;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct SliderControlConfig {
|
|
||||||
String id;
|
|
||||||
String name;
|
|
||||||
int minimum;
|
|
||||||
int maximum;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct ButtonControlConfig {
|
|
||||||
String id;
|
|
||||||
String name;
|
|
||||||
ButtonMode mode;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct NumberControlConfig {
|
|
||||||
String id;
|
|
||||||
String name;
|
|
||||||
int minimum;
|
|
||||||
int maximum;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct TextControlConfig {
|
|
||||||
String id;
|
|
||||||
String name;
|
|
||||||
size_t maximumLength;
|
|
||||||
};
|
|
||||||
```
|
|
||||||
|
|
||||||
Defaults cover values that are commonly shared, but required hardware and display values remain explicit. The implementation must validate the completed struct when it is registered rather than assuming that every default-constructed object is usable.
|
|
||||||
|
|
||||||
The API uses ordinary field assignments instead of C++ designated initializers. This keeps example sketches compatible with ESP32 Arduino toolchains that are not configured for C++20.
|
|
||||||
|
|
||||||
### Generic-control registration
|
|
||||||
|
|
||||||
A complete sketch for one servo slider, one light-brightness slider, and one custom momentary button is:
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
#include <Arduino.h>
|
|
||||||
#include <ConfigurableFirmata.h>
|
|
||||||
#include <RoverPeripheralFirmata.h>
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Controls are advertised in the order they are added to this object. The
|
|
||||||
* browser preserves that order when it renders the peripheral's column.
|
|
||||||
*/
|
|
||||||
RoverPeripheralFirmata peripheral("Example peripheral");
|
|
||||||
|
|
||||||
/*
|
|
||||||
* This is ordinary application code rather than Firmata plumbing. A real
|
|
||||||
* peripheral can replace it with any device-specific sequence or library call.
|
|
||||||
*/
|
|
||||||
void runSpecialAction() {
|
|
||||||
// Start or schedule the peripheral's custom behavior here.
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void setup() {
|
void setRepeatCount(int value) {
|
||||||
Firmata.begin(115200);
|
repeatCount = value;
|
||||||
|
|
||||||
/*
|
|
||||||
* roverd handles this control with standard Firmata SERVO commands. The
|
|
||||||
* ESP32 application does not need a callback for each slider update.
|
|
||||||
*/
|
|
||||||
SliderControlConfig servoPosition;
|
|
||||||
servoPosition.id = "servoPosition";
|
|
||||||
servoPosition.name = "Servo position";
|
|
||||||
servoPosition.minimum = 0;
|
|
||||||
servoPosition.maximum = 180;
|
|
||||||
|
|
||||||
FirmataServoOutput servoOutput;
|
|
||||||
servoOutput.pin = 14;
|
|
||||||
|
|
||||||
peripheral.addServoSlider(servoPosition, servoOutput);
|
|
||||||
|
|
||||||
/*
|
|
||||||
* roverd handles this control with standard Firmata PWM commands. The range
|
|
||||||
* is included in the generated description and displayed by the web UI.
|
|
||||||
*/
|
|
||||||
SliderControlConfig lightBrightness;
|
|
||||||
lightBrightness.id = "lightBrightness";
|
|
||||||
lightBrightness.name = "Light brightness";
|
|
||||||
lightBrightness.minimum = 0;
|
|
||||||
lightBrightness.maximum = 255;
|
|
||||||
|
|
||||||
FirmataPwmOutput lightOutput;
|
|
||||||
lightOutput.pin = 18;
|
|
||||||
|
|
||||||
peripheral.addPwmSlider(lightBrightness, lightOutput);
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Custom controls are delivered through the rover-peripheral Firmata feature.
|
|
||||||
* The library finds this registration by control ID and invokes the callback
|
|
||||||
* with true on press and false on release.
|
|
||||||
*/
|
|
||||||
ButtonControlConfig specialAction;
|
|
||||||
specialAction.id = "specialAction";
|
|
||||||
specialAction.name = "Run special action";
|
|
||||||
specialAction.mode = ButtonMode::Momentary;
|
|
||||||
|
|
||||||
peripheral.addButton(
|
|
||||||
specialAction,
|
|
||||||
[](bool pressed) {
|
|
||||||
if (pressed) {
|
|
||||||
runSpecialAction();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
// Register the extension with Firmata and finalize the control description.
|
|
||||||
peripheral.begin();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void loop() {
|
void setDisplayMessage(const String& value) {
|
||||||
// Standard Firmata messages and rover-peripheral SysEx messages share this parser.
|
displayMessage = value;
|
||||||
while (Firmata.available()) {
|
|
||||||
Firmata.processInput();
|
|
||||||
}
|
|
||||||
|
|
||||||
// Let the peripheral library perform any deferred send or callback work.
|
|
||||||
peripheral.update();
|
|
||||||
}
|
}
|
||||||
```
|
} // namespace
|
||||||
|
|
||||||
The intended generic registration methods are:
|
void configureRoverPeripheral(RoverPeripheral& peripheral) {
|
||||||
|
peripheral.name("Example rover peripheral");
|
||||||
|
|
||||||
```cpp
|
|
||||||
addServoSlider(const SliderControlConfig&, const FirmataServoOutput&)
|
|
||||||
addPwmSlider(const SliderControlConfig&, const FirmataPwmOutput&)
|
|
||||||
addDigitalButton(const ButtonControlConfig&, const FirmataDigitalOutput&)
|
|
||||||
|
|
||||||
addSlider(const SliderControlConfig&, SliderCallback)
|
|
||||||
addButton(const ButtonControlConfig&, ButtonCallback)
|
|
||||||
addNumber(const NumberControlConfig&, NumberCallback)
|
|
||||||
addText(const TextControlConfig&, TextCallback)
|
|
||||||
```
|
|
||||||
|
|
||||||
These helpers still produce only the four agreed UI types. The overload or method name distinguishes a standard Firmata output from a custom callback; it does not create an additional UI type.
|
|
||||||
|
|
||||||
The standardized built-in replacements use separate methods because they do not create generic UI controls:
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
addRoverCameraServo(const RoverCameraServoConfig&)
|
|
||||||
addRoverHeadlight(const RoverDigitalOutputConfig&)
|
|
||||||
addRoverLaser(const RoverDigitalOutputConfig&)
|
|
||||||
```
|
|
||||||
|
|
||||||
A laptop GPIO peripheral can combine built-in replacements and additional controls:
|
|
||||||
|
|
||||||
```cpp
|
|
||||||
#include <Arduino.h>
|
|
||||||
#include <ConfigurableFirmata.h>
|
|
||||||
#include <RoverPeripheralFirmata.h>
|
|
||||||
|
|
||||||
RoverPeripheralFirmata peripheral("Laptop rover GPIO");
|
|
||||||
|
|
||||||
void setup() {
|
|
||||||
Firmata.begin(115200);
|
|
||||||
|
|
||||||
/*
|
|
||||||
* These declarations satisfy existing rover roles. They retain the normal
|
|
||||||
* camera, headlight, and laser UI instead of entering the generic column.
|
|
||||||
*/
|
|
||||||
RoverCameraServoConfig cameraServo;
|
RoverCameraServoConfig cameraServo;
|
||||||
cameraServo.pin = 14;
|
cameraServo.pin = 14;
|
||||||
cameraServo.minimumAngleDegrees = -15;
|
cameraServo.minimumAngleDegrees = -15;
|
||||||
@@ -718,68 +539,289 @@ void setup() {
|
|||||||
cameraServo.maximumPulseMicroseconds = 2100;
|
cameraServo.maximumPulseMicroseconds = 2100;
|
||||||
cameraServo.allowRawPulse = false;
|
cameraServo.allowRawPulse = false;
|
||||||
cameraServo.inverted = false;
|
cameraServo.inverted = false;
|
||||||
|
peripheral.addCameraServo(cameraServo);
|
||||||
peripheral.addRoverCameraServo(cameraServo);
|
|
||||||
|
|
||||||
RoverDigitalOutputConfig headlight;
|
RoverDigitalOutputConfig headlight;
|
||||||
headlight.pin = 18;
|
headlight.pin = 18;
|
||||||
headlight.polarity = OutputPolarity::ActiveHigh;
|
headlight.polarity = OutputPolarity::ActiveHigh;
|
||||||
headlight.initiallyOn = false;
|
headlight.initiallyOn = false;
|
||||||
|
peripheral.addHeadlight(headlight);
|
||||||
peripheral.addRoverHeadlight(headlight);
|
|
||||||
|
|
||||||
RoverDigitalOutputConfig laser;
|
RoverDigitalOutputConfig laser;
|
||||||
laser.pin = 19;
|
laser.pin = 16;
|
||||||
laser.polarity = OutputPolarity::ActiveHigh;
|
laser.polarity = OutputPolarity::ActiveHigh;
|
||||||
laser.initiallyOn = false;
|
laser.initiallyOn = false;
|
||||||
|
peripheral.addLaser(laser);
|
||||||
|
|
||||||
peripheral.addRoverLaser(laser);
|
pinMode(specialActionPin, OUTPUT);
|
||||||
|
digitalWrite(specialActionPin, LOW);
|
||||||
|
|
||||||
/*
|
SliderControlConfig brightness;
|
||||||
* This is an additional feature, so it appears below the peripheral heading
|
brightness.name = "Light brightness";
|
||||||
* in the ordered generic-control column.
|
brightness.minimum = 0;
|
||||||
*/
|
brightness.maximum = 255;
|
||||||
SliderControlConfig underglowBrightness;
|
|
||||||
underglowBrightness.id = "underglowBrightness";
|
|
||||||
underglowBrightness.name = "Underglow brightness";
|
|
||||||
underglowBrightness.minimum = 0;
|
|
||||||
underglowBrightness.maximum = 255;
|
|
||||||
|
|
||||||
peripheral.addSlider(
|
PwmOutput brightnessOutput;
|
||||||
underglowBrightness,
|
brightnessOutput.pin = 17;
|
||||||
[](int brightness) {
|
|
||||||
setUnderglowBrightness(brightness);
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
peripheral.begin();
|
peripheral.addSlider(brightness, brightnessOutput);
|
||||||
}
|
|
||||||
|
|
||||||
void loop() {
|
ButtonControlConfig action;
|
||||||
while (Firmata.available()) {
|
action.name = "Special action";
|
||||||
Firmata.processInput();
|
action.mode = ButtonMode::Momentary;
|
||||||
}
|
|
||||||
peripheral.update();
|
peripheral.addButton(action, runSpecialAction);
|
||||||
|
|
||||||
|
NumberControlConfig repeats;
|
||||||
|
repeats.name = "Repeat count";
|
||||||
|
repeats.minimum = 1;
|
||||||
|
repeats.maximum = 20;
|
||||||
|
|
||||||
|
peripheral.addNumber(repeats, setRepeatCount);
|
||||||
|
|
||||||
|
TextControlConfig message;
|
||||||
|
message.name = "Display message";
|
||||||
|
message.maximumLength = 64;
|
||||||
|
|
||||||
|
peripheral.addText(message, setDisplayMessage);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Controls appear in registration order. Each accessory control name must be
|
||||||
|
non-empty and unique within its peripheral. The name is also its wire
|
||||||
|
identifier.
|
||||||
|
|
||||||
|
### Built-in rover roles
|
||||||
|
|
||||||
|
The standard roles use these configuration types:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
RoverCameraServoConfig
|
||||||
|
RoverDigitalOutputConfig
|
||||||
|
```
|
||||||
|
|
||||||
|
They are registered with:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
peripheral.addCameraServo(cameraServo);
|
||||||
|
peripheral.addHeadlight(headlight);
|
||||||
|
peripheral.addLaser(laser);
|
||||||
|
```
|
||||||
|
|
||||||
|
Camera servo programs set the pin, logical angle range, home angle, nudge size,
|
||||||
|
pulse range, raw-pulse policy, and inversion in
|
||||||
|
`RoverCameraServoConfig`. Headlight and laser programs set the pin, polarity,
|
||||||
|
and initial state in `RoverDigitalOutputConfig`.
|
||||||
|
|
||||||
|
These roles keep the existing camera tilt, headlight, and laser HUD controls.
|
||||||
|
They do not add entries to the accessory list.
|
||||||
|
|
||||||
|
### Standard accessory outputs
|
||||||
|
|
||||||
|
A servo slider combines `SliderControlConfig` with `ServoOutput`:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
SliderControlConfig position;
|
||||||
|
position.name = "Arm position";
|
||||||
|
position.minimum = 0;
|
||||||
|
position.maximum = 180;
|
||||||
|
|
||||||
|
ServoOutput servo;
|
||||||
|
servo.pin = 13;
|
||||||
|
|
||||||
|
peripheral.addSlider(position, servo);
|
||||||
|
```
|
||||||
|
|
||||||
|
A PWM slider combines `SliderControlConfig` with `PwmOutput`:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
SliderControlConfig brightness;
|
||||||
|
brightness.name = "Light brightness";
|
||||||
|
brightness.minimum = 0;
|
||||||
|
brightness.maximum = 255;
|
||||||
|
|
||||||
|
PwmOutput light;
|
||||||
|
light.pin = 17;
|
||||||
|
|
||||||
|
peripheral.addSlider(brightness, light);
|
||||||
|
```
|
||||||
|
|
||||||
|
A digital button combines `ButtonControlConfig` with `DigitalOutput`:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
ButtonControlConfig workLight;
|
||||||
|
workLight.name = "Work light";
|
||||||
|
workLight.mode = ButtonMode::Toggle;
|
||||||
|
|
||||||
|
DigitalOutput light;
|
||||||
|
light.pin = 21;
|
||||||
|
light.polarity = OutputPolarity::ActiveHigh;
|
||||||
|
|
||||||
|
peripheral.addButton(workLight, light);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Custom accessory functions
|
||||||
|
|
||||||
|
A custom slider passes its value to a callback:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
SliderControlConfig speed;
|
||||||
|
speed.name = "Motor speed";
|
||||||
|
speed.minimum = 0;
|
||||||
|
speed.maximum = 100;
|
||||||
|
|
||||||
|
peripheral.addSlider(speed, setMotorSpeed);
|
||||||
|
```
|
||||||
|
|
||||||
|
A custom button passes its logical state to a bool callback:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
ButtonControlConfig motor;
|
||||||
|
motor.name = "Motor";
|
||||||
|
motor.mode = ButtonMode::Momentary;
|
||||||
|
|
||||||
|
peripheral.addButton(motor, setMotorRunning);
|
||||||
|
```
|
||||||
|
|
||||||
|
Momentary bool callbacks receive `true` on press and `false` on release. A
|
||||||
|
zero-argument callback may be registered for a momentary action that runs only
|
||||||
|
on press.
|
||||||
|
|
||||||
|
Number and text inputs use their corresponding configuration structs:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
NumberControlConfig repeats;
|
||||||
|
repeats.name = "Repeat count";
|
||||||
|
repeats.minimum = 1;
|
||||||
|
repeats.maximum = 20;
|
||||||
|
peripheral.addNumber(repeats, setRepeatCount);
|
||||||
|
|
||||||
|
TextControlConfig message;
|
||||||
|
message.name = "Display message";
|
||||||
|
message.maximumLength = 64;
|
||||||
|
peripheral.addText(message, setDisplayMessage);
|
||||||
|
```
|
||||||
|
|
||||||
|
A program may define `updateRoverPeripheral()` for recurring work:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
void updateRoverPeripheral() {
|
||||||
|
// Update application state.
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Callbacks and recurring work must not block Firmata processing. Programs must
|
||||||
|
not write debug output to `Serial` because Firmata uses that stream.
|
||||||
|
|
||||||
|
### Library runtime
|
||||||
|
|
||||||
|
The library runtime performs these steps:
|
||||||
|
|
||||||
|
1. opens `Serial` at 115200 baud;
|
||||||
|
2. calls `configureRoverPeripheral()`;
|
||||||
|
3. sets the serial timeout to zero;
|
||||||
|
4. initializes Firmata and the rover-peripheral feature;
|
||||||
|
5. applies initial output states; and
|
||||||
|
6. processes Firmata messages and optional recurring work.
|
||||||
|
|
||||||
|
The zero timeout prevents ConfigurableFirmata from waiting for its receive
|
||||||
|
buffer to fill before processing a short command.
|
||||||
|
|
||||||
|
### PlatformIO package
|
||||||
|
|
||||||
|
The package source and reference project are:
|
||||||
|
|
||||||
|
```text
|
||||||
|
esp32/
|
||||||
|
├── libraries/
|
||||||
|
│ └── RoverPeripheralFirmata/
|
||||||
|
│ ├── library.json
|
||||||
|
│ ├── LICENSE
|
||||||
|
│ ├── README.md
|
||||||
|
│ ├── examples/
|
||||||
|
│ └── src/
|
||||||
|
└── rover-gpio-peripheral/
|
||||||
|
├── platformio.ini
|
||||||
|
└── src/main.cpp
|
||||||
|
```
|
||||||
|
|
||||||
|
The published package name is `legop3/RoverPeripheral`. Version `2.0.0`
|
||||||
|
contains the struct-based public API.
|
||||||
|
|
||||||
|
A classic ESP32 PlatformIO project declares:
|
||||||
|
|
||||||
|
```ini
|
||||||
|
[env:esp32dev]
|
||||||
|
platform = espressif32
|
||||||
|
board = esp32dev
|
||||||
|
framework = arduino
|
||||||
|
|
||||||
|
lib_deps =
|
||||||
|
legop3/RoverPeripheral @ ^2.0.0
|
||||||
|
```
|
||||||
|
|
||||||
|
A native-USB ESP32-S3 uses `board = esp32-s3-devkitc-1` and:
|
||||||
|
|
||||||
|
```ini
|
||||||
|
build_flags =
|
||||||
|
-D ARDUINO_USB_MODE=1
|
||||||
|
-D ARDUINO_USB_CDC_ON_BOOT=1
|
||||||
|
```
|
||||||
|
|
||||||
|
The package manifest installs ConfigurableFirmata, ArduinoJson, and ESP32Servo.
|
||||||
|
|
||||||
|
Release validation and publication use:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
pio pkg pack esp32/libraries/RoverPeripheralFirmata
|
||||||
|
pio pkg publish esp32/libraries/RoverPeripheralFirmata --owner legop3
|
||||||
|
```
|
||||||
|
|
||||||
|
Published versions are immutable. Each release uses a new version in
|
||||||
|
`library.json`.
|
||||||
|
|
||||||
|
### Building and probing
|
||||||
|
|
||||||
|
Build and upload the repository reference firmware with:
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd esp32/rover-gpio-peripheral
|
||||||
|
pio run -e esp32dev
|
||||||
|
pio run -e esp32dev -t upload --upload-port /dev/ttyUSB0
|
||||||
|
```
|
||||||
|
|
||||||
|
Use `esp32-s3-devkitc-1` and the matching `/dev/ttyACM*` device for a
|
||||||
|
native-USB ESP32-S3.
|
||||||
|
|
||||||
|
```bash
|
||||||
|
cd pi/roverd
|
||||||
|
go run ./cmd/peripheral-probe -port /dev/ttyUSB0
|
||||||
|
```
|
||||||
## Connection lifecycle
|
## Connection lifecycle
|
||||||
|
|
||||||
### Startup discovery
|
### Startup discovery
|
||||||
|
|
||||||
Peripheral discovery happens exactly once per `roverd` process. Before constructing the built-in hardware controllers or connecting to the server, `roverd`:
|
Peripheral discovery happens exactly once per `roverd` process. The currently implemented startup path runs before `roverd` constructs its existing built-in hardware controllers or connects to the server:
|
||||||
|
|
||||||
1. Enumerates the serial devices present on Linux.
|
1. Enumerates the serial devices present on Linux.
|
||||||
2. Opens each candidate device found by the startup scan.
|
2. Opens each candidate device found by the startup scan.
|
||||||
3. Starts one Firmata client per opened connection.
|
3. Waits for a possible board reset and drains stale serial bytes to a quiet read boundary.
|
||||||
4. Performs the normal Firmata firmware and capability queries.
|
4. Starts one Firmata client per opened connection.
|
||||||
5. Sends the rover-peripheral `DESCRIBE` operation.
|
5. Performs the normal Firmata firmware and capability queries.
|
||||||
6. Decodes and parses each `DESCRIPTION` response.
|
6. Sends the rover-peripheral `DESCRIBE` operation.
|
||||||
7. Assigns process-local IDs such as `firmata-0` and `firmata-1`.
|
7. Decodes and validates each `DESCRIPTION` response.
|
||||||
8. Resolves the optional `cameraServo`, `headlight`, and `laser` roles.
|
8. Validates every advertised standard-output pin against Firmata capabilities.
|
||||||
9. Builds the fixed generic peripheral list.
|
9. Configures generic digital, PWM, and servo pin modes once.
|
||||||
10. Constructs `WSClient` with the resolved built-in controllers and peripherals.
|
10. Assigns process-local IDs such as `firmata-0` and `firmata-1` in discovery order.
|
||||||
11. Connects to the server and sends the normal rover hello.
|
11. Resolves `cameraServo`, `headlight`, and `laser` against the native configuration.
|
||||||
|
12. Rejects duplicate ESP32 providers only when the corresponding native role is disabled and Firmata selection would otherwise be ambiguous.
|
||||||
|
13. Constructs the selected native or Firmata controllers and fixed generic inventory.
|
||||||
|
14. Constructs `WSClient` with those controllers and that inventory.
|
||||||
|
15. Connects to the server and includes the effective built-in configuration and renderable inventory in the normal rover hello.
|
||||||
|
|
||||||
|
The Linux scan checks stable `/dev/serial/by-id/*` names first, then `/dev/ttyUSB*` and `/dev/ttyACM*`. It canonicalizes symlinks so one device is not opened twice under its stable name and kernel name, and it excludes the configured Roomba Open Interface serial device. Each opened candidate receives the same reset wait used by the probe, followed by a read-until-quiet drain so an old partial SysEx cannot contaminate the new handshake.
|
||||||
|
|
||||||
|
Firmware and capability queries remain standard Firmata. `RoverPeripheralFirmata::begin()` registers the standard Firmata firmware name `RoverPeripheralFirmata`, so individual sketches do not repeat that discovery detail. A Firmata device with another firmware name is closed and ignored. Once a device identifies itself as rover-peripheral firmware, a malformed capability or description response is a startup error rather than a silently missing configured accessory.
|
||||||
|
|
||||||
Linux paths such as `/dev/ttyACM0` remain private `roverd` connection details. The browser and server use only the process-local peripheral ID from the hello.
|
Linux paths such as `/dev/ttyACM0` remain private `roverd` connection details. The browser and server use only the process-local peripheral ID from the hello.
|
||||||
|
|
||||||
@@ -802,8 +844,20 @@ If an ESP32 is unplugged or its serial connection fails while `roverd` is runnin
|
|||||||
|
|
||||||
1. Its Firmata client marks the connection unavailable.
|
1. Its Firmata client marks the connection unavailable.
|
||||||
2. Commands routed to that peripheral or one of its built-in roles return an error.
|
2. Commands routed to that peripheral or one of its built-in roles return an error.
|
||||||
3. `roverd` logs that the peripheral requires reconnection followed by a restart.
|
3. The failed command is logged by the existing rover WebSocket command path.
|
||||||
4. The advertised roster and visible controls do not change during that process lifetime.
|
4. The advertised inventory does not change during that process lifetime.
|
||||||
|
|
||||||
|
The first terminal read or write error also produces one concise `tty1`
|
||||||
|
broadcast through the existing `ConsoleNotifier`:
|
||||||
|
|
||||||
|
```text
|
||||||
|
Rover peripheral "Rover GPIO" (firmata-0) disconnected: <error>. Reconnect it and restart roverd.
|
||||||
|
```
|
||||||
|
|
||||||
|
Normal startup uses the same local-console mechanism to announce every fixed
|
||||||
|
peripheral, the selected native or ESP32 backend for camera servo, headlight,
|
||||||
|
and laser, any ignored ESP32 roles, or that no ESP32 was found. Detailed Linux
|
||||||
|
paths and Firmata handshake diagnostics remain in the systemd journal.
|
||||||
|
|
||||||
The disconnected device is never replaced automatically by another serial device. This ensures that a command cannot be redirected merely because Linux reused a `/dev/ttyACM*` path.
|
The disconnected device is never replaced automatically by another serial device. This ensures that a command cannot be redirected merely because Linux reused a `/dev/ttyACM*` path.
|
||||||
|
|
||||||
@@ -870,10 +924,12 @@ No global `session.features` flag is necessary. Peripherals are inherently optio
|
|||||||
|
|
||||||
## Browser-to-server control path
|
## Browser-to-server control path
|
||||||
|
|
||||||
The browser sends one generic Socket.IO event for every peripheral control:
|
The browser sends every peripheral interaction through the existing Socket.IO
|
||||||
|
`command` event. Peripheral actuation is a rover command, so it does not need a
|
||||||
|
parallel event or authorization path.
|
||||||
|
|
||||||
```text
|
```text
|
||||||
peripheral:set
|
command
|
||||||
```
|
```
|
||||||
|
|
||||||
Payload:
|
Payload:
|
||||||
@@ -881,9 +937,14 @@ Payload:
|
|||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"roverId": "rover-name",
|
"roverId": "rover-name",
|
||||||
"peripheralId": "firmata-0",
|
"type": "peripheral",
|
||||||
"controlId": "servoPosition",
|
"data": {
|
||||||
"value": 90
|
"peripheral": {
|
||||||
|
"id": "firmata-0",
|
||||||
|
"control": "Servo position",
|
||||||
|
"value": 90
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -900,7 +961,7 @@ If the socket cannot drive that rover, the event acknowledgement returns an erro
|
|||||||
"type": "peripheral",
|
"type": "peripheral",
|
||||||
"peripheral": {
|
"peripheral": {
|
||||||
"id": "firmata-0",
|
"id": "firmata-0",
|
||||||
"control": "servoPosition",
|
"control": "Servo position",
|
||||||
"value": 90
|
"value": 90
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -960,10 +1021,10 @@ A toggle sends one of the last two writes per activation. A momentary button sen
|
|||||||
|
|
||||||
## Custom callback communication
|
## Custom callback communication
|
||||||
|
|
||||||
Suppose `specialAction` is pressed. `roverd` creates the JSON payload:
|
Suppose `Special action` is pressed. `roverd` creates the JSON payload:
|
||||||
|
|
||||||
```json
|
```json
|
||||||
{"control":"specialAction","value":true}
|
{"control":"Special action","value":true}
|
||||||
```
|
```
|
||||||
|
|
||||||
After 8-to-7-bit encoding, it is placed in:
|
After 8-to-7-bit encoding, it is placed in:
|
||||||
@@ -981,19 +1042,18 @@ The ESP32 library:
|
|||||||
1. Receives the SysEx feature message through Firmata.
|
1. Receives the SysEx feature message through Firmata.
|
||||||
2. Decodes the JSON bytes.
|
2. Decodes the JSON bytes.
|
||||||
3. Reads `control` and `value`.
|
3. Reads `control` and `value`.
|
||||||
4. Finds the control registered as `specialAction`.
|
4. Finds the control registered as `Special action`.
|
||||||
5. Converts the JSON boolean to the registered button callback's `bool` argument.
|
5. Converts the JSON boolean to the registered button callback's `bool` argument.
|
||||||
6. Calls the callback with `true`.
|
6. Calls the callback with `true`.
|
||||||
|
|
||||||
On release the same path carries `false`.
|
On release the same path carries `false`.
|
||||||
|
|
||||||
For the example sketch, only the press runs the one-shot function:
|
For the reference sketch, the callback drives its output high on press and low
|
||||||
|
again on release:
|
||||||
|
|
||||||
```cpp
|
```cpp
|
||||||
[](bool pressed) {
|
void runSpecialAction(bool pressed) {
|
||||||
if (pressed) {
|
digitalWrite(specialActionPin, pressed ? HIGH : LOW);
|
||||||
runSpecialAction();
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -1034,9 +1094,17 @@ The generic renderer maps:
|
|||||||
- `number` to a labeled numeric input.
|
- `number` to a labeled numeric input.
|
||||||
- `text` to a labeled single-line text input.
|
- `text` to a labeled single-line text input.
|
||||||
|
|
||||||
The same generic component is reused by desktop and mobile layouts. Layout wrappers decide where the column appears; device-specific components are not created for individual peripherals.
|
Generic peripheral controls are rover controls, so they follow the new driver's HUD language. They do not belong in either sidebar: the sidebars contain chat, queues, room controls, settings, and other controls that are not direct rover actuation.
|
||||||
|
|
||||||
Control values are local UI values in the first implementation. Slider and toggle changes update the displayed value immediately and are then sent to the server. Restarting `roverd` recreates controls from the new hello rather than persisting peripheral values in `roverSettings`.
|
The standardized replacements do not create any new UI. `cameraServo`, `headlight`, and `laser` continue to use their current camera-tilt, headlight, and laser HUD controls. Only entries in the generic `controls` arrays appear in a new surface named `Accessories`.
|
||||||
|
|
||||||
|
On desktop, `Accessories` is a vertical button centered on the left wall of the video. It uses the existing translucent black HUD treatment and opens a height-limited, vertically scrollable panel toward the right. The panel uses the same compact control renderer as mobile and is independent of the bottom-left horn, headlight, and laser pod.
|
||||||
|
|
||||||
|
On mobile, a vertical `Accessories` button sits directly to the right of the vacuum-forward and vacuum-backward buttons. Activating it replaces the complete `AuxColumn` contents with the ordered, vertically scrollable accessory list. A small `Aux` button shares the first compact device heading and returns to the normal vacuum, camera, light, laser, and horn controls without creating a separate rail or overlay border.
|
||||||
|
|
||||||
|
Desktop and mobile reuse one placement-independent `RoverAccessoryControls` renderer inside their different containers. Device-specific React components are not created for individual peripherals. The renderer sends actions through `ControlSystemProvider`, `ControlContext`, and the existing command pipeline so assignment gating, input cancellation, and command behavior remain consistent with other rover HUD controls. Both parents and the renderer disappear completely when the assigned rover has no generic controls; no launcher, empty shell, or reserved space remains.
|
||||||
|
|
||||||
|
Control values are local UI values in the first implementation. Slider and toggle changes update the displayed value immediately and are then sent to the server. Generic sliders use the same custom pointer-capture approach as mobile camera tilt rather than a browser-native range control, which keeps touch behavior and appearance consistent while driving. Restarting `roverd` recreates controls from the new hello rather than persisting peripheral values in `roverSettings`.
|
||||||
|
|
||||||
## Permissions
|
## Permissions
|
||||||
|
|
||||||
@@ -1046,7 +1114,7 @@ The server enforces this with the existing `roverManager.canDrive(roverId, socke
|
|||||||
|
|
||||||
No peripheral-specific roles, administrator-only controls, access lists, or permissions in ESP32 configuration are part of this design.
|
No peripheral-specific roles, administrator-only controls, access lists, or permissions in ESP32 configuration are part of this design.
|
||||||
|
|
||||||
When the driver loses the rover assignment, the UI stops presenting enabled controls and subsequent `peripheral:set` requests fail the same server-side drive check.
|
When the driver loses the rover assignment, the UI stops presenting enabled controls and subsequent peripheral commands fail the same server-side drive check.
|
||||||
|
|
||||||
## Expected repository changes
|
## Expected repository changes
|
||||||
|
|
||||||
@@ -1054,7 +1122,7 @@ Implementation should remain concentrated in a few clear areas.
|
|||||||
|
|
||||||
### ESP32 library
|
### ESP32 library
|
||||||
|
|
||||||
Create a small Arduino-compatible `RoverPeripheralFirmata` library containing:
|
The Arduino-compatible `RoverPeripheral` package now contains:
|
||||||
|
|
||||||
- Ordered control registration.
|
- Ordered control registration.
|
||||||
- Standardized `cameraServo`, `headlight`, and `laser` role registration.
|
- Standardized `cameraServo`, `headlight`, and `laser` role registration.
|
||||||
@@ -1063,15 +1131,24 @@ Create a small Arduino-compatible `RoverPeripheralFirmata` library containing:
|
|||||||
- `DESCRIBE` response handling.
|
- `DESCRIBE` response handling.
|
||||||
- `CONTROL` decoding and callback dispatch.
|
- `CONTROL` decoding and callback dispatch.
|
||||||
- 8-to-7-bit payload encoding and decoding.
|
- 8-to-7-bit payload encoding and decoding.
|
||||||
- The standard-output and custom-control helper methods listed above.
|
- The public configuration structs and registration methods listed above.
|
||||||
|
- Arduino `setup()` and `loop()` ownership, including the zero-timeout Firmata
|
||||||
|
parser configuration required for immediate short-command handling.
|
||||||
|
|
||||||
Example ESP32 sketches should use this library rather than hand-writing SysEx parsing.
|
Example ESP32 sketches import only `RoverPeripheral.h` rather than exposing or
|
||||||
|
hand-writing any Firmata setup or SysEx parsing.
|
||||||
|
|
||||||
|
The package source lives in `esp32/libraries/RoverPeripheralFirmata`, with the
|
||||||
|
complete `esp32/rover-gpio-peripheral` PlatformIO project serving as the
|
||||||
|
repository reference firmware. The package manifest, README, and examples are
|
||||||
|
self-contained so the same directory can be published directly to the
|
||||||
|
PlatformIO Registry as `legop3/RoverPeripheral`.
|
||||||
|
|
||||||
### `pi/roverd`
|
### `pi/roverd`
|
||||||
|
|
||||||
Add a peripheral manager responsible for:
|
`PeripheralManager` is responsible for:
|
||||||
|
|
||||||
- One-time Linux USB serial discovery during startup.
|
- One-time Linux USB serial discovery during startup on either rover host type.
|
||||||
- One Firmata client per connected peripheral.
|
- One Firmata client per connected peripheral.
|
||||||
- Firmata handshake and capability queries.
|
- Firmata handshake and capability queries.
|
||||||
- Rover-peripheral description queries.
|
- Rover-peripheral description queries.
|
||||||
@@ -1081,9 +1158,15 @@ Add a peripheral manager responsible for:
|
|||||||
- Custom `CONTROL` dispatch.
|
- Custom `CONTROL` dispatch.
|
||||||
- Rejecting commands for disconnected peripheral IDs.
|
- Rejecting commands for disconnected peripheral IDs.
|
||||||
|
|
||||||
|
The manager validates every advertised standard-output pin against the device's Firmata capability response and configures each generic pin mode once during startup. Runtime servo and PWM changes therefore send only value writes; they do not repeatedly detach and reconfigure the hardware output. Generic digital controls start logically off, including the corresponding high electrical level for active-low declarations.
|
||||||
|
|
||||||
|
Only renderable control metadata leaves `roverd`. Firmata pin numbers, output mappings, Linux paths, live clients, capabilities, and built-in-role declarations stay in the manager's private fixed inventory. The rover hello contains process-local peripheral IDs, names, and ordered generic controls.
|
||||||
|
|
||||||
The manager should remain independent of the existing Roomba Open Interface serial adapter. A peripheral serial connection is not the Roomba base serial connection and must not be routed through `SerialAdapter`.
|
The manager should remain independent of the existing Roomba Open Interface serial adapter. A peripheral serial connection is not the Roomba base serial connection and must not be routed through `SerialAdapter`.
|
||||||
|
|
||||||
Refactor camera servo and GPIO toggles so `WSClient` depends on the shared controller interfaces rather than platform-selected concrete types. Preserve the existing logical servo movement and toggle-state behavior above the Pi and Firmata physical writers.
|
The transport foundation is a focused Firmata parser/client in `pi/roverd/firmata.go`. It operates on `io.ReadWriteCloser`, which keeps byte-stream behavior testable without hardware and lets discovery pass either `/dev/ttyUSB*` or `/dev/ttyACM*` ports into the same client. `pi/roverd/cmd/peripheral-probe` remains the direct hardware diagnostic entry point, while `PeripheralManager` now connects the same client to automatic daemon startup discovery.
|
||||||
|
|
||||||
|
`WSClient` now depends on shared camera-servo and toggle controller interfaces rather than platform-selected concrete types. The startup resolver uses the same native-first rule in the ARM Pi and amd64 laptop binaries. Firmata camera movement retains the established limits, home position, nudging, inversion, pulse calibration, raw-pulse policy, and movement-rate behavior; Firmata toggles retain logical state and polarity conversion.
|
||||||
|
|
||||||
### Server
|
### Server
|
||||||
|
|
||||||
@@ -1092,7 +1175,7 @@ Extend the existing rover connection and roster path to:
|
|||||||
- Accept `peripherals` in rover hello metadata.
|
- Accept `peripherals` in rover hello metadata.
|
||||||
- Include peripherals in `roverManager.getRoster()`.
|
- Include peripherals in `roverManager.getRoster()`.
|
||||||
- Continue exposing effective `cameraServo`, `headlight`, and `laser` metadata through their existing roster fields regardless of physical backend.
|
- Continue exposing effective `cameraServo`, `headlight`, and `laser` metadata through their existing roster fields regardless of physical backend.
|
||||||
- Add the generic `peripheral:set` Socket.IO handler.
|
- Route generic controls through the existing Socket.IO `command` handler.
|
||||||
- Reuse `roverManager.canDrive()` for authorization.
|
- Reuse `roverManager.canDrive()` for authorization.
|
||||||
- Forward the command through `commandService` so rover acknowledgements remain consistent with other controls.
|
- Forward the command through `commandService` so rover acknowledgements remain consistent with other controls.
|
||||||
|
|
||||||
@@ -1103,26 +1186,24 @@ Add one generic peripheral control renderer that:
|
|||||||
- Selects the assigned rover and its peripherals from session state.
|
- Selects the assigned rover and its peripherals from session state.
|
||||||
- Preserves peripheral and control array order.
|
- Preserves peripheral and control array order.
|
||||||
- Renders only the four agreed control types.
|
- Renders only the four agreed control types.
|
||||||
- Sends every interaction through the same `peripheral:set` event.
|
- Sends every interaction through the existing `command` event with type `peripheral`.
|
||||||
- Supports momentary press and release for pointer, touch, and keyboard activation.
|
- Supports momentary press and release for pointer, touch, and keyboard activation.
|
||||||
- Fits into the existing desktop and mobile driver control layouts.
|
- Mounts in the desktop left-wall expansion and as a replacement view inside mobile `AuxColumn`.
|
||||||
|
- Uses the shared control context and command pipeline rather than emitting directly from layout code.
|
||||||
- Disappears completely when the assigned rover has no peripherals.
|
- Disappears completely when the assigned rover has no peripherals.
|
||||||
|
|
||||||
## Implementation sequence
|
## Implementation sequence
|
||||||
|
|
||||||
The smallest useful vertical implementation is:
|
The implemented vertical path is:
|
||||||
|
|
||||||
1. Build the ESP32 Firmata feature and the three-control example sketch.
|
1. The public ESP32 package declares built-in roles and ordered accessory controls.
|
||||||
2. Add boot-time one-device USB discovery and Firmata communication to `roverd`.
|
2. Its private Firmata implementation advertises the generated description.
|
||||||
3. Include the fixed description in the rover hello and server roster.
|
3. `roverd` discovers all startup peripherals and resolves hardware backends.
|
||||||
4. Render the ordered generic controls in the driver UI.
|
4. Rover hello metadata carries the fixed renderable inventory to the server.
|
||||||
5. Route generic servo and PWM controls through standard Firmata.
|
5. The server preserves that inventory in the roster and applies normal driver authorization.
|
||||||
6. Route the generic momentary button through the custom callback operation.
|
6. The shared web renderer presents the four control types on desktop and mobile.
|
||||||
7. Add the standardized ESP32 camera-servo, headlight, and laser declarations.
|
7. Commands return through the existing pipeline to standard Firmata outputs or custom callbacks.
|
||||||
8. Refactor built-in controllers to select native Pi or Firmata backends at startup.
|
8. The package README and examples give external authors the same concise API used by the repository firmware.
|
||||||
9. Verify that existing tilt, headlight, laser, keybinding, gamepad, state-event, and server-policy behavior is unchanged with both backends.
|
|
||||||
10. Generalize startup discovery from one connection to multiple simultaneous peripherals.
|
|
||||||
11. Add the remaining toggle, number, and text registration helpers and UI renderers.
|
|
||||||
|
|
||||||
The protocol and session shapes are arrays from the beginning, so supporting multiple devices does not require changing the external contracts after the first-device vertical slice.
|
The protocol and session shapes are arrays from the beginning, so supporting multiple devices does not require changing the external contracts after the first-device vertical slice.
|
||||||
|
|
||||||
@@ -1141,16 +1222,17 @@ The completed system should be verified with a real ESP32 and rover Linux comput
|
|||||||
|
|
||||||
### Standard controls
|
### Standard controls
|
||||||
|
|
||||||
- Move the servo slider and confirm pin 14 receives servo values across the declared range.
|
- Move the reference brightness slider and confirm pin 17 receives PWM values across the declared range.
|
||||||
- Move the brightness slider and confirm pin 18 receives PWM values across the declared range.
|
- Register a `SliderControlConfig` with a `ServoOutput` and confirm its selected pin receives servo values across the declared range.
|
||||||
- Confirm neither standard control invokes the custom callback path.
|
- Confirm neither standard control invokes the custom callback path.
|
||||||
|
|
||||||
### Custom controls
|
### Custom controls
|
||||||
|
|
||||||
- Press the momentary button and confirm the ESP32 callback receives `true` once.
|
- Press the momentary button and confirm the ESP32 callback receives `true` once.
|
||||||
- Release it and confirm the callback receives `false` once.
|
- Release it and confirm the callback receives `false` once.
|
||||||
|
- Submit number and text values and confirm their typed callbacks receive the advertised values.
|
||||||
- Cancel a held pointer or leave the control layout and confirm a release is sent.
|
- Cancel a held pointer or leave the control layout and confirm a release is sent.
|
||||||
- Confirm arbitrary non-blocking ESP32 behavior can continue from `loop()` after the callback changes its state.
|
- Confirm arbitrary non-blocking ESP32 behavior can continue from `updateRoverPeripheral()` after the callback changes its state.
|
||||||
|
|
||||||
### Permissions
|
### Permissions
|
||||||
|
|
||||||
@@ -1160,7 +1242,7 @@ The completed system should be verified with a real ESP32 and rover Linux comput
|
|||||||
|
|
||||||
### Built-in GPIO replacement
|
### Built-in GPIO replacement
|
||||||
|
|
||||||
- Start a laptop rover with native camera servo, headlight, and laser disabled and an ESP32 declaring all three roles.
|
- Start either rover host type with native camera servo, headlight, and laser disabled and an ESP32 declaring all three roles.
|
||||||
- Confirm the normal camera tilt, headlight, and laser UI appears without generic duplicates.
|
- Confirm the normal camera tilt, headlight, and laser UI appears without generic duplicates.
|
||||||
- Confirm camera angle limits, home position, nudge amount, inversion, pulse calibration, and rate limiting match the declared ESP32 configuration.
|
- Confirm camera angle limits, home position, nudge amount, inversion, pulse calibration, and rate limiting match the declared ESP32 configuration.
|
||||||
- Confirm headlight and laser toggle state events remain identical to the native Pi path.
|
- Confirm headlight and laser toggle state events remain identical to the native Pi path.
|
||||||
@@ -1168,6 +1250,7 @@ The completed system should be verified with a real ESP32 and rover Linux comput
|
|||||||
- Enable a native role and declare the same ESP32 role; confirm native wins and the ignored role is logged.
|
- Enable a native role and declare the same ESP32 role; confirm native wins and the ignored role is logged.
|
||||||
- Disable native and declare the same role from two ESP32s; confirm startup fails with a clear duplicate-role error.
|
- Disable native and declare the same role from two ESP32s; confirm startup fails with a clear duplicate-role error.
|
||||||
- Confirm a Pi rover can use native built-in controls and generic ESP32 controls simultaneously.
|
- Confirm a Pi rover can use native built-in controls and generic ESP32 controls simultaneously.
|
||||||
|
- Repeat ESP32 role selection on both the ARM Pi binary and amd64 laptop binary and confirm their commands and advertised configurations match.
|
||||||
|
|
||||||
### Fixed-device lifecycle
|
### Fixed-device lifecycle
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,21 @@
|
|||||||
|
MIT License
|
||||||
|
|
||||||
|
Copyright (c) 2026 Daniel Roberts
|
||||||
|
|
||||||
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||||
|
of this software and associated documentation files (the "Software"), to deal
|
||||||
|
in the Software without restriction, including without limitation the rights
|
||||||
|
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||||
|
copies of the Software, and to permit persons to whom the Software is
|
||||||
|
furnished to do so, subject to the following conditions:
|
||||||
|
|
||||||
|
The above copyright notice and this permission notice shall be included in all
|
||||||
|
copies or substantial portions of the Software.
|
||||||
|
|
||||||
|
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||||
|
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||||
|
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||||
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||||
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||||
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||||
|
SOFTWARE.
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
# RoverPeripheral
|
||||||
|
|
||||||
|
RoverPeripheral is an ESP32 Arduino library for MultiRoombaRover peripherals.
|
||||||
|
The ESP32 reports its built-in rover roles and accessory controls to `roverd`
|
||||||
|
over USB serial.
|
||||||
|
|
||||||
|
## PlatformIO installation
|
||||||
|
|
||||||
|
Classic ESP32 DevKitC-style board:
|
||||||
|
|
||||||
|
```ini
|
||||||
|
[env:esp32dev]
|
||||||
|
platform = espressif32
|
||||||
|
board = esp32dev
|
||||||
|
framework = arduino
|
||||||
|
|
||||||
|
lib_deps =
|
||||||
|
legop3/RoverPeripheral @ ^2.0.0
|
||||||
|
```
|
||||||
|
|
||||||
|
Native-USB ESP32-S3 DevKitC:
|
||||||
|
|
||||||
|
```ini
|
||||||
|
[env:esp32-s3-devkitc-1]
|
||||||
|
platform = espressif32
|
||||||
|
board = esp32-s3-devkitc-1
|
||||||
|
framework = arduino
|
||||||
|
build_flags =
|
||||||
|
-D ARDUINO_USB_MODE=1
|
||||||
|
-D ARDUINO_USB_CDC_ON_BOOT=1
|
||||||
|
|
||||||
|
lib_deps =
|
||||||
|
legop3/RoverPeripheral @ ^2.0.0
|
||||||
|
```
|
||||||
|
|
||||||
|
## Program structure
|
||||||
|
|
||||||
|
Include `RoverPeripheral.h` and define `configureRoverPeripheral()`:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
#include <RoverPeripheral.h>
|
||||||
|
|
||||||
|
void configureRoverPeripheral(RoverPeripheral& peripheral) {
|
||||||
|
peripheral.name("Headlight controller");
|
||||||
|
|
||||||
|
RoverDigitalOutputConfig headlight;
|
||||||
|
headlight.pin = 18;
|
||||||
|
headlight.polarity = OutputPolarity::ActiveHigh;
|
||||||
|
headlight.initiallyOn = false;
|
||||||
|
peripheral.addHeadlight(headlight);
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The library provides `setup()` and `loop()`. Do not define them in the
|
||||||
|
peripheral program.
|
||||||
|
|
||||||
|
## Built-in rover roles
|
||||||
|
|
||||||
|
Camera tilt:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
RoverCameraServoConfig cameraServo;
|
||||||
|
cameraServo.pin = 14;
|
||||||
|
cameraServo.minimumAngleDegrees = -15;
|
||||||
|
cameraServo.maximumAngleDegrees = 30;
|
||||||
|
cameraServo.homeAngleDegrees = 0;
|
||||||
|
cameraServo.nudgeDegrees = 2;
|
||||||
|
cameraServo.minimumPulseMicroseconds = 900;
|
||||||
|
cameraServo.maximumPulseMicroseconds = 2100;
|
||||||
|
cameraServo.allowRawPulse = false;
|
||||||
|
cameraServo.inverted = false;
|
||||||
|
peripheral.addCameraServo(cameraServo);
|
||||||
|
```
|
||||||
|
|
||||||
|
Headlight or laser:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
RoverDigitalOutputConfig headlight;
|
||||||
|
headlight.pin = 18;
|
||||||
|
headlight.polarity = OutputPolarity::ActiveHigh;
|
||||||
|
headlight.initiallyOn = false;
|
||||||
|
peripheral.addHeadlight(headlight);
|
||||||
|
|
||||||
|
RoverDigitalOutputConfig laser;
|
||||||
|
laser.pin = 16;
|
||||||
|
laser.polarity = OutputPolarity::ActiveHigh;
|
||||||
|
laser.initiallyOn = false;
|
||||||
|
peripheral.addLaser(laser);
|
||||||
|
```
|
||||||
|
|
||||||
|
These registrations use the existing camera, headlight, and laser controls in
|
||||||
|
the rover UI. They do not create accessory controls.
|
||||||
|
|
||||||
|
## Accessory controls
|
||||||
|
|
||||||
|
Controls appear in registration order. Each control name must be unique within
|
||||||
|
the peripheral. The name is also used as the control identifier.
|
||||||
|
|
||||||
|
### Servo slider
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
SliderControlConfig position;
|
||||||
|
position.name = "Arm position";
|
||||||
|
position.minimum = 0;
|
||||||
|
position.maximum = 180;
|
||||||
|
|
||||||
|
ServoOutput servo;
|
||||||
|
servo.pin = 13;
|
||||||
|
|
||||||
|
peripheral.addSlider(position, servo);
|
||||||
|
```
|
||||||
|
|
||||||
|
### PWM slider
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
SliderControlConfig brightness;
|
||||||
|
brightness.name = "Light brightness";
|
||||||
|
brightness.minimum = 0;
|
||||||
|
brightness.maximum = 255;
|
||||||
|
|
||||||
|
PwmOutput light;
|
||||||
|
light.pin = 17;
|
||||||
|
|
||||||
|
peripheral.addSlider(brightness, light);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Digital button
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
ButtonControlConfig workLight;
|
||||||
|
workLight.name = "Work light";
|
||||||
|
workLight.mode = ButtonMode::Toggle;
|
||||||
|
|
||||||
|
DigitalOutput light;
|
||||||
|
light.pin = 21;
|
||||||
|
light.polarity = OutputPolarity::ActiveHigh;
|
||||||
|
|
||||||
|
peripheral.addButton(workLight, light);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Custom slider
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
void setMotorSpeed(int value) {
|
||||||
|
// Apply value to the device.
|
||||||
|
}
|
||||||
|
|
||||||
|
SliderControlConfig speed;
|
||||||
|
speed.name = "Motor speed";
|
||||||
|
speed.minimum = 0;
|
||||||
|
speed.maximum = 100;
|
||||||
|
|
||||||
|
peripheral.addSlider(speed, setMotorSpeed);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Custom button
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
void setMotorRunning(bool running) {
|
||||||
|
// Start or stop the device.
|
||||||
|
}
|
||||||
|
|
||||||
|
ButtonControlConfig motor;
|
||||||
|
motor.name = "Motor";
|
||||||
|
motor.mode = ButtonMode::Momentary;
|
||||||
|
|
||||||
|
peripheral.addButton(motor, setMotorRunning);
|
||||||
|
```
|
||||||
|
|
||||||
|
A momentary bool callback receives `true` on press and `false` on release. A
|
||||||
|
zero-argument callback can be used for a one-shot momentary action.
|
||||||
|
|
||||||
|
### Number input
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
void setRepeatCount(int value) {
|
||||||
|
// Store or apply value.
|
||||||
|
}
|
||||||
|
|
||||||
|
NumberControlConfig repeats;
|
||||||
|
repeats.name = "Repeat count";
|
||||||
|
repeats.minimum = 1;
|
||||||
|
repeats.maximum = 20;
|
||||||
|
|
||||||
|
peripheral.addNumber(repeats, setRepeatCount);
|
||||||
|
```
|
||||||
|
|
||||||
|
### Text input
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
void setDisplayMessage(const String& value) {
|
||||||
|
// Store or display value.
|
||||||
|
}
|
||||||
|
|
||||||
|
TextControlConfig message;
|
||||||
|
message.name = "Display message";
|
||||||
|
message.maximumLength = 64;
|
||||||
|
|
||||||
|
peripheral.addText(message, setDisplayMessage);
|
||||||
|
```
|
||||||
|
|
||||||
|
## Recurring work
|
||||||
|
|
||||||
|
Define `updateRoverPeripheral()` when the program needs recurring non-blocking
|
||||||
|
work:
|
||||||
|
|
||||||
|
```cpp
|
||||||
|
void updateRoverPeripheral() {
|
||||||
|
// Update a state machine or device.
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Callbacks and `updateRoverPeripheral()` must not block serial processing.
|
||||||
|
`Serial` is reserved for Firmata and must not be used for debug output.
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
MIT
|
||||||
+76
@@ -0,0 +1,76 @@
|
|||||||
|
#include <RoverPeripheral.h>
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
constexpr uint8_t kActionPin = 21;
|
||||||
|
|
||||||
|
int repeatCount = 1;
|
||||||
|
String displayMessage;
|
||||||
|
|
||||||
|
void setActionActive(bool pressed) {
|
||||||
|
digitalWrite(kActionPin, pressed ? HIGH : LOW);
|
||||||
|
}
|
||||||
|
|
||||||
|
void setRepeatCount(int value) {
|
||||||
|
repeatCount = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
void setDisplayMessage(const String& value) {
|
||||||
|
displayMessage = value;
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
void configureRoverPeripheral(RoverPeripheral& io) {
|
||||||
|
io.name("Complete rover peripheral");
|
||||||
|
|
||||||
|
RoverCameraServoConfig cameraServo;
|
||||||
|
cameraServo.pin = 14;
|
||||||
|
cameraServo.minimumAngleDegrees = -15;
|
||||||
|
cameraServo.maximumAngleDegrees = 30;
|
||||||
|
cameraServo.homeAngleDegrees = 0;
|
||||||
|
cameraServo.nudgeDegrees = 2;
|
||||||
|
cameraServo.minimumPulseMicroseconds = 900;
|
||||||
|
cameraServo.maximumPulseMicroseconds = 2100;
|
||||||
|
cameraServo.allowRawPulse = false;
|
||||||
|
cameraServo.inverted = false;
|
||||||
|
io.addCameraServo(cameraServo);
|
||||||
|
|
||||||
|
RoverDigitalOutputConfig headlight;
|
||||||
|
headlight.pin = 18;
|
||||||
|
headlight.polarity = OutputPolarity::ActiveHigh;
|
||||||
|
headlight.initiallyOn = false;
|
||||||
|
io.addHeadlight(headlight);
|
||||||
|
|
||||||
|
RoverDigitalOutputConfig laser;
|
||||||
|
laser.pin = 16;
|
||||||
|
laser.polarity = OutputPolarity::ActiveHigh;
|
||||||
|
laser.initiallyOn = false;
|
||||||
|
io.addLaser(laser);
|
||||||
|
|
||||||
|
pinMode(kActionPin, OUTPUT);
|
||||||
|
digitalWrite(kActionPin, LOW);
|
||||||
|
|
||||||
|
SliderControlConfig brightness;
|
||||||
|
brightness.name = "Light brightness";
|
||||||
|
brightness.minimum = 0;
|
||||||
|
brightness.maximum = 255;
|
||||||
|
|
||||||
|
PwmOutput brightnessOutput;
|
||||||
|
brightnessOutput.pin = 17;
|
||||||
|
io.addSlider(brightness, brightnessOutput);
|
||||||
|
|
||||||
|
ButtonControlConfig action;
|
||||||
|
action.name = "Special action";
|
||||||
|
action.mode = ButtonMode::Momentary;
|
||||||
|
io.addButton(action, setActionActive);
|
||||||
|
|
||||||
|
NumberControlConfig repeats;
|
||||||
|
repeats.name = "Repeat count";
|
||||||
|
repeats.minimum = 1;
|
||||||
|
repeats.maximum = 20;
|
||||||
|
io.addNumber(repeats, setRepeatCount);
|
||||||
|
|
||||||
|
TextControlConfig message;
|
||||||
|
message.name = "Display message";
|
||||||
|
message.maximumLength = 64;
|
||||||
|
io.addText(message, setDisplayMessage);
|
||||||
|
}
|
||||||
+11
@@ -0,0 +1,11 @@
|
|||||||
|
#include <RoverPeripheral.h>
|
||||||
|
|
||||||
|
void configureRoverPeripheral(RoverPeripheral& io) {
|
||||||
|
io.name("Headlight controller");
|
||||||
|
|
||||||
|
RoverDigitalOutputConfig headlight;
|
||||||
|
headlight.pin = 18;
|
||||||
|
headlight.polarity = OutputPolarity::ActiveHigh;
|
||||||
|
headlight.initiallyOn = false;
|
||||||
|
io.addHeadlight(headlight);
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
{
|
||||||
|
"$schema": "https://raw.githubusercontent.com/platformio/platformio-core/develop/platformio/assets/schema/library.json",
|
||||||
|
"name": "RoverPeripheral",
|
||||||
|
"version": "2.0.1",
|
||||||
|
"description": "Create self-describing ESP32 hardware controls for MultiRoombaRover",
|
||||||
|
"keywords": [
|
||||||
|
"esp32",
|
||||||
|
"firmata",
|
||||||
|
"robotics",
|
||||||
|
"rover"
|
||||||
|
],
|
||||||
|
"repository": {
|
||||||
|
"type": "git",
|
||||||
|
"url": "https://github.com/legop3/MultiRoombaRover.git"
|
||||||
|
},
|
||||||
|
"homepage": "https://github.com/legop3/MultiRoombaRover/tree/main/esp32/libraries/RoverPeripheralFirmata",
|
||||||
|
"license": "MIT",
|
||||||
|
"frameworks": "arduino",
|
||||||
|
"platforms": "espressif32",
|
||||||
|
"headers": "RoverPeripheral.h",
|
||||||
|
"dependencies": {
|
||||||
|
"ConfigurableFirmata": "https://github.com/firmata/ConfigurableFirmata.git#3.2.0",
|
||||||
|
"bblanchon/ArduinoJson": "^7.4.2",
|
||||||
|
"madhephaestus/ESP32Servo": "^3.0.8"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
#include "RoverPeripheral.h"
|
||||||
|
|
||||||
|
#include "internal/RoverPeripheralFirmata.h"
|
||||||
|
|
||||||
|
RoverPeripheral::RoverPeripheral()
|
||||||
|
: implementation_(new RoverPeripheralFirmata("Rover peripheral")) {}
|
||||||
|
|
||||||
|
RoverPeripheral::~RoverPeripheral() {
|
||||||
|
delete implementation_;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheral::name(const String& peripheralName) {
|
||||||
|
implementation_->setName(peripheralName);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheral::addCameraServo(const RoverCameraServoConfig& config) {
|
||||||
|
implementation_->addRoverCameraServo(config);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheral::addHeadlight(const RoverDigitalOutputConfig& config) {
|
||||||
|
implementation_->addRoverHeadlight(config);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheral::addLaser(const RoverDigitalOutputConfig& config) {
|
||||||
|
implementation_->addRoverLaser(config);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheral::addSlider(const SliderControlConfig& config, const ServoOutput& output) {
|
||||||
|
implementation_->addServoSlider(config, output);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheral::addSlider(const SliderControlConfig& config, const PwmOutput& output) {
|
||||||
|
implementation_->addPwmSlider(config, output);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheral::addButton(const ButtonControlConfig& config, const DigitalOutput& output) {
|
||||||
|
implementation_->addDigitalButton(config, output);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheral::addSlider(const SliderControlConfig& config, SliderCallback callback) {
|
||||||
|
implementation_->addSlider(config, callback);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheral::addButton(const ButtonControlConfig& config, ButtonCallback callback) {
|
||||||
|
implementation_->addButton(config, callback);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheral::addButton(const ButtonControlConfig& config, ActionCallback callback) {
|
||||||
|
// One-shot callbacks apply only to momentary buttons. A toggle requires the
|
||||||
|
// bool callback overload because application code must receive its new state.
|
||||||
|
if (config.mode != ButtonMode::Momentary) {
|
||||||
|
abort();
|
||||||
|
}
|
||||||
|
implementation_->addButton(
|
||||||
|
config,
|
||||||
|
[callback](bool pressed) {
|
||||||
|
if (pressed && callback) {
|
||||||
|
callback();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheral::addNumber(const NumberControlConfig& config, NumberCallback callback) {
|
||||||
|
implementation_->addNumber(config, callback);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheral::addText(const TextControlConfig& config, TextCallback callback) {
|
||||||
|
implementation_->addText(config, callback);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheral::begin(FirmataExt& extension) {
|
||||||
|
implementation_->begin(extension);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheral::update() {
|
||||||
|
implementation_->update();
|
||||||
|
}
|
||||||
@@ -0,0 +1,156 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
|
||||||
|
#include <functional>
|
||||||
|
|
||||||
|
/** Describes whether a logical on value drives an output pin high or low. */
|
||||||
|
enum class OutputPolarity {
|
||||||
|
ActiveHigh,
|
||||||
|
ActiveLow,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Selects whether a button retains its state or is active only while held. */
|
||||||
|
enum class ButtonMode {
|
||||||
|
Toggle,
|
||||||
|
Momentary,
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Configuration for the rover's existing camera-tilt control. */
|
||||||
|
struct RoverCameraServoConfig {
|
||||||
|
uint8_t pin = 0;
|
||||||
|
float minimumAngleDegrees = -15;
|
||||||
|
float maximumAngleDegrees = 30;
|
||||||
|
float homeAngleDegrees = 0;
|
||||||
|
float nudgeDegrees = 2;
|
||||||
|
uint16_t minimumPulseMicroseconds = 900;
|
||||||
|
uint16_t maximumPulseMicroseconds = 2100;
|
||||||
|
bool allowRawPulse = false;
|
||||||
|
bool inverted = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Configuration for the rover's existing headlight or laser control. */
|
||||||
|
struct RoverDigitalOutputConfig {
|
||||||
|
uint8_t pin = 0;
|
||||||
|
OutputPolarity polarity = OutputPolarity::ActiveHigh;
|
||||||
|
bool initiallyOn = false;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Shared display and range settings for a slider control. */
|
||||||
|
struct SliderControlConfig {
|
||||||
|
String name;
|
||||||
|
int minimum = 0;
|
||||||
|
int maximum = 100;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Shared display and interaction settings for a button control. */
|
||||||
|
struct ButtonControlConfig {
|
||||||
|
String name;
|
||||||
|
ButtonMode mode = ButtonMode::Momentary;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Shared display and range settings for a number input. */
|
||||||
|
struct NumberControlConfig {
|
||||||
|
String name;
|
||||||
|
int minimum = 0;
|
||||||
|
int maximum = 100;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Shared display and length settings for a text input. */
|
||||||
|
struct TextControlConfig {
|
||||||
|
String name;
|
||||||
|
size_t maximumLength = 32;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Selects a standard Firmata servo as the destination for a slider. */
|
||||||
|
struct ServoOutput {
|
||||||
|
uint8_t pin = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Selects an ESP32 PWM pin as the destination for a slider. */
|
||||||
|
struct PwmOutput {
|
||||||
|
uint8_t pin = 0;
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Selects an ESP32 digital pin as the destination for a button. */
|
||||||
|
struct DigitalOutput {
|
||||||
|
uint8_t pin = 0;
|
||||||
|
OutputPolarity polarity = OutputPolarity::ActiveHigh;
|
||||||
|
};
|
||||||
|
|
||||||
|
using SliderCallback = std::function<void(int)>;
|
||||||
|
using ButtonCallback = std::function<void(bool)>;
|
||||||
|
using ActionCallback = std::function<void()>;
|
||||||
|
using NumberCallback = std::function<void(int)>;
|
||||||
|
using TextCallback = std::function<void(const String&)>;
|
||||||
|
|
||||||
|
class FirmataExt;
|
||||||
|
class RoverPeripheralFirmata;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Registration API for a self-describing rover peripheral.
|
||||||
|
*
|
||||||
|
* A sketch constructs each configuration one field at a time and registers it
|
||||||
|
* in configureRoverPeripheral(). Serial and protocol setup stay in the library.
|
||||||
|
*/
|
||||||
|
class RoverPeripheral {
|
||||||
|
public:
|
||||||
|
RoverPeripheral();
|
||||||
|
~RoverPeripheral();
|
||||||
|
|
||||||
|
RoverPeripheral(const RoverPeripheral&) = delete;
|
||||||
|
RoverPeripheral& operator=(const RoverPeripheral&) = delete;
|
||||||
|
|
||||||
|
/** Sets the peripheral name shown above its accessory controls. */
|
||||||
|
void name(const String& peripheralName);
|
||||||
|
|
||||||
|
/** Registers the rover's existing camera-tilt control. */
|
||||||
|
void addCameraServo(const RoverCameraServoConfig& config);
|
||||||
|
|
||||||
|
/** Registers the rover's existing headlight control. */
|
||||||
|
void addHeadlight(const RoverDigitalOutputConfig& config);
|
||||||
|
|
||||||
|
/** Registers the rover's existing laser control. */
|
||||||
|
void addLaser(const RoverDigitalOutputConfig& config);
|
||||||
|
|
||||||
|
/** Registers a slider backed by a standard Firmata servo output. */
|
||||||
|
void addSlider(const SliderControlConfig& config, const ServoOutput& output);
|
||||||
|
|
||||||
|
/** Registers a slider backed by an ESP32 PWM output. */
|
||||||
|
void addSlider(const SliderControlConfig& config, const PwmOutput& output);
|
||||||
|
|
||||||
|
/** Registers a button backed by an ESP32 digital output. */
|
||||||
|
void addButton(const ButtonControlConfig& config, const DigitalOutput& output);
|
||||||
|
|
||||||
|
/** Registers a slider handled by application code. */
|
||||||
|
void addSlider(const SliderControlConfig& config, SliderCallback callback);
|
||||||
|
|
||||||
|
/** Registers a button whose callback receives its logical state. */
|
||||||
|
void addButton(const ButtonControlConfig& config, ButtonCallback callback);
|
||||||
|
|
||||||
|
/** Registers a momentary button whose callback runs only on press. */
|
||||||
|
void addButton(const ButtonControlConfig& config, ActionCallback callback);
|
||||||
|
|
||||||
|
/** Registers a number input handled by application code. */
|
||||||
|
void addNumber(const NumberControlConfig& config, NumberCallback callback);
|
||||||
|
|
||||||
|
/** Registers a text input handled by application code. */
|
||||||
|
void addText(const TextControlConfig& config, TextCallback callback);
|
||||||
|
|
||||||
|
private:
|
||||||
|
// The implementation is opaque so importing this header does not expose any
|
||||||
|
// Firmata types or require firmware authors to understand the wire protocol.
|
||||||
|
RoverPeripheralFirmata* implementation_;
|
||||||
|
|
||||||
|
void begin(FirmataExt& extension);
|
||||||
|
void update();
|
||||||
|
|
||||||
|
friend void setup();
|
||||||
|
friend void loop();
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Called once by the library after Arduino and Serial initialization. */
|
||||||
|
void configureRoverPeripheral(RoverPeripheral& peripheral);
|
||||||
|
|
||||||
|
/** Optional non-blocking hook for recurring application work. */
|
||||||
|
void updateRoverPeripheral();
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
#include "RoverPeripheral.h"
|
||||||
|
|
||||||
|
#include <ConfigurableFirmata.h>
|
||||||
|
#include <FirmataExt.h>
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
FirmataExt firmataExtension;
|
||||||
|
RoverPeripheral peripheral;
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
// A weak no-op preserves the zero-boilerplate case while allowing a sketch to
|
||||||
|
// define the same function when animations or state machines need regular work.
|
||||||
|
void __attribute__((weak)) updateRoverPeripheral() {}
|
||||||
|
|
||||||
|
void setup() {
|
||||||
|
// The public configuration hook runs after Arduino initialization, allowing
|
||||||
|
// peripheral code to safely use pinMode() and initialize third-party devices.
|
||||||
|
Serial.begin(115200);
|
||||||
|
configureRoverPeripheral(peripheral);
|
||||||
|
|
||||||
|
// ConfigurableFirmata batches reads on ESP32-class boards. Arduino's default
|
||||||
|
// one-second Stream timeout would delay short commands while waiting for the
|
||||||
|
// batch buffer to fill, so consume only bytes that have already arrived.
|
||||||
|
Serial.setTimeout(0);
|
||||||
|
Firmata.begin(Serial);
|
||||||
|
peripheral.begin(firmataExtension);
|
||||||
|
|
||||||
|
// Applying a normal Firmata reset after registration establishes every
|
||||||
|
// declared initial output and makes the first host connection deterministic.
|
||||||
|
Firmata.parse(SYSTEM_RESET);
|
||||||
|
}
|
||||||
|
|
||||||
|
void loop() {
|
||||||
|
// ConfigurableFirmata retains partial parser state between iterations. Stop
|
||||||
|
// after each complete message so user update work cannot be starved by a
|
||||||
|
// sustained burst, while ordinary short commands are still drained at once.
|
||||||
|
while (Firmata.available()) {
|
||||||
|
Firmata.processInput();
|
||||||
|
if (!Firmata.isParsingMessage()) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
peripheral.update();
|
||||||
|
updateRoverPeripheral();
|
||||||
|
}
|
||||||
@@ -0,0 +1,521 @@
|
|||||||
|
#include "RoverPeripheralFirmata.h"
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
constexpr byte kPeripheralFeature = 0x01;
|
||||||
|
constexpr byte kDescribeOperation = 0x00;
|
||||||
|
constexpr byte kDescriptionOperation = 0x01;
|
||||||
|
constexpr byte kControlOperation = 0x02;
|
||||||
|
|
||||||
|
const char* buttonModeName(ButtonMode mode) {
|
||||||
|
return mode == ButtonMode::Toggle ? "toggle" : "momentary";
|
||||||
|
}
|
||||||
|
|
||||||
|
const char* outputTypeName(uint8_t value) {
|
||||||
|
switch (value) {
|
||||||
|
case 0:
|
||||||
|
return "servo";
|
||||||
|
case 1:
|
||||||
|
return "pwm";
|
||||||
|
case 2:
|
||||||
|
return "digital";
|
||||||
|
default:
|
||||||
|
return "custom";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
RoverPeripheralFirmata* RoverPeripheralFirmata::instance_ = nullptr;
|
||||||
|
|
||||||
|
RoverPeripheralFirmata::RoverPeripheralFirmata(const String& name) : name_(name) {}
|
||||||
|
|
||||||
|
void RoverPeripheralFirmata::setName(const String& name) {
|
||||||
|
if (name.length() == 0) {
|
||||||
|
// A blank heading makes multiple attached peripherals impossible to
|
||||||
|
// distinguish. Treat it as a firmware-authoring error at startup rather
|
||||||
|
// than advertising ambiguous controls to the rover.
|
||||||
|
abort();
|
||||||
|
}
|
||||||
|
name_ = name;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheralFirmata::validateControlName(const String& name) const {
|
||||||
|
if (name.length() == 0) {
|
||||||
|
// Registration errors are programmer errors discovered during setup. A
|
||||||
|
// hard stop is preferable to advertising a partially usable device whose
|
||||||
|
// behavior depends on which malformed control the driver touches first.
|
||||||
|
abort();
|
||||||
|
}
|
||||||
|
for (const ControlRegistration& existing : controls_) {
|
||||||
|
if (existing.id == name) {
|
||||||
|
abort();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheralFirmata::validateRange(const String& name, int minimum, int maximum) const {
|
||||||
|
if (name.length() == 0 || minimum > maximum) {
|
||||||
|
abort();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheralFirmata::addServoSlider(const SliderControlConfig& config, const ServoOutput& output) {
|
||||||
|
validateControlName(config.name);
|
||||||
|
validateRange(config.name, config.minimum, config.maximum);
|
||||||
|
ControlRegistration control;
|
||||||
|
control.id = config.name;
|
||||||
|
control.name = config.name;
|
||||||
|
control.type = ControlType::Slider;
|
||||||
|
control.output = OutputType::Servo;
|
||||||
|
control.minimum = config.minimum;
|
||||||
|
control.maximum = config.maximum;
|
||||||
|
control.pin = output.pin;
|
||||||
|
controls_.push_back(control);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheralFirmata::addPwmSlider(const SliderControlConfig& config, const PwmOutput& output) {
|
||||||
|
validateControlName(config.name);
|
||||||
|
validateRange(config.name, config.minimum, config.maximum);
|
||||||
|
ControlRegistration control;
|
||||||
|
control.id = config.name;
|
||||||
|
control.name = config.name;
|
||||||
|
control.type = ControlType::Slider;
|
||||||
|
control.output = OutputType::Pwm;
|
||||||
|
control.minimum = config.minimum;
|
||||||
|
control.maximum = config.maximum;
|
||||||
|
control.pin = output.pin;
|
||||||
|
controls_.push_back(control);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheralFirmata::addDigitalButton(const ButtonControlConfig& config, const DigitalOutput& output) {
|
||||||
|
validateControlName(config.name);
|
||||||
|
ControlRegistration control;
|
||||||
|
control.id = config.name;
|
||||||
|
control.name = config.name;
|
||||||
|
control.type = ControlType::Button;
|
||||||
|
control.output = OutputType::Digital;
|
||||||
|
control.buttonMode = config.mode;
|
||||||
|
control.pin = output.pin;
|
||||||
|
control.polarity = output.polarity;
|
||||||
|
controls_.push_back(control);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheralFirmata::addSlider(const SliderControlConfig& config, SliderCallback callback) {
|
||||||
|
validateControlName(config.name);
|
||||||
|
validateRange(config.name, config.minimum, config.maximum);
|
||||||
|
ControlRegistration control;
|
||||||
|
control.id = config.name;
|
||||||
|
control.name = config.name;
|
||||||
|
control.type = ControlType::Slider;
|
||||||
|
control.output = OutputType::Custom;
|
||||||
|
control.minimum = config.minimum;
|
||||||
|
control.maximum = config.maximum;
|
||||||
|
control.sliderCallback = callback;
|
||||||
|
controls_.push_back(control);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheralFirmata::addButton(const ButtonControlConfig& config, ButtonCallback callback) {
|
||||||
|
validateControlName(config.name);
|
||||||
|
ControlRegistration control;
|
||||||
|
control.id = config.name;
|
||||||
|
control.name = config.name;
|
||||||
|
control.type = ControlType::Button;
|
||||||
|
control.output = OutputType::Custom;
|
||||||
|
control.buttonMode = config.mode;
|
||||||
|
control.buttonCallback = callback;
|
||||||
|
controls_.push_back(control);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheralFirmata::addNumber(const NumberControlConfig& config, NumberCallback callback) {
|
||||||
|
validateControlName(config.name);
|
||||||
|
validateRange(config.name, config.minimum, config.maximum);
|
||||||
|
ControlRegistration control;
|
||||||
|
control.id = config.name;
|
||||||
|
control.name = config.name;
|
||||||
|
control.type = ControlType::Number;
|
||||||
|
control.output = OutputType::Custom;
|
||||||
|
control.minimum = config.minimum;
|
||||||
|
control.maximum = config.maximum;
|
||||||
|
control.numberCallback = callback;
|
||||||
|
controls_.push_back(control);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheralFirmata::addText(const TextControlConfig& config, TextCallback callback) {
|
||||||
|
validateControlName(config.name);
|
||||||
|
if (config.maximumLength == 0) {
|
||||||
|
abort();
|
||||||
|
}
|
||||||
|
ControlRegistration control;
|
||||||
|
control.id = config.name;
|
||||||
|
control.name = config.name;
|
||||||
|
control.type = ControlType::Text;
|
||||||
|
control.output = OutputType::Custom;
|
||||||
|
control.maximumLength = config.maximumLength;
|
||||||
|
control.textCallback = callback;
|
||||||
|
controls_.push_back(control);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheralFirmata::addRoverCameraServo(const RoverCameraServoConfig& config) {
|
||||||
|
cameraServo_ = config;
|
||||||
|
hasCameraServo_ = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheralFirmata::addRoverHeadlight(const RoverDigitalOutputConfig& config) {
|
||||||
|
headlight_ = config;
|
||||||
|
hasHeadlight_ = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheralFirmata::addRoverLaser(const RoverDigitalOutputConfig& config) {
|
||||||
|
laser_ = config;
|
||||||
|
hasLaser_ = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheralFirmata::begin(FirmataExt& extension) {
|
||||||
|
if (instance_ != nullptr && instance_ != this) {
|
||||||
|
abort();
|
||||||
|
}
|
||||||
|
instance_ = this;
|
||||||
|
extension.addFeature(*this);
|
||||||
|
|
||||||
|
// Discovery uses Firmata's standard REPORT_FIRMWARE query to distinguish a
|
||||||
|
// rover peripheral from unrelated Firmata devices. The helper owns this
|
||||||
|
// identity so every sketch gets it without repeating protocol boilerplate.
|
||||||
|
Firmata.setFirmwareNameAndVersion("RoverPeripheralFirmata", 1, 0);
|
||||||
|
|
||||||
|
// SET_DIGITAL_PIN_VALUE is a fixed Firmata command rather than SysEx, so it
|
||||||
|
// cannot travel through FirmataFeature::handleSysex. Firmata exposes one
|
||||||
|
// callback for it and this peripheral owns the standard output implementation.
|
||||||
|
Firmata.attach(SET_DIGITAL_PIN_VALUE, digitalPinValueCallback);
|
||||||
|
Firmata.attach(SYSTEM_RESET, systemResetCallback);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheralFirmata::update() {
|
||||||
|
// Custom callbacks execute synchronously from Firmata's parser for now. This
|
||||||
|
// method intentionally remains available so future non-blocking peripheral
|
||||||
|
// work can be serviced without changing the sketch's main loop shape.
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheralFirmata::handleCapability(byte pin) {
|
||||||
|
if (!IS_PIN_DIGITAL(pin)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The peripheral supports the output modes roverd may select. Capability
|
||||||
|
// reporting stays standard Firmata, so the Linux probe can also inspect it
|
||||||
|
// with any other conforming client.
|
||||||
|
Firmata.write(PIN_MODE_OUTPUT);
|
||||||
|
Firmata.write(1);
|
||||||
|
if (IS_PIN_PWM(pin)) {
|
||||||
|
Firmata.write(PIN_MODE_PWM);
|
||||||
|
Firmata.write(DEFAULT_PWM_RESOLUTION);
|
||||||
|
}
|
||||||
|
Firmata.write(PIN_MODE_SERVO);
|
||||||
|
Firmata.write(14);
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean RoverPeripheralFirmata::handlePinMode(byte pin, int mode) {
|
||||||
|
if (pin >= TOTAL_PINS || !IS_PIN_DIGITAL(pin)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
// A pin can only have one active hardware generator. Detaching a previous
|
||||||
|
// servo before switching modes prevents it from continuing to pulse after a
|
||||||
|
// later digital or PWM configuration takes ownership of the pin.
|
||||||
|
if (mode != PIN_MODE_SERVO) {
|
||||||
|
detachServo(pin);
|
||||||
|
}
|
||||||
|
|
||||||
|
switch (mode) {
|
||||||
|
case PIN_MODE_OUTPUT:
|
||||||
|
pinMode(PIN_TO_DIGITAL(pin), OUTPUT);
|
||||||
|
digitalWrite(PIN_TO_DIGITAL(pin), LOW);
|
||||||
|
Firmata.setPinState(pin, 0);
|
||||||
|
return true;
|
||||||
|
case PIN_MODE_PWM:
|
||||||
|
if (!IS_PIN_PWM(pin)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
pinMode(PIN_TO_PWM(pin), OUTPUT);
|
||||||
|
analogWrite(PIN_TO_PWM(pin), 0);
|
||||||
|
Firmata.setPinState(pin, 0);
|
||||||
|
return true;
|
||||||
|
case PIN_MODE_SERVO:
|
||||||
|
attachServo(pin);
|
||||||
|
Firmata.setPinState(pin, 0);
|
||||||
|
return true;
|
||||||
|
default:
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
boolean RoverPeripheralFirmata::handleSysex(byte command, byte argc, byte* argv) {
|
||||||
|
if (command == kPeripheralFeature) {
|
||||||
|
if (argc == 0) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
if (argv[0] == kDescribeOperation) {
|
||||||
|
buildAndSendDescription();
|
||||||
|
} else if (argv[0] == kControlOperation) {
|
||||||
|
dispatchCustomControl(argc, argv);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (command == SERVO_CONFIG && argc >= 5) {
|
||||||
|
const byte pin = argv[0];
|
||||||
|
const int minimumPulse = argv[1] | (argv[2] << 7);
|
||||||
|
const int maximumPulse = argv[3] | (argv[4] << 7);
|
||||||
|
if (pin < TOTAL_PINS && IS_PIN_DIGITAL(pin)) {
|
||||||
|
Firmata.setPinMode(pin, PIN_MODE_SERVO);
|
||||||
|
attachServo(pin, minimumPulse, maximumPulse);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (command == EXTENDED_ANALOG && argc >= 2) {
|
||||||
|
const byte pin = argv[0];
|
||||||
|
if (pin >= TOTAL_PINS) {
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
int value = 0;
|
||||||
|
// Extended analog values contain a variable number of seven-bit chunks.
|
||||||
|
// Reassembling every received chunk keeps servo angles and PWM values fully
|
||||||
|
// compatible with normal Firmata clients rather than assuming eight bits.
|
||||||
|
for (byte index = 1; index < argc && index <= 4; ++index) {
|
||||||
|
value |= static_cast<int>(argv[index]) << (7 * (index - 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
const byte mode = Firmata.getPinMode(pin);
|
||||||
|
if (mode == PIN_MODE_PWM && IS_PIN_PWM(pin)) {
|
||||||
|
analogWrite(PIN_TO_PWM(pin), value);
|
||||||
|
Firmata.setPinState(pin, value);
|
||||||
|
} else if (mode == PIN_MODE_SERVO && servos_[pin] != nullptr) {
|
||||||
|
servos_[pin]->write(value);
|
||||||
|
Firmata.setPinState(pin, value);
|
||||||
|
}
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheralFirmata::reset() {
|
||||||
|
for (byte pin = 0; pin < TOTAL_PINS; ++pin) {
|
||||||
|
detachServo(pin);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Built-in role defaults are applied on Firmata reset as well as boot. This
|
||||||
|
// makes reconnecting a client deterministic without creating a second state
|
||||||
|
// model on the ESP32.
|
||||||
|
if (hasHeadlight_) {
|
||||||
|
pinMode(headlight_.pin, OUTPUT);
|
||||||
|
const bool physicalHigh = headlight_.initiallyOn != (headlight_.polarity == OutputPolarity::ActiveLow);
|
||||||
|
writeDigitalPin(headlight_.pin, physicalHigh);
|
||||||
|
}
|
||||||
|
if (hasLaser_) {
|
||||||
|
pinMode(laser_.pin, OUTPUT);
|
||||||
|
const bool physicalHigh = laser_.initiallyOn != (laser_.polarity == OutputPolarity::ActiveLow);
|
||||||
|
writeDigitalPin(laser_.pin, physicalHigh);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheralFirmata::buildAndSendDescription() {
|
||||||
|
JsonDocument document;
|
||||||
|
document["name"] = name_;
|
||||||
|
|
||||||
|
if (hasCameraServo_ || hasHeadlight_ || hasLaser_) {
|
||||||
|
JsonObject roverControls = document["roverControls"].to<JsonObject>();
|
||||||
|
if (hasCameraServo_) {
|
||||||
|
JsonObject servo = roverControls["cameraServo"].to<JsonObject>();
|
||||||
|
servo["pin"] = cameraServo_.pin;
|
||||||
|
servo["minimumAngleDegrees"] = cameraServo_.minimumAngleDegrees;
|
||||||
|
servo["maximumAngleDegrees"] = cameraServo_.maximumAngleDegrees;
|
||||||
|
servo["homeAngleDegrees"] = cameraServo_.homeAngleDegrees;
|
||||||
|
servo["nudgeDegrees"] = cameraServo_.nudgeDegrees;
|
||||||
|
servo["minimumPulseMicroseconds"] = cameraServo_.minimumPulseMicroseconds;
|
||||||
|
servo["maximumPulseMicroseconds"] = cameraServo_.maximumPulseMicroseconds;
|
||||||
|
servo["allowRawPulse"] = cameraServo_.allowRawPulse;
|
||||||
|
servo["inverted"] = cameraServo_.inverted;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto addDigitalRole = [&roverControls](const char* key, const RoverDigitalOutputConfig& config) {
|
||||||
|
JsonObject role = roverControls[key].to<JsonObject>();
|
||||||
|
role["pin"] = config.pin;
|
||||||
|
role["activeLow"] = config.polarity == OutputPolarity::ActiveLow;
|
||||||
|
role["initiallyOn"] = config.initiallyOn;
|
||||||
|
};
|
||||||
|
if (hasHeadlight_) {
|
||||||
|
addDigitalRole("headlight", headlight_);
|
||||||
|
}
|
||||||
|
if (hasLaser_) {
|
||||||
|
addDigitalRole("laser", laser_);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonArray controls = document["controls"].to<JsonArray>();
|
||||||
|
for (const ControlRegistration& registration : controls_) {
|
||||||
|
JsonObject control = controls.add<JsonObject>();
|
||||||
|
control["id"] = registration.id;
|
||||||
|
control["name"] = registration.name;
|
||||||
|
|
||||||
|
switch (registration.type) {
|
||||||
|
case ControlType::Slider:
|
||||||
|
control["type"] = "slider";
|
||||||
|
control["min"] = registration.minimum;
|
||||||
|
control["max"] = registration.maximum;
|
||||||
|
break;
|
||||||
|
case ControlType::Button:
|
||||||
|
control["type"] = "button";
|
||||||
|
control["mode"] = buttonModeName(registration.buttonMode);
|
||||||
|
break;
|
||||||
|
case ControlType::Number:
|
||||||
|
control["type"] = "number";
|
||||||
|
control["min"] = registration.minimum;
|
||||||
|
control["max"] = registration.maximum;
|
||||||
|
break;
|
||||||
|
case ControlType::Text:
|
||||||
|
control["type"] = "text";
|
||||||
|
control["maxLength"] = registration.maximumLength;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonObject output = control["output"].to<JsonObject>();
|
||||||
|
output["type"] = outputTypeName(static_cast<uint8_t>(registration.output));
|
||||||
|
if (registration.output != OutputType::Custom) {
|
||||||
|
output["pin"] = registration.pin;
|
||||||
|
}
|
||||||
|
if (registration.output == OutputType::Digital && registration.polarity == OutputPolarity::ActiveLow) {
|
||||||
|
output["activeLow"] = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
String payload;
|
||||||
|
serializeJson(document, payload);
|
||||||
|
|
||||||
|
// ConfigurableFirmata's convenience sendSysex takes a byte-sized raw length.
|
||||||
|
// Descriptions can exceed that, so write the standard framing and each 7-bit
|
||||||
|
// pair directly. This remains one ordinary Firmata SysEx message on the wire.
|
||||||
|
Firmata.startSysex();
|
||||||
|
Firmata.write(kPeripheralFeature);
|
||||||
|
Firmata.write(kDescriptionOperation);
|
||||||
|
for (size_t index = 0; index < payload.length(); ++index) {
|
||||||
|
Firmata.sendValueAsTwo7bitBytes(static_cast<uint8_t>(payload[index]));
|
||||||
|
}
|
||||||
|
Firmata.endSysex();
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheralFirmata::dispatchCustomControl(byte argc, byte* argv) {
|
||||||
|
if (argc < 3 || ((argc - 1) % 2) != 0) {
|
||||||
|
Firmata.sendString(F("Invalid rover control payload"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
String decoded;
|
||||||
|
decoded.reserve((argc - 1) / 2);
|
||||||
|
for (byte index = 1; index + 1 < argc; index += 2) {
|
||||||
|
if (argv[index + 1] > 1) {
|
||||||
|
Firmata.sendString(F("Invalid rover control encoding"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
decoded += static_cast<char>(argv[index] | (argv[index + 1] << 7));
|
||||||
|
}
|
||||||
|
|
||||||
|
JsonDocument document;
|
||||||
|
if (deserializeJson(document, decoded) != DeserializationError::Ok) {
|
||||||
|
Firmata.sendString(F("Invalid rover control JSON"));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const String controlID = document["control"].as<String>();
|
||||||
|
for (ControlRegistration& registration : controls_) {
|
||||||
|
if (registration.id != controlID || registration.output != OutputType::Custom) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// The registration type is the source of truth for value conversion. This
|
||||||
|
// prevents an unexpected JSON value from silently selecting a different
|
||||||
|
// callback signature or invoking unrelated application behavior.
|
||||||
|
switch (registration.type) {
|
||||||
|
case ControlType::Slider:
|
||||||
|
if (registration.sliderCallback) {
|
||||||
|
registration.sliderCallback(document["value"].as<int>());
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case ControlType::Button:
|
||||||
|
if (registration.buttonCallback) {
|
||||||
|
registration.buttonCallback(document["value"].as<bool>());
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case ControlType::Number:
|
||||||
|
if (registration.numberCallback) {
|
||||||
|
registration.numberCallback(document["value"].as<int>());
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
case ControlType::Text:
|
||||||
|
if (registration.textCallback) {
|
||||||
|
String value = document["value"].as<String>();
|
||||||
|
if (value.length() > registration.maximumLength) {
|
||||||
|
value.remove(registration.maximumLength);
|
||||||
|
}
|
||||||
|
registration.textCallback(value);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
Firmata.sendString(F("Unknown rover control"));
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheralFirmata::writeDigitalPin(byte pin, bool physicalHigh) {
|
||||||
|
// Standard Firmata digital values represent the electrical pin level. roverd
|
||||||
|
// applies the advertised activeLow mapping before sending a command, keeping
|
||||||
|
// this firmware compatible with raw Firmata clients and avoiding inversion in
|
||||||
|
// two different layers.
|
||||||
|
digitalWrite(PIN_TO_DIGITAL(pin), physicalHigh ? HIGH : LOW);
|
||||||
|
Firmata.setPinState(pin, physicalHigh ? 1 : 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheralFirmata::attachServo(byte pin, int minimumPulseMicroseconds, int maximumPulseMicroseconds) {
|
||||||
|
if (pin >= TOTAL_PINS || !IS_PIN_DIGITAL(pin)) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (servos_[pin] == nullptr) {
|
||||||
|
servos_[pin] = new Servo();
|
||||||
|
}
|
||||||
|
if (servos_[pin]->attached()) {
|
||||||
|
servos_[pin]->detach();
|
||||||
|
}
|
||||||
|
if (minimumPulseMicroseconds > 0 && maximumPulseMicroseconds > minimumPulseMicroseconds) {
|
||||||
|
servos_[pin]->attach(PIN_TO_SERVO(pin), minimumPulseMicroseconds, maximumPulseMicroseconds);
|
||||||
|
} else {
|
||||||
|
servos_[pin]->attach(PIN_TO_SERVO(pin));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheralFirmata::detachServo(byte pin) {
|
||||||
|
if (pin >= TOTAL_PINS || servos_[pin] == nullptr) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (servos_[pin]->attached()) {
|
||||||
|
servos_[pin]->detach();
|
||||||
|
}
|
||||||
|
delete servos_[pin];
|
||||||
|
servos_[pin] = nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheralFirmata::digitalPinValueCallback(byte pin, int value) {
|
||||||
|
if (instance_ == nullptr || pin >= TOTAL_PINS || Firmata.getPinMode(pin) != PIN_MODE_OUTPUT) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Polarity is advertised by the peripheral and applied by roverd before this
|
||||||
|
// standard raw pin-level command reaches the ESP32.
|
||||||
|
instance_->writeDigitalPin(pin, value != 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
void RoverPeripheralFirmata::systemResetCallback() {
|
||||||
|
if (instance_ != nullptr) {
|
||||||
|
instance_->reset();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <Arduino.h>
|
||||||
|
#include <ArduinoJson.h>
|
||||||
|
#include <ConfigurableFirmata.h>
|
||||||
|
#include <ESP32Servo.h>
|
||||||
|
#include <FirmataExt.h>
|
||||||
|
#include <RoverPeripheral.h>
|
||||||
|
|
||||||
|
#include <vector>
|
||||||
|
|
||||||
|
/*
|
||||||
|
* RoverPeripheralFirmata is the protocol-facing implementation behind the
|
||||||
|
* small RoverPeripheral public facade. Keeping this class private prevents
|
||||||
|
* peripheral sketches from depending on Firmata types while ordinary Firmata
|
||||||
|
* tooling can still use digital, PWM, and servo commands on the same stream.
|
||||||
|
*/
|
||||||
|
class RoverPeripheralFirmata : public FirmataFeature {
|
||||||
|
public:
|
||||||
|
explicit RoverPeripheralFirmata(const String& name);
|
||||||
|
|
||||||
|
void setName(const String& name);
|
||||||
|
|
||||||
|
void addServoSlider(const SliderControlConfig& config, const ServoOutput& output);
|
||||||
|
void addPwmSlider(const SliderControlConfig& config, const PwmOutput& output);
|
||||||
|
void addDigitalButton(const ButtonControlConfig& config, const DigitalOutput& output);
|
||||||
|
void addSlider(const SliderControlConfig& config, SliderCallback callback);
|
||||||
|
void addButton(const ButtonControlConfig& config, ButtonCallback callback);
|
||||||
|
void addNumber(const NumberControlConfig& config, NumberCallback callback);
|
||||||
|
void addText(const TextControlConfig& config, TextCallback callback);
|
||||||
|
|
||||||
|
void addRoverCameraServo(const RoverCameraServoConfig& config);
|
||||||
|
void addRoverHeadlight(const RoverDigitalOutputConfig& config);
|
||||||
|
void addRoverLaser(const RoverDigitalOutputConfig& config);
|
||||||
|
|
||||||
|
void begin(FirmataExt& extension);
|
||||||
|
void update();
|
||||||
|
|
||||||
|
// FirmataFeature methods let FirmataExt route standard and custom SysEx
|
||||||
|
// operations through the same parser that owns the serial connection.
|
||||||
|
void handleCapability(byte pin) override;
|
||||||
|
boolean handlePinMode(byte pin, int mode) override;
|
||||||
|
boolean handleSysex(byte command, byte argc, byte* argv) override;
|
||||||
|
void reset() override;
|
||||||
|
|
||||||
|
private:
|
||||||
|
enum class ControlType {
|
||||||
|
Slider,
|
||||||
|
Button,
|
||||||
|
Number,
|
||||||
|
Text,
|
||||||
|
};
|
||||||
|
|
||||||
|
enum class OutputType {
|
||||||
|
Servo,
|
||||||
|
Pwm,
|
||||||
|
Digital,
|
||||||
|
Custom,
|
||||||
|
};
|
||||||
|
|
||||||
|
struct ControlRegistration {
|
||||||
|
String id;
|
||||||
|
String name;
|
||||||
|
ControlType type;
|
||||||
|
OutputType output;
|
||||||
|
int minimum = 0;
|
||||||
|
int maximum = 0;
|
||||||
|
size_t maximumLength = 0;
|
||||||
|
ButtonMode buttonMode = ButtonMode::Momentary;
|
||||||
|
uint8_t pin = 0;
|
||||||
|
OutputPolarity polarity = OutputPolarity::ActiveHigh;
|
||||||
|
SliderCallback sliderCallback;
|
||||||
|
ButtonCallback buttonCallback;
|
||||||
|
NumberCallback numberCallback;
|
||||||
|
TextCallback textCallback;
|
||||||
|
};
|
||||||
|
|
||||||
|
String name_;
|
||||||
|
std::vector<ControlRegistration> controls_;
|
||||||
|
bool hasCameraServo_ = false;
|
||||||
|
bool hasHeadlight_ = false;
|
||||||
|
bool hasLaser_ = false;
|
||||||
|
RoverCameraServoConfig cameraServo_;
|
||||||
|
RoverDigitalOutputConfig headlight_;
|
||||||
|
RoverDigitalOutputConfig laser_;
|
||||||
|
Servo* servos_[TOTAL_PINS] = {};
|
||||||
|
|
||||||
|
void validateControlName(const String& name) const;
|
||||||
|
void validateRange(const String& name, int minimum, int maximum) const;
|
||||||
|
void buildAndSendDescription();
|
||||||
|
void dispatchCustomControl(byte argc, byte* argv);
|
||||||
|
void writeDigitalPin(byte pin, bool enabled);
|
||||||
|
void attachServo(byte pin, int minimumPulseMicroseconds = -1, int maximumPulseMicroseconds = -1);
|
||||||
|
void detachServo(byte pin);
|
||||||
|
|
||||||
|
static RoverPeripheralFirmata* instance_;
|
||||||
|
static void digitalPinValueCallback(byte pin, int value);
|
||||||
|
static void systemResetCallback();
|
||||||
|
};
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
[platformio]
|
||||||
|
default_envs = esp32dev
|
||||||
|
|
||||||
|
[env]
|
||||||
|
platform = espressif32
|
||||||
|
framework = arduino
|
||||||
|
monitor_speed = 115200
|
||||||
|
lib_deps =
|
||||||
|
; Install the local package through PlatformIO's dependency manager so this
|
||||||
|
; reference project exercises the same transitive dependency behavior as an
|
||||||
|
; external project using the published Registry package.
|
||||||
|
RoverPeripheral=file://../libraries/RoverPeripheralFirmata
|
||||||
|
|
||||||
|
; This is the generic ESP32-WROOM-32/DevKitC target used by boards carrying a
|
||||||
|
; CH340 or CP210x USB-to-UART bridge. Linux normally exposes it as ttyUSB*.
|
||||||
|
[env:esp32dev]
|
||||||
|
board = esp32dev
|
||||||
|
|
||||||
|
; Native USB boards use the same sketch and Firmata stream. These flags make the
|
||||||
|
; ESP32-S3's USB CDC serial port active at boot, normally appearing as ttyACM*.
|
||||||
|
[env:esp32-s3-devkitc-1]
|
||||||
|
board = esp32-s3-devkitc-1
|
||||||
|
build_flags =
|
||||||
|
-D ARDUINO_USB_MODE=1
|
||||||
|
-D ARDUINO_USB_CDC_ON_BOOT=1
|
||||||
@@ -0,0 +1,97 @@
|
|||||||
|
#include <RoverPeripheral.h>
|
||||||
|
|
||||||
|
namespace {
|
||||||
|
// Every example pin is present on both the classic ESP32 DevKitC and the
|
||||||
|
// ESP32-S3 DevKitC. GPIO 19 and 20 are deliberately avoided because native-USB
|
||||||
|
// S3 boards use them for USB D- and D+.
|
||||||
|
constexpr uint8_t kSpecialActionPin = 21;
|
||||||
|
|
||||||
|
int repeatCount = 1;
|
||||||
|
String displayMessage;
|
||||||
|
|
||||||
|
void runSpecialAction(bool pressed) {
|
||||||
|
// Receiving both button edges lets application hardware remain active only
|
||||||
|
// while the driver holds the momentary control.
|
||||||
|
digitalWrite(kSpecialActionPin, pressed ? HIGH : LOW);
|
||||||
|
}
|
||||||
|
|
||||||
|
void setRepeatCount(int value) {
|
||||||
|
// A real device can use this value when it starts its next animation or
|
||||||
|
// actuator sequence. Storing it keeps this reference callback non-blocking.
|
||||||
|
repeatCount = value;
|
||||||
|
}
|
||||||
|
|
||||||
|
void setDisplayMessage(const String& value) {
|
||||||
|
// Display hardware can render the stored value from updateRoverPeripheral().
|
||||||
|
// Avoiding Serial output is important because Serial belongs to Firmata.
|
||||||
|
displayMessage = value;
|
||||||
|
}
|
||||||
|
} // namespace
|
||||||
|
|
||||||
|
void configureRoverPeripheral(RoverPeripheral& io) {
|
||||||
|
io.name("Rover GPIO");
|
||||||
|
|
||||||
|
// Standard roles retain the rover's existing HUD controls while moving the
|
||||||
|
// electrical outputs to this ESP32 on either a Pi or laptop rover host.
|
||||||
|
RoverCameraServoConfig cameraServo;
|
||||||
|
cameraServo.pin = 14;
|
||||||
|
cameraServo.minimumAngleDegrees = -15;
|
||||||
|
cameraServo.maximumAngleDegrees = 30;
|
||||||
|
cameraServo.homeAngleDegrees = 0;
|
||||||
|
cameraServo.nudgeDegrees = 2;
|
||||||
|
cameraServo.minimumPulseMicroseconds = 900;
|
||||||
|
cameraServo.maximumPulseMicroseconds = 2100;
|
||||||
|
cameraServo.allowRawPulse = false;
|
||||||
|
cameraServo.inverted = false;
|
||||||
|
io.addCameraServo(cameraServo);
|
||||||
|
|
||||||
|
RoverDigitalOutputConfig headlight;
|
||||||
|
headlight.pin = 18;
|
||||||
|
headlight.polarity = OutputPolarity::ActiveHigh;
|
||||||
|
headlight.initiallyOn = false;
|
||||||
|
io.addHeadlight(headlight);
|
||||||
|
|
||||||
|
RoverDigitalOutputConfig laser;
|
||||||
|
laser.pin = 16;
|
||||||
|
laser.polarity = OutputPolarity::ActiveHigh;
|
||||||
|
laser.initiallyOn = false;
|
||||||
|
io.addLaser(laser);
|
||||||
|
|
||||||
|
pinMode(kSpecialActionPin, OUTPUT);
|
||||||
|
digitalWrite(kSpecialActionPin, LOW);
|
||||||
|
|
||||||
|
// Accessory controls render in precisely this registration order.
|
||||||
|
SliderControlConfig servoPosition;
|
||||||
|
servoPosition.name = "Servo position";
|
||||||
|
servoPosition.minimum = 0;
|
||||||
|
servoPosition.maximum = 180;
|
||||||
|
|
||||||
|
ServoOutput servoOutput;
|
||||||
|
servoOutput.pin = 13;
|
||||||
|
io.addSlider(servoPosition, servoOutput);
|
||||||
|
|
||||||
|
SliderControlConfig lightBrightness;
|
||||||
|
lightBrightness.name = "Light brightness";
|
||||||
|
lightBrightness.minimum = 0;
|
||||||
|
lightBrightness.maximum = 255;
|
||||||
|
|
||||||
|
PwmOutput lightOutput;
|
||||||
|
lightOutput.pin = 17;
|
||||||
|
io.addSlider(lightBrightness, lightOutput);
|
||||||
|
|
||||||
|
ButtonControlConfig specialAction;
|
||||||
|
specialAction.name = "Special action";
|
||||||
|
specialAction.mode = ButtonMode::Momentary;
|
||||||
|
io.addButton(specialAction, runSpecialAction);
|
||||||
|
|
||||||
|
NumberControlConfig repeats;
|
||||||
|
repeats.name = "Repeat count";
|
||||||
|
repeats.minimum = 1;
|
||||||
|
repeats.maximum = 20;
|
||||||
|
io.addNumber(repeats, setRepeatCount);
|
||||||
|
|
||||||
|
TextControlConfig message;
|
||||||
|
message.name = "Display message";
|
||||||
|
message.maximumLength = 64;
|
||||||
|
io.addText(message, setDisplayMessage);
|
||||||
|
}
|
||||||
@@ -25,10 +25,6 @@ type CameraServo struct {
|
|||||||
closed bool
|
closed bool
|
||||||
}
|
}
|
||||||
|
|
||||||
const maxServoDegPerSec = 60.0
|
|
||||||
const servoStepInterval = 20 * time.Millisecond
|
|
||||||
const servoAngleEpsilon = 0.01
|
|
||||||
|
|
||||||
func NewCameraServo(cfg CameraServoConfig, logger *log.Logger) (*CameraServo, error) {
|
func NewCameraServo(cfg CameraServoConfig, logger *log.Logger) (*CameraServo, error) {
|
||||||
if !cfg.Enabled {
|
if !cfg.Enabled {
|
||||||
return nil, fmt.Errorf("camera servo disabled")
|
return nil, fmt.Errorf("camera servo disabled")
|
||||||
@@ -132,6 +128,16 @@ func (s *CameraServo) CurrentAngle() float64 {
|
|||||||
return s.currentAngle
|
return s.currentAngle
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Configuration reports the effective public behavior advertised to the
|
||||||
|
// server. The native implementation simply returns its validated YAML config.
|
||||||
|
func (s *CameraServo) Configuration() CameraServoConfig {
|
||||||
|
return s.cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
func (s *CameraServo) BackendDescription() string {
|
||||||
|
return "native GPIO"
|
||||||
|
}
|
||||||
|
|
||||||
func (s *CameraServo) applyPulseLocked(micros int) {
|
func (s *CameraServo) applyPulseLocked(micros int) {
|
||||||
micros = clampInt(micros, s.cfg.MinPulseUs, s.cfg.MaxPulseUs)
|
micros = clampInt(micros, s.cfg.MinPulseUs, s.cfg.MaxPulseUs)
|
||||||
s.pin.DutyCycle(uint32(micros), uint32(s.cfg.CycleLen))
|
s.pin.DutyCycle(uint32(micros), uint32(s.cfg.CycleLen))
|
||||||
|
|||||||
@@ -11,10 +11,9 @@ type CameraServo struct{}
|
|||||||
|
|
||||||
func NewCameraServo(_ CameraServoConfig, _ *log.Logger) (*CameraServo, error) {
|
func NewCameraServo(_ CameraServoConfig, _ *log.Logger) (*CameraServo, error) {
|
||||||
/*
|
/*
|
||||||
The Debian laptop profile starts with the laptop's built-in webcam and no
|
This constructor represents only native host GPIO. The shared startup
|
||||||
Pi PWM servo. If a laptop rover eventually grows an external servo board,
|
resolver selects the normal Firmata implementation when an ESP32 provides
|
||||||
it should get its own implementation instead of reusing Raspberry Pi GPIO
|
the role, so external hardware is not laptop-specific code.
|
||||||
assumptions.
|
|
||||||
*/
|
*/
|
||||||
return nil, fmt.Errorf("camera servo not supported in the debian-laptop build")
|
return nil, fmt.Errorf("camera servo not supported in the debian-laptop build")
|
||||||
}
|
}
|
||||||
@@ -36,3 +35,11 @@ func (c *CameraServo) SetPulseWidth(micros int) error {
|
|||||||
func (c *CameraServo) CurrentAngle() float64 {
|
func (c *CameraServo) CurrentAngle() float64 {
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *CameraServo) Configuration() CameraServoConfig {
|
||||||
|
return CameraServoConfig{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *CameraServo) BackendDescription() string {
|
||||||
|
return "native GPIO"
|
||||||
|
}
|
||||||
|
|||||||
@@ -30,3 +30,11 @@ func (c *CameraServo) SetPulseWidth(micros int) error {
|
|||||||
func (c *CameraServo) CurrentAngle() float64 {
|
func (c *CameraServo) CurrentAngle() float64 {
|
||||||
return 0
|
return 0
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (c *CameraServo) Configuration() CameraServoConfig {
|
||||||
|
return CameraServoConfig{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *CameraServo) BackendDescription() string {
|
||||||
|
return "native GPIO"
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,151 @@
|
|||||||
|
package main
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"flag"
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
roverd "multiroombarover/pi/roverd"
|
||||||
|
|
||||||
|
"github.com/tarm/serial"
|
||||||
|
)
|
||||||
|
|
||||||
|
func main() {
|
||||||
|
var portName string
|
||||||
|
var baud int
|
||||||
|
var timeout time.Duration
|
||||||
|
var startupWait time.Duration
|
||||||
|
var controlID string
|
||||||
|
var rawValue string
|
||||||
|
|
||||||
|
flag.StringVar(&portName, "port", "", "serial device, for example /dev/ttyUSB0 or /dev/ttyACM0")
|
||||||
|
flag.IntVar(&baud, "baud", 115200, "Firmata serial baud rate")
|
||||||
|
flag.DurationVar(&timeout, "timeout", 5*time.Second, "timeout for each Firmata response")
|
||||||
|
flag.DurationVar(&startupWait, "startup-wait", 2*time.Second, "time allowed for boards that reset when the port opens")
|
||||||
|
flag.StringVar(&controlID, "control", "", "optional declared control ID to exercise")
|
||||||
|
flag.StringVar(&rawValue, "value", "", "JSON value for -control, such as 90, true, or \"hello\"")
|
||||||
|
flag.Parse()
|
||||||
|
|
||||||
|
if portName == "" {
|
||||||
|
log.Fatal("-port is required")
|
||||||
|
}
|
||||||
|
if (controlID == "") != (rawValue == "") {
|
||||||
|
log.Fatal("-control and -value must be provided together")
|
||||||
|
}
|
||||||
|
|
||||||
|
port, err := serial.OpenPort(&serial.Config{
|
||||||
|
Name: portName,
|
||||||
|
Baud: baud,
|
||||||
|
ReadTimeout: 100 * time.Millisecond,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("open %s: %v", portName, err)
|
||||||
|
}
|
||||||
|
defer port.Close()
|
||||||
|
|
||||||
|
// CH340 and native-USB development boards may reset when the host opens the
|
||||||
|
// port. Waiting here makes the same probe work with both connection styles
|
||||||
|
// without baking that diagnostic delay into the production Firmata client.
|
||||||
|
time.Sleep(startupWait)
|
||||||
|
|
||||||
|
rootContext, cancelRoot := context.WithCancel(context.Background())
|
||||||
|
defer cancelRoot()
|
||||||
|
client := roverd.NewFirmataClient(port)
|
||||||
|
client.Start(rootContext)
|
||||||
|
|
||||||
|
firmware, err := withTimeout(timeout, client.QueryFirmware)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("query firmware: %v", err)
|
||||||
|
}
|
||||||
|
fmt.Printf("Firmata firmware: %s %d.%d\n", firmware.Name, firmware.Major, firmware.Minor)
|
||||||
|
|
||||||
|
capabilities, err := withTimeout(timeout, client.QueryCapabilities)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("query capabilities: %v", err)
|
||||||
|
}
|
||||||
|
fmt.Printf("Firmata pins described: %d\n", len(capabilities))
|
||||||
|
|
||||||
|
description, err := withTimeout(timeout, client.Describe)
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("describe rover peripheral: %v", err)
|
||||||
|
}
|
||||||
|
formatted, err := json.MarshalIndent(description, "", " ")
|
||||||
|
if err != nil {
|
||||||
|
log.Fatalf("format description: %v", err)
|
||||||
|
}
|
||||||
|
fmt.Printf("Peripheral description:\n%s\n", formatted)
|
||||||
|
|
||||||
|
if controlID != "" {
|
||||||
|
if err := exerciseControl(client, description, controlID, json.RawMessage(rawValue)); err != nil {
|
||||||
|
log.Fatalf("exercise control %q: %v", controlID, err)
|
||||||
|
}
|
||||||
|
fmt.Fprintf(os.Stdout, "Control %q accepted.\n", controlID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// withTimeout gives every boot-time exchange its own deadline. A missing board
|
||||||
|
// therefore reports the exact handshake stage that failed instead of consuming
|
||||||
|
// one shared timeout and obscuring which response was absent.
|
||||||
|
func withTimeout[T any](timeout time.Duration, operation func(context.Context) (T, error)) (T, error) {
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), timeout)
|
||||||
|
defer cancel()
|
||||||
|
return operation(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
func exerciseControl(client *roverd.FirmataClient, description roverd.PeripheralDescription, controlID string, rawValue json.RawMessage) error {
|
||||||
|
var selected *roverd.PeripheralControl
|
||||||
|
for index := range description.Controls {
|
||||||
|
if description.Controls[index].ID == controlID {
|
||||||
|
selected = &description.Controls[index]
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if selected == nil {
|
||||||
|
return errors.New("control is not present in the device description")
|
||||||
|
}
|
||||||
|
|
||||||
|
var value any
|
||||||
|
if err := json.Unmarshal(rawValue, &value); err != nil {
|
||||||
|
return fmt.Errorf("parse -value as JSON: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Standard outputs deliberately use standard Firmata commands. Only custom
|
||||||
|
// callbacks use the rover-peripheral CONTROL operation, which is the central
|
||||||
|
// distinction the probe is intended to validate on real hardware.
|
||||||
|
switch selected.Output.Type {
|
||||||
|
case "custom":
|
||||||
|
return client.SendPeripheralControl(selected.ID, value)
|
||||||
|
case "digital":
|
||||||
|
enabled, ok := value.(bool)
|
||||||
|
if !ok {
|
||||||
|
return errors.New("digital control value must be true or false")
|
||||||
|
}
|
||||||
|
if selected.Output.ActiveLow {
|
||||||
|
enabled = !enabled
|
||||||
|
}
|
||||||
|
if err := client.SetPinMode(byte(*selected.Output.Pin), roverd.FirmataPinModeOutput); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return client.SetDigitalPin(byte(*selected.Output.Pin), enabled)
|
||||||
|
case "pwm", "servo":
|
||||||
|
number, ok := value.(float64)
|
||||||
|
if !ok || number != float64(int(number)) {
|
||||||
|
return errors.New("PWM and servo control values must be whole numbers")
|
||||||
|
}
|
||||||
|
mode := roverd.FirmataPinModePWM
|
||||||
|
if selected.Output.Type == "servo" {
|
||||||
|
mode = roverd.FirmataPinModeServo
|
||||||
|
}
|
||||||
|
if err := client.SetPinMode(byte(*selected.Output.Pin), mode); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return client.ExtendedAnalog(byte(*selected.Output.Pin), int(number))
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("unsupported output %q", selected.Output.Type)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -3,6 +3,7 @@ package main
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"flag"
|
"flag"
|
||||||
|
"fmt"
|
||||||
"log"
|
"log"
|
||||||
"os"
|
"os"
|
||||||
"os/signal"
|
"os/signal"
|
||||||
@@ -29,6 +30,7 @@ func main() {
|
|||||||
defer cancel()
|
defer cancel()
|
||||||
|
|
||||||
logger := log.New(os.Stdout, "roverd: ", log.LstdFlags|log.Lmicroseconds|log.LUTC)
|
logger := log.New(os.Stdout, "roverd: ", log.LstdFlags|log.Lmicroseconds|log.LUTC)
|
||||||
|
console := roverd.NewConsoleNotifier(logger)
|
||||||
|
|
||||||
serialPort, err := roverd.OpenSerial(cfg.Serial)
|
serialPort, err := roverd.OpenSerial(cfg.Serial)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
@@ -36,6 +38,19 @@ func main() {
|
|||||||
}
|
}
|
||||||
defer serialPort.Close()
|
defer serialPort.Close()
|
||||||
|
|
||||||
|
// Peripheral discovery is intentionally a boot-time operation. The manager
|
||||||
|
// keeps successful USB ports open across server WebSocket reconnects and is
|
||||||
|
// rebuilt only when the roverd process itself restarts.
|
||||||
|
peripherals, err := roverd.DiscoverPeripheralManager(ctx, cfg.Serial.Device, logger)
|
||||||
|
if err != nil {
|
||||||
|
console.Notify(fmt.Sprintf("Rover peripheral startup failed: %v", err))
|
||||||
|
logger.Fatalf("discover rover peripherals: %v", err)
|
||||||
|
}
|
||||||
|
defer peripherals.Close()
|
||||||
|
for _, message := range peripherals.StartupBroadcasts() {
|
||||||
|
console.Notify(message)
|
||||||
|
}
|
||||||
|
|
||||||
var pulser *roverd.BRCPulser
|
var pulser *roverd.BRCPulser
|
||||||
if cfg.BRC.Enabled() {
|
if cfg.BRC.Enabled() {
|
||||||
pulser, err = roverd.NewBRCPulser(cfg.BRC, logger)
|
pulser, err = roverd.NewBRCPulser(cfg.BRC, logger)
|
||||||
@@ -60,37 +75,47 @@ func main() {
|
|||||||
mediaSupervisor.Start(ctx)
|
mediaSupervisor.Start(ctx)
|
||||||
}
|
}
|
||||||
|
|
||||||
var cameraServo *roverd.CameraServo
|
// Backend selection is identical on Pi and laptop hosts: enabled native
|
||||||
if cfg.CameraServo.Enabled {
|
// GPIO wins, otherwise a discovered ESP32 may provide the built-in role.
|
||||||
cameraServo, err = roverd.NewCameraServo(cfg.CameraServo, logger)
|
hardwareControllers, err := roverd.ResolveRoverHardwareControllers(cfg, peripherals, logger)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
logger.Fatalf("init camera servo: %v", err)
|
console.Notify(fmt.Sprintf("Rover peripheral startup failed while selecting hardware: %v", err))
|
||||||
}
|
logger.Fatalf("resolve rover hardware controllers: %v", err)
|
||||||
defer cameraServo.Close()
|
}
|
||||||
|
defer hardwareControllers.Close()
|
||||||
|
for _, message := range hardwareControllers.StartupBroadcasts() {
|
||||||
|
console.Notify(message)
|
||||||
}
|
}
|
||||||
|
|
||||||
var headlight *roverd.GPIOToggle
|
// A peripheral is never hot-reconnected. Report the first terminal serial
|
||||||
if cfg.Headlight.Enabled {
|
// failure for each discovered board and tell the local operator exactly what
|
||||||
headlight, err = roverd.NewGPIOToggle("headlight", cfg.Headlight, logger)
|
// recovery action the fixed boot-time lifecycle requires.
|
||||||
if err != nil {
|
go func() {
|
||||||
logger.Fatalf("init headlight: %v", err)
|
for {
|
||||||
|
select {
|
||||||
|
case failure := <-peripherals.Failures():
|
||||||
|
console.Notify(fmt.Sprintf(
|
||||||
|
"Rover peripheral %q (%s) disconnected: %v. Reconnect it and restart roverd.",
|
||||||
|
failure.Name,
|
||||||
|
failure.ID,
|
||||||
|
failure.Err,
|
||||||
|
))
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
}
|
||||||
}
|
}
|
||||||
defer headlight.Close()
|
}()
|
||||||
}
|
|
||||||
|
|
||||||
var laser *roverd.GPIOToggle
|
|
||||||
if cfg.Laser.Enabled {
|
|
||||||
laser, err = roverd.NewGPIOToggle("laser", cfg.Laser, logger)
|
|
||||||
if err != nil {
|
|
||||||
logger.Fatalf("init laser: %v", err)
|
|
||||||
}
|
|
||||||
defer laser.Close()
|
|
||||||
}
|
|
||||||
|
|
||||||
autoCharge := roverd.NewAutoChargeController(adapter, eventStream, logger)
|
autoCharge := roverd.NewAutoChargeController(adapter, eventStream, logger)
|
||||||
go autoCharge.Run(ctx, sensorSamples)
|
go autoCharge.Run(ctx, sensorSamples)
|
||||||
|
|
||||||
client := roverd.NewWSClient(cfg, adapter, sensorFrames, eventStream, mediaSupervisor, cameraServo, headlight, laser, logger)
|
client := roverd.NewWSClient(cfg, adapter, sensorFrames, eventStream, mediaSupervisor, hardwareControllers.CameraServo, hardwareControllers.Headlight, hardwareControllers.Laser, peripherals, logger, console)
|
||||||
|
|
||||||
|
// Startup is announced only after every configured hardware dependency has
|
||||||
|
// initialized successfully. A message here therefore means the control loop
|
||||||
|
// is genuinely ready, rather than merely that systemd launched the process.
|
||||||
|
console.Notify("roverd started and hardware initialization completed.")
|
||||||
|
defer console.Notify("roverd stopped.")
|
||||||
|
|
||||||
retryDelay := time.Second
|
retryDelay := time.Second
|
||||||
for ctx.Err() == nil {
|
for ctx.Err() == nil {
|
||||||
|
|||||||
+23
-13
@@ -1,19 +1,22 @@
|
|||||||
package roverd
|
package roverd
|
||||||
|
|
||||||
|
import "encoding/json"
|
||||||
|
|
||||||
type helloMessage struct {
|
type helloMessage struct {
|
||||||
Type string `json:"type"`
|
Type string `json:"type"`
|
||||||
Name string `json:"name"`
|
Name string `json:"name"`
|
||||||
Description string `json:"description,omitempty"`
|
Description string `json:"description,omitempty"`
|
||||||
Color string `json:"color,omitempty"`
|
Color string `json:"color,omitempty"`
|
||||||
Battery BatteryConfig `json:"battery"`
|
Battery BatteryConfig `json:"battery"`
|
||||||
MaxWheelSpeed int `json:"maxWheelSpeed"`
|
MaxWheelSpeed int `json:"maxWheelSpeed"`
|
||||||
Media MediaConfig `json:"media"`
|
Media MediaConfig `json:"media"`
|
||||||
CameraServo CameraServoConfig `json:"cameraServo"`
|
CameraServo CameraServoConfig `json:"cameraServo"`
|
||||||
Audio AudioConfig `json:"audio"`
|
Audio AudioConfig `json:"audio"`
|
||||||
Horn HornConfig `json:"horn"`
|
Horn HornConfig `json:"horn"`
|
||||||
Headlight GPIOToggleConfig `json:"headlight"`
|
Headlight GPIOToggleConfig `json:"headlight"`
|
||||||
Laser GPIOToggleConfig `json:"laser"`
|
Laser GPIOToggleConfig `json:"laser"`
|
||||||
Private PrivateConfig `json:"private"`
|
Peripherals []RoverPeripheralMetadata `json:"peripherals,omitempty"`
|
||||||
|
Private PrivateConfig `json:"private"`
|
||||||
}
|
}
|
||||||
|
|
||||||
type sensorMessage struct {
|
type sensorMessage struct {
|
||||||
@@ -45,6 +48,7 @@ type inboundMessage struct {
|
|||||||
AudioLevels *audioLevelsPayload `json:"audioLevels,omitempty"`
|
AudioLevels *audioLevelsPayload `json:"audioLevels,omitempty"`
|
||||||
Headlight *togglePayload `json:"headlight,omitempty"`
|
Headlight *togglePayload `json:"headlight,omitempty"`
|
||||||
Laser *togglePayload `json:"laser,omitempty"`
|
Laser *togglePayload `json:"laser,omitempty"`
|
||||||
|
Peripheral *peripheralPayload `json:"peripheral,omitempty"`
|
||||||
Song *songPayload `json:"song,omitempty"`
|
Song *songPayload `json:"song,omitempty"`
|
||||||
Reboot *rebootPayload `json:"reboot,omitempty"`
|
Reboot *rebootPayload `json:"reboot,omitempty"`
|
||||||
// Update is intentionally just a marker payload. The server can request the
|
// Update is intentionally just a marker payload. The server can request the
|
||||||
@@ -103,6 +107,12 @@ type togglePayload struct {
|
|||||||
Action string `json:"action"`
|
Action string `json:"action"`
|
||||||
}
|
}
|
||||||
|
|
||||||
|
type peripheralPayload struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Control string `json:"control"`
|
||||||
|
Value json.RawMessage `json:"value"`
|
||||||
|
}
|
||||||
|
|
||||||
type songPayload struct {
|
type songPayload struct {
|
||||||
Slot *int `json:"slot,omitempty"`
|
Slot *int `json:"slot,omitempty"`
|
||||||
Notes []songNote `json:"notes"`
|
Notes []songNote `json:"notes"`
|
||||||
|
|||||||
@@ -0,0 +1,67 @@
|
|||||||
|
package roverd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
const roverConsolePath = "/dev/tty1"
|
||||||
|
|
||||||
|
// ConsoleNotifier writes the small set of rover lifecycle events that must be
|
||||||
|
// visible even when nobody is logged in. This intentionally targets tty1
|
||||||
|
// directly instead of using wall: wall discovers recipients through utmp, so
|
||||||
|
// it does not reliably reach a virtual console that is only showing a login
|
||||||
|
// prompt.
|
||||||
|
type ConsoleNotifier struct {
|
||||||
|
path string
|
||||||
|
logger *log.Logger
|
||||||
|
mu sync.Mutex
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewConsoleNotifier returns the production notifier for the rover's primary
|
||||||
|
// local virtual console. Keeping the path inside the notifier also gives tests
|
||||||
|
// a way to substitute a regular temporary file without touching a real TTY.
|
||||||
|
func NewConsoleNotifier(logger *log.Logger) *ConsoleNotifier {
|
||||||
|
return newConsoleNotifier(roverConsolePath, logger)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newConsoleNotifier(path string, logger *log.Logger) *ConsoleNotifier {
|
||||||
|
return &ConsoleNotifier{path: path, logger: logger}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Notify appends one self-contained alert to the console. Console output is a
|
||||||
|
// diagnostic convenience rather than part of rover control, so an unavailable
|
||||||
|
// tty is logged but never allowed to stop startup, reconnection, docking, or
|
||||||
|
// reboot behavior.
|
||||||
|
func (n *ConsoleNotifier) Notify(message string) {
|
||||||
|
if n == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
n.mu.Lock()
|
||||||
|
defer n.mu.Unlock()
|
||||||
|
|
||||||
|
console, err := os.OpenFile(n.path, os.O_WRONLY|os.O_APPEND, 0)
|
||||||
|
if err != nil {
|
||||||
|
n.logFailure("open", err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
defer console.Close()
|
||||||
|
|
||||||
|
// Leading and trailing CRLFs keep the alert separate from an agetty login
|
||||||
|
// prompt, while plain text avoids leaving an unknown terminal in a modified
|
||||||
|
// color or cursor state.
|
||||||
|
timestamp := time.Now().UTC().Format("2006-01-02 15:04:05 UTC")
|
||||||
|
if _, err := fmt.Fprintf(console, "\r\n*** rover alert - %s ***\r\n%s\r\n", timestamp, message); err != nil {
|
||||||
|
n.logFailure("write", err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (n *ConsoleNotifier) logFailure(operation string, err error) {
|
||||||
|
if n.logger != nil {
|
||||||
|
n.logger.Printf("console notification %s failed for %s: %v", operation, n.path, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
package roverd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestConsoleNotifierWritesVisibleAlert(t *testing.T) {
|
||||||
|
path := filepath.Join(t.TempDir(), "tty1")
|
||||||
|
if err := os.WriteFile(path, nil, 0o600); err != nil {
|
||||||
|
t.Fatalf("create fake console: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
notifier := newConsoleNotifier(path, log.New(io.Discard, "", 0))
|
||||||
|
notifier.Notify("control server connection lost")
|
||||||
|
|
||||||
|
contents, err := os.ReadFile(path)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("read fake console: %v", err)
|
||||||
|
}
|
||||||
|
output := string(contents)
|
||||||
|
if !strings.Contains(output, "*** rover alert - ") {
|
||||||
|
t.Fatalf("alert header missing from %q", output)
|
||||||
|
}
|
||||||
|
if !strings.Contains(output, "control server connection lost") {
|
||||||
|
t.Fatalf("alert message missing from %q", output)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestConsoleNotifierTreatsMissingConsoleAsNonfatal(t *testing.T) {
|
||||||
|
// A missing TTY is normal on some headless or containerized hosts. The
|
||||||
|
// contract is therefore simply that Notify returns instead of escalating a
|
||||||
|
// display failure into a rover-process failure.
|
||||||
|
notifier := newConsoleNotifier(filepath.Join(t.TempDir(), "missing"), log.New(io.Discard, "", 0))
|
||||||
|
notifier.Notify("roverd started")
|
||||||
|
}
|
||||||
@@ -0,0 +1,664 @@
|
|||||||
|
package roverd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"sync"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Firmata command and mode constants are kept here instead of scattering raw
|
||||||
|
// bytes through the peripheral code. The values come directly from the Firmata
|
||||||
|
// protocol, so captures from a rover can be compared with the specification.
|
||||||
|
const (
|
||||||
|
firmataReportVersion byte = 0xF9
|
||||||
|
firmataSetPinMode byte = 0xF4
|
||||||
|
firmataSetDigitalPin byte = 0xF5
|
||||||
|
firmataStartSysex byte = 0xF0
|
||||||
|
firmataEndSysex byte = 0xF7
|
||||||
|
firmataReportFirmware byte = 0x79
|
||||||
|
firmataCapabilityQuery byte = 0x6B
|
||||||
|
firmataCapabilityReply byte = 0x6C
|
||||||
|
firmataExtendedAnalog byte = 0x6F
|
||||||
|
firmataServoConfig byte = 0x70
|
||||||
|
firmataPeripheralFeature byte = 0x01
|
||||||
|
|
||||||
|
firmataPeripheralDescribe byte = 0x00
|
||||||
|
firmataPeripheralDescription byte = 0x01
|
||||||
|
firmataPeripheralControl byte = 0x02
|
||||||
|
firmataMaximumSysexDataBytes = 252
|
||||||
|
|
||||||
|
FirmataPinModeOutput byte = 0x01
|
||||||
|
FirmataPinModePWM byte = 0x03
|
||||||
|
FirmataPinModeServo byte = 0x04
|
||||||
|
)
|
||||||
|
|
||||||
|
// FirmataMessage is the transport-neutral result of parsing one complete
|
||||||
|
// Firmata message. For SysEx messages Command is the SysEx feature byte and
|
||||||
|
// Data is everything between that feature byte and END_SYSEX.
|
||||||
|
type FirmataMessage struct {
|
||||||
|
Command byte
|
||||||
|
Data []byte
|
||||||
|
Sysex bool
|
||||||
|
}
|
||||||
|
|
||||||
|
// FirmataParser incrementally parses a byte stream. USB serial reads may split
|
||||||
|
// a message anywhere or combine several messages, so parsing whole Read calls
|
||||||
|
// as though they were packets would intermittently corrupt valid traffic.
|
||||||
|
type FirmataParser struct {
|
||||||
|
inSysex bool
|
||||||
|
sysex []byte
|
||||||
|
command byte
|
||||||
|
data []byte
|
||||||
|
expected int
|
||||||
|
}
|
||||||
|
|
||||||
|
// Feed accepts any fragment of the serial stream and returns every complete
|
||||||
|
// message found in it, preserving wire order.
|
||||||
|
func (p *FirmataParser) Feed(fragment []byte) ([]FirmataMessage, error) {
|
||||||
|
var messages []FirmataMessage
|
||||||
|
|
||||||
|
for _, value := range fragment {
|
||||||
|
if p.inSysex {
|
||||||
|
switch {
|
||||||
|
case value == firmataEndSysex:
|
||||||
|
if len(p.sysex) == 0 {
|
||||||
|
p.resetSysex()
|
||||||
|
return messages, errors.New("Firmata SysEx message is missing a feature byte")
|
||||||
|
}
|
||||||
|
messages = append(messages, FirmataMessage{
|
||||||
|
Command: p.sysex[0],
|
||||||
|
Data: append([]byte(nil), p.sysex[1:]...),
|
||||||
|
Sysex: true,
|
||||||
|
})
|
||||||
|
p.resetSysex()
|
||||||
|
case value&0x80 != 0:
|
||||||
|
// Bytes inside SysEx must be seven-bit clean. Reset immediately so
|
||||||
|
// a damaged frame cannot consume every later message on the port.
|
||||||
|
p.resetSysex()
|
||||||
|
return messages, fmt.Errorf("invalid 8-bit value 0x%02x inside Firmata SysEx", value)
|
||||||
|
default:
|
||||||
|
p.sysex = append(p.sysex, value)
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if value == firmataStartSysex {
|
||||||
|
p.inSysex = true
|
||||||
|
p.sysex = p.sysex[:0]
|
||||||
|
p.resetFixed()
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
if value&0x80 != 0 {
|
||||||
|
p.command = value
|
||||||
|
p.data = p.data[:0]
|
||||||
|
p.expected = firmataDataLength(value)
|
||||||
|
if p.expected == 0 {
|
||||||
|
messages = append(messages, FirmataMessage{Command: value})
|
||||||
|
p.resetFixed()
|
||||||
|
}
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// Stray data before a status byte is harmless serial noise. Firmata
|
||||||
|
// has no framing information that could assign it to a command.
|
||||||
|
if p.expected == 0 {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
p.data = append(p.data, value)
|
||||||
|
if len(p.data) == p.expected {
|
||||||
|
messages = append(messages, FirmataMessage{
|
||||||
|
Command: p.command,
|
||||||
|
Data: append([]byte(nil), p.data...),
|
||||||
|
})
|
||||||
|
p.resetFixed()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return messages, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *FirmataParser) resetSysex() {
|
||||||
|
p.inSysex = false
|
||||||
|
p.sysex = p.sysex[:0]
|
||||||
|
}
|
||||||
|
|
||||||
|
func (p *FirmataParser) resetFixed() {
|
||||||
|
p.command = 0
|
||||||
|
p.data = p.data[:0]
|
||||||
|
p.expected = 0
|
||||||
|
}
|
||||||
|
|
||||||
|
// firmataDataLength returns the number of seven-bit data bytes used by the
|
||||||
|
// fixed-length messages relevant to normal Firmata traffic. Unknown system
|
||||||
|
// commands are treated as single-byte messages so they cannot stall parsing of
|
||||||
|
// the rover-peripheral SysEx frames that follow them.
|
||||||
|
func firmataDataLength(command byte) int {
|
||||||
|
switch command {
|
||||||
|
case firmataReportVersion, firmataSetPinMode, firmataSetDigitalPin:
|
||||||
|
return 2
|
||||||
|
}
|
||||||
|
|
||||||
|
switch command & 0xF0 {
|
||||||
|
case 0x80, 0x90, 0xA0, 0xE0:
|
||||||
|
return 2
|
||||||
|
case 0xC0, 0xD0:
|
||||||
|
return 1
|
||||||
|
default:
|
||||||
|
return 0
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// EncodeFirmata7Bit converts arbitrary bytes into the two-byte representation
|
||||||
|
// required inside Firmata SysEx. Keeping this transform below the JSON layer
|
||||||
|
// means firmware authors and UI code never need to think about wire encoding.
|
||||||
|
func EncodeFirmata7Bit(raw []byte) []byte {
|
||||||
|
encoded := make([]byte, 0, len(raw)*2)
|
||||||
|
for _, value := range raw {
|
||||||
|
encoded = append(encoded, value&0x7F, (value>>7)&0x01)
|
||||||
|
}
|
||||||
|
return encoded
|
||||||
|
}
|
||||||
|
|
||||||
|
// DecodeFirmata7Bit reverses EncodeFirmata7Bit and rejects malformed pairs.
|
||||||
|
func DecodeFirmata7Bit(encoded []byte) ([]byte, error) {
|
||||||
|
if len(encoded)%2 != 0 {
|
||||||
|
return nil, fmt.Errorf("Firmata 7-bit payload has odd length %d", len(encoded))
|
||||||
|
}
|
||||||
|
|
||||||
|
decoded := make([]byte, 0, len(encoded)/2)
|
||||||
|
for index := 0; index < len(encoded); index += 2 {
|
||||||
|
low, high := encoded[index], encoded[index+1]
|
||||||
|
if low&0x80 != 0 || high > 1 {
|
||||||
|
return nil, fmt.Errorf("invalid Firmata 7-bit pair at byte %d", index)
|
||||||
|
}
|
||||||
|
decoded = append(decoded, low|(high<<7))
|
||||||
|
}
|
||||||
|
return decoded, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// PeripheralDescription is generated by the ESP32 at boot. Controls is a slice
|
||||||
|
// intentionally: registration order is part of the UI contract and must never
|
||||||
|
// be replaced by map iteration or alphabetical sorting.
|
||||||
|
type PeripheralDescription struct {
|
||||||
|
Name string `json:"name"`
|
||||||
|
RoverControls PeripheralRoverControls `json:"roverControls,omitempty"`
|
||||||
|
Controls []PeripheralControl `json:"controls"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PeripheralRoverControls struct {
|
||||||
|
CameraServo *PeripheralCameraServo `json:"cameraServo,omitempty"`
|
||||||
|
Headlight *PeripheralDigitalRole `json:"headlight,omitempty"`
|
||||||
|
Laser *PeripheralDigitalRole `json:"laser,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PeripheralCameraServo struct {
|
||||||
|
Pin int `json:"pin"`
|
||||||
|
MinimumAngleDegrees float64 `json:"minimumAngleDegrees"`
|
||||||
|
MaximumAngleDegrees float64 `json:"maximumAngleDegrees"`
|
||||||
|
HomeAngleDegrees float64 `json:"homeAngleDegrees"`
|
||||||
|
NudgeDegrees float64 `json:"nudgeDegrees"`
|
||||||
|
MinimumPulseMicroseconds int `json:"minimumPulseMicroseconds"`
|
||||||
|
MaximumPulseMicroseconds int `json:"maximumPulseMicroseconds"`
|
||||||
|
AllowRawPulse bool `json:"allowRawPulse"`
|
||||||
|
Inverted bool `json:"inverted"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PeripheralDigitalRole struct {
|
||||||
|
Pin int `json:"pin"`
|
||||||
|
ActiveLow bool `json:"activeLow"`
|
||||||
|
InitiallyOn bool `json:"initiallyOn"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PeripheralControl struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Mode string `json:"mode,omitempty"`
|
||||||
|
Minimum *int `json:"min,omitempty"`
|
||||||
|
Maximum *int `json:"max,omitempty"`
|
||||||
|
MaximumLength *int `json:"maxLength,omitempty"`
|
||||||
|
Output PeripheralOutput `json:"output"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type PeripheralOutput struct {
|
||||||
|
Type string `json:"type"`
|
||||||
|
Pin *int `json:"pin,omitempty"`
|
||||||
|
ActiveLow bool `json:"activeLow,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// Validate catches authoring mistakes at connection time, where the error can
|
||||||
|
// name the offending peripheral, instead of allowing a malformed declaration
|
||||||
|
// to turn into a confusing no-op later when a driver uses the control.
|
||||||
|
func (description PeripheralDescription) Validate() error {
|
||||||
|
if description.Name == "" {
|
||||||
|
return errors.New("peripheral description requires a name")
|
||||||
|
}
|
||||||
|
if camera := description.RoverControls.CameraServo; camera != nil {
|
||||||
|
if err := validateFirmataPin("cameraServo", camera.Pin); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if camera.MinimumAngleDegrees >= camera.MaximumAngleDegrees {
|
||||||
|
return errors.New("cameraServo angle range must be increasing")
|
||||||
|
}
|
||||||
|
if camera.HomeAngleDegrees < camera.MinimumAngleDegrees || camera.HomeAngleDegrees > camera.MaximumAngleDegrees {
|
||||||
|
return errors.New("cameraServo home angle must be inside its angle range")
|
||||||
|
}
|
||||||
|
if camera.NudgeDegrees <= 0 {
|
||||||
|
return errors.New("cameraServo nudge must be positive")
|
||||||
|
}
|
||||||
|
if camera.MinimumPulseMicroseconds <= 0 || camera.MaximumPulseMicroseconds <= camera.MinimumPulseMicroseconds {
|
||||||
|
return errors.New("cameraServo pulse range must be positive and increasing")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if role := description.RoverControls.Headlight; role != nil {
|
||||||
|
if err := validateFirmataPin("headlight", role.Pin); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if role := description.RoverControls.Laser; role != nil {
|
||||||
|
if err := validateFirmataPin("laser", role.Pin); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
seen := make(map[string]struct{}, len(description.Controls))
|
||||||
|
for index, control := range description.Controls {
|
||||||
|
if control.ID == "" || control.Name == "" {
|
||||||
|
return fmt.Errorf("control %d requires both id and name", index)
|
||||||
|
}
|
||||||
|
if _, exists := seen[control.ID]; exists {
|
||||||
|
return fmt.Errorf("control id %q is duplicated", control.ID)
|
||||||
|
}
|
||||||
|
seen[control.ID] = struct{}{}
|
||||||
|
|
||||||
|
switch control.Type {
|
||||||
|
case "slider", "number":
|
||||||
|
if control.Minimum == nil || control.Maximum == nil || *control.Minimum > *control.Maximum {
|
||||||
|
return fmt.Errorf("control %q requires a valid min and max", control.ID)
|
||||||
|
}
|
||||||
|
case "button":
|
||||||
|
if control.Mode != "toggle" && control.Mode != "momentary" {
|
||||||
|
return fmt.Errorf("button %q requires toggle or momentary mode", control.ID)
|
||||||
|
}
|
||||||
|
case "text":
|
||||||
|
if control.MaximumLength == nil || *control.MaximumLength <= 0 {
|
||||||
|
return fmt.Errorf("text control %q requires a positive maxLength", control.ID)
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("control %q has unsupported type %q", control.ID, control.Type)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch control.Output.Type {
|
||||||
|
case "digital":
|
||||||
|
if control.Output.Pin == nil {
|
||||||
|
return fmt.Errorf("control %q output %q requires a pin", control.ID, control.Output.Type)
|
||||||
|
}
|
||||||
|
if err := validateFirmataPin("control "+control.ID, *control.Output.Pin); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if control.Type != "button" {
|
||||||
|
return fmt.Errorf("digital output control %q must be a button", control.ID)
|
||||||
|
}
|
||||||
|
case "pwm", "servo":
|
||||||
|
if control.Output.Pin == nil {
|
||||||
|
return fmt.Errorf("control %q output %q requires a pin", control.ID, control.Output.Type)
|
||||||
|
}
|
||||||
|
if err := validateFirmataPin("control "+control.ID, *control.Output.Pin); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if control.Type != "slider" && control.Type != "number" {
|
||||||
|
return fmt.Errorf("%s output control %q must be a slider or number", control.Output.Type, control.ID)
|
||||||
|
}
|
||||||
|
case "custom":
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("control %q has unsupported output %q", control.ID, control.Output.Type)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func validateFirmataPin(owner string, pin int) error {
|
||||||
|
// Firmata represents pin numbers with one seven-bit byte. Rejecting values
|
||||||
|
// outside that wire range avoids silently wrapping a declaration when it is
|
||||||
|
// converted to a byte for output commands.
|
||||||
|
if pin < 0 || pin > 127 {
|
||||||
|
return fmt.Errorf("%s pin must be between 0 and 127", owner)
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// FirmataFirmware identifies the implementation answering the standard
|
||||||
|
// REPORT_FIRMWARE query. It is diagnostic metadata, not a protocol gate.
|
||||||
|
type FirmataFirmware struct {
|
||||||
|
Major int
|
||||||
|
Minor int
|
||||||
|
Name string
|
||||||
|
}
|
||||||
|
|
||||||
|
// FirmataPinCapability is one mode/resolution pair from CAPABILITY_RESPONSE.
|
||||||
|
type FirmataPinCapability struct {
|
||||||
|
Mode byte
|
||||||
|
Resolution byte
|
||||||
|
}
|
||||||
|
|
||||||
|
// FirmataClient owns one already-open serial connection. Its reader goroutine
|
||||||
|
// separates arbitrary USB read boundaries from request/response handling while
|
||||||
|
// writeMu prevents two commands from interleaving on the byte stream.
|
||||||
|
type FirmataClient struct {
|
||||||
|
connection io.ReadWriteCloser
|
||||||
|
parser FirmataParser
|
||||||
|
messages chan FirmataMessage
|
||||||
|
errors chan error
|
||||||
|
writeMu sync.Mutex
|
||||||
|
requestMu sync.Mutex
|
||||||
|
stateMu sync.RWMutex
|
||||||
|
terminalErr error
|
||||||
|
// terminalErrorHandler is invoked only for the first non-timeout read
|
||||||
|
// failure while the client context remains active. PeripheralManager uses it
|
||||||
|
// to turn an unexpected USB loss into one operator-facing broadcast.
|
||||||
|
terminalErrorHandler func(error)
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewFirmataClient(connection io.ReadWriteCloser) *FirmataClient {
|
||||||
|
return &FirmataClient{
|
||||||
|
connection: connection,
|
||||||
|
messages: make(chan FirmataMessage, 16),
|
||||||
|
errors: make(chan error, 1),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Start begins consuming the serial stream. The caller still owns the port and
|
||||||
|
// closes it during shutdown; this makes the client usable with both real serial
|
||||||
|
// ports and deterministic in-memory test connections.
|
||||||
|
func (client *FirmataClient) Start(ctx context.Context) {
|
||||||
|
go client.readLoop(ctx)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (client *FirmataClient) readLoop(ctx context.Context) {
|
||||||
|
buffer := make([]byte, 256)
|
||||||
|
for {
|
||||||
|
count, err := client.connection.Read(buffer)
|
||||||
|
if count > 0 {
|
||||||
|
messages, parseErr := client.parser.Feed(buffer[:count])
|
||||||
|
if parseErr != nil {
|
||||||
|
client.publishError(ctx, parseErr)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, message := range messages {
|
||||||
|
select {
|
||||||
|
case client.messages <- message:
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
if errors.Is(err, io.EOF) {
|
||||||
|
// tarm/serial represents an ordinary ReadTimeout with io.EOF. A
|
||||||
|
// Firmata connection is expected to be quiet between commands, so
|
||||||
|
// treating that timeout as a closed device kills the reader before
|
||||||
|
// the next request can receive its reply. A real USB removal is
|
||||||
|
// reported by the serial driver as a non-EOF error.
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
}
|
||||||
|
client.publishError(ctx, err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case <-ctx.Done():
|
||||||
|
return
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (client *FirmataClient) publishError(ctx context.Context, err error) {
|
||||||
|
firstTerminalError, handler := client.recordTerminalError(err)
|
||||||
|
if firstTerminalError && handler != nil && ctx.Err() == nil {
|
||||||
|
handler(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
select {
|
||||||
|
case client.errors <- err:
|
||||||
|
case <-ctx.Done():
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (client *FirmataClient) recordTerminalError(err error) (bool, func(error)) {
|
||||||
|
client.stateMu.Lock()
|
||||||
|
defer client.stateMu.Unlock()
|
||||||
|
firstTerminalError := client.terminalErr == nil
|
||||||
|
if client.terminalErr == nil {
|
||||||
|
client.terminalErr = err
|
||||||
|
}
|
||||||
|
handler := client.terminalErrorHandler
|
||||||
|
return firstTerminalError, handler
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetTerminalErrorHandler registers the one-shot observer used after a device
|
||||||
|
// has completed discovery. If the connection already failed, the observer is
|
||||||
|
// called immediately so a narrow handshake-to-registration race is not lost.
|
||||||
|
func (client *FirmataClient) SetTerminalErrorHandler(handler func(error)) {
|
||||||
|
client.stateMu.Lock()
|
||||||
|
client.terminalErrorHandler = handler
|
||||||
|
terminalErr := client.terminalErr
|
||||||
|
client.stateMu.Unlock()
|
||||||
|
if terminalErr != nil && handler != nil {
|
||||||
|
handler(terminalErr)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (client *FirmataClient) write(message []byte) error {
|
||||||
|
client.writeMu.Lock()
|
||||||
|
defer client.writeMu.Unlock()
|
||||||
|
client.stateMu.RLock()
|
||||||
|
terminalErr := client.terminalErr
|
||||||
|
client.stateMu.RUnlock()
|
||||||
|
if terminalErr != nil {
|
||||||
|
return fmt.Errorf("Firmata connection unavailable: %w", terminalErr)
|
||||||
|
}
|
||||||
|
|
||||||
|
written, err := client.connection.Write(message)
|
||||||
|
if err != nil {
|
||||||
|
firstTerminalError, handler := client.recordTerminalError(err)
|
||||||
|
if firstTerminalError && handler != nil {
|
||||||
|
handler(err)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
if written != len(message) {
|
||||||
|
err := fmt.Errorf("short Firmata write %d/%d", written, len(message))
|
||||||
|
firstTerminalError, handler := client.recordTerminalError(err)
|
||||||
|
if firstTerminalError && handler != nil {
|
||||||
|
handler(err)
|
||||||
|
}
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (client *FirmataClient) writeSysex(command byte, data []byte) error {
|
||||||
|
message := make([]byte, 0, len(data)+3)
|
||||||
|
message = append(message, firmataStartSysex, command)
|
||||||
|
message = append(message, data...)
|
||||||
|
message = append(message, firmataEndSysex)
|
||||||
|
return client.write(message)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (client *FirmataClient) waitFor(ctx context.Context, match func(FirmataMessage) bool) (FirmataMessage, error) {
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case message := <-client.messages:
|
||||||
|
if match(message) {
|
||||||
|
return message, nil
|
||||||
|
}
|
||||||
|
case err := <-client.errors:
|
||||||
|
return FirmataMessage{}, err
|
||||||
|
case <-ctx.Done():
|
||||||
|
return FirmataMessage{}, ctx.Err()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (client *FirmataClient) QueryFirmware(ctx context.Context) (FirmataFirmware, error) {
|
||||||
|
client.requestMu.Lock()
|
||||||
|
defer client.requestMu.Unlock()
|
||||||
|
|
||||||
|
if err := client.writeSysex(firmataReportFirmware, nil); err != nil {
|
||||||
|
return FirmataFirmware{}, err
|
||||||
|
}
|
||||||
|
message, err := client.waitFor(ctx, func(message FirmataMessage) bool {
|
||||||
|
return message.Sysex && message.Command == firmataReportFirmware
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return FirmataFirmware{}, err
|
||||||
|
}
|
||||||
|
if len(message.Data) < 2 {
|
||||||
|
return FirmataFirmware{}, errors.New("Firmata firmware response is missing version bytes")
|
||||||
|
}
|
||||||
|
name, err := DecodeFirmata7Bit(message.Data[2:])
|
||||||
|
if err != nil {
|
||||||
|
return FirmataFirmware{}, fmt.Errorf("decode Firmata firmware name: %w", err)
|
||||||
|
}
|
||||||
|
return FirmataFirmware{Major: int(message.Data[0]), Minor: int(message.Data[1]), Name: string(name)}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (client *FirmataClient) QueryCapabilities(ctx context.Context) ([][]FirmataPinCapability, error) {
|
||||||
|
client.requestMu.Lock()
|
||||||
|
defer client.requestMu.Unlock()
|
||||||
|
|
||||||
|
if err := client.writeSysex(firmataCapabilityQuery, nil); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
message, err := client.waitFor(ctx, func(message FirmataMessage) bool {
|
||||||
|
return message.Sysex && message.Command == firmataCapabilityReply
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return parseFirmataCapabilities(message.Data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func parseFirmataCapabilities(data []byte) ([][]FirmataPinCapability, error) {
|
||||||
|
var pins [][]FirmataPinCapability
|
||||||
|
var pin []FirmataPinCapability
|
||||||
|
for index := 0; index < len(data); {
|
||||||
|
if data[index] == 0x7F {
|
||||||
|
pins = append(pins, pin)
|
||||||
|
pin = nil
|
||||||
|
index++
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if index+1 >= len(data) {
|
||||||
|
return nil, errors.New("Firmata capability response ends inside a mode pair")
|
||||||
|
}
|
||||||
|
pin = append(pin, FirmataPinCapability{Mode: data[index], Resolution: data[index+1]})
|
||||||
|
index += 2
|
||||||
|
}
|
||||||
|
if pin != nil {
|
||||||
|
return nil, errors.New("Firmata capability response is missing its final pin separator")
|
||||||
|
}
|
||||||
|
return pins, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (client *FirmataClient) Describe(ctx context.Context) (PeripheralDescription, error) {
|
||||||
|
client.requestMu.Lock()
|
||||||
|
defer client.requestMu.Unlock()
|
||||||
|
|
||||||
|
if err := client.writeSysex(firmataPeripheralFeature, []byte{firmataPeripheralDescribe}); err != nil {
|
||||||
|
return PeripheralDescription{}, err
|
||||||
|
}
|
||||||
|
message, err := client.waitFor(ctx, func(message FirmataMessage) bool {
|
||||||
|
return message.Sysex && message.Command == firmataPeripheralFeature && len(message.Data) > 0 && message.Data[0] == firmataPeripheralDescription
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
return PeripheralDescription{}, err
|
||||||
|
}
|
||||||
|
|
||||||
|
raw, err := DecodeFirmata7Bit(message.Data[1:])
|
||||||
|
if err != nil {
|
||||||
|
return PeripheralDescription{}, fmt.Errorf("decode peripheral description: %w", err)
|
||||||
|
}
|
||||||
|
var description PeripheralDescription
|
||||||
|
if err := json.Unmarshal(raw, &description); err != nil {
|
||||||
|
return PeripheralDescription{}, fmt.Errorf("parse peripheral description: %w", err)
|
||||||
|
}
|
||||||
|
if err := description.Validate(); err != nil {
|
||||||
|
return PeripheralDescription{}, fmt.Errorf("validate peripheral description: %w", err)
|
||||||
|
}
|
||||||
|
return description, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (client *FirmataClient) SetPinMode(pin, mode byte) error {
|
||||||
|
return client.write([]byte{firmataSetPinMode, pin & 0x7F, mode & 0x7F})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (client *FirmataClient) SetDigitalPin(pin byte, enabled bool) error {
|
||||||
|
value := byte(0)
|
||||||
|
if enabled {
|
||||||
|
value = 1
|
||||||
|
}
|
||||||
|
return client.write([]byte{firmataSetDigitalPin, pin & 0x7F, value})
|
||||||
|
}
|
||||||
|
|
||||||
|
func (client *FirmataClient) ExtendedAnalog(pin byte, value int) error {
|
||||||
|
if value < 0 {
|
||||||
|
return fmt.Errorf("Firmata analog value cannot be negative: %d", value)
|
||||||
|
}
|
||||||
|
|
||||||
|
payload := []byte{pin & 0x7F}
|
||||||
|
// Firmata encodes integers as many seven-bit chunks as necessary. Zero
|
||||||
|
// still needs one value byte so the receiver can distinguish it from a
|
||||||
|
// message that contains only the pin.
|
||||||
|
for {
|
||||||
|
payload = append(payload, byte(value&0x7F))
|
||||||
|
value >>= 7
|
||||||
|
if value == 0 {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return client.writeSysex(firmataExtendedAnalog, payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (client *FirmataClient) ConfigureServo(pin byte, minimumPulseMicroseconds, maximumPulseMicroseconds int) error {
|
||||||
|
if minimumPulseMicroseconds <= 0 || maximumPulseMicroseconds <= minimumPulseMicroseconds {
|
||||||
|
return errors.New("servo pulse range must be positive and increasing")
|
||||||
|
}
|
||||||
|
payload := []byte{
|
||||||
|
pin & 0x7F,
|
||||||
|
byte(minimumPulseMicroseconds & 0x7F), byte((minimumPulseMicroseconds >> 7) & 0x7F),
|
||||||
|
byte(maximumPulseMicroseconds & 0x7F), byte((maximumPulseMicroseconds >> 7) & 0x7F),
|
||||||
|
}
|
||||||
|
return client.writeSysex(firmataServoConfig, payload)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (client *FirmataClient) SendPeripheralControl(controlID string, value any) error {
|
||||||
|
payload, err := json.Marshal(struct {
|
||||||
|
Control string `json:"control"`
|
||||||
|
Value any `json:"value"`
|
||||||
|
}{Control: controlID, Value: value})
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("encode peripheral control: %w", err)
|
||||||
|
}
|
||||||
|
data := append([]byte{firmataPeripheralControl}, EncodeFirmata7Bit(payload)...)
|
||||||
|
// ConfigurableFirmata on ESP32 stores at most 252 bytes including the SysEx
|
||||||
|
// feature byte. Refuse a value that the board would otherwise discard as an
|
||||||
|
// incomplete frame; this is a transport constraint, not an application-level
|
||||||
|
// text policy.
|
||||||
|
if len(data)+1 > firmataMaximumSysexDataBytes {
|
||||||
|
return fmt.Errorf("peripheral control needs %d SysEx data bytes; Firmata accepts at most %d", len(data)+1, firmataMaximumSysexDataBytes)
|
||||||
|
}
|
||||||
|
return client.writeSysex(firmataPeripheralFeature, data)
|
||||||
|
}
|
||||||
@@ -0,0 +1,304 @@
|
|||||||
|
package roverd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"math"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// FirmataCameraServo preserves the established logical camera movement model
|
||||||
|
// while replacing only the final physical write. The ESP32 receives ordinary
|
||||||
|
// Firmata servo configuration and angle messages, regardless of rover host.
|
||||||
|
type FirmataCameraServo struct {
|
||||||
|
cfg CameraServoConfig
|
||||||
|
client *FirmataClient
|
||||||
|
pin byte
|
||||||
|
peripheralID string
|
||||||
|
mu sync.Mutex
|
||||||
|
currentAngle float64
|
||||||
|
desiredAngle float64
|
||||||
|
lastMove time.Time
|
||||||
|
moving bool
|
||||||
|
stopCh chan struct{}
|
||||||
|
closed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func newFirmataCameraServo(peripheral *managedPeripheral, declaration PeripheralCameraServo, logger *log.Logger) (*FirmataCameraServo, error) {
|
||||||
|
cfg := CameraServoConfig{
|
||||||
|
Enabled: true,
|
||||||
|
Pin: declaration.Pin,
|
||||||
|
FreqHz: 50,
|
||||||
|
CycleLen: 20000,
|
||||||
|
MinPulseUs: declaration.MinimumPulseMicroseconds,
|
||||||
|
MaxPulseUs: declaration.MaximumPulseMicroseconds,
|
||||||
|
MinAngle: declaration.MinimumAngleDegrees,
|
||||||
|
MaxAngle: declaration.MaximumAngleDegrees,
|
||||||
|
HomeAngle: declaration.HomeAngleDegrees,
|
||||||
|
NudgeDegrees: declaration.NudgeDegrees,
|
||||||
|
AllowRawPulse: declaration.AllowRawPulse,
|
||||||
|
Invert: declaration.Inverted,
|
||||||
|
}
|
||||||
|
servo := &FirmataCameraServo{
|
||||||
|
cfg: cfg,
|
||||||
|
client: peripheral.client,
|
||||||
|
pin: byte(declaration.Pin),
|
||||||
|
peripheralID: peripheral.metadata.ID,
|
||||||
|
stopCh: make(chan struct{}),
|
||||||
|
}
|
||||||
|
|
||||||
|
// SERVO_CONFIG establishes the peripheral-owned pulse calibration before
|
||||||
|
// selecting servo mode. This is standard Firmata, not a rover extension.
|
||||||
|
if err := servo.client.ConfigureServo(servo.pin, cfg.MinPulseUs, cfg.MaxPulseUs); err != nil {
|
||||||
|
return nil, fmt.Errorf("configure Firmata servo: %w", err)
|
||||||
|
}
|
||||||
|
if err := servo.client.SetPinMode(servo.pin, FirmataPinModeServo); err != nil {
|
||||||
|
return nil, fmt.Errorf("select Firmata servo mode: %w", err)
|
||||||
|
}
|
||||||
|
if err := servo.setAngleLocked(cfg.HomeAngle); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
logger.Printf("camera servo using ESP32 %s pin %d (%.1f..%.1f deg)", peripheral.metadata.ID, declaration.Pin, cfg.MinAngle, cfg.MaxAngle)
|
||||||
|
return servo, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (servo *FirmataCameraServo) SetAngle(angle float64) error {
|
||||||
|
servo.mu.Lock()
|
||||||
|
defer servo.mu.Unlock()
|
||||||
|
return servo.setAngleLocked(angle)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (servo *FirmataCameraServo) setAngleLocked(angle float64) error {
|
||||||
|
if servo.closed {
|
||||||
|
return errorsNewControllerClosed("camera servo")
|
||||||
|
}
|
||||||
|
servo.desiredAngle = clampFloat(angle, servo.cfg.MinAngle, servo.cfg.MaxAngle)
|
||||||
|
limited := servo.rateLimitAngleLocked(servo.desiredAngle)
|
||||||
|
if err := servo.writeAngleLocked(limited); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
servo.currentAngle = limited
|
||||||
|
if math.Abs(limited-servo.desiredAngle) > servoAngleEpsilon {
|
||||||
|
servo.startMoveLoopLocked()
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (servo *FirmataCameraServo) Nudge(delta float64) error {
|
||||||
|
servo.mu.Lock()
|
||||||
|
defer servo.mu.Unlock()
|
||||||
|
if delta == 0 {
|
||||||
|
delta = servo.cfg.NudgeDegrees
|
||||||
|
}
|
||||||
|
return servo.setAngleLocked(servo.currentAngle + delta)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (servo *FirmataCameraServo) SetPulseWidth(micros int) error {
|
||||||
|
servo.mu.Lock()
|
||||||
|
defer servo.mu.Unlock()
|
||||||
|
if !servo.cfg.AllowRawPulse {
|
||||||
|
return fmt.Errorf("raw pulse commands disabled")
|
||||||
|
}
|
||||||
|
if micros <= 0 {
|
||||||
|
return fmt.Errorf("pulse width must be > 0")
|
||||||
|
}
|
||||||
|
pulse := clampInt(micros, servo.cfg.MinPulseUs, servo.cfg.MaxPulseUs)
|
||||||
|
return servo.setAngleLocked(servo.pulseToAngle(pulse))
|
||||||
|
}
|
||||||
|
|
||||||
|
func (servo *FirmataCameraServo) CurrentAngle() float64 {
|
||||||
|
servo.mu.Lock()
|
||||||
|
defer servo.mu.Unlock()
|
||||||
|
return servo.currentAngle
|
||||||
|
}
|
||||||
|
|
||||||
|
func (servo *FirmataCameraServo) Configuration() CameraServoConfig {
|
||||||
|
return servo.cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
func (servo *FirmataCameraServo) BackendDescription() string {
|
||||||
|
return "ESP32 " + servo.peripheralID
|
||||||
|
}
|
||||||
|
|
||||||
|
func (servo *FirmataCameraServo) Close() {
|
||||||
|
servo.mu.Lock()
|
||||||
|
defer servo.mu.Unlock()
|
||||||
|
if servo.closed {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Returning home matches the native Pi implementation. Any write failure is
|
||||||
|
// ignored during shutdown because the serial connection may already be gone.
|
||||||
|
_ = servo.writeAngleLocked(servo.cfg.HomeAngle)
|
||||||
|
close(servo.stopCh)
|
||||||
|
servo.closed = true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (servo *FirmataCameraServo) writeAngleLocked(angle float64) error {
|
||||||
|
rangeDegrees := servo.cfg.MaxAngle - servo.cfg.MinAngle
|
||||||
|
normalized := (angle - servo.cfg.MinAngle) / rangeDegrees
|
||||||
|
normalized = math.Max(0, math.Min(1, normalized))
|
||||||
|
if servo.cfg.Invert {
|
||||||
|
normalized = 1 - normalized
|
||||||
|
}
|
||||||
|
// Standard Firmata servo values are positions from 0 through 180. Pulse
|
||||||
|
// calibration was already supplied through SERVO_CONFIG above.
|
||||||
|
position := int(math.Round(normalized * 180))
|
||||||
|
return servo.client.ExtendedAnalog(servo.pin, position)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (servo *FirmataCameraServo) pulseToAngle(pulse int) float64 {
|
||||||
|
normalized := float64(pulse-servo.cfg.MinPulseUs) / float64(servo.cfg.MaxPulseUs-servo.cfg.MinPulseUs)
|
||||||
|
if servo.cfg.Invert {
|
||||||
|
normalized = 1 - normalized
|
||||||
|
}
|
||||||
|
return servo.cfg.MinAngle + normalized*(servo.cfg.MaxAngle-servo.cfg.MinAngle)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (servo *FirmataCameraServo) rateLimitAngleLocked(target float64) float64 {
|
||||||
|
now := time.Now()
|
||||||
|
if servo.lastMove.IsZero() {
|
||||||
|
servo.lastMove = now
|
||||||
|
}
|
||||||
|
elapsed := now.Sub(servo.lastMove).Seconds()
|
||||||
|
if elapsed > servoStepInterval.Seconds() {
|
||||||
|
elapsed = servoStepInterval.Seconds()
|
||||||
|
}
|
||||||
|
maximumDelta := maxServoDegPerSec * elapsed
|
||||||
|
delta := target - servo.currentAngle
|
||||||
|
if math.Abs(delta) <= maximumDelta {
|
||||||
|
servo.lastMove = now
|
||||||
|
return target
|
||||||
|
}
|
||||||
|
servo.lastMove = now
|
||||||
|
if delta > 0 {
|
||||||
|
return servo.currentAngle + maximumDelta
|
||||||
|
}
|
||||||
|
return servo.currentAngle - maximumDelta
|
||||||
|
}
|
||||||
|
|
||||||
|
func (servo *FirmataCameraServo) startMoveLoopLocked() {
|
||||||
|
if servo.moving || servo.closed {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
servo.moving = true
|
||||||
|
go func() {
|
||||||
|
ticker := time.NewTicker(servoStepInterval)
|
||||||
|
defer ticker.Stop()
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ticker.C:
|
||||||
|
servo.mu.Lock()
|
||||||
|
if servo.closed || math.Abs(servo.currentAngle-servo.desiredAngle) <= servoAngleEpsilon {
|
||||||
|
servo.moving = false
|
||||||
|
servo.mu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
limited := servo.rateLimitAngleLocked(servo.desiredAngle)
|
||||||
|
if err := servo.writeAngleLocked(limited); err != nil {
|
||||||
|
// A failed serial write makes further automatic steps pointless.
|
||||||
|
// The next user command returns the connection error normally.
|
||||||
|
servo.moving = false
|
||||||
|
servo.mu.Unlock()
|
||||||
|
return
|
||||||
|
}
|
||||||
|
servo.currentAngle = limited
|
||||||
|
servo.mu.Unlock()
|
||||||
|
case <-servo.stopCh:
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}()
|
||||||
|
}
|
||||||
|
|
||||||
|
// FirmataToggle owns logical state exactly like GPIOToggle but sends the final
|
||||||
|
// electrical level through Firmata's standard digital-pin command.
|
||||||
|
type FirmataToggle struct {
|
||||||
|
cfg GPIOToggleConfig
|
||||||
|
name string
|
||||||
|
client *FirmataClient
|
||||||
|
pin byte
|
||||||
|
peripheralID string
|
||||||
|
mu sync.Mutex
|
||||||
|
on bool
|
||||||
|
closed bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func newFirmataToggle(name string, peripheral *managedPeripheral, declaration PeripheralDigitalRole, logger *log.Logger) (*FirmataToggle, error) {
|
||||||
|
cfg := GPIOToggleConfig{Enabled: true, GPIOPin: declaration.Pin, InitialOn: declaration.InitiallyOn, ActiveLow: declaration.ActiveLow}
|
||||||
|
toggle := &FirmataToggle{
|
||||||
|
cfg: cfg,
|
||||||
|
name: name,
|
||||||
|
client: peripheral.client,
|
||||||
|
pin: byte(declaration.Pin),
|
||||||
|
peripheralID: peripheral.metadata.ID,
|
||||||
|
on: cfg.InitialOn,
|
||||||
|
}
|
||||||
|
if err := toggle.client.SetPinMode(toggle.pin, FirmataPinModeOutput); err != nil {
|
||||||
|
return nil, fmt.Errorf("select Firmata output mode: %w", err)
|
||||||
|
}
|
||||||
|
if err := toggle.writeLocked(toggle.on); err != nil {
|
||||||
|
return nil, fmt.Errorf("initialize Firmata output: %w", err)
|
||||||
|
}
|
||||||
|
logger.Printf("%s using ESP32 %s pin %d (initial=%v activeLow=%v)", name, peripheral.metadata.ID, declaration.Pin, cfg.InitialOn, cfg.ActiveLow)
|
||||||
|
return toggle, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (toggle *FirmataToggle) HandleAction(action string) error {
|
||||||
|
toggle.mu.Lock()
|
||||||
|
defer toggle.mu.Unlock()
|
||||||
|
if toggle.closed {
|
||||||
|
return errorsNewControllerClosed(toggle.name)
|
||||||
|
}
|
||||||
|
switch strings.ToLower(strings.TrimSpace(action)) {
|
||||||
|
case "", "toggle":
|
||||||
|
return toggle.setLocked(!toggle.on)
|
||||||
|
case "on":
|
||||||
|
return toggle.setLocked(true)
|
||||||
|
case "off":
|
||||||
|
return toggle.setLocked(false)
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("unknown action %q", action)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (toggle *FirmataToggle) setLocked(on bool) error {
|
||||||
|
if err := toggle.writeLocked(on); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
toggle.on = on
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (toggle *FirmataToggle) writeLocked(on bool) error {
|
||||||
|
physicalHigh := on
|
||||||
|
if toggle.cfg.ActiveLow {
|
||||||
|
physicalHigh = !physicalHigh
|
||||||
|
}
|
||||||
|
return toggle.client.SetDigitalPin(toggle.pin, physicalHigh)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (toggle *FirmataToggle) On() bool {
|
||||||
|
toggle.mu.Lock()
|
||||||
|
defer toggle.mu.Unlock()
|
||||||
|
return toggle.on
|
||||||
|
}
|
||||||
|
|
||||||
|
func (toggle *FirmataToggle) Configuration() GPIOToggleConfig {
|
||||||
|
return toggle.cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
func (toggle *FirmataToggle) BackendDescription() string {
|
||||||
|
return "ESP32 " + toggle.peripheralID
|
||||||
|
}
|
||||||
|
|
||||||
|
func (toggle *FirmataToggle) Close() {
|
||||||
|
toggle.mu.Lock()
|
||||||
|
defer toggle.mu.Unlock()
|
||||||
|
toggle.closed = true
|
||||||
|
}
|
||||||
|
|
||||||
|
func errorsNewControllerClosed(name string) error {
|
||||||
|
return fmt.Errorf("%s controller closed", name)
|
||||||
|
}
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
package roverd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"log"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestDisabledNativeRolesResolveToFirmataOnEveryHostBuild(t *testing.T) {
|
||||||
|
description := PeripheralDescription{
|
||||||
|
Name: "Rover GPIO",
|
||||||
|
RoverControls: PeripheralRoverControls{
|
||||||
|
CameraServo: &PeripheralCameraServo{
|
||||||
|
Pin: 14, MinimumAngleDegrees: -15, MaximumAngleDegrees: 30,
|
||||||
|
HomeAngleDegrees: 0, NudgeDegrees: 2,
|
||||||
|
MinimumPulseMicroseconds: 900, MaximumPulseMicroseconds: 2100,
|
||||||
|
},
|
||||||
|
Headlight: &PeripheralDigitalRole{Pin: 18, ActiveLow: true, InitiallyOn: true},
|
||||||
|
Laser: &PeripheralDigitalRole{Pin: 16, ActiveLow: false, InitiallyOn: false},
|
||||||
|
},
|
||||||
|
Controls: []PeripheralControl{},
|
||||||
|
}
|
||||||
|
connection := scriptedPeripheralConnection(t, description)
|
||||||
|
manager, err := discoverPeripheralManager(
|
||||||
|
context.Background(),
|
||||||
|
"/dev/roomba",
|
||||||
|
discardLogger(),
|
||||||
|
testPeripheralDiscoveryDependencies([]string{"/dev/rover-gpio"}, map[string]*scriptedConnection{"/dev/rover-gpio": connection}),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("discover: %v", err)
|
||||||
|
}
|
||||||
|
defer manager.Close()
|
||||||
|
|
||||||
|
// All native entries are disabled, exactly as they can be on either a Pi or
|
||||||
|
// laptop rover. The shared resolver must therefore select every ESP32 role.
|
||||||
|
baseline := len(connection.Bytes())
|
||||||
|
controllers, err := ResolveRoverHardwareControllers(&Config{}, manager, discardLogger())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("resolve: %v", err)
|
||||||
|
}
|
||||||
|
defer controllers.Close()
|
||||||
|
if controllers.CameraServo == nil || controllers.Headlight == nil || controllers.Laser == nil {
|
||||||
|
t.Fatalf("missing Firmata controller: %#v", controllers)
|
||||||
|
}
|
||||||
|
if !controllers.CameraServo.Configuration().Enabled || !controllers.Headlight.Configuration().Enabled || !controllers.Laser.Configuration().Enabled {
|
||||||
|
t.Fatal("ESP32-backed roles were not advertised as enabled")
|
||||||
|
}
|
||||||
|
wantHardwareBroadcast := "Rover hardware ready: camera servo via ESP32 firmata-0, headlight via ESP32 firmata-0, laser via ESP32 firmata-0."
|
||||||
|
if messages := controllers.StartupBroadcasts(); len(messages) != 1 || messages[0] != wantHardwareBroadcast {
|
||||||
|
t.Fatalf("hardware broadcasts = %#v, want %q", messages, wantHardwareBroadcast)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Initialization uses only standard Firmata: servo calibration and mode,
|
||||||
|
// followed by the home position and digital initial states. The active-low
|
||||||
|
// headlight starts logically on, so its physical output is low.
|
||||||
|
writes := connection.Bytes()[baseline:]
|
||||||
|
wantPrefix := []byte{
|
||||||
|
firmataStartSysex, firmataServoConfig, 14, 4, 7, 52, 16, firmataEndSysex,
|
||||||
|
firmataSetPinMode, 14, FirmataPinModeServo,
|
||||||
|
firmataStartSysex, firmataExtendedAnalog, 14, 60, firmataEndSysex,
|
||||||
|
firmataSetPinMode, 18, FirmataPinModeOutput,
|
||||||
|
firmataSetDigitalPin, 18, 0,
|
||||||
|
firmataSetPinMode, 16, FirmataPinModeOutput,
|
||||||
|
firmataSetDigitalPin, 16, 0,
|
||||||
|
}
|
||||||
|
if !bytes.Equal(writes, wantPrefix) {
|
||||||
|
t.Fatalf("initial controller bytes = %v, want %v", writes, wantPrefix)
|
||||||
|
}
|
||||||
|
|
||||||
|
baseline = len(connection.Bytes())
|
||||||
|
if err := controllers.Headlight.HandleAction("off"); err != nil {
|
||||||
|
t.Fatalf("turn headlight off: %v", err)
|
||||||
|
}
|
||||||
|
if controllers.Headlight.On() {
|
||||||
|
t.Fatal("headlight remained logically on")
|
||||||
|
}
|
||||||
|
// Active-low means logical off becomes a high electrical output.
|
||||||
|
if got, want := connection.Bytes()[baseline:], []byte{firmataSetDigitalPin, 18, 1}; !bytes.Equal(got, want) {
|
||||||
|
t.Fatalf("headlight bytes = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestMissingNativeAndFirmataRolesRemainDisabled(t *testing.T) {
|
||||||
|
manager := &PeripheralManager{byID: make(map[string]*managedPeripheral)}
|
||||||
|
controllers, err := ResolveRoverHardwareControllers(&Config{}, manager, discardLogger())
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("resolve: %v", err)
|
||||||
|
}
|
||||||
|
if controllers.CameraServo != nil || controllers.Headlight != nil || controllers.Laser != nil {
|
||||||
|
t.Fatalf("unexpected controllers without providers: %#v", controllers)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestEnabledNativeRolesWinEvenWithSeveralFirmataProviders(t *testing.T) {
|
||||||
|
roleDescription := PeripheralDescription{RoverControls: PeripheralRoverControls{
|
||||||
|
CameraServo: &PeripheralCameraServo{},
|
||||||
|
Headlight: &PeripheralDigitalRole{},
|
||||||
|
Laser: &PeripheralDigitalRole{},
|
||||||
|
}}
|
||||||
|
manager := &PeripheralManager{
|
||||||
|
byID: make(map[string]*managedPeripheral),
|
||||||
|
peripherals: []*managedPeripheral{
|
||||||
|
{metadata: RoverPeripheralMetadata{ID: "firmata-0"}, description: roleDescription},
|
||||||
|
{metadata: RoverPeripheralMetadata{ID: "firmata-1"}, description: roleDescription},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
cfg := &Config{
|
||||||
|
CameraServo: CameraServoConfig{Enabled: true},
|
||||||
|
Headlight: GPIOToggleConfig{Enabled: true},
|
||||||
|
Laser: GPIOToggleConfig{Enabled: true},
|
||||||
|
}
|
||||||
|
nativeCamera := &testCameraServoController{cfg: cfg.CameraServo}
|
||||||
|
nativeToggles := map[string]*testToggleController{}
|
||||||
|
factories := nativeHardwareControllerFactories{
|
||||||
|
newCameraServo: func(_ CameraServoConfig, _ *log.Logger) (CameraServoController, error) {
|
||||||
|
return nativeCamera, nil
|
||||||
|
},
|
||||||
|
newToggle: func(name string, config GPIOToggleConfig, _ *log.Logger) (ToggleController, error) {
|
||||||
|
controller := &testToggleController{cfg: config}
|
||||||
|
nativeToggles[name] = controller
|
||||||
|
return controller, nil
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
// Duplicate Firmata declarations are irrelevant when native hardware wins;
|
||||||
|
// selection must neither fail nor initialize either ESP32 provider.
|
||||||
|
controllers, err := resolveRoverHardwareControllers(cfg, manager, discardLogger(), factories)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("resolve native precedence: %v", err)
|
||||||
|
}
|
||||||
|
if controllers.CameraServo != nativeCamera || controllers.Headlight != nativeToggles["headlight"] || controllers.Laser != nativeToggles["laser"] {
|
||||||
|
t.Fatal("resolver did not retain native controllers")
|
||||||
|
}
|
||||||
|
messages := controllers.StartupBroadcasts()
|
||||||
|
if len(messages) != 2 || messages[0] != "Ignored ESP32 camera servo, headlight, laser because native GPIO is enabled." || messages[1] != "Rover hardware ready: camera servo via native GPIO, headlight via native GPIO, laser via native GPIO." {
|
||||||
|
t.Fatalf("native precedence broadcasts = %#v", messages)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
type testCameraServoController struct {
|
||||||
|
cfg CameraServoConfig
|
||||||
|
}
|
||||||
|
|
||||||
|
func (controller *testCameraServoController) SetAngle(float64) error { return nil }
|
||||||
|
func (controller *testCameraServoController) Nudge(float64) error { return nil }
|
||||||
|
func (controller *testCameraServoController) SetPulseWidth(int) error { return nil }
|
||||||
|
func (controller *testCameraServoController) CurrentAngle() float64 { return 0 }
|
||||||
|
func (controller *testCameraServoController) Configuration() CameraServoConfig { return controller.cfg }
|
||||||
|
func (controller *testCameraServoController) BackendDescription() string { return "native GPIO" }
|
||||||
|
func (controller *testCameraServoController) Close() {}
|
||||||
|
|
||||||
|
type testToggleController struct {
|
||||||
|
cfg GPIOToggleConfig
|
||||||
|
on bool
|
||||||
|
}
|
||||||
|
|
||||||
|
func (controller *testToggleController) HandleAction(string) error { return nil }
|
||||||
|
func (controller *testToggleController) On() bool { return controller.on }
|
||||||
|
func (controller *testToggleController) Configuration() GPIOToggleConfig { return controller.cfg }
|
||||||
|
func (controller *testToggleController) BackendDescription() string { return "native GPIO" }
|
||||||
|
func (controller *testToggleController) Close() {}
|
||||||
@@ -0,0 +1,441 @@
|
|||||||
|
package roverd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"io"
|
||||||
|
"reflect"
|
||||||
|
"sync"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestFirmataParserHandlesFragmentedSysex(t *testing.T) {
|
||||||
|
parser := FirmataParser{}
|
||||||
|
|
||||||
|
first, err := parser.Feed([]byte{firmataStartSysex, firmataPeripheralFeature, firmataPeripheralDescription, 1})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("first fragment: %v", err)
|
||||||
|
}
|
||||||
|
if len(first) != 0 {
|
||||||
|
t.Fatalf("first fragment unexpectedly produced %d messages", len(first))
|
||||||
|
}
|
||||||
|
|
||||||
|
second, err := parser.Feed([]byte{0, 2, 0, firmataEndSysex})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("second fragment: %v", err)
|
||||||
|
}
|
||||||
|
want := []FirmataMessage{{
|
||||||
|
Command: firmataPeripheralFeature,
|
||||||
|
Data: []byte{firmataPeripheralDescription, 1, 0, 2, 0},
|
||||||
|
Sysex: true,
|
||||||
|
}}
|
||||||
|
if !reflect.DeepEqual(second, want) {
|
||||||
|
t.Fatalf("messages = %#v, want %#v", second, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFirmataParserReturnsSeveralMessagesFromOneRead(t *testing.T) {
|
||||||
|
parser := FirmataParser{}
|
||||||
|
messages, err := parser.Feed([]byte{
|
||||||
|
firmataReportVersion, 2, 5,
|
||||||
|
firmataStartSysex, firmataCapabilityReply, 0x01, 0x01, 0x7F, firmataEndSysex,
|
||||||
|
firmataSetDigitalPin, 18, 1,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("feed: %v", err)
|
||||||
|
}
|
||||||
|
if len(messages) != 3 {
|
||||||
|
t.Fatalf("got %d messages, want 3", len(messages))
|
||||||
|
}
|
||||||
|
if messages[0].Command != firmataReportVersion || messages[1].Command != firmataCapabilityReply || messages[2].Command != firmataSetDigitalPin {
|
||||||
|
t.Fatalf("commands were not preserved in wire order: %#v", messages)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFirmataParserRejectsEightBitSysexDataAndRecovers(t *testing.T) {
|
||||||
|
parser := FirmataParser{}
|
||||||
|
if _, err := parser.Feed([]byte{firmataStartSysex, firmataPeripheralFeature, 0x80}); err == nil {
|
||||||
|
t.Fatal("expected invalid SysEx data to fail")
|
||||||
|
}
|
||||||
|
|
||||||
|
messages, err := parser.Feed([]byte{firmataReportVersion, 2, 5})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("feed after invalid SysEx: %v", err)
|
||||||
|
}
|
||||||
|
if len(messages) != 1 || messages[0].Command != firmataReportVersion {
|
||||||
|
t.Fatalf("parser did not recover: %#v", messages)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFirmataSevenBitRoundTripIncludesUTF8(t *testing.T) {
|
||||||
|
raw := []byte(`{"name":"Café lights","value":255}`)
|
||||||
|
encoded := EncodeFirmata7Bit(raw)
|
||||||
|
for index, value := range encoded {
|
||||||
|
if value&0x80 != 0 {
|
||||||
|
t.Fatalf("encoded byte %d is not seven-bit clean: 0x%02x", index, value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
decoded, err := DecodeFirmata7Bit(encoded)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("decode: %v", err)
|
||||||
|
}
|
||||||
|
if !bytes.Equal(decoded, raw) {
|
||||||
|
t.Fatalf("decoded %q, want %q", decoded, raw)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestDecodeFirmataSevenBitRejectsMalformedPairs(t *testing.T) {
|
||||||
|
for name, encoded := range map[string][]byte{
|
||||||
|
"odd length": {1},
|
||||||
|
"high byte": {1, 2},
|
||||||
|
"eight bit": {0x80, 0},
|
||||||
|
} {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
if _, err := DecodeFirmata7Bit(encoded); err == nil {
|
||||||
|
t.Fatal("expected malformed pair to fail")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPeripheralDescriptionPreservesControlOrder(t *testing.T) {
|
||||||
|
raw := []byte(`{
|
||||||
|
"name":"Test peripheral",
|
||||||
|
"controls":[
|
||||||
|
{"id":"servo","type":"slider","name":"Servo","min":0,"max":180,"output":{"type":"servo","pin":14}},
|
||||||
|
{"id":"lights","type":"slider","name":"Lights","min":0,"max":255,"output":{"type":"pwm","pin":18}},
|
||||||
|
{"id":"action","type":"button","name":"Action","mode":"momentary","output":{"type":"custom"}}
|
||||||
|
]
|
||||||
|
}`)
|
||||||
|
var description PeripheralDescription
|
||||||
|
if err := json.Unmarshal(raw, &description); err != nil {
|
||||||
|
t.Fatalf("unmarshal: %v", err)
|
||||||
|
}
|
||||||
|
if err := description.Validate(); err != nil {
|
||||||
|
t.Fatalf("validate: %v", err)
|
||||||
|
}
|
||||||
|
want := []string{"servo", "lights", "action"}
|
||||||
|
for index, id := range want {
|
||||||
|
if description.Controls[index].ID != id {
|
||||||
|
t.Fatalf("control %d = %q, want %q", index, description.Controls[index].ID, id)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPeripheralDescriptionRejectsInvalidDeclarations(t *testing.T) {
|
||||||
|
minimum, maximum, pin := 10, 1, 200
|
||||||
|
for name, description := range map[string]PeripheralDescription{
|
||||||
|
"duplicate id": {
|
||||||
|
Name: "device",
|
||||||
|
Controls: []PeripheralControl{
|
||||||
|
{ID: "same", Name: "First", Type: "button", Mode: "toggle", Output: PeripheralOutput{Type: "custom"}},
|
||||||
|
{ID: "same", Name: "Second", Type: "button", Mode: "toggle", Output: PeripheralOutput{Type: "custom"}},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
"reversed range": {
|
||||||
|
Name: "device",
|
||||||
|
Controls: []PeripheralControl{{
|
||||||
|
ID: "level", Name: "Level", Type: "slider", Minimum: &minimum, Maximum: &maximum, Output: PeripheralOutput{Type: "custom"},
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
"pin outside Firmata": {
|
||||||
|
Name: "device",
|
||||||
|
Controls: []PeripheralControl{{
|
||||||
|
ID: "switch", Name: "Switch", Type: "button", Mode: "toggle", Output: PeripheralOutput{Type: "digital", Pin: &pin},
|
||||||
|
}},
|
||||||
|
},
|
||||||
|
} {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
if err := description.Validate(); err == nil {
|
||||||
|
t.Fatal("expected invalid description to fail")
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestParseFirmataCapabilities(t *testing.T) {
|
||||||
|
pins, err := parseFirmataCapabilities([]byte{
|
||||||
|
FirmataPinModeOutput, 1, FirmataPinModePWM, 8, 0x7F,
|
||||||
|
FirmataPinModeOutput, 1, FirmataPinModeServo, 14, 0x7F,
|
||||||
|
})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("parse capabilities: %v", err)
|
||||||
|
}
|
||||||
|
if len(pins) != 2 || len(pins[0]) != 2 || pins[1][1].Mode != FirmataPinModeServo {
|
||||||
|
t.Fatalf("unexpected capabilities: %#v", pins)
|
||||||
|
}
|
||||||
|
|
||||||
|
if _, err := parseFirmataCapabilities([]byte{FirmataPinModeOutput}); err == nil {
|
||||||
|
t.Fatal("expected incomplete capability pair to fail")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFirmataClientWritesStandardCommands(t *testing.T) {
|
||||||
|
connection := &recordingConnection{}
|
||||||
|
client := NewFirmataClient(connection)
|
||||||
|
|
||||||
|
if err := client.SetPinMode(14, FirmataPinModeServo); err != nil {
|
||||||
|
t.Fatalf("set pin mode: %v", err)
|
||||||
|
}
|
||||||
|
if err := client.ConfigureServo(14, 900, 2100); err != nil {
|
||||||
|
t.Fatalf("configure servo: %v", err)
|
||||||
|
}
|
||||||
|
if err := client.ExtendedAnalog(14, 180); err != nil {
|
||||||
|
t.Fatalf("extended analog: %v", err)
|
||||||
|
}
|
||||||
|
if err := client.SetDigitalPin(19, true); err != nil {
|
||||||
|
t.Fatalf("digital write: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
want := []byte{
|
||||||
|
firmataSetPinMode, 14, FirmataPinModeServo,
|
||||||
|
firmataStartSysex, firmataServoConfig, 14, 4, 7, 52, 16, firmataEndSysex,
|
||||||
|
firmataStartSysex, firmataExtendedAnalog, 14, 52, 1, firmataEndSysex,
|
||||||
|
firmataSetDigitalPin, 19, 1,
|
||||||
|
}
|
||||||
|
if got := connection.Bytes(); !bytes.Equal(got, want) {
|
||||||
|
t.Fatalf("wire bytes = %v, want %v", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFirmataClientQueriesAndDecodesDescription(t *testing.T) {
|
||||||
|
descriptionJSON := []byte(`{"name":"Bench device","controls":[{"id":"go","type":"button","name":"Go","mode":"momentary","output":{"type":"custom"}}]}`)
|
||||||
|
firmwareName := EncodeFirmata7Bit([]byte("RoverPeripheralFirmata"))
|
||||||
|
description := append([]byte{firmataStartSysex, firmataPeripheralFeature, firmataPeripheralDescription}, EncodeFirmata7Bit(descriptionJSON)...)
|
||||||
|
description = append(description, firmataEndSysex)
|
||||||
|
|
||||||
|
connection := newScriptedConnection(
|
||||||
|
append(append([]byte{firmataStartSysex, firmataReportFirmware, 1, 0}, firmwareName...), firmataEndSysex),
|
||||||
|
description,
|
||||||
|
)
|
||||||
|
client := NewFirmataClient(connection)
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||||
|
defer cancel()
|
||||||
|
client.Start(ctx)
|
||||||
|
|
||||||
|
firmware, err := client.QueryFirmware(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("query firmware: %v", err)
|
||||||
|
}
|
||||||
|
if firmware.Name != "RoverPeripheralFirmata" || firmware.Major != 1 || firmware.Minor != 0 {
|
||||||
|
t.Fatalf("unexpected firmware: %#v", firmware)
|
||||||
|
}
|
||||||
|
|
||||||
|
got, err := client.Describe(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("describe: %v", err)
|
||||||
|
}
|
||||||
|
if got.Name != "Bench device" || len(got.Controls) != 1 || got.Controls[0].ID != "go" {
|
||||||
|
t.Fatalf("unexpected description: %#v", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
writes := connection.Bytes()
|
||||||
|
wantWrites := []byte{
|
||||||
|
firmataStartSysex, firmataReportFirmware, firmataEndSysex,
|
||||||
|
firmataStartSysex, firmataPeripheralFeature, firmataPeripheralDescribe, firmataEndSysex,
|
||||||
|
}
|
||||||
|
if !bytes.Equal(writes, wantWrites) {
|
||||||
|
t.Fatalf("queries = %v, want %v", writes, wantWrites)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFirmataClientKeepsReadingAfterSerialTimeoutEOF(t *testing.T) {
|
||||||
|
firmwareName := EncodeFirmata7Bit([]byte("RoverPeripheralFirmata"))
|
||||||
|
response := append([]byte{firmataStartSysex, firmataReportFirmware, 1, 0}, firmwareName...)
|
||||||
|
response = append(response, firmataEndSysex)
|
||||||
|
|
||||||
|
// tarm/serial returns io.EOF when its ReadTimeout expires without bytes.
|
||||||
|
// Reproducing that behavior before the response prevents this regression
|
||||||
|
// from being hidden by an in-memory reader that blocks indefinitely instead.
|
||||||
|
connection := newScriptedConnection(response)
|
||||||
|
connection.timeoutsBeforeRead = 1
|
||||||
|
client := NewFirmataClient(connection)
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||||
|
defer cancel()
|
||||||
|
client.Start(ctx)
|
||||||
|
|
||||||
|
firmware, err := client.QueryFirmware(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("query firmware after timeout: %v", err)
|
||||||
|
}
|
||||||
|
if firmware.Name != "RoverPeripheralFirmata" {
|
||||||
|
t.Fatalf("firmware name = %q", firmware.Name)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFirmataClientEncodesCustomControl(t *testing.T) {
|
||||||
|
for name, testCase := range map[string]struct {
|
||||||
|
controlID string
|
||||||
|
value any
|
||||||
|
wantJSON string
|
||||||
|
}{
|
||||||
|
"button": {controlID: "specialAction", value: true, wantJSON: `{"control":"specialAction","value":true}`},
|
||||||
|
"text": {controlID: "displayText", value: "Café ready", wantJSON: `{"control":"displayText","value":"Café ready"}`},
|
||||||
|
} {
|
||||||
|
t.Run(name, func(t *testing.T) {
|
||||||
|
connection := &recordingConnection{}
|
||||||
|
client := NewFirmataClient(connection)
|
||||||
|
if err := client.SendPeripheralControl(testCase.controlID, testCase.value); err != nil {
|
||||||
|
t.Fatalf("send control: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
wire := connection.Bytes()
|
||||||
|
if len(wire) < 5 || wire[0] != firmataStartSysex || wire[1] != firmataPeripheralFeature || wire[2] != firmataPeripheralControl || wire[len(wire)-1] != firmataEndSysex {
|
||||||
|
t.Fatalf("invalid control frame: %v", wire)
|
||||||
|
}
|
||||||
|
raw, err := DecodeFirmata7Bit(wire[3 : len(wire)-1])
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("decode control: %v", err)
|
||||||
|
}
|
||||||
|
if string(raw) != testCase.wantJSON {
|
||||||
|
t.Fatalf("control JSON = %s, want %s", raw, testCase.wantJSON)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFirmataClientQueriesCapabilities(t *testing.T) {
|
||||||
|
response := []byte{
|
||||||
|
firmataStartSysex, firmataCapabilityReply,
|
||||||
|
FirmataPinModeOutput, 1, FirmataPinModePWM, 8, 0x7F,
|
||||||
|
FirmataPinModeOutput, 1, FirmataPinModeServo, 14, 0x7F,
|
||||||
|
firmataEndSysex,
|
||||||
|
}
|
||||||
|
connection := newScriptedConnection(response)
|
||||||
|
client := NewFirmataClient(connection)
|
||||||
|
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
|
||||||
|
defer cancel()
|
||||||
|
client.Start(ctx)
|
||||||
|
|
||||||
|
pins, err := client.QueryCapabilities(ctx)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("query capabilities: %v", err)
|
||||||
|
}
|
||||||
|
if len(pins) != 2 || pins[0][1].Mode != FirmataPinModePWM || pins[1][1].Mode != FirmataPinModeServo {
|
||||||
|
t.Fatalf("unexpected capabilities: %#v", pins)
|
||||||
|
}
|
||||||
|
if want := []byte{firmataStartSysex, firmataCapabilityQuery, firmataEndSysex}; !bytes.Equal(connection.Bytes(), want) {
|
||||||
|
t.Fatalf("query bytes = %v, want %v", connection.Bytes(), want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestFirmataClientRejectsControlTooLargeForFirmwareParser(t *testing.T) {
|
||||||
|
connection := &recordingConnection{}
|
||||||
|
client := NewFirmataClient(connection)
|
||||||
|
if err := client.SendPeripheralControl("displayText", string(bytes.Repeat([]byte{'x'}, 200))); err == nil {
|
||||||
|
t.Fatal("expected oversized control to fail")
|
||||||
|
}
|
||||||
|
if len(connection.Bytes()) != 0 {
|
||||||
|
t.Fatalf("oversized control wrote bytes: %v", connection.Bytes())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// recordingConnection is deliberately minimal: write-focused tests should not
|
||||||
|
// need goroutines or a real serial device merely to inspect exact Firmata bytes.
|
||||||
|
type recordingConnection struct {
|
||||||
|
mu sync.Mutex
|
||||||
|
writes bytes.Buffer
|
||||||
|
closed bool
|
||||||
|
writeErr error
|
||||||
|
}
|
||||||
|
|
||||||
|
func (connection *recordingConnection) Read(_ []byte) (int, error) { return 0, io.EOF }
|
||||||
|
|
||||||
|
func (connection *recordingConnection) Write(data []byte) (int, error) {
|
||||||
|
connection.mu.Lock()
|
||||||
|
defer connection.mu.Unlock()
|
||||||
|
if connection.closed {
|
||||||
|
return 0, io.ErrClosedPipe
|
||||||
|
}
|
||||||
|
if connection.writeErr != nil {
|
||||||
|
return 0, connection.writeErr
|
||||||
|
}
|
||||||
|
return connection.writes.Write(data)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (connection *recordingConnection) Close() error {
|
||||||
|
connection.mu.Lock()
|
||||||
|
defer connection.mu.Unlock()
|
||||||
|
connection.closed = true
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (connection *recordingConnection) Bytes() []byte {
|
||||||
|
connection.mu.Lock()
|
||||||
|
defer connection.mu.Unlock()
|
||||||
|
return append([]byte(nil), connection.writes.Bytes()...)
|
||||||
|
}
|
||||||
|
|
||||||
|
func (connection *recordingConnection) Closed() bool {
|
||||||
|
connection.mu.Lock()
|
||||||
|
defer connection.mu.Unlock()
|
||||||
|
return connection.closed
|
||||||
|
}
|
||||||
|
|
||||||
|
func (connection *recordingConnection) SetWriteError(err error) {
|
||||||
|
connection.mu.Lock()
|
||||||
|
defer connection.mu.Unlock()
|
||||||
|
connection.writeErr = err
|
||||||
|
}
|
||||||
|
|
||||||
|
// scriptedConnection releases one response after each client write. This
|
||||||
|
// mirrors request/response serial behavior and prevents a fast reader goroutine
|
||||||
|
// from publishing all scripted answers before the matching query is sent.
|
||||||
|
type scriptedConnection struct {
|
||||||
|
recordingConnection
|
||||||
|
responses chan []byte
|
||||||
|
reads chan []byte
|
||||||
|
timeoutsBeforeRead int
|
||||||
|
pendingRead []byte
|
||||||
|
closeOnce sync.Once
|
||||||
|
}
|
||||||
|
|
||||||
|
func newScriptedConnection(responses ...[]byte) *scriptedConnection {
|
||||||
|
connection := &scriptedConnection{
|
||||||
|
responses: make(chan []byte, len(responses)),
|
||||||
|
reads: make(chan []byte, len(responses)),
|
||||||
|
}
|
||||||
|
for _, response := range responses {
|
||||||
|
connection.responses <- append([]byte(nil), response...)
|
||||||
|
}
|
||||||
|
return connection
|
||||||
|
}
|
||||||
|
|
||||||
|
func (connection *scriptedConnection) Read(target []byte) (int, error) {
|
||||||
|
if connection.timeoutsBeforeRead > 0 {
|
||||||
|
connection.timeoutsBeforeRead--
|
||||||
|
return 0, io.EOF
|
||||||
|
}
|
||||||
|
if len(connection.pendingRead) == 0 {
|
||||||
|
response, ok := <-connection.reads
|
||||||
|
if !ok {
|
||||||
|
return 0, io.ErrClosedPipe
|
||||||
|
}
|
||||||
|
connection.pendingRead = response
|
||||||
|
}
|
||||||
|
written := copy(target, connection.pendingRead)
|
||||||
|
connection.pendingRead = connection.pendingRead[written:]
|
||||||
|
return written, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (connection *scriptedConnection) Write(data []byte) (int, error) {
|
||||||
|
written, err := connection.recordingConnection.Write(data)
|
||||||
|
if err == nil {
|
||||||
|
select {
|
||||||
|
case response := <-connection.responses:
|
||||||
|
connection.reads <- response
|
||||||
|
default:
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return written, err
|
||||||
|
}
|
||||||
|
|
||||||
|
func (connection *scriptedConnection) Close() error {
|
||||||
|
connection.closeOnce.Do(func() {
|
||||||
|
_ = connection.recordingConnection.Close()
|
||||||
|
close(connection.reads)
|
||||||
|
})
|
||||||
|
return nil
|
||||||
|
}
|
||||||
@@ -87,6 +87,15 @@ func (g *GPIOToggle) On() bool {
|
|||||||
return g.on
|
return g.on
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Configuration returns the native toggle behavior used in the rover hello.
|
||||||
|
func (g *GPIOToggle) Configuration() GPIOToggleConfig {
|
||||||
|
return g.cfg
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *GPIOToggle) BackendDescription() string {
|
||||||
|
return "native GPIO"
|
||||||
|
}
|
||||||
|
|
||||||
func (g *GPIOToggle) setLocked(on bool) error {
|
func (g *GPIOToggle) setLocked(on bool) error {
|
||||||
// This is the only place a logical device state becomes an electrical GPIO
|
// This is the only place a logical device state becomes an electrical GPIO
|
||||||
// value. Hardware that turns on when pulled low sets activeLow in roverd
|
// value. Hardware that turns on when pulled low sets activeLow in roverd
|
||||||
|
|||||||
@@ -13,10 +13,10 @@ type GPIOToggle struct {
|
|||||||
|
|
||||||
func NewGPIOToggle(name string, _ GPIOToggleConfig, _ *log.Logger) (*GPIOToggle, error) {
|
func NewGPIOToggle(name string, _ GPIOToggleConfig, _ *log.Logger) (*GPIOToggle, error) {
|
||||||
/*
|
/*
|
||||||
A Debian laptop has no Raspberry Pi GPIO character-device contract for
|
A Debian laptop has no native Raspberry Pi GPIO contract. Returning an
|
||||||
headlights or lasers. Returning an error when enabled makes bad laptop
|
error here catches an invalid native configuration; the shared resolver
|
||||||
configs fail during startup instead of advertising controls that cannot
|
selects an ESP32 Firmata toggle before this constructor when native GPIO
|
||||||
change any hardware.
|
is disabled.
|
||||||
*/
|
*/
|
||||||
return nil, fmt.Errorf("%s not supported in the debian-laptop build", name)
|
return nil, fmt.Errorf("%s not supported in the debian-laptop build", name)
|
||||||
}
|
}
|
||||||
@@ -30,3 +30,11 @@ func (g *GPIOToggle) HandleAction(action string) error {
|
|||||||
func (g *GPIOToggle) On() bool {
|
func (g *GPIOToggle) On() bool {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (g *GPIOToggle) Configuration() GPIOToggleConfig {
|
||||||
|
return GPIOToggleConfig{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *GPIOToggle) BackendDescription() string {
|
||||||
|
return "native GPIO"
|
||||||
|
}
|
||||||
|
|||||||
@@ -24,3 +24,11 @@ func (g *GPIOToggle) HandleAction(action string) error {
|
|||||||
func (g *GPIOToggle) On() bool {
|
func (g *GPIOToggle) On() bool {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func (g *GPIOToggle) Configuration() GPIOToggleConfig {
|
||||||
|
return GPIOToggleConfig{}
|
||||||
|
}
|
||||||
|
|
||||||
|
func (g *GPIOToggle) BackendDescription() string {
|
||||||
|
return "native GPIO"
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,164 @@
|
|||||||
|
package roverd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"strings"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Both physical servo backends consume these exact motion constants. Keeping
|
||||||
|
// them in shared code prevents Pi PWM and ESP32 Firmata movement from drifting
|
||||||
|
// apart as either implementation evolves.
|
||||||
|
const (
|
||||||
|
maxServoDegPerSec = 60.0
|
||||||
|
servoStepInterval = 20 * time.Millisecond
|
||||||
|
servoAngleEpsilon = 0.01
|
||||||
|
)
|
||||||
|
|
||||||
|
// CameraServoController is the hardware-neutral camera-tilt contract used by
|
||||||
|
// WSClient. Native Pi PWM and ESP32 Firmata implementations expose identical
|
||||||
|
// logical behavior, so command handling never branches on the rover host type.
|
||||||
|
type CameraServoController interface {
|
||||||
|
SetAngle(angle float64) error
|
||||||
|
Nudge(delta float64) error
|
||||||
|
SetPulseWidth(micros int) error
|
||||||
|
CurrentAngle() float64
|
||||||
|
Configuration() CameraServoConfig
|
||||||
|
BackendDescription() string
|
||||||
|
Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ToggleController keeps headlight and laser command/state behavior independent
|
||||||
|
// of whether the electrical write happens on native Pi GPIO or an ESP32 pin.
|
||||||
|
type ToggleController interface {
|
||||||
|
HandleAction(action string) error
|
||||||
|
On() bool
|
||||||
|
Configuration() GPIOToggleConfig
|
||||||
|
BackendDescription() string
|
||||||
|
Close()
|
||||||
|
}
|
||||||
|
|
||||||
|
// RoverHardwareControllers is the result of the single startup-time backend
|
||||||
|
// decision. Its effective configurations are derived from whichever backend
|
||||||
|
// won, making the normal rover hello accurate on both Pi and laptop hosts.
|
||||||
|
type RoverHardwareControllers struct {
|
||||||
|
CameraServo CameraServoController
|
||||||
|
Headlight ToggleController
|
||||||
|
Laser ToggleController
|
||||||
|
ignoredESP32Roles []string
|
||||||
|
}
|
||||||
|
|
||||||
|
// StartupBroadcasts returns short operator-facing messages. Detailed pin and
|
||||||
|
// protocol information remains in the journal; tty1 only explains which
|
||||||
|
// physical backend won and whether an advertised ESP32 role was ignored.
|
||||||
|
func (controllers RoverHardwareControllers) StartupBroadcasts() []string {
|
||||||
|
var messages []string
|
||||||
|
if len(controllers.ignoredESP32Roles) > 0 {
|
||||||
|
messages = append(messages, fmt.Sprintf(
|
||||||
|
"Ignored ESP32 %s because native GPIO is enabled.",
|
||||||
|
strings.Join(controllers.ignoredESP32Roles, ", "),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
messages = append(messages, fmt.Sprintf(
|
||||||
|
"Rover hardware ready: camera servo via %s, headlight via %s, laser via %s.",
|
||||||
|
controllerBackend(controllers.CameraServo),
|
||||||
|
controllerBackend(controllers.Headlight),
|
||||||
|
controllerBackend(controllers.Laser),
|
||||||
|
))
|
||||||
|
return messages
|
||||||
|
}
|
||||||
|
|
||||||
|
func controllerBackend(controller interface{ BackendDescription() string }) string {
|
||||||
|
if controller == nil {
|
||||||
|
return "disabled"
|
||||||
|
}
|
||||||
|
return controller.BackendDescription()
|
||||||
|
}
|
||||||
|
|
||||||
|
type nativeHardwareControllerFactories struct {
|
||||||
|
newCameraServo func(CameraServoConfig, *log.Logger) (CameraServoController, error)
|
||||||
|
newToggle func(string, GPIOToggleConfig, *log.Logger) (ToggleController, error)
|
||||||
|
}
|
||||||
|
|
||||||
|
// ResolveRoverHardwareControllers applies one rule on every real rover build:
|
||||||
|
// enabled native GPIO wins, otherwise one discovered ESP32 may fill the role.
|
||||||
|
// The rule is intentionally not selected by GOARCH or the debian_laptop tag.
|
||||||
|
func ResolveRoverHardwareControllers(cfg *Config, peripherals *PeripheralManager, logger *log.Logger) (RoverHardwareControllers, error) {
|
||||||
|
factories := nativeHardwareControllerFactories{
|
||||||
|
newCameraServo: func(config CameraServoConfig, logger *log.Logger) (CameraServoController, error) {
|
||||||
|
return NewCameraServo(config, logger)
|
||||||
|
},
|
||||||
|
newToggle: func(name string, config GPIOToggleConfig, logger *log.Logger) (ToggleController, error) {
|
||||||
|
return NewGPIOToggle(name, config, logger)
|
||||||
|
},
|
||||||
|
}
|
||||||
|
return resolveRoverHardwareControllers(cfg, peripherals, logger, factories)
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveRoverHardwareControllers(cfg *Config, peripherals *PeripheralManager, logger *log.Logger, factories nativeHardwareControllerFactories) (RoverHardwareControllers, error) {
|
||||||
|
var controllers RoverHardwareControllers
|
||||||
|
var err error
|
||||||
|
// Record ignored declarations separately from selecting controllers so the
|
||||||
|
// same native-first decision can be explained on the local rover console.
|
||||||
|
if cfg.CameraServo.Enabled && peripherals.HasRoverRole("cameraServo") {
|
||||||
|
controllers.ignoredESP32Roles = append(controllers.ignoredESP32Roles, "camera servo")
|
||||||
|
}
|
||||||
|
if cfg.Headlight.Enabled && peripherals.HasRoverRole("headlight") {
|
||||||
|
controllers.ignoredESP32Roles = append(controllers.ignoredESP32Roles, "headlight")
|
||||||
|
}
|
||||||
|
if cfg.Laser.Enabled && peripherals.HasRoverRole("laser") {
|
||||||
|
controllers.ignoredESP32Roles = append(controllers.ignoredESP32Roles, "laser")
|
||||||
|
}
|
||||||
|
|
||||||
|
controllers.CameraServo, err = resolveCameraServoController(cfg.CameraServo, peripherals, logger, factories.newCameraServo)
|
||||||
|
if err != nil {
|
||||||
|
return RoverHardwareControllers{}, fmt.Errorf("init camera servo: %w", err)
|
||||||
|
}
|
||||||
|
controllers.Headlight, err = resolveToggleController("headlight", cfg.Headlight, peripherals, logger, factories.newToggle)
|
||||||
|
if err != nil {
|
||||||
|
controllers.Close()
|
||||||
|
return RoverHardwareControllers{}, fmt.Errorf("init headlight: %w", err)
|
||||||
|
}
|
||||||
|
controllers.Laser, err = resolveToggleController("laser", cfg.Laser, peripherals, logger, factories.newToggle)
|
||||||
|
if err != nil {
|
||||||
|
controllers.Close()
|
||||||
|
return RoverHardwareControllers{}, fmt.Errorf("init laser: %w", err)
|
||||||
|
}
|
||||||
|
return controllers, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveCameraServoController(nativeConfig CameraServoConfig, peripherals *PeripheralManager, logger *log.Logger, newNative func(CameraServoConfig, *log.Logger) (CameraServoController, error)) (CameraServoController, error) {
|
||||||
|
if nativeConfig.Enabled {
|
||||||
|
if peripherals.HasRoverRole("cameraServo") {
|
||||||
|
logger.Printf("ignoring ESP32 cameraServo because native camera servo is enabled")
|
||||||
|
}
|
||||||
|
return newNative(nativeConfig, logger)
|
||||||
|
}
|
||||||
|
return peripherals.NewFirmataCameraServo(logger)
|
||||||
|
}
|
||||||
|
|
||||||
|
func resolveToggleController(name string, nativeConfig GPIOToggleConfig, peripherals *PeripheralManager, logger *log.Logger, newNative func(string, GPIOToggleConfig, *log.Logger) (ToggleController, error)) (ToggleController, error) {
|
||||||
|
if nativeConfig.Enabled {
|
||||||
|
if peripherals.HasRoverRole(name) {
|
||||||
|
logger.Printf("ignoring ESP32 %s because native %s is enabled", name, name)
|
||||||
|
}
|
||||||
|
return newNative(name, nativeConfig, logger)
|
||||||
|
}
|
||||||
|
return peripherals.NewFirmataToggle(name, logger)
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close releases selected controller resources in reverse dependency order.
|
||||||
|
// Firmata controllers do not close the shared serial connection; that remains
|
||||||
|
// owned by PeripheralManager and is released by its separate shutdown defer.
|
||||||
|
func (controllers *RoverHardwareControllers) Close() {
|
||||||
|
if controllers.Laser != nil {
|
||||||
|
controllers.Laser.Close()
|
||||||
|
}
|
||||||
|
if controllers.Headlight != nil {
|
||||||
|
controllers.Headlight.Close()
|
||||||
|
}
|
||||||
|
if controllers.CameraServo != nil {
|
||||||
|
controllers.CameraServo.Close()
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
package roverd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"encoding/json"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestHelloPeripheralMetadataContainsOnlyRenderableFields(t *testing.T) {
|
||||||
|
minimum, maximum := 0, 180
|
||||||
|
message := helloMessage{
|
||||||
|
Type: "hello",
|
||||||
|
Name: "test-rover",
|
||||||
|
Peripherals: []RoverPeripheralMetadata{{
|
||||||
|
ID: "firmata-0",
|
||||||
|
Name: "Camera arm",
|
||||||
|
Controls: []RoverPeripheralControl{{
|
||||||
|
ID: "position", Type: "slider", Name: "Position", Minimum: &minimum, Maximum: &maximum,
|
||||||
|
}},
|
||||||
|
}},
|
||||||
|
}
|
||||||
|
|
||||||
|
encoded, err := json.Marshal(message)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal hello: %v", err)
|
||||||
|
}
|
||||||
|
text := string(encoded)
|
||||||
|
if !strings.Contains(text, `"peripherals":[{"id":"firmata-0","name":"Camera arm","controls":[{"id":"position","type":"slider","name":"Position","min":0,"max":180}]`) {
|
||||||
|
t.Fatalf("hello is missing ordered peripheral metadata: %s", text)
|
||||||
|
}
|
||||||
|
var envelope map[string]json.RawMessage
|
||||||
|
if err := json.Unmarshal(encoded, &envelope); err != nil {
|
||||||
|
t.Fatalf("unmarshal hello envelope: %v", err)
|
||||||
|
}
|
||||||
|
peripheralJSON := string(envelope["peripherals"])
|
||||||
|
if strings.Contains(peripheralJSON, `"pin"`) || strings.Contains(peripheralJSON, `"output"`) {
|
||||||
|
t.Fatalf("hello exposed private Firmata routing: %s", peripheralJSON)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestInboundPeripheralCommandPreservesRawJSONValue(t *testing.T) {
|
||||||
|
var message inboundMessage
|
||||||
|
err := json.Unmarshal([]byte(`{
|
||||||
|
"type":"peripheral",
|
||||||
|
"id":"command-1",
|
||||||
|
"peripheral":{"id":"firmata-0","control":"displayText","value":"hello rover"}
|
||||||
|
}`), &message)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("unmarshal command: %v", err)
|
||||||
|
}
|
||||||
|
if message.Peripheral == nil || message.Peripheral.ID != "firmata-0" || message.Peripheral.Control != "displayText" {
|
||||||
|
t.Fatalf("unexpected peripheral command: %#v", message.Peripheral)
|
||||||
|
}
|
||||||
|
if string(message.Peripheral.Value) != `"hello rover"` {
|
||||||
|
t.Fatalf("raw value = %s", message.Peripheral.Value)
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
//go:build dummy
|
||||||
|
|
||||||
|
package roverd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
// DiscoverPeripheralManager remains inert in a dummy build. The dummy daemon is
|
||||||
|
// specifically used without rover hardware and must not probe or reset serial
|
||||||
|
// devices that happen to be attached to a developer's machine.
|
||||||
|
func DiscoverPeripheralManager(ctx context.Context, excludedDevice string, logger *log.Logger) (*PeripheralManager, error) {
|
||||||
|
dependencies := peripheralDiscoveryDependencies{
|
||||||
|
listCandidates: func(string) ([]string, error) { return nil, nil },
|
||||||
|
open: func(string) (io.ReadWriteCloser, error) { return nil, nil },
|
||||||
|
sleep: func(time.Duration) {},
|
||||||
|
startupWait: 0,
|
||||||
|
handshakeWait: 0,
|
||||||
|
}
|
||||||
|
return discoverPeripheralManager(ctx, excludedDevice, logger, dependencies)
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
//go:build !dummy
|
||||||
|
|
||||||
|
package roverd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"time"
|
||||||
|
|
||||||
|
"github.com/tarm/serial"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
peripheralBaud = 115200
|
||||||
|
peripheralReadTimeout = 100 * time.Millisecond
|
||||||
|
)
|
||||||
|
|
||||||
|
// DiscoverPeripheralManager performs the one and only peripheral scan for this
|
||||||
|
// roverd process. The Roomba Open Interface serial device is explicitly
|
||||||
|
// excluded because it belongs to SerialAdapter and must never be probed as an
|
||||||
|
// ESP32 peripheral.
|
||||||
|
func DiscoverPeripheralManager(ctx context.Context, excludedDevice string, logger *log.Logger) (*PeripheralManager, error) {
|
||||||
|
dependencies := peripheralDiscoveryDependencies{
|
||||||
|
listCandidates: listPeripheralCandidates,
|
||||||
|
open: func(devicePath string) (io.ReadWriteCloser, error) {
|
||||||
|
return serial.OpenPort(&serial.Config{
|
||||||
|
Name: devicePath,
|
||||||
|
Baud: peripheralBaud,
|
||||||
|
ReadTimeout: peripheralReadTimeout,
|
||||||
|
})
|
||||||
|
},
|
||||||
|
sleep: time.Sleep,
|
||||||
|
startupWait: peripheralStartupWait,
|
||||||
|
handshakeWait: peripheralHandshakeTimeout,
|
||||||
|
}
|
||||||
|
return discoverPeripheralManager(ctx, excludedDevice, logger, dependencies)
|
||||||
|
}
|
||||||
@@ -0,0 +1,584 @@
|
|||||||
|
package roverd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"fmt"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"path/filepath"
|
||||||
|
"sort"
|
||||||
|
"strings"
|
||||||
|
"sync"
|
||||||
|
"time"
|
||||||
|
"unicode/utf8"
|
||||||
|
)
|
||||||
|
|
||||||
|
const (
|
||||||
|
peripheralStartupWait = 2 * time.Second
|
||||||
|
peripheralHandshakeTimeout = 5 * time.Second
|
||||||
|
peripheralFirmwareName = "RoverPeripheralFirmata"
|
||||||
|
)
|
||||||
|
|
||||||
|
// RoverPeripheralMetadata is the part of a peripheral description that leaves
|
||||||
|
// roverd. Pin numbers and output mappings intentionally remain private to the
|
||||||
|
// rover process; the server and browser identify only the declared control.
|
||||||
|
type RoverPeripheralMetadata struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Controls []RoverPeripheralControl `json:"controls"`
|
||||||
|
}
|
||||||
|
|
||||||
|
// RoverPeripheralControl contains only fields needed to render and operate one
|
||||||
|
// of the four generic UI controls. Pointer fields preserve legitimate zero
|
||||||
|
// bounds while still omitting properties that do not apply to a control type.
|
||||||
|
type RoverPeripheralControl struct {
|
||||||
|
ID string `json:"id"`
|
||||||
|
Type string `json:"type"`
|
||||||
|
Name string `json:"name"`
|
||||||
|
Mode string `json:"mode,omitempty"`
|
||||||
|
Minimum *int `json:"min,omitempty"`
|
||||||
|
Maximum *int `json:"max,omitempty"`
|
||||||
|
MaximumLength *int `json:"maxLength,omitempty"`
|
||||||
|
}
|
||||||
|
|
||||||
|
type managedPeripheral struct {
|
||||||
|
metadata RoverPeripheralMetadata
|
||||||
|
description PeripheralDescription
|
||||||
|
controls map[string]PeripheralControl
|
||||||
|
client *FirmataClient
|
||||||
|
connection io.ReadWriteCloser
|
||||||
|
devicePath string
|
||||||
|
capabilities [][]FirmataPinCapability
|
||||||
|
}
|
||||||
|
|
||||||
|
// PeripheralManager owns the immutable boot-time inventory and every serial
|
||||||
|
// connection behind it. The inventory never changes after discovery, even if a
|
||||||
|
// USB device later disappears; a process restart is the only rescan mechanism.
|
||||||
|
type PeripheralManager struct {
|
||||||
|
mu sync.RWMutex
|
||||||
|
peripherals []*managedPeripheral
|
||||||
|
byID map[string]*managedPeripheral
|
||||||
|
cancel context.CancelFunc
|
||||||
|
closeOnce sync.Once
|
||||||
|
logger *log.Logger
|
||||||
|
failures chan PeripheralFailure
|
||||||
|
}
|
||||||
|
|
||||||
|
// PeripheralFailure is emitted once when a successfully discovered device's
|
||||||
|
// serial reader terminates unexpectedly. Device identity is retained even
|
||||||
|
// though reconnection still requires restarting roverd.
|
||||||
|
type PeripheralFailure struct {
|
||||||
|
ID string
|
||||||
|
Name string
|
||||||
|
Err error
|
||||||
|
}
|
||||||
|
|
||||||
|
type peripheralDiscoveryDependencies struct {
|
||||||
|
listCandidates func(excludedDevice string) ([]string, error)
|
||||||
|
open func(devicePath string) (io.ReadWriteCloser, error)
|
||||||
|
sleep func(time.Duration)
|
||||||
|
startupWait time.Duration
|
||||||
|
handshakeWait time.Duration
|
||||||
|
}
|
||||||
|
|
||||||
|
func discoverPeripheralManager(ctx context.Context, excludedDevice string, logger *log.Logger, dependencies peripheralDiscoveryDependencies) (*PeripheralManager, error) {
|
||||||
|
managerContext, cancel := context.WithCancel(ctx)
|
||||||
|
manager := &PeripheralManager{
|
||||||
|
byID: make(map[string]*managedPeripheral),
|
||||||
|
cancel: cancel,
|
||||||
|
logger: logger,
|
||||||
|
failures: make(chan PeripheralFailure, 16),
|
||||||
|
}
|
||||||
|
|
||||||
|
candidates, err := dependencies.listCandidates(excludedDevice)
|
||||||
|
if err != nil {
|
||||||
|
manager.Close()
|
||||||
|
return nil, fmt.Errorf("list peripheral serial devices: %w", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, devicePath := range candidates {
|
||||||
|
connection, err := dependencies.open(devicePath)
|
||||||
|
if err != nil {
|
||||||
|
logger.Printf("skipping peripheral candidate %s: open failed: %v", devicePath, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
// UART bridge and native-USB development boards may reset when opened.
|
||||||
|
// Waiting and then draining boot fragments gives the handshake a fresh
|
||||||
|
// parser boundary instead of occasionally starting inside an old SysEx.
|
||||||
|
dependencies.sleep(dependencies.startupWait)
|
||||||
|
if err := drainPeripheralSerial(connection); err != nil {
|
||||||
|
connection.Close()
|
||||||
|
logger.Printf("skipping peripheral candidate %s: drain failed: %v", devicePath, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
client := NewFirmataClient(connection)
|
||||||
|
client.Start(managerContext)
|
||||||
|
firmware, err := queryPeripheralFirmware(managerContext, client, dependencies.handshakeWait)
|
||||||
|
if err != nil {
|
||||||
|
connection.Close()
|
||||||
|
logger.Printf("skipping peripheral candidate %s: Firmata query failed: %v", devicePath, err)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if firmware.Name != peripheralFirmwareName {
|
||||||
|
connection.Close()
|
||||||
|
logger.Printf("skipping Firmata device %s: firmware %q does not expose rover peripherals", devicePath, firmware.Name)
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
|
||||||
|
capabilities, err := queryPeripheralCapabilities(managerContext, client, dependencies.handshakeWait)
|
||||||
|
if err != nil {
|
||||||
|
connection.Close()
|
||||||
|
manager.Close()
|
||||||
|
return nil, fmt.Errorf("query capabilities from rover peripheral %s: %w", devicePath, err)
|
||||||
|
}
|
||||||
|
description, err := queryPeripheralDescription(managerContext, client, dependencies.handshakeWait)
|
||||||
|
if err != nil {
|
||||||
|
connection.Close()
|
||||||
|
manager.Close()
|
||||||
|
return nil, fmt.Errorf("describe rover peripheral %s: %w", devicePath, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
peripheral := newManagedPeripheral(len(manager.peripherals), devicePath, connection, client, description, capabilities)
|
||||||
|
if err := peripheral.initializeStandardOutputs(); err != nil {
|
||||||
|
connection.Close()
|
||||||
|
manager.Close()
|
||||||
|
return nil, fmt.Errorf("initialize rover peripheral %s: %w", devicePath, err)
|
||||||
|
}
|
||||||
|
manager.peripherals = append(manager.peripherals, peripheral)
|
||||||
|
manager.byID[peripheral.metadata.ID] = peripheral
|
||||||
|
client.SetTerminalErrorHandler(func(terminalErr error) {
|
||||||
|
failure := PeripheralFailure{ID: peripheral.metadata.ID, Name: peripheral.metadata.Name, Err: terminalErr}
|
||||||
|
select {
|
||||||
|
case manager.failures <- failure:
|
||||||
|
default:
|
||||||
|
// The channel is intentionally bounded because broadcasts are
|
||||||
|
// diagnostic. Never block a Firmata reader during a fleet-wide
|
||||||
|
// shutdown or an unlikely burst of simultaneous USB failures.
|
||||||
|
logger.Printf("peripheral failure notification queue full for %s: %v", peripheral.metadata.ID, terminalErr)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
logger.Printf("discovered rover peripheral %s on %s with %d generic controls", description.Name, devicePath, len(description.Controls))
|
||||||
|
}
|
||||||
|
|
||||||
|
return manager, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// StartupBroadcasts describes the fixed inventory without exposing device
|
||||||
|
// paths or wiring details on the rover's local console.
|
||||||
|
func (manager *PeripheralManager) StartupBroadcasts() []string {
|
||||||
|
inventory := manager.Inventory()
|
||||||
|
if len(inventory) == 0 {
|
||||||
|
return []string{"No ESP32 rover peripherals detected during startup."}
|
||||||
|
}
|
||||||
|
messages := make([]string, 0, len(inventory))
|
||||||
|
for _, peripheral := range inventory {
|
||||||
|
messages = append(messages, fmt.Sprintf(
|
||||||
|
"Rover peripheral %q connected as %s with %d additional controls.",
|
||||||
|
peripheral.Name,
|
||||||
|
peripheral.ID,
|
||||||
|
len(peripheral.Controls),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
return messages
|
||||||
|
}
|
||||||
|
|
||||||
|
// Failures exposes unexpected runtime disconnects to the daemon entry point,
|
||||||
|
// which owns the ConsoleNotifier and therefore owns user-facing wording.
|
||||||
|
func (manager *PeripheralManager) Failures() <-chan PeripheralFailure {
|
||||||
|
if manager == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
return manager.failures
|
||||||
|
}
|
||||||
|
|
||||||
|
func listPeripheralCandidates(excludedDevice string) ([]string, error) {
|
||||||
|
patterns := []string{
|
||||||
|
"/dev/serial/by-id/*",
|
||||||
|
"/dev/ttyUSB*",
|
||||||
|
"/dev/ttyACM*",
|
||||||
|
}
|
||||||
|
var matchesInPreferenceOrder []string
|
||||||
|
|
||||||
|
for _, pattern := range patterns {
|
||||||
|
matches, err := filepath.Glob(pattern)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
sort.Strings(matches)
|
||||||
|
matchesInPreferenceOrder = append(matchesInPreferenceOrder, matches...)
|
||||||
|
}
|
||||||
|
return uniquePeripheralCandidates(matchesInPreferenceOrder, excludedDevice), nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func uniquePeripheralCandidates(matches []string, excludedDevice string) []string {
|
||||||
|
excludedCanonical := canonicalDevicePath(excludedDevice)
|
||||||
|
seen := make(map[string]struct{})
|
||||||
|
var candidates []string
|
||||||
|
for _, match := range matches {
|
||||||
|
canonical := canonicalDevicePath(match)
|
||||||
|
if canonical == excludedCanonical {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
if _, exists := seen[canonical]; exists {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
seen[canonical] = struct{}{}
|
||||||
|
// /dev/serial/by-id matches are passed first, so retaining the first
|
||||||
|
// spelling favors stable names while still removing each tty alias.
|
||||||
|
candidates = append(candidates, match)
|
||||||
|
}
|
||||||
|
return candidates
|
||||||
|
}
|
||||||
|
|
||||||
|
func canonicalDevicePath(devicePath string) string {
|
||||||
|
if devicePath == "" {
|
||||||
|
return ""
|
||||||
|
}
|
||||||
|
resolved, err := filepath.EvalSymlinks(devicePath)
|
||||||
|
if err == nil {
|
||||||
|
return resolved
|
||||||
|
}
|
||||||
|
abs, err := filepath.Abs(devicePath)
|
||||||
|
if err == nil {
|
||||||
|
return filepath.Clean(abs)
|
||||||
|
}
|
||||||
|
return filepath.Clean(devicePath)
|
||||||
|
}
|
||||||
|
|
||||||
|
func drainPeripheralSerial(connection io.Reader) error {
|
||||||
|
buffer := make([]byte, 256)
|
||||||
|
for {
|
||||||
|
_, err := connection.Read(buffer)
|
||||||
|
if errors.Is(err, io.EOF) {
|
||||||
|
// tarm/serial uses EOF to mean its short read timeout elapsed. That
|
||||||
|
// quiet interval is precisely the boundary needed before handshaking.
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func queryPeripheralFirmware(ctx context.Context, client *FirmataClient, timeout time.Duration) (FirmataFirmware, error) {
|
||||||
|
queryContext, cancel := context.WithTimeout(ctx, timeout)
|
||||||
|
defer cancel()
|
||||||
|
return client.QueryFirmware(queryContext)
|
||||||
|
}
|
||||||
|
|
||||||
|
func queryPeripheralCapabilities(ctx context.Context, client *FirmataClient, timeout time.Duration) ([][]FirmataPinCapability, error) {
|
||||||
|
queryContext, cancel := context.WithTimeout(ctx, timeout)
|
||||||
|
defer cancel()
|
||||||
|
return client.QueryCapabilities(queryContext)
|
||||||
|
}
|
||||||
|
|
||||||
|
func queryPeripheralDescription(ctx context.Context, client *FirmataClient, timeout time.Duration) (PeripheralDescription, error) {
|
||||||
|
queryContext, cancel := context.WithTimeout(ctx, timeout)
|
||||||
|
defer cancel()
|
||||||
|
return client.Describe(queryContext)
|
||||||
|
}
|
||||||
|
|
||||||
|
func newManagedPeripheral(index int, devicePath string, connection io.ReadWriteCloser, client *FirmataClient, description PeripheralDescription, capabilities [][]FirmataPinCapability) *managedPeripheral {
|
||||||
|
controls := make(map[string]PeripheralControl, len(description.Controls))
|
||||||
|
metadataControls := make([]RoverPeripheralControl, 0, len(description.Controls))
|
||||||
|
for _, control := range description.Controls {
|
||||||
|
controls[control.ID] = control
|
||||||
|
metadataControls = append(metadataControls, RoverPeripheralControl{
|
||||||
|
ID: control.ID,
|
||||||
|
Type: control.Type,
|
||||||
|
Name: control.Name,
|
||||||
|
Mode: control.Mode,
|
||||||
|
Minimum: cloneIntPointer(control.Minimum),
|
||||||
|
Maximum: cloneIntPointer(control.Maximum),
|
||||||
|
MaximumLength: cloneIntPointer(control.MaximumLength),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
return &managedPeripheral{
|
||||||
|
metadata: RoverPeripheralMetadata{
|
||||||
|
ID: fmt.Sprintf("firmata-%d", index),
|
||||||
|
Name: description.Name,
|
||||||
|
Controls: metadataControls,
|
||||||
|
},
|
||||||
|
description: description,
|
||||||
|
controls: controls,
|
||||||
|
client: client,
|
||||||
|
connection: connection,
|
||||||
|
devicePath: devicePath,
|
||||||
|
capabilities: capabilities,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func cloneIntPointer(value *int) *int {
|
||||||
|
if value == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
cloned := *value
|
||||||
|
return &cloned
|
||||||
|
}
|
||||||
|
|
||||||
|
func (peripheral *managedPeripheral) initializeStandardOutputs() error {
|
||||||
|
if camera := peripheral.description.RoverControls.CameraServo; camera != nil {
|
||||||
|
if err := peripheral.requirePinMode("cameraServo", camera.Pin, FirmataPinModeServo); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if headlight := peripheral.description.RoverControls.Headlight; headlight != nil {
|
||||||
|
if err := peripheral.requirePinMode("headlight", headlight.Pin, FirmataPinModeOutput); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if laser := peripheral.description.RoverControls.Laser; laser != nil {
|
||||||
|
if err := peripheral.requirePinMode("laser", laser.Pin, FirmataPinModeOutput); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for _, control := range peripheral.description.Controls {
|
||||||
|
if control.Output.Type == "custom" {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
pin := byte(*control.Output.Pin)
|
||||||
|
requiredMode := FirmataPinModeOutput
|
||||||
|
if control.Output.Type == "pwm" {
|
||||||
|
requiredMode = FirmataPinModePWM
|
||||||
|
} else if control.Output.Type == "servo" {
|
||||||
|
requiredMode = FirmataPinModeServo
|
||||||
|
}
|
||||||
|
if err := peripheral.requirePinMode("control "+control.ID, int(pin), requiredMode); err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
switch control.Output.Type {
|
||||||
|
case "digital":
|
||||||
|
if err := peripheral.client.SetPinMode(pin, FirmataPinModeOutput); err != nil {
|
||||||
|
return fmt.Errorf("configure control %q as digital: %w", control.ID, err)
|
||||||
|
}
|
||||||
|
// A generic button begins logically off. Active-low hardware needs a
|
||||||
|
// high electrical level to represent that same initial state.
|
||||||
|
if err := peripheral.client.SetDigitalPin(pin, control.Output.ActiveLow); err != nil {
|
||||||
|
return fmt.Errorf("initialize digital control %q: %w", control.ID, err)
|
||||||
|
}
|
||||||
|
case "pwm":
|
||||||
|
if err := peripheral.client.SetPinMode(pin, FirmataPinModePWM); err != nil {
|
||||||
|
return fmt.Errorf("configure control %q as PWM: %w", control.ID, err)
|
||||||
|
}
|
||||||
|
case "servo":
|
||||||
|
if err := peripheral.client.SetPinMode(pin, FirmataPinModeServo); err != nil {
|
||||||
|
return fmt.Errorf("configure control %q as servo: %w", control.ID, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (peripheral *managedPeripheral) requirePinMode(owner string, pin int, requiredMode byte) error {
|
||||||
|
if pin < 0 || pin >= len(peripheral.capabilities) {
|
||||||
|
return fmt.Errorf("%s advertises pin %d, but Firmata reported only %d pins", owner, pin, len(peripheral.capabilities))
|
||||||
|
}
|
||||||
|
for _, capability := range peripheral.capabilities[pin] {
|
||||||
|
if capability.Mode == requiredMode {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return fmt.Errorf("%s advertises pin %d without required Firmata mode 0x%02x", owner, pin, requiredMode)
|
||||||
|
}
|
||||||
|
|
||||||
|
// HasRoverRole reports whether discovery found an ESP32 implementation of one
|
||||||
|
// established rover control. It is used only for startup selection and logging;
|
||||||
|
// commands continue to target the selected controller interface directly.
|
||||||
|
func (manager *PeripheralManager) HasRoverRole(role string) bool {
|
||||||
|
return len(manager.roverRoleProviders(role)) > 0
|
||||||
|
}
|
||||||
|
|
||||||
|
func (manager *PeripheralManager) roverRoleProviders(role string) []*managedPeripheral {
|
||||||
|
if manager == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
manager.mu.RLock()
|
||||||
|
defer manager.mu.RUnlock()
|
||||||
|
var providers []*managedPeripheral
|
||||||
|
for _, peripheral := range manager.peripherals {
|
||||||
|
switch role {
|
||||||
|
case "cameraServo":
|
||||||
|
if peripheral.description.RoverControls.CameraServo != nil {
|
||||||
|
providers = append(providers, peripheral)
|
||||||
|
}
|
||||||
|
case "headlight":
|
||||||
|
if peripheral.description.RoverControls.Headlight != nil {
|
||||||
|
providers = append(providers, peripheral)
|
||||||
|
}
|
||||||
|
case "laser":
|
||||||
|
if peripheral.description.RoverControls.Laser != nil {
|
||||||
|
providers = append(providers, peripheral)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return providers
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewFirmataCameraServo constructs the shared camera controller only when a
|
||||||
|
// discovered peripheral declared that standardized role. Absence is a normal
|
||||||
|
// disabled-feature result rather than an error.
|
||||||
|
func (manager *PeripheralManager) NewFirmataCameraServo(logger *log.Logger) (CameraServoController, error) {
|
||||||
|
providers := manager.roverRoleProviders("cameraServo")
|
||||||
|
if len(providers) == 0 {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if len(providers) > 1 {
|
||||||
|
return nil, duplicateRoverRoleError("cameraServo", providers)
|
||||||
|
}
|
||||||
|
peripheral := providers[0]
|
||||||
|
return newFirmataCameraServo(peripheral, *peripheral.description.RoverControls.CameraServo, logger)
|
||||||
|
}
|
||||||
|
|
||||||
|
// NewFirmataToggle resolves either standardized digital role without exposing
|
||||||
|
// the peripheral connection or ESP32 pin to WSClient.
|
||||||
|
func (manager *PeripheralManager) NewFirmataToggle(role string, logger *log.Logger) (ToggleController, error) {
|
||||||
|
providers := manager.roverRoleProviders(role)
|
||||||
|
if len(providers) == 0 {
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
if len(providers) > 1 {
|
||||||
|
return nil, duplicateRoverRoleError(role, providers)
|
||||||
|
}
|
||||||
|
peripheral := providers[0]
|
||||||
|
var declaration *PeripheralDigitalRole
|
||||||
|
switch role {
|
||||||
|
case "headlight":
|
||||||
|
declaration = peripheral.description.RoverControls.Headlight
|
||||||
|
case "laser":
|
||||||
|
declaration = peripheral.description.RoverControls.Laser
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unknown Firmata toggle role %q", role)
|
||||||
|
}
|
||||||
|
return newFirmataToggle(role, peripheral, *declaration, logger)
|
||||||
|
}
|
||||||
|
|
||||||
|
func duplicateRoverRoleError(role string, providers []*managedPeripheral) error {
|
||||||
|
providerIDs := make([]string, 0, len(providers))
|
||||||
|
for _, provider := range providers {
|
||||||
|
providerIDs = append(providerIDs, provider.metadata.ID)
|
||||||
|
}
|
||||||
|
return fmt.Errorf("rover peripheral role %s has multiple providers: %s", role, strings.Join(providerIDs, ", "))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Inventory returns a defensive copy in startup order. Server reconnects reuse
|
||||||
|
// this same list and therefore never cause a USB rescan or ID reassignment.
|
||||||
|
func (manager *PeripheralManager) Inventory() []RoverPeripheralMetadata {
|
||||||
|
if manager == nil {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
manager.mu.RLock()
|
||||||
|
defer manager.mu.RUnlock()
|
||||||
|
|
||||||
|
inventory := make([]RoverPeripheralMetadata, 0, len(manager.peripherals))
|
||||||
|
for _, peripheral := range manager.peripherals {
|
||||||
|
metadata := peripheral.metadata
|
||||||
|
metadata.Controls = make([]RoverPeripheralControl, 0, len(peripheral.metadata.Controls))
|
||||||
|
for _, control := range peripheral.metadata.Controls {
|
||||||
|
control.Minimum = cloneIntPointer(control.Minimum)
|
||||||
|
control.Maximum = cloneIntPointer(control.Maximum)
|
||||||
|
control.MaximumLength = cloneIntPointer(control.MaximumLength)
|
||||||
|
metadata.Controls = append(metadata.Controls, control)
|
||||||
|
}
|
||||||
|
inventory = append(inventory, metadata)
|
||||||
|
}
|
||||||
|
return inventory
|
||||||
|
}
|
||||||
|
|
||||||
|
// SetControl validates the browser-shaped value against the ESP32 declaration,
|
||||||
|
// then uses the private output mapping selected during startup. Neither the
|
||||||
|
// server nor browser can choose a pin or switch a custom control into raw GPIO.
|
||||||
|
func (manager *PeripheralManager) SetControl(peripheralID, controlID string, rawValue json.RawMessage) error {
|
||||||
|
if manager == nil {
|
||||||
|
return errors.New("rover peripherals disabled")
|
||||||
|
}
|
||||||
|
manager.mu.RLock()
|
||||||
|
peripheral := manager.byID[peripheralID]
|
||||||
|
manager.mu.RUnlock()
|
||||||
|
if peripheral == nil {
|
||||||
|
return fmt.Errorf("unknown peripheral %q", peripheralID)
|
||||||
|
}
|
||||||
|
control, exists := peripheral.controls[controlID]
|
||||||
|
if !exists {
|
||||||
|
return fmt.Errorf("unknown control %q on peripheral %q", controlID, peripheralID)
|
||||||
|
}
|
||||||
|
|
||||||
|
value, err := decodePeripheralControlValue(control, rawValue)
|
||||||
|
if err != nil {
|
||||||
|
return fmt.Errorf("control %q: %w", controlID, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
switch control.Output.Type {
|
||||||
|
case "digital":
|
||||||
|
enabled := value.(bool)
|
||||||
|
if control.Output.ActiveLow {
|
||||||
|
enabled = !enabled
|
||||||
|
}
|
||||||
|
return peripheral.client.SetDigitalPin(byte(*control.Output.Pin), enabled)
|
||||||
|
case "pwm", "servo":
|
||||||
|
return peripheral.client.ExtendedAnalog(byte(*control.Output.Pin), value.(int))
|
||||||
|
case "custom":
|
||||||
|
return peripheral.client.SendPeripheralControl(control.ID, value)
|
||||||
|
default:
|
||||||
|
return fmt.Errorf("control has unsupported output %q", control.Output.Type)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func decodePeripheralControlValue(control PeripheralControl, rawValue json.RawMessage) (any, error) {
|
||||||
|
if len(rawValue) == 0 {
|
||||||
|
return nil, errors.New("value is required")
|
||||||
|
}
|
||||||
|
|
||||||
|
switch control.Type {
|
||||||
|
case "slider", "number":
|
||||||
|
var value int
|
||||||
|
if err := json.Unmarshal(rawValue, &value); err != nil {
|
||||||
|
return nil, errors.New("value must be a whole number")
|
||||||
|
}
|
||||||
|
if value < *control.Minimum || value > *control.Maximum {
|
||||||
|
return nil, fmt.Errorf("value must be between %d and %d", *control.Minimum, *control.Maximum)
|
||||||
|
}
|
||||||
|
return value, nil
|
||||||
|
case "button":
|
||||||
|
var value bool
|
||||||
|
if err := json.Unmarshal(rawValue, &value); err != nil {
|
||||||
|
return nil, errors.New("value must be true or false")
|
||||||
|
}
|
||||||
|
return value, nil
|
||||||
|
case "text":
|
||||||
|
var value string
|
||||||
|
if err := json.Unmarshal(rawValue, &value); err != nil {
|
||||||
|
return nil, errors.New("value must be text")
|
||||||
|
}
|
||||||
|
if utf8.RuneCountInString(value) > *control.MaximumLength {
|
||||||
|
return nil, fmt.Errorf("value must contain at most %d characters", *control.MaximumLength)
|
||||||
|
}
|
||||||
|
return value, nil
|
||||||
|
default:
|
||||||
|
return nil, fmt.Errorf("unsupported control type %q", control.Type)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Close releases every discovered USB connection exactly once. It does not
|
||||||
|
// alter inventory or attempt to reconnect devices because shutdown/restart is
|
||||||
|
// the lifecycle boundary chosen for this feature.
|
||||||
|
func (manager *PeripheralManager) Close() {
|
||||||
|
if manager == nil {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
manager.closeOnce.Do(func() {
|
||||||
|
manager.cancel()
|
||||||
|
manager.mu.Lock()
|
||||||
|
defer manager.mu.Unlock()
|
||||||
|
for _, peripheral := range manager.peripherals {
|
||||||
|
if err := peripheral.connection.Close(); err != nil {
|
||||||
|
manager.logger.Printf("close rover peripheral %s on %s: %v", peripheral.metadata.ID, peripheral.devicePath, err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
@@ -0,0 +1,425 @@
|
|||||||
|
package roverd
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"context"
|
||||||
|
"encoding/json"
|
||||||
|
"errors"
|
||||||
|
"io"
|
||||||
|
"log"
|
||||||
|
"os"
|
||||||
|
"path/filepath"
|
||||||
|
"strings"
|
||||||
|
"testing"
|
||||||
|
"time"
|
||||||
|
)
|
||||||
|
|
||||||
|
func TestPeripheralManagerDiscoversInventoryAndDispatchesControls(t *testing.T) {
|
||||||
|
description := testPeripheralDescription("Bench accessory", false)
|
||||||
|
connection := scriptedPeripheralConnection(t, description)
|
||||||
|
dependencies := testPeripheralDiscoveryDependencies(
|
||||||
|
[]string{"/dev/ttyUSB9"},
|
||||||
|
map[string]*scriptedConnection{"/dev/ttyUSB9": connection},
|
||||||
|
)
|
||||||
|
|
||||||
|
manager, err := discoverPeripheralManager(context.Background(), "/dev/ttyUSB0", discardLogger(), dependencies)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("discover: %v", err)
|
||||||
|
}
|
||||||
|
defer manager.Close()
|
||||||
|
|
||||||
|
inventory := manager.Inventory()
|
||||||
|
if len(inventory) != 1 {
|
||||||
|
t.Fatalf("inventory length = %d, want 1", len(inventory))
|
||||||
|
}
|
||||||
|
if inventory[0].ID != "firmata-0" || inventory[0].Name != "Bench accessory" {
|
||||||
|
t.Fatalf("unexpected peripheral metadata: %#v", inventory[0])
|
||||||
|
}
|
||||||
|
wantBroadcast := `Rover peripheral "Bench accessory" connected as firmata-0 with 3 additional controls.`
|
||||||
|
if broadcasts := manager.StartupBroadcasts(); len(broadcasts) != 1 || broadcasts[0] != wantBroadcast {
|
||||||
|
t.Fatalf("startup broadcasts = %#v, want %q", broadcasts, wantBroadcast)
|
||||||
|
}
|
||||||
|
wantOrder := []string{"servoPosition", "lightBrightness", "specialAction"}
|
||||||
|
for index, controlID := range wantOrder {
|
||||||
|
if inventory[0].Controls[index].ID != controlID {
|
||||||
|
t.Fatalf("control %d = %q, want %q", index, inventory[0].Controls[index].ID, controlID)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
*inventory[0].Controls[0].Minimum = 99
|
||||||
|
if fresh := manager.Inventory(); *fresh[0].Controls[0].Minimum != 0 {
|
||||||
|
t.Fatal("caller mutation changed the manager's fixed inventory")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Standard modes are configured once during discovery. Runtime slider
|
||||||
|
// commands should consequently contain only EXTENDED_ANALOG, not repeated
|
||||||
|
// mode changes that would detach and reattach a servo while it is moving.
|
||||||
|
baseline := len(connection.Bytes())
|
||||||
|
if err := manager.SetControl("firmata-0", "servoPosition", json.RawMessage(`90`)); err != nil {
|
||||||
|
t.Fatalf("set servo: %v", err)
|
||||||
|
}
|
||||||
|
servoWrite := connection.Bytes()[baseline:]
|
||||||
|
wantServo := []byte{firmataStartSysex, firmataExtendedAnalog, 13, 90, firmataEndSysex}
|
||||||
|
if !bytes.Equal(servoWrite, wantServo) {
|
||||||
|
t.Fatalf("servo bytes = %v, want %v", servoWrite, wantServo)
|
||||||
|
}
|
||||||
|
|
||||||
|
baseline = len(connection.Bytes())
|
||||||
|
if err := manager.SetControl("firmata-0", "lightBrightness", json.RawMessage(`128`)); err != nil {
|
||||||
|
t.Fatalf("set PWM: %v", err)
|
||||||
|
}
|
||||||
|
pwmWrite := connection.Bytes()[baseline:]
|
||||||
|
wantPWM := []byte{firmataStartSysex, firmataExtendedAnalog, 17, 0, 1, firmataEndSysex}
|
||||||
|
if !bytes.Equal(pwmWrite, wantPWM) {
|
||||||
|
t.Fatalf("PWM bytes = %v, want %v", pwmWrite, wantPWM)
|
||||||
|
}
|
||||||
|
|
||||||
|
baseline = len(connection.Bytes())
|
||||||
|
if err := manager.SetControl("firmata-0", "specialAction", json.RawMessage(`true`)); err != nil {
|
||||||
|
t.Fatalf("set custom button: %v", err)
|
||||||
|
}
|
||||||
|
customWrite := connection.Bytes()[baseline:]
|
||||||
|
if len(customWrite) < 5 || customWrite[1] != firmataPeripheralFeature || customWrite[2] != firmataPeripheralControl {
|
||||||
|
t.Fatalf("custom control did not use rover-peripheral SysEx: %v", customWrite)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPeripheralManagerBroadcastsNoDevices(t *testing.T) {
|
||||||
|
manager := &PeripheralManager{byID: make(map[string]*managedPeripheral)}
|
||||||
|
want := "No ESP32 rover peripherals detected during startup."
|
||||||
|
if messages := manager.StartupBroadcasts(); len(messages) != 1 || messages[0] != want {
|
||||||
|
t.Fatalf("startup broadcasts = %#v, want %q", messages, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPeripheralManagerReportsUnexpectedDisconnectOnce(t *testing.T) {
|
||||||
|
connection := scriptedPeripheralConnection(t, testPeripheralDescription("Bench accessory", false))
|
||||||
|
manager, err := discoverPeripheralManager(
|
||||||
|
context.Background(),
|
||||||
|
"/dev/roomba",
|
||||||
|
discardLogger(),
|
||||||
|
testPeripheralDiscoveryDependencies([]string{"/dev/accessory"}, map[string]*scriptedConnection{"/dev/accessory": connection}),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("discover: %v", err)
|
||||||
|
}
|
||||||
|
defer manager.Close()
|
||||||
|
|
||||||
|
// Closing the fake read stream models an unplugged USB serial adapter. The
|
||||||
|
// manager should publish one identified failure and never attempt reconnect.
|
||||||
|
_ = connection.Close()
|
||||||
|
select {
|
||||||
|
case failure := <-manager.Failures():
|
||||||
|
if failure.ID != "firmata-0" || failure.Name != "Bench accessory" || !errors.Is(failure.Err, io.ErrClosedPipe) {
|
||||||
|
t.Fatalf("unexpected failure: %#v", failure)
|
||||||
|
}
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
t.Fatal("timed out waiting for peripheral disconnect")
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case duplicate := <-manager.Failures():
|
||||||
|
t.Fatalf("unexpected duplicate disconnect: %#v", duplicate)
|
||||||
|
case <-time.After(20 * time.Millisecond):
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPeripheralManagerRejectsInvalidValuesBeforeWriting(t *testing.T) {
|
||||||
|
connection := scriptedPeripheralConnection(t, testPeripheralDescription("Bench accessory", false))
|
||||||
|
manager, err := discoverPeripheralManager(
|
||||||
|
context.Background(),
|
||||||
|
"/dev/roomba",
|
||||||
|
discardLogger(),
|
||||||
|
testPeripheralDiscoveryDependencies([]string{"/dev/accessory"}, map[string]*scriptedConnection{"/dev/accessory": connection}),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("discover: %v", err)
|
||||||
|
}
|
||||||
|
defer manager.Close()
|
||||||
|
|
||||||
|
baseline := len(connection.Bytes())
|
||||||
|
invalid := []struct {
|
||||||
|
control string
|
||||||
|
value string
|
||||||
|
}{
|
||||||
|
{control: "servoPosition", value: `181`},
|
||||||
|
{control: "lightBrightness", value: `12.5`},
|
||||||
|
{control: "specialAction", value: `"yes"`},
|
||||||
|
}
|
||||||
|
for _, testCase := range invalid {
|
||||||
|
if err := manager.SetControl("firmata-0", testCase.control, json.RawMessage(testCase.value)); err == nil {
|
||||||
|
t.Fatalf("expected %s=%s to fail", testCase.control, testCase.value)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got := len(connection.Bytes()); got != baseline {
|
||||||
|
t.Fatalf("invalid values wrote %d bytes", got-baseline)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPeripheralManagerSkipsOtherFirmataFirmware(t *testing.T) {
|
||||||
|
other := newScriptedConnection(testFirmwareFrame("StandardFirmata"))
|
||||||
|
other.timeoutsBeforeRead = 1
|
||||||
|
rover := scriptedPeripheralConnection(t, testPeripheralDescription("Rover accessory", false))
|
||||||
|
dependencies := testPeripheralDiscoveryDependencies(
|
||||||
|
[]string{"/dev/ttyACM0", "/dev/ttyUSB0"},
|
||||||
|
map[string]*scriptedConnection{
|
||||||
|
"/dev/ttyACM0": other,
|
||||||
|
"/dev/ttyUSB0": rover,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
manager, err := discoverPeripheralManager(context.Background(), "/dev/roomba", discardLogger(), dependencies)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("discover: %v", err)
|
||||||
|
}
|
||||||
|
defer manager.Close()
|
||||||
|
if inventory := manager.Inventory(); len(inventory) != 1 || inventory[0].ID != "firmata-0" || inventory[0].Name != "Rover accessory" {
|
||||||
|
t.Fatalf("unexpected inventory: %#v", inventory)
|
||||||
|
}
|
||||||
|
if !other.Closed() {
|
||||||
|
t.Fatal("non-rover Firmata port was not closed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPeripheralManagerFailsMalformedRoverDescription(t *testing.T) {
|
||||||
|
connection := newScriptedConnection(
|
||||||
|
testFirmwareFrame(peripheralFirmwareName),
|
||||||
|
testCapabilityFrame(),
|
||||||
|
testDescriptionFrame([]byte(`not-json`)),
|
||||||
|
)
|
||||||
|
connection.timeoutsBeforeRead = 1
|
||||||
|
dependencies := testPeripheralDiscoveryDependencies(
|
||||||
|
[]string{"/dev/ttyUSB0"},
|
||||||
|
map[string]*scriptedConnection{"/dev/ttyUSB0": connection},
|
||||||
|
)
|
||||||
|
|
||||||
|
manager, err := discoverPeripheralManager(context.Background(), "/dev/roomba", discardLogger(), dependencies)
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "describe rover peripheral") {
|
||||||
|
t.Fatalf("expected malformed description error, got manager=%v err=%v", manager, err)
|
||||||
|
}
|
||||||
|
if !connection.Closed() {
|
||||||
|
t.Fatal("malformed rover peripheral connection was not closed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPeripheralManagerRejectsAdvertisedUnsupportedPinMode(t *testing.T) {
|
||||||
|
description := testPeripheralDescription("Bad capability", false)
|
||||||
|
rawDescription, err := json.Marshal(description)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal description: %v", err)
|
||||||
|
}
|
||||||
|
connection := newScriptedConnection(
|
||||||
|
testFirmwareFrame(peripheralFirmwareName),
|
||||||
|
[]byte{
|
||||||
|
firmataStartSysex, firmataCapabilityReply,
|
||||||
|
FirmataPinModeOutput, 1, 0x7F,
|
||||||
|
firmataEndSysex,
|
||||||
|
},
|
||||||
|
testDescriptionFrame(rawDescription),
|
||||||
|
)
|
||||||
|
connection.timeoutsBeforeRead = 1
|
||||||
|
dependencies := testPeripheralDiscoveryDependencies(
|
||||||
|
[]string{"/dev/ttyUSB0"},
|
||||||
|
map[string]*scriptedConnection{"/dev/ttyUSB0": connection},
|
||||||
|
)
|
||||||
|
|
||||||
|
manager, err := discoverPeripheralManager(context.Background(), "/dev/roomba", discardLogger(), dependencies)
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "Firmata reported only 1 pins") {
|
||||||
|
t.Fatalf("expected unsupported capability error, got manager=%v err=%v", manager, err)
|
||||||
|
}
|
||||||
|
if !connection.Closed() {
|
||||||
|
t.Fatal("unsupported peripheral connection was not closed")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPeripheralManagerRejectsDuplicateBuiltInProvidersWhenRoleIsSelected(t *testing.T) {
|
||||||
|
first := scriptedPeripheralConnection(t, testPeripheralDescription("First", true))
|
||||||
|
second := scriptedPeripheralConnection(t, testPeripheralDescription("Second", true))
|
||||||
|
dependencies := testPeripheralDiscoveryDependencies(
|
||||||
|
[]string{"/dev/ttyUSB0", "/dev/ttyUSB1"},
|
||||||
|
map[string]*scriptedConnection{
|
||||||
|
"/dev/ttyUSB0": first,
|
||||||
|
"/dev/ttyUSB1": second,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
|
||||||
|
manager, err := discoverPeripheralManager(context.Background(), "/dev/roomba", discardLogger(), dependencies)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("discovery should retain providers until native precedence is known: %v", err)
|
||||||
|
}
|
||||||
|
defer manager.Close()
|
||||||
|
if _, err := manager.NewFirmataToggle("headlight", discardLogger()); err == nil || !strings.Contains(err.Error(), "role headlight has multiple providers") {
|
||||||
|
t.Fatalf("expected duplicate provider selection error, got %v", err)
|
||||||
|
}
|
||||||
|
if first.Closed() || second.Closed() {
|
||||||
|
t.Fatal("selection validation unexpectedly closed manager-owned ports")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPeripheralManagerReturnsHardwareWriteFailure(t *testing.T) {
|
||||||
|
connection := scriptedPeripheralConnection(t, testPeripheralDescription("Bench accessory", false))
|
||||||
|
manager, err := discoverPeripheralManager(
|
||||||
|
context.Background(),
|
||||||
|
"/dev/roomba",
|
||||||
|
discardLogger(),
|
||||||
|
testPeripheralDiscoveryDependencies([]string{"/dev/accessory"}, map[string]*scriptedConnection{"/dev/accessory": connection}),
|
||||||
|
)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("discover: %v", err)
|
||||||
|
}
|
||||||
|
defer manager.Close()
|
||||||
|
|
||||||
|
connection.SetWriteError(errors.New("USB device removed"))
|
||||||
|
err = manager.SetControl("firmata-0", "lightBrightness", json.RawMessage(`128`))
|
||||||
|
if err == nil || !strings.Contains(err.Error(), "USB device removed") {
|
||||||
|
t.Fatalf("expected hardware error, got %v", err)
|
||||||
|
}
|
||||||
|
select {
|
||||||
|
case failure := <-manager.Failures():
|
||||||
|
if failure.ID != "firmata-0" || !strings.Contains(failure.Err.Error(), "USB device removed") {
|
||||||
|
t.Fatalf("unexpected write failure notification: %#v", failure)
|
||||||
|
}
|
||||||
|
case <-time.After(time.Second):
|
||||||
|
t.Fatal("timed out waiting for write failure notification")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestPeripheralManagerPassesRoombaDeviceToCandidateExclusion(t *testing.T) {
|
||||||
|
const roombaDevice = "/dev/serial/by-id/roomba-base"
|
||||||
|
listed := false
|
||||||
|
dependencies := peripheralDiscoveryDependencies{
|
||||||
|
listCandidates: func(excluded string) ([]string, error) {
|
||||||
|
listed = true
|
||||||
|
if excluded != roombaDevice {
|
||||||
|
t.Fatalf("excluded device = %q, want %q", excluded, roombaDevice)
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
},
|
||||||
|
open: func(string) (io.ReadWriteCloser, error) { return nil, errors.New("unexpected open") },
|
||||||
|
sleep: func(time.Duration) {},
|
||||||
|
startupWait: 0,
|
||||||
|
handshakeWait: time.Second,
|
||||||
|
}
|
||||||
|
|
||||||
|
manager, err := discoverPeripheralManager(context.Background(), roombaDevice, discardLogger(), dependencies)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("discover: %v", err)
|
||||||
|
}
|
||||||
|
manager.Close()
|
||||||
|
if !listed {
|
||||||
|
t.Fatal("candidate listing was not called")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestUniquePeripheralCandidatesPrefersStableAliasAndExcludesRoomba(t *testing.T) {
|
||||||
|
temporaryDirectory := t.TempDir()
|
||||||
|
peripheralTarget := filepath.Join(temporaryDirectory, "ttyUSB0")
|
||||||
|
roombaTarget := filepath.Join(temporaryDirectory, "ttyUSB1")
|
||||||
|
if err := os.WriteFile(peripheralTarget, nil, 0o600); err != nil {
|
||||||
|
t.Fatalf("create peripheral target: %v", err)
|
||||||
|
}
|
||||||
|
if err := os.WriteFile(roombaTarget, nil, 0o600); err != nil {
|
||||||
|
t.Fatalf("create Roomba target: %v", err)
|
||||||
|
}
|
||||||
|
stableAlias := filepath.Join(temporaryDirectory, "usb-rover-peripheral")
|
||||||
|
if err := os.Symlink(peripheralTarget, stableAlias); err != nil {
|
||||||
|
t.Fatalf("create stable alias: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
candidates := uniquePeripheralCandidates(
|
||||||
|
[]string{stableAlias, peripheralTarget, roombaTarget},
|
||||||
|
roombaTarget,
|
||||||
|
)
|
||||||
|
if len(candidates) != 1 || candidates[0] != stableAlias {
|
||||||
|
t.Fatalf("candidates = %v, want stable peripheral alias only", candidates)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func testPeripheralDiscoveryDependencies(paths []string, connections map[string]*scriptedConnection) peripheralDiscoveryDependencies {
|
||||||
|
return peripheralDiscoveryDependencies{
|
||||||
|
listCandidates: func(string) ([]string, error) {
|
||||||
|
return append([]string(nil), paths...), nil
|
||||||
|
},
|
||||||
|
open: func(devicePath string) (io.ReadWriteCloser, error) {
|
||||||
|
connection := connections[devicePath]
|
||||||
|
if connection == nil {
|
||||||
|
return nil, errors.New("test connection not found")
|
||||||
|
}
|
||||||
|
return connection, nil
|
||||||
|
},
|
||||||
|
sleep: func(time.Duration) {},
|
||||||
|
startupWait: 0,
|
||||||
|
handshakeWait: time.Second,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func scriptedPeripheralConnection(t *testing.T, description PeripheralDescription) *scriptedConnection {
|
||||||
|
t.Helper()
|
||||||
|
rawDescription, err := json.Marshal(description)
|
||||||
|
if err != nil {
|
||||||
|
t.Fatalf("marshal description: %v", err)
|
||||||
|
}
|
||||||
|
connection := newScriptedConnection(
|
||||||
|
testFirmwareFrame(peripheralFirmwareName),
|
||||||
|
testCapabilityFrame(),
|
||||||
|
testDescriptionFrame(rawDescription),
|
||||||
|
)
|
||||||
|
// The first read represents the quiet timeout used to drain boot output
|
||||||
|
// before the client's parser starts consuming explicit query responses.
|
||||||
|
connection.timeoutsBeforeRead = 1
|
||||||
|
return connection
|
||||||
|
}
|
||||||
|
|
||||||
|
func testPeripheralDescription(name string, provideHeadlight bool) PeripheralDescription {
|
||||||
|
minimumServo, maximumServo := 0, 180
|
||||||
|
minimumPWM, maximumPWM := 0, 255
|
||||||
|
servoPin, pwmPin := 13, 17
|
||||||
|
description := PeripheralDescription{
|
||||||
|
Name: name,
|
||||||
|
Controls: []PeripheralControl{
|
||||||
|
{
|
||||||
|
ID: "servoPosition", Type: "slider", Name: "Servo position",
|
||||||
|
Minimum: &minimumServo, Maximum: &maximumServo,
|
||||||
|
Output: PeripheralOutput{Type: "servo", Pin: &servoPin},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
ID: "lightBrightness", Type: "slider", Name: "Light brightness",
|
||||||
|
Minimum: &minimumPWM, Maximum: &maximumPWM,
|
||||||
|
Output: PeripheralOutput{Type: "pwm", Pin: &pwmPin},
|
||||||
|
},
|
||||||
|
{
|
||||||
|
ID: "specialAction", Type: "button", Name: "Run special action", Mode: "momentary",
|
||||||
|
Output: PeripheralOutput{Type: "custom"},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
if provideHeadlight {
|
||||||
|
description.RoverControls.Headlight = &PeripheralDigitalRole{Pin: 18}
|
||||||
|
}
|
||||||
|
return description
|
||||||
|
}
|
||||||
|
|
||||||
|
func testFirmwareFrame(name string) []byte {
|
||||||
|
frame := []byte{firmataStartSysex, firmataReportFirmware, 1, 0}
|
||||||
|
frame = append(frame, EncodeFirmata7Bit([]byte(name))...)
|
||||||
|
return append(frame, firmataEndSysex)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testCapabilityFrame() []byte {
|
||||||
|
frame := []byte{firmataStartSysex, firmataCapabilityReply}
|
||||||
|
for pin := 0; pin < 40; pin++ {
|
||||||
|
// The test ESP32 reports the same three output modes as the reference
|
||||||
|
// firmware. Repeating real pin entries also exercises capability parsing
|
||||||
|
// independently of any particular example control pin.
|
||||||
|
frame = append(frame, FirmataPinModeOutput, 1, FirmataPinModePWM, 8, FirmataPinModeServo, 14, 0x7F)
|
||||||
|
}
|
||||||
|
return append(frame, firmataEndSysex)
|
||||||
|
}
|
||||||
|
|
||||||
|
func testDescriptionFrame(rawDescription []byte) []byte {
|
||||||
|
frame := []byte{firmataStartSysex, firmataPeripheralFeature, firmataPeripheralDescription}
|
||||||
|
frame = append(frame, EncodeFirmata7Bit(rawDescription)...)
|
||||||
|
return append(frame, firmataEndSysex)
|
||||||
|
}
|
||||||
|
|
||||||
|
func discardLogger() *log.Logger {
|
||||||
|
return log.New(io.Discard, "", 0)
|
||||||
|
}
|
||||||
+104
-11
@@ -19,13 +19,18 @@ type WSClient struct {
|
|||||||
sensorFrames <-chan []byte
|
sensorFrames <-chan []byte
|
||||||
events chan RoverEvent
|
events chan RoverEvent
|
||||||
media *MediaSupervisor
|
media *MediaSupervisor
|
||||||
servo *CameraServo
|
servo CameraServoController
|
||||||
horn *HornSynth
|
horn *HornSynth
|
||||||
headlight *GPIOToggle
|
headlight ToggleController
|
||||||
laser *GPIOToggle
|
laser ToggleController
|
||||||
|
peripherals *PeripheralManager
|
||||||
log *log.Logger
|
log *log.Logger
|
||||||
|
console *ConsoleNotifier
|
||||||
recoverMu sync.Mutex
|
recoverMu sync.Mutex
|
||||||
recovering bool
|
recovering bool
|
||||||
|
watchdogMu sync.Mutex
|
||||||
|
watchdogOpen bool
|
||||||
|
watchdogOK bool
|
||||||
ttsQueue chan *ttsPayload
|
ttsQueue chan *ttsPayload
|
||||||
chromeTTS *chromeTTSDaemon
|
chromeTTS *chromeTTSDaemon
|
||||||
lastAux motorPWMPayload
|
lastAux motorPWMPayload
|
||||||
@@ -41,7 +46,7 @@ type WSClient struct {
|
|||||||
audioMu sync.RWMutex
|
audioMu sync.RWMutex
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewWSClient(cfg *Config, adapter *SerialAdapter, frames <-chan []byte, events chan RoverEvent, media *MediaSupervisor, servo *CameraServo, headlight *GPIOToggle, laser *GPIOToggle, logger *log.Logger) *WSClient {
|
func NewWSClient(cfg *Config, adapter *SerialAdapter, frames <-chan []byte, events chan RoverEvent, media *MediaSupervisor, servo CameraServoController, headlight ToggleController, laser ToggleController, peripherals *PeripheralManager, logger *log.Logger, console *ConsoleNotifier) *WSClient {
|
||||||
var ttsQueue chan *ttsPayload
|
var ttsQueue chan *ttsPayload
|
||||||
if cfg.Audio.TTSEnabled {
|
if cfg.Audio.TTSEnabled {
|
||||||
ttsQueue = make(chan *ttsPayload, 2)
|
ttsQueue = make(chan *ttsPayload, 2)
|
||||||
@@ -64,7 +69,9 @@ func NewWSClient(cfg *Config, adapter *SerialAdapter, frames <-chan []byte, even
|
|||||||
horn: horn,
|
horn: horn,
|
||||||
headlight: headlight,
|
headlight: headlight,
|
||||||
laser: laser,
|
laser: laser,
|
||||||
|
peripherals: peripherals,
|
||||||
log: logger,
|
log: logger,
|
||||||
|
console: console,
|
||||||
ttsQueue: ttsQueue,
|
ttsQueue: ttsQueue,
|
||||||
chromeTTS: chromeTTS,
|
chromeTTS: chromeTTS,
|
||||||
audioLevels: AudioLevels{
|
audioLevels: AudioLevels{
|
||||||
@@ -124,6 +131,20 @@ func (c *WSClient) Run(ctx context.Context) error {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (c *WSClient) sendHello(ctx context.Context, conn *websocket.Conn) error {
|
func (c *WSClient) sendHello(ctx context.Context, conn *websocket.Conn) error {
|
||||||
|
// Built-in metadata comes from the selected controller, not necessarily
|
||||||
|
// YAML. An ESP32 can enable a role whose native GPIO entry is disabled.
|
||||||
|
cameraServoConfig := CameraServoConfig{}
|
||||||
|
if c.servo != nil {
|
||||||
|
cameraServoConfig = c.servo.Configuration()
|
||||||
|
}
|
||||||
|
headlightConfig := GPIOToggleConfig{}
|
||||||
|
if c.headlight != nil {
|
||||||
|
headlightConfig = c.headlight.Configuration()
|
||||||
|
}
|
||||||
|
laserConfig := GPIOToggleConfig{}
|
||||||
|
if c.laser != nil {
|
||||||
|
laserConfig = c.laser.Configuration()
|
||||||
|
}
|
||||||
msg := helloMessage{
|
msg := helloMessage{
|
||||||
Type: "hello",
|
Type: "hello",
|
||||||
Name: c.cfg.Name,
|
Name: c.cfg.Name,
|
||||||
@@ -132,11 +153,12 @@ func (c *WSClient) sendHello(ctx context.Context, conn *websocket.Conn) error {
|
|||||||
Battery: c.cfg.Battery,
|
Battery: c.cfg.Battery,
|
||||||
MaxWheelSpeed: c.cfg.MaxWheelMMs,
|
MaxWheelSpeed: c.cfg.MaxWheelMMs,
|
||||||
Media: c.cfg.Media,
|
Media: c.cfg.Media,
|
||||||
CameraServo: c.cfg.CameraServo,
|
CameraServo: cameraServoConfig,
|
||||||
Audio: c.cfg.Audio,
|
Audio: c.cfg.Audio,
|
||||||
Horn: c.cfg.Horn,
|
Horn: c.cfg.Horn,
|
||||||
Headlight: c.cfg.Headlight,
|
Headlight: headlightConfig,
|
||||||
Laser: c.cfg.Laser,
|
Laser: laserConfig,
|
||||||
|
Peripherals: c.peripherals.Inventory(),
|
||||||
Private: c.cfg.Private,
|
Private: c.cfg.Private,
|
||||||
}
|
}
|
||||||
c.log.Printf("sending hello (camera servo enabled=%v pin=%d)", msg.CameraServo.Enabled, msg.CameraServo.Pin)
|
c.log.Printf("sending hello (camera servo enabled=%v pin=%d)", msg.CameraServo.Enabled, msg.CameraServo.Pin)
|
||||||
@@ -233,6 +255,8 @@ func (c *WSClient) dispatch(ctx context.Context, msg *inboundMessage) error {
|
|||||||
return c.handleToggleCommand("headlight", c.headlight, msg.Headlight)
|
return c.handleToggleCommand("headlight", c.headlight, msg.Headlight)
|
||||||
case msg.Laser != nil:
|
case msg.Laser != nil:
|
||||||
return c.handleToggleCommand("laser", c.laser, msg.Laser)
|
return c.handleToggleCommand("laser", c.laser, msg.Laser)
|
||||||
|
case msg.Peripheral != nil:
|
||||||
|
return c.peripherals.SetControl(msg.Peripheral.ID, msg.Peripheral.Control, msg.Peripheral.Value)
|
||||||
case msg.Song != nil:
|
case msg.Song != nil:
|
||||||
slot := 0
|
slot := 0
|
||||||
if msg.Song.Slot != nil {
|
if msg.Song.Slot != nil {
|
||||||
@@ -248,7 +272,7 @@ func (c *WSClient) dispatch(ctx context.Context, msg *inboundMessage) error {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *WSClient) handleToggleCommand(name string, toggle *GPIOToggle, payload *togglePayload) error {
|
func (c *WSClient) handleToggleCommand(name string, toggle ToggleController, payload *togglePayload) error {
|
||||||
if toggle == nil {
|
if toggle == nil {
|
||||||
return fmt.Errorf("%s disabled", name)
|
return fmt.Errorf("%s disabled", name)
|
||||||
}
|
}
|
||||||
@@ -305,6 +329,7 @@ func (c *WSClient) handleRebootCommand(payload *rebootPayload) error {
|
|||||||
|
|
||||||
go func() {
|
go func() {
|
||||||
time.Sleep(delay)
|
time.Sleep(delay)
|
||||||
|
c.console.Notify("Remote reboot requested. Rebooting the rover now.")
|
||||||
c.log.Printf("rebooting pi after remote reboot command")
|
c.log.Printf("rebooting pi after remote reboot command")
|
||||||
cmd := exec.Command("systemctl", "reboot")
|
cmd := exec.Command("systemctl", "reboot")
|
||||||
if err := cmd.Start(); err != nil {
|
if err := cmd.Start(); err != nil {
|
||||||
@@ -331,6 +356,7 @@ func (c *WSClient) handleUpdateCommand() error {
|
|||||||
c.emitEvent("system.updateStarting", map[string]any{
|
c.emitEvent("system.updateStarting", map[string]any{
|
||||||
"source": "remoteCommand",
|
"source": "remoteCommand",
|
||||||
})
|
})
|
||||||
|
c.console.Notify("Remote software update requested. roverd will restart if the update succeeds.")
|
||||||
|
|
||||||
// The helper is launched asynchronously because a successful update may
|
// The helper is launched asynchronously because a successful update may
|
||||||
// restart roverd before this websocket command could stream progress back to
|
// restart roverd before this websocket command could stream progress back to
|
||||||
@@ -495,6 +521,10 @@ func (c *WSClient) forwardSensors(ctx context.Context, conn *websocket.Conn) {
|
|||||||
lastRecovery = now
|
lastRecovery = now
|
||||||
resetTimer()
|
resetTimer()
|
||||||
case frame := <-c.sensorFrames:
|
case frame := <-c.sensorFrames:
|
||||||
|
// A real sensor frame is the authoritative end of a watchdog
|
||||||
|
// episode. Successfully sending the OI restart commands alone does
|
||||||
|
// not prove that the Roomba resumed producing sensor data.
|
||||||
|
c.closeSensorWatchdogEpisode()
|
||||||
lastFrame = time.Now()
|
lastFrame = time.Now()
|
||||||
resetTimer()
|
resetTimer()
|
||||||
msg := sensorMessage{
|
msg := sensorMessage{
|
||||||
@@ -641,6 +671,7 @@ func (c *WSClient) keepalive(ctx context.Context, conn *websocket.Conn) error {
|
|||||||
|
|
||||||
func (c *WSClient) markConnected() {
|
func (c *WSClient) markConnected() {
|
||||||
c.connMu.Lock()
|
c.connMu.Lock()
|
||||||
|
wasConnected := c.connected
|
||||||
c.connected = true
|
c.connected = true
|
||||||
c.seekIssued = false
|
c.seekIssued = false
|
||||||
c.rebootIssued = false
|
c.rebootIssued = false
|
||||||
@@ -654,13 +685,19 @@ func (c *WSClient) markConnected() {
|
|||||||
c.rebootT = nil
|
c.rebootT = nil
|
||||||
}
|
}
|
||||||
c.connMu.Unlock()
|
c.connMu.Unlock()
|
||||||
|
|
||||||
|
// Only print on a state transition. Run is retried indefinitely, and a
|
||||||
|
// message on every successful internal operation would quickly bury the
|
||||||
|
// useful lifecycle history at the login prompt.
|
||||||
|
if !wasConnected {
|
||||||
|
c.console.Notify("Control server connected.")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *WSClient) markDisconnected() {
|
func (c *WSClient) markDisconnected() {
|
||||||
c.connMu.Lock()
|
c.connMu.Lock()
|
||||||
if c.connected {
|
wasConnected := c.connected
|
||||||
c.connected = false
|
c.connected = false
|
||||||
}
|
|
||||||
if c.disconnectT == nil {
|
if c.disconnectT == nil {
|
||||||
c.disconnectT = time.AfterFunc(disconnectSeekDelay, c.handleDisconnectTimeout)
|
c.disconnectT = time.AfterFunc(disconnectSeekDelay, c.handleDisconnectTimeout)
|
||||||
}
|
}
|
||||||
@@ -668,6 +705,13 @@ func (c *WSClient) markDisconnected() {
|
|||||||
c.rebootT = time.AfterFunc(disconnectRebootDelay, c.handleRebootTimeout)
|
c.rebootT = time.AfterFunc(disconnectRebootDelay, c.handleRebootTimeout)
|
||||||
}
|
}
|
||||||
c.connMu.Unlock()
|
c.connMu.Unlock()
|
||||||
|
|
||||||
|
// Initial dial failures are already represented by the startup message and
|
||||||
|
// journal retry logs. The prominent disconnect alert is reserved for losing
|
||||||
|
// a connection that was actually established.
|
||||||
|
if wasConnected {
|
||||||
|
c.console.Notify("Control server connection lost. Automatic dock seek in 1 minute; rover reboot in 6 minutes if the connection is not restored.")
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
func (c *WSClient) handleDisconnectTimeout() {
|
func (c *WSClient) handleDisconnectTimeout() {
|
||||||
@@ -679,6 +723,7 @@ func (c *WSClient) handleDisconnectTimeout() {
|
|||||||
c.seekIssued = true
|
c.seekIssued = true
|
||||||
c.connMu.Unlock()
|
c.connMu.Unlock()
|
||||||
|
|
||||||
|
c.console.Notify("Control server has been disconnected for 1 minute. Seeking the dock now.")
|
||||||
if err := c.adapter.SeekDock(); err != nil {
|
if err := c.adapter.SeekDock(); err != nil {
|
||||||
c.log.Printf("seek dock on disconnect failed: %v", err)
|
c.log.Printf("seek dock on disconnect failed: %v", err)
|
||||||
return
|
return
|
||||||
@@ -695,6 +740,7 @@ func (c *WSClient) handleRebootTimeout() {
|
|||||||
c.rebootIssued = true
|
c.rebootIssued = true
|
||||||
c.connMu.Unlock()
|
c.connMu.Unlock()
|
||||||
|
|
||||||
|
c.console.Notify("Control server has been disconnected for 6 minutes. Rebooting the rover now.")
|
||||||
c.log.Printf("rebooting pi after prolonged websocket disconnect")
|
c.log.Printf("rebooting pi after prolonged websocket disconnect")
|
||||||
cmd := exec.Command("systemctl", "reboot")
|
cmd := exec.Command("systemctl", "reboot")
|
||||||
if err := cmd.Start(); err != nil {
|
if err := cmd.Start(); err != nil {
|
||||||
@@ -720,10 +766,16 @@ func (c *WSClient) recoverSensorStream(idleFor time.Duration, cmdPause time.Dura
|
|||||||
c.emitEvent("sensorWatchdog.restart", map[string]any{
|
c.emitEvent("sensorWatchdog.restart", map[string]any{
|
||||||
"idleMs": idleFor.Milliseconds(),
|
"idleMs": idleFor.Milliseconds(),
|
||||||
})
|
})
|
||||||
|
if c.openSensorWatchdogEpisode() {
|
||||||
|
c.console.Notify(fmt.Sprintf("Sensor watchdog is restarting the Roomba sensor stream after %.1f seconds without data.", idleFor.Seconds()))
|
||||||
|
}
|
||||||
|
|
||||||
if err := c.adapter.StartOI(); err != nil {
|
if err := c.adapter.StartOI(); err != nil {
|
||||||
c.log.Printf("watchdog start OI failed: %v", err)
|
c.log.Printf("watchdog start OI failed: %v", err)
|
||||||
c.emitEvent("sensorWatchdog.error", map[string]any{"error": err.Error()})
|
c.emitEvent("sensorWatchdog.error", map[string]any{"error": err.Error()})
|
||||||
|
// Unlike the restart notice, every concrete command failure is useful
|
||||||
|
// diagnostic information and may change between recovery attempts.
|
||||||
|
c.console.Notify(fmt.Sprintf("Sensor watchdog recovery failed while starting the Roomba OI: %v", err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
if cmdPause > 0 {
|
if cmdPause > 0 {
|
||||||
@@ -733,12 +785,53 @@ func (c *WSClient) recoverSensorStream(idleFor time.Duration, cmdPause time.Dura
|
|||||||
if err := c.adapter.StartSensorStream(defaultStreamPackets); err != nil {
|
if err := c.adapter.StartSensorStream(defaultStreamPackets); err != nil {
|
||||||
c.log.Printf("watchdog start stream failed: %v", err)
|
c.log.Printf("watchdog start stream failed: %v", err)
|
||||||
c.emitEvent("sensorWatchdog.error", map[string]any{"error": err.Error()})
|
c.emitEvent("sensorWatchdog.error", map[string]any{"error": err.Error()})
|
||||||
|
c.console.Notify(fmt.Sprintf("Sensor watchdog recovery failed while starting the sensor stream: %v", err))
|
||||||
return
|
return
|
||||||
}
|
}
|
||||||
|
|
||||||
c.emitEvent("sensorWatchdog.ok", map[string]any{
|
c.emitEvent("sensorWatchdog.ok", map[string]any{
|
||||||
"idleMs": idleFor.Milliseconds(),
|
"idleMs": idleFor.Milliseconds(),
|
||||||
})
|
})
|
||||||
|
if c.markSensorWatchdogCommandsOK() {
|
||||||
|
// Match the existing sensorWatchdog.ok contract precisely: this says
|
||||||
|
// the recovery commands succeeded, not that a new frame has arrived.
|
||||||
|
c.console.Notify("Sensor watchdog successfully sent the sensor-stream restart commands.")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// openSensorWatchdogEpisode reports whether this is the first recovery attempt
|
||||||
|
// since sensor frames stopped. The watchdog can retry every few seconds, so
|
||||||
|
// tracking the outage as one episode keeps the login console readable.
|
||||||
|
func (c *WSClient) openSensorWatchdogEpisode() bool {
|
||||||
|
c.watchdogMu.Lock()
|
||||||
|
defer c.watchdogMu.Unlock()
|
||||||
|
|
||||||
|
if c.watchdogOpen {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
c.watchdogOpen = true
|
||||||
|
c.watchdogOK = false
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
// markSensorWatchdogCommandsOK suppresses duplicate success notices while the
|
||||||
|
// rover is still waiting for a real frame to close the current outage.
|
||||||
|
func (c *WSClient) markSensorWatchdogCommandsOK() bool {
|
||||||
|
c.watchdogMu.Lock()
|
||||||
|
defer c.watchdogMu.Unlock()
|
||||||
|
|
||||||
|
if c.watchdogOK {
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
c.watchdogOK = true
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
func (c *WSClient) closeSensorWatchdogEpisode() {
|
||||||
|
c.watchdogMu.Lock()
|
||||||
|
c.watchdogOpen = false
|
||||||
|
c.watchdogOK = false
|
||||||
|
c.watchdogMu.Unlock()
|
||||||
}
|
}
|
||||||
|
|
||||||
func isModeOpcode(op byte) bool {
|
func isModeOpcode(op byte) bool {
|
||||||
|
|||||||
@@ -0,0 +1,27 @@
|
|||||||
|
package roverd
|
||||||
|
|
||||||
|
import "testing"
|
||||||
|
|
||||||
|
func TestSensorWatchdogConsoleEpisodeSuppressesDuplicateStatusMessages(t *testing.T) {
|
||||||
|
client := &WSClient{}
|
||||||
|
|
||||||
|
if !client.openSensorWatchdogEpisode() {
|
||||||
|
t.Fatal("first recovery attempt should announce the watchdog episode")
|
||||||
|
}
|
||||||
|
if client.openSensorWatchdogEpisode() {
|
||||||
|
t.Fatal("repeated recovery attempt should not repeat the outage announcement")
|
||||||
|
}
|
||||||
|
if !client.markSensorWatchdogCommandsOK() {
|
||||||
|
t.Fatal("first successful command restart should be announced")
|
||||||
|
}
|
||||||
|
if client.markSensorWatchdogCommandsOK() {
|
||||||
|
t.Fatal("repeated successful command restart should not be announced")
|
||||||
|
}
|
||||||
|
|
||||||
|
// Receiving a real frame closes the outage. A later silence is a distinct
|
||||||
|
// incident and must therefore be visible on the console again.
|
||||||
|
client.closeSensorWatchdogEpisode()
|
||||||
|
if !client.openSensorWatchdogEpisode() {
|
||||||
|
t.Fatal("new outage after a sensor frame should be announced")
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -6,6 +6,10 @@ Wants=network-online.target
|
|||||||
[Service]
|
[Service]
|
||||||
Type=simple
|
Type=simple
|
||||||
ExecStart=/usr/local/bin/roverd -config /etc/roverd.yaml
|
ExecStart=/usr/local/bin/roverd -config /etc/roverd.yaml
|
||||||
|
# roverd cannot report an unexpected exit after its process is already gone.
|
||||||
|
# ExecStopPost fills only that gap; ordinary lifecycle messages remain owned by
|
||||||
|
# roverd, and SERVICE_RESULT prevents clean stops from being labeled failures.
|
||||||
|
ExecStopPost=/bin/sh -c 'if [ "$SERVICE_RESULT" != "success" ]; then /usr/bin/printf "\r\n*** rover alert ***\r\nroverd exited unexpectedly; systemd will restart it.\r\n" > /dev/tty1 || true; fi'
|
||||||
Restart=on-failure
|
Restart=on-failure
|
||||||
RestartSec=5
|
RestartSec=5
|
||||||
AmbientCapabilities=CAP_SYS_TTY_CONFIG CAP_SYS_RAWIO
|
AmbientCapabilities=CAP_SYS_TTY_CONFIG CAP_SYS_RAWIO
|
||||||
|
|||||||
+2
-2
File diff suppressed because one or more lines are too long
+1
-1
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
Binary file not shown.
|
After Width: | Height: | Size: 337 KiB |
@@ -12,8 +12,8 @@
|
|||||||
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent" />
|
||||||
<!-- site-metadata:inject -->
|
<!-- site-metadata:inject -->
|
||||||
<!-- analytics:inject -->
|
<!-- analytics:inject -->
|
||||||
<script type="module" crossorigin src="/assets/index-C0lpCbci.js"></script>
|
<script type="module" crossorigin src="/assets/index-CNVNbsvk.js"></script>
|
||||||
<link rel="stylesheet" crossorigin href="/assets/index-BITzjVQo.css">
|
<link rel="stylesheet" crossorigin href="/assets/index-B5TEaoXl.css">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="root"></div>
|
<div id="root"></div>
|
||||||
|
|||||||
@@ -97,8 +97,20 @@ roverManager.managerEvents.on('private', ({ roverId, open }) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
roverManager.managerEvents.on('rover', ({ action }) => {
|
roverManager.managerEvents.on('rover', ({ roverId, action }) => {
|
||||||
if (action === 'removed' || action === 'upsert') {
|
if (action === 'removed') {
|
||||||
|
/*
|
||||||
|
The physical rover record is the authority for current driver ownership.
|
||||||
|
Once it disappears, every assignment that names it must be released and
|
||||||
|
run through ordinary placement again. Leaving those map entries intact
|
||||||
|
lets the same id become visible after reconnect without recreating its
|
||||||
|
driver membership, which is the exact stale-UI/video-auth split this
|
||||||
|
lifecycle boundary must prevent.
|
||||||
|
*/
|
||||||
|
reassignFromRover(roverId);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (action === 'upsert') {
|
||||||
reassignWaiting();
|
reassignWaiting();
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -72,6 +72,7 @@ const {
|
|||||||
} = privateAccess;
|
} = privateAccess;
|
||||||
|
|
||||||
const roverLifecycle = createRoverLifecycle({
|
const roverLifecycle = createRoverLifecycle({
|
||||||
|
io,
|
||||||
rovers,
|
rovers,
|
||||||
socketToRovers,
|
socketToRovers,
|
||||||
managerEvents,
|
managerEvents,
|
||||||
@@ -86,6 +87,7 @@ const roverLifecycle = createRoverLifecycle({
|
|||||||
const {
|
const {
|
||||||
requestControl,
|
requestControl,
|
||||||
releaseControl,
|
releaseControl,
|
||||||
|
removeRoverDrivers,
|
||||||
isDriver,
|
isDriver,
|
||||||
canDrive,
|
canDrive,
|
||||||
getRoversForSocket,
|
getRoversForSocket,
|
||||||
@@ -119,6 +121,7 @@ const rosterLifecycle = createRosterLifecycle({
|
|||||||
normalizePrivateSafety,
|
normalizePrivateSafety,
|
||||||
stopDockGuard: (...args) => stopDockGuard(...args),
|
stopDockGuard: (...args) => stopDockGuard(...args),
|
||||||
getControlDenialReason,
|
getControlDenialReason,
|
||||||
|
removeRoverDrivers,
|
||||||
});
|
});
|
||||||
|
|
||||||
const {
|
const {
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ function createRosterLifecycle(deps) {
|
|||||||
isRoverVisibleToSocket,
|
isRoverVisibleToSocket,
|
||||||
normalizePrivateSafety,
|
normalizePrivateSafety,
|
||||||
stopDockGuard,
|
stopDockGuard,
|
||||||
|
removeRoverDrivers,
|
||||||
} = deps;
|
} = deps;
|
||||||
|
|
||||||
function ensureRecord(id) {
|
function ensureRecord(id) {
|
||||||
@@ -106,7 +107,14 @@ function createRosterLifecycle(deps) {
|
|||||||
function removeRover(id) {
|
function removeRover(id) {
|
||||||
const record = rovers.get(id);
|
const record = rovers.get(id);
|
||||||
if (!record) return;
|
if (!record) return;
|
||||||
|
/*
|
||||||
|
Remove the public record before emitting driver-removal events. Any
|
||||||
|
session sync caused by those events must already see this rover as
|
||||||
|
offline, while removeRoverDrivers still receives the captured record so
|
||||||
|
it can clean the reverse membership index and Socket.IO room membership.
|
||||||
|
*/
|
||||||
rovers.delete(id);
|
rovers.delete(id);
|
||||||
|
removeRoverDrivers(id, record);
|
||||||
stopDockGuard(id);
|
stopDockGuard(id);
|
||||||
privateButtonStates.delete(id);
|
privateButtonStates.delete(id);
|
||||||
privateNoUsersSince.delete(id);
|
privateNoUsersSince.delete(id);
|
||||||
@@ -231,6 +239,11 @@ function createRosterLifecycle(deps) {
|
|||||||
cameraServo: record.meta?.cameraServo,
|
cameraServo: record.meta?.cameraServo,
|
||||||
audio: record.meta?.audio,
|
audio: record.meta?.audio,
|
||||||
horn: record.meta?.horn,
|
horn: record.meta?.horn,
|
||||||
|
// Generic peripheral metadata is already reduced by roverd to the fields
|
||||||
|
// the browser needs: stable process-local IDs, display names, and ordered
|
||||||
|
// controls. Preserve that order here instead of rebuilding the inventory,
|
||||||
|
// because ESP32 registration order is also the driver's display order.
|
||||||
|
peripherals: Array.isArray(record.meta?.peripherals) ? record.meta.peripherals : [],
|
||||||
headlight: record.meta?.headlight
|
headlight: record.meta?.headlight
|
||||||
? { ...record.meta.headlight, state: record.headlightState }
|
? { ...record.meta.headlight, state: record.headlightState }
|
||||||
: record.meta?.headlight,
|
: record.meta?.headlight,
|
||||||
|
|||||||
@@ -0,0 +1,65 @@
|
|||||||
|
// Rover Roster Lifecycle Tests
|
||||||
|
// Purpose: Verifies that boot-discovered accessory metadata reaches the public rover roster unchanged.
|
||||||
|
// Scope: Covers roster projection only; roverd remains responsible for validating and reducing device descriptions.
|
||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const { createRosterLifecycle } = require('./rosterLifecycle');
|
||||||
|
|
||||||
|
function createRosterManager(meta) {
|
||||||
|
const rovers = new Map([[
|
||||||
|
meta.name,
|
||||||
|
{
|
||||||
|
id: meta.name,
|
||||||
|
meta,
|
||||||
|
batteryState: null,
|
||||||
|
headlightState: null,
|
||||||
|
laserState: null,
|
||||||
|
locked: false,
|
||||||
|
lockReason: null,
|
||||||
|
lastSeen: 123,
|
||||||
|
},
|
||||||
|
]]);
|
||||||
|
|
||||||
|
return createRosterLifecycle({
|
||||||
|
rovers,
|
||||||
|
isPrivateRecord: () => false,
|
||||||
|
isPrivateOpen: () => true,
|
||||||
|
getPrivateSafety: () => ({}),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
test('getRoster preserves peripheral and control registration order', () => {
|
||||||
|
const peripherals = [
|
||||||
|
{
|
||||||
|
id: 'firmata-0',
|
||||||
|
name: 'Camera arm',
|
||||||
|
controls: [
|
||||||
|
{ id: 'position', type: 'slider', name: 'Position', min: 0, max: 180 },
|
||||||
|
{ id: 'action', type: 'button', name: 'Action', mode: 'momentary' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 'firmata-1',
|
||||||
|
name: 'Lighting',
|
||||||
|
controls: [
|
||||||
|
{ id: 'brightness', type: 'number', name: 'Brightness', min: 0, max: 255 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
const manager = createRosterManager({ name: 'rover-one', peripherals });
|
||||||
|
|
||||||
|
const [entry] = manager.getRoster();
|
||||||
|
|
||||||
|
// Deep equality verifies both the public field set and array order. The
|
||||||
|
// server must not alphabetize controls because their firmware order is a UI
|
||||||
|
// contract rather than incidental transport ordering.
|
||||||
|
assert.deepEqual(entry.peripherals, peripherals);
|
||||||
|
});
|
||||||
|
|
||||||
|
test('getRoster supplies an empty peripheral inventory when none was advertised', () => {
|
||||||
|
const manager = createRosterManager({ name: 'rover-one' });
|
||||||
|
|
||||||
|
const [entry] = manager.getRoster();
|
||||||
|
|
||||||
|
assert.deepEqual(entry.peripherals, []);
|
||||||
|
});
|
||||||
@@ -3,6 +3,7 @@
|
|||||||
// Scope: Keeps runtime behavior unchanged by reusing rover-manager state maps and injected policy helpers.
|
// Scope: Keeps runtime behavior unchanged by reusing rover-manager state maps and injected policy helpers.
|
||||||
function createRoverLifecycle(deps) {
|
function createRoverLifecycle(deps) {
|
||||||
const {
|
const {
|
||||||
|
io,
|
||||||
rovers,
|
rovers,
|
||||||
socketToRovers,
|
socketToRovers,
|
||||||
managerEvents,
|
managerEvents,
|
||||||
@@ -85,6 +86,40 @@ function createRoverLifecycle(deps) {
|
|||||||
managerEvents.emit('driver', { socketId: socket.id, roverId, action: 'remove' });
|
managerEvents.emit('driver', { socketId: socket.id, roverId, action: 'remove' });
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function removeRoverDrivers(roverId, removedRecord = null) {
|
||||||
|
/*
|
||||||
|
A rover connection owns the record that contains its driver set, but the
|
||||||
|
reverse socket-to-rover index outlives that record. Disconnect cleanup
|
||||||
|
must therefore remove both halves before a reconnect creates a fresh
|
||||||
|
record with the same id. Otherwise session assignment can name the rover
|
||||||
|
while video/control authorization correctly sees no driver membership.
|
||||||
|
|
||||||
|
removedRecord is accepted because rosterLifecycle deliberately deletes
|
||||||
|
the public rover record first. Session syncs triggered by the driver
|
||||||
|
events below will consequently hide the unavailable rover immediately,
|
||||||
|
even before assignmentService finishes normal reassignment.
|
||||||
|
*/
|
||||||
|
const record = removedRecord || rovers.get(roverId);
|
||||||
|
if (!record) return [];
|
||||||
|
const driverIds = Array.from(record.drivers || []);
|
||||||
|
|
||||||
|
driverIds.forEach((socketId) => {
|
||||||
|
const joined = socketToRovers.get(socketId);
|
||||||
|
if (joined) {
|
||||||
|
joined.delete(roverId);
|
||||||
|
if (joined.size === 0) socketToRovers.delete(socketId);
|
||||||
|
}
|
||||||
|
|
||||||
|
const socket = io.sockets.sockets.get(socketId);
|
||||||
|
socket?.leave(record.room);
|
||||||
|
record.drivers.delete(socketId);
|
||||||
|
turnService.driverRemoved(roverId, socketId);
|
||||||
|
managerEvents.emit('driver', { socketId, roverId, action: 'remove' });
|
||||||
|
});
|
||||||
|
|
||||||
|
return driverIds;
|
||||||
|
}
|
||||||
|
|
||||||
function isDriver(roverId, socket) {
|
function isDriver(roverId, socket) {
|
||||||
const record = rovers.get(roverId);
|
const record = rovers.get(roverId);
|
||||||
if (!record) return false;
|
if (!record) return false;
|
||||||
@@ -175,6 +210,7 @@ function createRoverLifecycle(deps) {
|
|||||||
removeSocket,
|
removeSocket,
|
||||||
requestControl,
|
requestControl,
|
||||||
releaseControl,
|
releaseControl,
|
||||||
|
removeRoverDrivers,
|
||||||
isDriver,
|
isDriver,
|
||||||
canDrive,
|
canDrive,
|
||||||
getRoversForSocket,
|
getRoversForSocket,
|
||||||
|
|||||||
@@ -0,0 +1,59 @@
|
|||||||
|
// Rover Manager Lifecycle Tests
|
||||||
|
// Purpose: Verifies that physical rover removal clears every ownership index before a same-id reconnect.
|
||||||
|
// Scope: Covers driver membership cleanup only; assignment placement policy remains in assignmentService.
|
||||||
|
const test = require('node:test');
|
||||||
|
const assert = require('node:assert/strict');
|
||||||
|
const EventEmitter = require('node:events');
|
||||||
|
const { createRoverLifecycle } = require('./roverLifecycle');
|
||||||
|
|
||||||
|
test('removing a rover clears driver sets, reverse membership, rooms, and turns', () => {
|
||||||
|
const roverId = 'rover-one';
|
||||||
|
const socketId = 'driver-one';
|
||||||
|
const leftRooms = [];
|
||||||
|
const removedTurns = [];
|
||||||
|
const driverEvents = [];
|
||||||
|
const socket = {
|
||||||
|
id: socketId,
|
||||||
|
leave: (room) => leftRooms.push(room),
|
||||||
|
};
|
||||||
|
const record = {
|
||||||
|
id: roverId,
|
||||||
|
room: `rover:${roverId}`,
|
||||||
|
drivers: new Set([socketId]),
|
||||||
|
};
|
||||||
|
const rovers = new Map([[roverId, record]]);
|
||||||
|
const socketToRovers = new Map([[socketId, new Set([roverId])]]);
|
||||||
|
const managerEvents = new EventEmitter();
|
||||||
|
managerEvents.on('driver', (event) => driverEvents.push(event));
|
||||||
|
|
||||||
|
const lifecycle = createRoverLifecycle({
|
||||||
|
io: { sockets: { sockets: new Map([[socketId, socket]]) } },
|
||||||
|
rovers,
|
||||||
|
socketToRovers,
|
||||||
|
managerEvents,
|
||||||
|
turnService: {
|
||||||
|
driverRemoved: (removedRoverId, removedSocketId) => {
|
||||||
|
removedTurns.push([removedRoverId, removedSocketId]);
|
||||||
|
},
|
||||||
|
},
|
||||||
|
isAdmin: () => false,
|
||||||
|
sendAlert: () => {},
|
||||||
|
ALERT_COLOR: '#000000',
|
||||||
|
getMode: () => 'public',
|
||||||
|
getControlDenialReason: () => null,
|
||||||
|
});
|
||||||
|
|
||||||
|
/* Mirror rosterLifecycle's ordering: the public record is gone before the
|
||||||
|
captured record is supplied for complete membership cleanup. */
|
||||||
|
rovers.delete(roverId);
|
||||||
|
const removedDriverIds = lifecycle.removeRoverDrivers(roverId, record);
|
||||||
|
|
||||||
|
assert.deepEqual(removedDriverIds, [socketId]);
|
||||||
|
assert.equal(record.drivers.size, 0);
|
||||||
|
assert.equal(socketToRovers.has(socketId), false);
|
||||||
|
assert.deepEqual(leftRooms, [`rover:${roverId}`]);
|
||||||
|
assert.deepEqual(removedTurns, [[roverId, socketId]]);
|
||||||
|
assert.deepEqual(driverEvents, [
|
||||||
|
{ socketId, roverId, action: 'remove' },
|
||||||
|
]);
|
||||||
|
});
|
||||||
@@ -135,6 +135,20 @@ function buildUserEntry(socket) {
|
|||||||
const role = getRole(socket);
|
const role = getRole(socket);
|
||||||
const assignment = assignmentService.describeAssignment(socket.id);
|
const assignment = assignmentService.describeAssignment(socket.id);
|
||||||
const primaryRover = roverManager.getPrimaryRoverForSocket(socket.id);
|
const primaryRover = roverManager.getPrimaryRoverForSocket(socket.id);
|
||||||
|
/*
|
||||||
|
assignmentService owns automatic placement policy, while roverManager owns
|
||||||
|
actual control membership. Validate both candidate indexes before exposing
|
||||||
|
presence because neither cached direction is authoritative without the
|
||||||
|
physical rover record agreeing that this socket is one of its drivers.
|
||||||
|
*/
|
||||||
|
const verifiedPrimaryRover = primaryRover
|
||||||
|
&& roverManager.isDriver(primaryRover, socket)
|
||||||
|
? primaryRover
|
||||||
|
: null;
|
||||||
|
const verifiedAssignmentRover = assignment?.roverId
|
||||||
|
&& roverManager.isDriver(assignment.roverId, socket)
|
||||||
|
? assignment.roverId
|
||||||
|
: null;
|
||||||
const ptzChatTarget = getPtzChatTargetForSocket(socket.id);
|
const ptzChatTarget = getPtzChatTargetForSocket(socket.id);
|
||||||
return {
|
return {
|
||||||
socketId: socket.id,
|
socketId: socket.id,
|
||||||
@@ -147,7 +161,7 @@ function buildUserEntry(socket) {
|
|||||||
the PTZ chat target while the socket is queued or operating so presence,
|
the PTZ chat target while the socket is queued or operating so presence,
|
||||||
queue lookup, and chat identity all agree.
|
queue lookup, and chat identity all agree.
|
||||||
*/
|
*/
|
||||||
roverId: ptzChatTarget?.roverId || primaryRover || assignment?.roverId || null,
|
roverId: ptzChatTarget?.roverId || verifiedPrimaryRover || verifiedAssignmentRover || null,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -172,7 +186,17 @@ function buildSession(socket) {
|
|||||||
}));
|
}));
|
||||||
const roster = roverManager.getRosterForSocket(socket);
|
const roster = roverManager.getRosterForSocket(socket);
|
||||||
const assignment = assignmentService.describeAssignment(socket?.id || '');
|
const assignment = assignmentService.describeAssignment(socket?.id || '');
|
||||||
const assignmentRoverId = filterVisibleRoverId(socket, assignment?.roverId);
|
/*
|
||||||
|
Visibility alone is insufficient here: a reconnected rover can be visible
|
||||||
|
before a stale assignment map has recreated actual driver membership. The
|
||||||
|
session contract consumed by every UI surface must require both visibility
|
||||||
|
and roverManager's authoritative membership check.
|
||||||
|
*/
|
||||||
|
const verifiedAssignmentRover = assignment?.roverId
|
||||||
|
&& roverManager.isDriver(assignment.roverId, socket)
|
||||||
|
? assignment.roverId
|
||||||
|
: null;
|
||||||
|
const assignmentRoverId = filterVisibleRoverId(socket, verifiedAssignmentRover);
|
||||||
const activeDrivers = filterActiveDriversForSocket(getActiveDrivers(), socket);
|
const activeDrivers = filterActiveDriversForSocket(getActiveDrivers(), socket);
|
||||||
const turnQueues = filterTurnQueuesForSocket(getTurnQueues(), socket);
|
const turnQueues = filterTurnQueuesForSocket(getTurnQueues(), socket);
|
||||||
const socials = features.socials && configuredSocials?.length ? configuredSocials : [];
|
const socials = features.socials && configuredSocials?.length ? configuredSocials : [];
|
||||||
|
|||||||
Binary file not shown.
|
After Width: | Height: | Size: 337 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 4.8 MiB |
@@ -0,0 +1,42 @@
|
|||||||
|
// Desktop Accessories Expansion
|
||||||
|
// Purpose: Places generic rover controls on a collapsible surface centered along the video's left wall.
|
||||||
|
// Scope: Owns desktop positioning and persisted visibility while reusing the layout-independent control renderer.
|
||||||
|
import RoverAccessoryControls from '../../../RoverAccessoryControls/index.jsx';
|
||||||
|
import AccessoriesToggle from '../../../RoverAccessoryControls/AccessoriesToggle.jsx';
|
||||||
|
import useRoverAccessories from '../../../RoverAccessoryControls/useRoverAccessories.js';
|
||||||
|
import usePodVisibility from './usePodVisibility.js';
|
||||||
|
|
||||||
|
export default function AccessoriesExpansion({ roverId }) {
|
||||||
|
const { hasAccessories } = useRoverAccessories(roverId);
|
||||||
|
const [open, setOpen] = usePodVisibility('accessories', false);
|
||||||
|
|
||||||
|
// Do not leave an invisible anchor or reserved HUD area on rovers whose
|
||||||
|
// peripherals provide only standardized controls or no controls at all.
|
||||||
|
if (!hasAccessories) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="pointer-events-none absolute inset-y-0 left-0 z-20 flex items-center">
|
||||||
|
{/* The tab remains attached to the video's left wall. When open, this
|
||||||
|
single shell grows around both the unchanged tab position and the
|
||||||
|
controls to its right, so the controls are not rendered as a second
|
||||||
|
disconnected panel. Its height follows content until the shared
|
||||||
|
renderer reaches the scrolling boundary. */}
|
||||||
|
<div className="pointer-events-auto flex max-h-[70vh] items-center overflow-hidden rounded-r-xl bg-black/60">
|
||||||
|
<AccessoriesToggle
|
||||||
|
label="Accessories"
|
||||||
|
ariaLabel={open ? 'Hide accessory controls' : 'Show accessory controls'}
|
||||||
|
onClick={() => setOpen(!open)}
|
||||||
|
hud
|
||||||
|
className="!h-28"
|
||||||
|
/>
|
||||||
|
{open ? (
|
||||||
|
<RoverAccessoryControls
|
||||||
|
roverId={roverId}
|
||||||
|
plainCenteredHeadings
|
||||||
|
className="w-64 max-h-[70vh]"
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -4,6 +4,7 @@ import TopLeftPod from './TopLeftPod.jsx';
|
|||||||
import TopRightPod from './TopRightPod.jsx';
|
import TopRightPod from './TopRightPod.jsx';
|
||||||
import BottomLeftPod from './BottomLeftPod.jsx';
|
import BottomLeftPod from './BottomLeftPod.jsx';
|
||||||
import BottomRightPod from './BottomRightPod.jsx';
|
import BottomRightPod from './BottomRightPod.jsx';
|
||||||
|
import AccessoriesExpansion from './AccessoriesExpansion.jsx';
|
||||||
import { useDriverLayout } from '../../../../layouts/driver/DriverLayoutContext.jsx';
|
import { useDriverLayout } from '../../../../layouts/driver/DriverLayoutContext.jsx';
|
||||||
|
|
||||||
export default function CornerPods({ roverId }) {
|
export default function CornerPods({ roverId }) {
|
||||||
@@ -17,6 +18,9 @@ export default function CornerPods({ roverId }) {
|
|||||||
{/* The mobile layouts already provide large touch controls around the video.
|
{/* The mobile layouts already provide large touch controls around the video.
|
||||||
Omitting this pod avoids presenting duplicate horn, light, and laser actions. */}
|
Omitting this pod avoids presenting duplicate horn, light, and laser actions. */}
|
||||||
{showPhysicalControlPods ? <BottomLeftPod roverId={roverId} /> : null}
|
{showPhysicalControlPods ? <BottomLeftPod roverId={roverId} /> : null}
|
||||||
|
{/* Generic accessory controls stay on the same left side at every
|
||||||
|
breakpoint, but mobile owns their placement inside AuxColumn. */}
|
||||||
|
{showPhysicalControlPods ? <AccessoriesExpansion roverId={roverId} /> : null}
|
||||||
{/* BottomRightPod also owns the independent chat expansion, so it remains mounted
|
{/* BottomRightPod also owns the independent chat expansion, so it remains mounted
|
||||||
on mobile and determines its own camera-control visibility from layout context. */}
|
on mobile and determines its own camera-control visibility from layout context. */}
|
||||||
<BottomRightPod roverId={roverId} />
|
<BottomRightPod roverId={roverId} />
|
||||||
|
|||||||
@@ -18,42 +18,69 @@ import ExpansionPanel from '../CornerPods/ExpansionPanel.jsx';
|
|||||||
import usePodVisibility from '../CornerPods/usePodVisibility.js';
|
import usePodVisibility from '../CornerPods/usePodVisibility.js';
|
||||||
|
|
||||||
function DockedAction({ driveKeyLabel, pending, controlsDisabled, error, onUndock }) {
|
function DockedAction({ driveKeyLabel, pending, controlsDisabled, error, onUndock }) {
|
||||||
|
const [hidden, setHidden] = useState(false);
|
||||||
const waitingForTurn = controlsDisabled && !pending;
|
const waitingForTurn = controlsDisabled && !pending;
|
||||||
|
|
||||||
|
/* The dismissal belongs to this mounted docked episode. DockingHud unmounts
|
||||||
|
this component when the rover leaves the base, and its roverId key remounts
|
||||||
|
it for a different assignment, so no persistence or reset effect is needed. */
|
||||||
|
if (hidden && !pending) return null;
|
||||||
|
|
||||||
|
const mainToneClass = waitingForTurn
|
||||||
|
? 'cursor-not-allowed bg-slate-950/95 ring-slate-400/70'
|
||||||
|
: 'bg-emerald-950/90 ring-emerald-300/80 hover:bg-emerald-900/95 focus-visible:ring-emerald-200 disabled:cursor-wait disabled:opacity-75';
|
||||||
|
const hideToneClass = waitingForTurn
|
||||||
|
? 'bg-slate-950/95 ring-slate-400/70 hover:bg-slate-900'
|
||||||
|
: 'bg-emerald-950/90 ring-emerald-300/80 hover:bg-emerald-900/95 focus-visible:ring-emerald-200';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="pointer-events-none absolute inset-0 z-30 flex items-center justify-center p-6">
|
<>
|
||||||
<button
|
{/* The docked shield is owned by the dismissible action so hiding the
|
||||||
type="button"
|
prompt also reveals the video and ordinary HUD instead of leaving an
|
||||||
disabled={pending || controlsDisabled}
|
unexplained dark, input-blocking layer behind. */}
|
||||||
onClick={onUndock}
|
<div className="pointer-events-auto absolute inset-0 z-[25] bg-black/75" aria-hidden="true" />
|
||||||
className={`pointer-events-auto flex w-[min(32rem,80%)] flex-col items-center gap-2 px-8 py-7 text-center text-white shadow-2xl ring-2 transition focus-visible:outline-none focus-visible:ring-4 ${
|
<div className="pointer-events-none absolute inset-0 z-30 flex items-center justify-center p-6">
|
||||||
waitingForTurn
|
<div className="relative w-[min(32rem,80%)]">
|
||||||
? 'cursor-not-allowed bg-slate-950/95 ring-slate-400/70'
|
<button
|
||||||
: 'bg-emerald-950/90 ring-emerald-300/80 hover:bg-emerald-900/95 focus-visible:ring-emerald-200 disabled:cursor-wait disabled:opacity-75'
|
type="button"
|
||||||
}`}
|
disabled={pending || controlsDisabled}
|
||||||
>
|
onClick={onUndock}
|
||||||
<strong className="text-3xl leading-tight">{pending ? 'Undocking…' : 'Your rover is docked'}</strong>
|
className={`pointer-events-auto flex w-full flex-col items-center gap-2 px-8 py-7 text-center text-white shadow-2xl ring-2 transition focus-visible:outline-none focus-visible:ring-4 ${mainToneClass}`}
|
||||||
{pending ? (
|
>
|
||||||
null
|
<strong className="text-3xl leading-tight">{pending ? 'Undocking…' : 'Your rover is docked'}</strong>
|
||||||
) : waitingForTurn ? (
|
{pending ? (
|
||||||
/* A disabled action must explain the ownership constraint instead of
|
null
|
||||||
continuing to advertise a click and keybind that cannot succeed. */
|
) : waitingForTurn ? (
|
||||||
<span className="text-lg font-semibold leading-snug text-slate-300">
|
/* A disabled action must explain the ownership constraint instead of
|
||||||
Wait for your turn to undock.
|
continuing to advertise a click and keybind that cannot succeed. */
|
||||||
</span>
|
<span className="text-lg font-semibold leading-snug text-slate-300">
|
||||||
) : (
|
Wait for your turn to undock.
|
||||||
<span className="text-lg font-semibold leading-snug text-emerald-50">
|
</span>
|
||||||
Click here
|
) : (
|
||||||
{driveKeyLabel ? (
|
<span className="text-lg font-semibold leading-snug text-emerald-50">
|
||||||
<>
|
Click here
|
||||||
{' '}or press <KeyPill label={driveKeyLabel} />
|
{driveKeyLabel ? (
|
||||||
</>
|
<>
|
||||||
) : null}
|
{' '}or press <KeyPill label={driveKeyLabel} />
|
||||||
{' '}to undock and drive the rover
|
</>
|
||||||
</span>
|
) : null}
|
||||||
)}
|
{' '}to undock and drive the rover
|
||||||
{error ? <span className="text-sm font-semibold text-red-200">{error}</span> : null}
|
</span>
|
||||||
</button>
|
)}
|
||||||
</div>
|
{error ? <span className="text-sm font-semibold text-red-200">{error}</span> : null}
|
||||||
|
</button>
|
||||||
|
{!pending ? (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setHidden(true)}
|
||||||
|
className={`pointer-events-auto absolute left-1/2 top-full -translate-x-1/2 rounded-b-lg px-6 py-1.5 text-sm font-bold text-white shadow-xl ring-2 transition focus-visible:outline-none focus-visible:ring-4 ${hideToneClass}`}
|
||||||
|
>
|
||||||
|
Hide
|
||||||
|
</button>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -318,15 +345,12 @@ export default function DockingHud({ roverId }) {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{/* This single layer both dims and blocks the ordinary rover HUD. A passive
|
{/* Automatic docking keeps its own lighter blocking shield. The ordinary
|
||||||
undocked rover is still moving autonomously, so it gets a lighter but equally
|
docked shield lives inside DockedAction because the new Hide control
|
||||||
blocking shield. Explicit pending state keeps the correct shield mounted until
|
must dismiss the prompt and its dimming as one coherent surface. */}
|
||||||
the complete drive sequence finishes even as telemetry changes underneath it. */}
|
|
||||||
<div
|
<div
|
||||||
className={`absolute inset-0 z-[25] transition-all duration-300 ${
|
className={`absolute inset-0 z-[25] transition-all duration-300 ${
|
||||||
docked || pendingAction === 'undocking'
|
autoDocking || pendingAction === 'resuming'
|
||||||
? 'pointer-events-auto bg-black/75 opacity-100'
|
|
||||||
: autoDocking || pendingAction === 'resuming'
|
|
||||||
? 'pointer-events-auto bg-black/55 opacity-100'
|
? 'pointer-events-auto bg-black/55 opacity-100'
|
||||||
: 'pointer-events-none opacity-0'
|
: 'pointer-events-none opacity-0'
|
||||||
}`}
|
}`}
|
||||||
@@ -335,6 +359,7 @@ export default function DockingHud({ roverId }) {
|
|||||||
|
|
||||||
{docked || pendingAction === 'undocking' ? (
|
{docked || pendingAction === 'undocking' ? (
|
||||||
<DockedAction
|
<DockedAction
|
||||||
|
key={roverId}
|
||||||
driveKeyLabel={driveKeyLabel}
|
driveKeyLabel={driveKeyLabel}
|
||||||
pending={pendingAction === 'undocking'}
|
pending={pendingAction === 'undocking'}
|
||||||
controlsDisabled={!canControl}
|
controlsDisabled={!canControl}
|
||||||
|
|||||||
@@ -0,0 +1,40 @@
|
|||||||
|
// Initial Session Overlay
|
||||||
|
// Purpose: Hides incomplete driver-page placeholders until the first authoritative session snapshot arrives.
|
||||||
|
// Scope: Provides startup presentation only; it deliberately does not delay or alter page initialization underneath.
|
||||||
|
import { useSessionSelector } from '../../context/SessionContext.jsx';
|
||||||
|
import spinnerImage from '../../assets/spinner.png';
|
||||||
|
import './styles.css';
|
||||||
|
|
||||||
|
export default function InitialSessionOverlay() {
|
||||||
|
const connected = useSessionSelector((state) => Boolean(state.connected));
|
||||||
|
const sessionReady = useSessionSelector((state) => state.session !== null);
|
||||||
|
|
||||||
|
if (sessionReady) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className="fixed inset-0 z-[1000] flex items-center justify-center bg-black text-slate-200"
|
||||||
|
role="status"
|
||||||
|
aria-live="polite"
|
||||||
|
aria-label={connected ? 'Loading session' : 'Connecting'}
|
||||||
|
>
|
||||||
|
<div className="flex flex-col items-center gap-3">
|
||||||
|
{/* The source image is intentionally constrained to a small fixed box;
|
||||||
|
its intrinsic pixel dimensions must never determine overlay layout.
|
||||||
|
Reduced-motion users still see the identifying image without either
|
||||||
|
the rotation or continuously changing color. */}
|
||||||
|
<div className="initial-session-spinner-rotation h-20 w-20" aria-hidden="true">
|
||||||
|
<img
|
||||||
|
src={spinnerImage}
|
||||||
|
alt=""
|
||||||
|
draggable="false"
|
||||||
|
className="initial-session-spinner-image h-full w-full select-none object-contain"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="text-sm font-medium text-slate-300">
|
||||||
|
{connected ? 'Loading session…' : 'Connecting…'}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
/*
|
||||||
|
These animations belong only to InitialSessionOverlay. Keeping them beside
|
||||||
|
the component avoids adding feature-specific behavior to the global styles.
|
||||||
|
Rotation and hue use separate elements so their independent infinite cycles
|
||||||
|
cannot overwrite one another's transform or filter properties.
|
||||||
|
*/
|
||||||
|
@keyframes initial-session-spinner-rotate {
|
||||||
|
from {
|
||||||
|
transform: rotate(0deg);
|
||||||
|
}
|
||||||
|
|
||||||
|
to {
|
||||||
|
transform: rotate(360deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@keyframes initial-session-spinner-hue {
|
||||||
|
from {
|
||||||
|
filter: hue-rotate(0deg);
|
||||||
|
}
|
||||||
|
|
||||||
|
to {
|
||||||
|
filter: hue-rotate(360deg);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
@media (prefers-reduced-motion: no-preference) {
|
||||||
|
.initial-session-spinner-rotation {
|
||||||
|
animation: initial-session-spinner-rotate 1.8s linear infinite;
|
||||||
|
}
|
||||||
|
|
||||||
|
.initial-session-spinner-image {
|
||||||
|
animation: initial-session-spinner-hue 2.8s linear infinite;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,7 @@
|
|||||||
// Aux Column
|
// Aux Column
|
||||||
// Purpose: Assembles the mobile auxiliary controls column, which is the left column by default.
|
// Purpose: Assembles the mobile auxiliary controls column, which is the left column by default.
|
||||||
// Scope: Owns mobile aux/camera/headlight/laser/horn wiring while reusing desktop variation components where intended.
|
// Scope: Owns mobile aux/camera/headlight/laser/horn wiring while reusing desktop variation components where intended.
|
||||||
import { useCallback, useEffect, useRef } from 'react';
|
import { useCallback, useEffect, useRef, useState } from 'react';
|
||||||
import { FaBullhorn, FaCrosshairs, FaLightbulb } from 'react-icons/fa';
|
import { FaBullhorn, FaCrosshairs, FaLightbulb } from 'react-icons/fa';
|
||||||
import './mobileControls.css';
|
import './mobileControls.css';
|
||||||
import { useControlActions, useControlSelector } from '../../controls/index.js';
|
import { useControlActions, useControlSelector } from '../../controls/index.js';
|
||||||
@@ -15,11 +15,14 @@ import { AUX_ZERO } from './constants.js';
|
|||||||
import VacuumControls from './VacuumControls.jsx';
|
import VacuumControls from './VacuumControls.jsx';
|
||||||
import VerticalCameraTilt from './VerticalCameraTilt.jsx';
|
import VerticalCameraTilt from './VerticalCameraTilt.jsx';
|
||||||
import { useSessionSelector } from '../../context/SessionContext.jsx';
|
import { useSessionSelector } from '../../context/SessionContext.jsx';
|
||||||
|
import RoverAccessoryControls from '../RoverAccessoryControls/index.jsx';
|
||||||
|
import AccessoriesToggle from '../RoverAccessoryControls/AccessoriesToggle.jsx';
|
||||||
|
import useRoverAccessories from '../RoverAccessoryControls/useRoverAccessories.js';
|
||||||
|
|
||||||
const CAMERA_TILT_STEP_DEGREES = 0.5;
|
const CAMERA_TILT_STEP_DEGREES = 0.5;
|
||||||
const CAMERA_TILT_PRECISION_STEP_DEGREES = 0.1;
|
const CAMERA_TILT_PRECISION_STEP_DEGREES = 0.1;
|
||||||
|
|
||||||
function AuxColumnContent() {
|
function AuxColumnContent({ accessoriesAvailable, onShowAccessories }) {
|
||||||
const roverId = useControlSelector((control) => control.state.roverId);
|
const roverId = useControlSelector((control) => control.state.roverId);
|
||||||
const roomLightsLockedOn = useSessionSelector((state) => Boolean(state.session?.homeAssistant?.lightPolicy?.lockedOn));
|
const roomLightsLockedOn = useSessionSelector((state) => Boolean(state.session?.homeAssistant?.lightPolicy?.lockedOn));
|
||||||
const camera = useControlSelector((control) => control.state.camera);
|
const camera = useControlSelector((control) => control.state.camera);
|
||||||
@@ -119,11 +122,20 @@ function AuxColumnContent() {
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="mobile-touch-control grid h-full min-h-0 w-full grid-rows-[minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)] gap-0.5 text-slate-100">
|
<div className="mobile-touch-control grid h-full min-h-0 w-full grid-rows-[minmax(0,1fr)_minmax(0,1fr)_minmax(0,1fr)] gap-0.5 text-slate-100">
|
||||||
<VacuumControls
|
<div className={`mobile-touch-control grid min-h-0 gap-0.5 ${accessoriesAvailable ? 'grid-cols-[minmax(0,1fr)_2rem]' : 'grid-cols-1'}`}>
|
||||||
disabled={vacuumDisabled}
|
<VacuumControls
|
||||||
onPress={handleAuxPress}
|
disabled={vacuumDisabled}
|
||||||
onRelease={handleAuxRelease}
|
onPress={handleAuxPress}
|
||||||
/>
|
onRelease={handleAuxRelease}
|
||||||
|
/>
|
||||||
|
{accessoriesAvailable ? (
|
||||||
|
<AccessoriesToggle
|
||||||
|
label="Accessories"
|
||||||
|
ariaLabel="Show accessory controls"
|
||||||
|
onClick={onShowAccessories}
|
||||||
|
/>
|
||||||
|
) : null}
|
||||||
|
</div>
|
||||||
<div className="mobile-touch-control flex min-h-0 items-stretch gap-0.5">
|
<div className="mobile-touch-control flex min-h-0 items-stretch gap-0.5">
|
||||||
{cameraEnabled ? (
|
{cameraEnabled ? (
|
||||||
<VerticalCameraTilt
|
<VerticalCameraTilt
|
||||||
@@ -180,10 +192,49 @@ function AuxColumnContent() {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
export default function AuxColumn({ layout, className = '' }) {
|
function RoverAuxColumn({ roverId, layout, className }) {
|
||||||
|
const [showAccessories, setShowAccessories] = useState(false);
|
||||||
|
const { hasAccessories } = useRoverAccessories(roverId);
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className={`mobile-touch-control flex flex-col gap-0.5 ${className}`.trim()} data-mobile-layout={layout}>
|
<div className={`mobile-touch-control flex flex-col gap-0.5 ${className}`.trim()} data-mobile-layout={layout}>
|
||||||
<AuxColumnContent />
|
{showAccessories && hasAccessories ? (
|
||||||
|
<div className="mobile-touch-control h-full min-h-0 overflow-hidden">
|
||||||
|
<RoverAccessoryControls
|
||||||
|
roverId={roverId}
|
||||||
|
className="h-full"
|
||||||
|
headerAction={(
|
||||||
|
<AccessoriesToggle
|
||||||
|
label="Back"
|
||||||
|
ariaLabel="Return to auxiliary controls"
|
||||||
|
compact
|
||||||
|
onClick={() => setShowAccessories(false)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<AuxColumnContent
|
||||||
|
accessoriesAvailable={hasAccessories}
|
||||||
|
onShowAccessories={() => setShowAccessories(true)}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export default function AuxColumn({ layout, className = '' }) {
|
||||||
|
const roverId = useControlSelector((control) => control.state.roverId);
|
||||||
|
|
||||||
|
// Keying the stateful view by assignment makes every newly selected rover
|
||||||
|
// start in the familiar Aux view. It also guarantees that an Accessories
|
||||||
|
// view cannot remain open after changing to a rover without accessories.
|
||||||
|
return (
|
||||||
|
<RoverAuxColumn
|
||||||
|
key={roverId || 'no-rover'}
|
||||||
|
roverId={roverId}
|
||||||
|
layout={layout}
|
||||||
|
className={className}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|||||||
@@ -19,9 +19,9 @@ function ControlRow({ label, keyLabel }) {
|
|||||||
function DesktopQuickstart({ keymap }) {
|
function DesktopQuickstart({ keymap }) {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-0.5">
|
<div className="space-y-0.5">
|
||||||
<p className="text-sm text-slate-200">1. Press "Start Driving" put your rover into driving mode.</p>
|
<p className="text-sm text-slate-200">1. Click "Your rover is docked" to undock.</p>
|
||||||
<div className="space-y-0.5">
|
<div className="space-y-0.5">
|
||||||
<p className="text-sm text-slate-200">2. Use the drive controls to move your rover:</p>
|
<p className="text-sm text-slate-200">2. Drive with these keybindings:</p>
|
||||||
<div className="space-y-0.5">
|
<div className="space-y-0.5">
|
||||||
<ControlRow label="Forward" keyLabel={formatKeyLabel(keymap?.driveForward?.[0])} />
|
<ControlRow label="Forward" keyLabel={formatKeyLabel(keymap?.driveForward?.[0])} />
|
||||||
<ControlRow label="Backward" keyLabel={formatKeyLabel(keymap?.driveBackward?.[0])} />
|
<ControlRow label="Backward" keyLabel={formatKeyLabel(keymap?.driveBackward?.[0])} />
|
||||||
@@ -31,7 +31,8 @@ function DesktopQuickstart({ keymap }) {
|
|||||||
<ControlRow label="Move slower" keyLabel={formatKeyLabel(keymap?.slowModifier?.[0])} />
|
<ControlRow label="Move slower" keyLabel={formatKeyLabel(keymap?.slowModifier?.[0])} />
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<p className="text-sm text-slate-200">3. When done, enter "Docking Assist" and line up the front sensor with the dock sensor.</p>
|
<p className="text-sm text-slate-200">3. Use the video HUD for rover controls and information.</p>
|
||||||
|
<p className="text-sm text-slate-200">4. Click "Dock rover" when finished.</p>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -39,10 +40,11 @@ function DesktopQuickstart({ keymap }) {
|
|||||||
function MobileQuickstart() {
|
function MobileQuickstart() {
|
||||||
return (
|
return (
|
||||||
<div className="space-y-0.5 text-sm text-slate-200">
|
<div className="space-y-0.5 text-sm text-slate-200">
|
||||||
<p>1. Press "Start Driving" put your rover into driving mode.</p>
|
<p>1. Tap "Your rover is docked" to undock.</p>
|
||||||
<p>2. Touch and hold in Joystick area to move.</p>
|
<p>2. Hold and drag on the drive pad.</p>
|
||||||
<p>3. Use the other column for motor, horn, and camera controls.</p>
|
<p>3. Choose Precision, Normal, or Turbo above the drive pad.</p>
|
||||||
<p>4. When done, enter "Docking Assist" and line up the front sensor with the dock sensor.</p>
|
<p>4. Use the other column for rover controls.</p>
|
||||||
|
<p>5. Tap "Dock and charge" when finished.</p>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -71,7 +73,6 @@ export default function QuickstartOverlay({
|
|||||||
layout,
|
layout,
|
||||||
showOnLoad,
|
showOnLoad,
|
||||||
onToggleShowOnLoad,
|
onToggleShowOnLoad,
|
||||||
onOpenHelp,
|
|
||||||
onClose,
|
onClose,
|
||||||
}) {
|
}) {
|
||||||
const rawKeymap = useControlSelector((control) => control.state.keymap);
|
const rawKeymap = useControlSelector((control) => control.state.keymap);
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
// Accessories Vertical Toggle
|
||||||
|
// Purpose: Gives mobile and desktop the same edge-mounted control for changing accessory visibility.
|
||||||
|
// Scope: Owns only visual treatment and activation; each parent decides its position and destination.
|
||||||
|
import { FaPuzzlePiece } from 'react-icons/fa';
|
||||||
|
import { triggerTouchHaptic } from '../../lib/touchHaptics.js';
|
||||||
|
|
||||||
|
export default function AccessoriesToggle({
|
||||||
|
label,
|
||||||
|
ariaLabel,
|
||||||
|
onClick,
|
||||||
|
compact = false,
|
||||||
|
hud = false,
|
||||||
|
className = '',
|
||||||
|
}) {
|
||||||
|
// The Back action is still shorter than the vertical launcher, but it needs
|
||||||
|
// a normal touch target and a readable word instead of the previous tiny
|
||||||
|
// abbreviated control. The full launcher continues to fill the height its
|
||||||
|
// desktop or mobile parent assigns to it.
|
||||||
|
const sizeClass = compact ? 'h-8 w-14' : 'h-full w-8';
|
||||||
|
const toneClass = hud
|
||||||
|
// On desktop the tab sits inside the shared popout shell. Rounding only
|
||||||
|
// its exposed right edge preserves its left-wall attachment without
|
||||||
|
// introducing a separate accessory-specific panel treatment.
|
||||||
|
? 'rounded-r-xl border-0 bg-black/60 text-white shadow-none'
|
||||||
|
: 'rounded-xl border-2 border-cyan-300/70 bg-cyan-900 text-cyan-50 shadow-md';
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-label={ariaLabel || label}
|
||||||
|
onClick={() => {
|
||||||
|
triggerTouchHaptic('button');
|
||||||
|
onClick();
|
||||||
|
}}
|
||||||
|
className={`mobile-touch-control flex shrink-0 items-center justify-center text-sm font-semibold ${sizeClass} ${toneClass} ${className}`.trim()}
|
||||||
|
>
|
||||||
|
{/* Full launchers use vertical writing in the narrow wall space. The
|
||||||
|
compact Back action stays horizontal so it fits in the heading. */}
|
||||||
|
<span className={compact ? 'flex items-center' : 'flex items-center gap-1 [writing-mode:vertical-rl] rotate-180'}>
|
||||||
|
{!compact ? <FaPuzzlePiece className="shrink-0 text-sm" aria-hidden="true" /> : null}
|
||||||
|
<span>{label}</span>
|
||||||
|
</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,337 @@
|
|||||||
|
// Accessory Control Field
|
||||||
|
// Purpose: Maps one firmware-advertised generic control to a compact rover-control surface.
|
||||||
|
// Scope: Owns browser-local input semantics; transport and device-specific behavior stay outside this file.
|
||||||
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
|
import { triggerTouchHaptic } from '../../lib/touchHaptics.js';
|
||||||
|
|
||||||
|
function integerBound(value, fallback) {
|
||||||
|
return Number.isInteger(value) ? value : fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
function clampInteger(value, minimum, maximum) {
|
||||||
|
const numeric = Number(value);
|
||||||
|
if (!Number.isFinite(numeric)) return minimum;
|
||||||
|
return Math.min(maximum, Math.max(minimum, Math.round(numeric)));
|
||||||
|
}
|
||||||
|
|
||||||
|
function trimUnicode(value, maximumLength) {
|
||||||
|
// Array.from counts Unicode code points instead of UTF-16 code units. That
|
||||||
|
// mirrors Go's rune-count validation for emoji and other non-BMP characters.
|
||||||
|
return Array.from(String(value ?? '')).slice(0, maximumLength).join('');
|
||||||
|
}
|
||||||
|
|
||||||
|
const CARD_CLASS = 'mobile-touch-control rounded-xl border-2 px-2 py-1 text-slate-50';
|
||||||
|
// Sliders already contain a label row and a separate track. Giving that
|
||||||
|
// two-row control the same vertical padding as a one-row button made it much
|
||||||
|
// taller than its neighbors without improving its touch target.
|
||||||
|
const SLIDER_CARD_CLASS = 'mobile-touch-control rounded-xl border-2 px-1.5 py-0.5 text-slate-50';
|
||||||
|
const DISABLED_CLASS = 'disabled:cursor-not-allowed disabled:opacity-40';
|
||||||
|
|
||||||
|
function SliderControl({ peripheralId, control, disabled, send, value: storedValue }) {
|
||||||
|
const minimum = integerBound(control.min, 0);
|
||||||
|
const maximum = integerBound(control.max, minimum);
|
||||||
|
const value = Number.isInteger(storedValue)
|
||||||
|
? clampInteger(storedValue, minimum, maximum)
|
||||||
|
: minimum;
|
||||||
|
const trackRef = useRef(null);
|
||||||
|
const pointerIdRef = useRef(null);
|
||||||
|
const lastHapticValueRef = useRef(value);
|
||||||
|
|
||||||
|
const valuePercent = useMemo(() => {
|
||||||
|
if (maximum === minimum) return 50;
|
||||||
|
return ((value - minimum) / (maximum - minimum)) * 100;
|
||||||
|
}, [maximum, minimum, value]);
|
||||||
|
|
||||||
|
const sendValue = useCallback((nextValue) => {
|
||||||
|
const next = clampInteger(nextValue, minimum, maximum);
|
||||||
|
const hapticStep = Math.max(1, Math.round((maximum - minimum) / 20));
|
||||||
|
if (Math.abs(next - lastHapticValueRef.current) >= hapticStep) {
|
||||||
|
triggerTouchHaptic('camera');
|
||||||
|
lastHapticValueRef.current = next;
|
||||||
|
}
|
||||||
|
send(peripheralId, control.id, next);
|
||||||
|
}, [control.id, maximum, minimum, peripheralId, send]);
|
||||||
|
|
||||||
|
const valueFromPointer = useCallback((event) => {
|
||||||
|
const track = trackRef.current;
|
||||||
|
if (!track) return value;
|
||||||
|
const bounds = track.getBoundingClientRect();
|
||||||
|
const rawPercent = (event.clientX - bounds.left) / Math.max(1, bounds.width);
|
||||||
|
return minimum + Math.max(0, Math.min(1, rawPercent)) * (maximum - minimum);
|
||||||
|
}, [maximum, minimum, value]);
|
||||||
|
|
||||||
|
const updateFromPointer = useCallback((event) => {
|
||||||
|
sendValue(valueFromPointer(event));
|
||||||
|
}, [sendValue, valueFromPointer]);
|
||||||
|
|
||||||
|
const handlePointerDown = useCallback((event) => {
|
||||||
|
if (disabled || pointerIdRef.current !== null) return;
|
||||||
|
// This follows VerticalCameraTilt's custom pointer-capture path so a range
|
||||||
|
// drag remains reliable while another finger is operating the drive pad.
|
||||||
|
event.preventDefault();
|
||||||
|
pointerIdRef.current = event.pointerId;
|
||||||
|
lastHapticValueRef.current = value;
|
||||||
|
trackRef.current?.setPointerCapture?.(event.pointerId);
|
||||||
|
updateFromPointer(event);
|
||||||
|
}, [disabled, updateFromPointer, value]);
|
||||||
|
|
||||||
|
const handlePointerMove = useCallback((event) => {
|
||||||
|
if (pointerIdRef.current !== event.pointerId) return;
|
||||||
|
event.preventDefault();
|
||||||
|
updateFromPointer(event);
|
||||||
|
}, [updateFromPointer]);
|
||||||
|
|
||||||
|
const handlePointerEnd = useCallback((event) => {
|
||||||
|
if (pointerIdRef.current !== event.pointerId) return;
|
||||||
|
event.preventDefault();
|
||||||
|
pointerIdRef.current = null;
|
||||||
|
trackRef.current?.releasePointerCapture?.(event.pointerId);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const handleKeyDown = (event) => {
|
||||||
|
if (disabled) return;
|
||||||
|
let next = null;
|
||||||
|
if (event.key === 'ArrowLeft' || event.key === 'ArrowDown') next = value - 1;
|
||||||
|
if (event.key === 'ArrowRight' || event.key === 'ArrowUp') next = value + 1;
|
||||||
|
if (event.key === 'Home') next = minimum;
|
||||||
|
if (event.key === 'End') next = maximum;
|
||||||
|
if (next == null) return;
|
||||||
|
event.preventDefault();
|
||||||
|
sendValue(next);
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className={`${SLIDER_CARD_CLASS} border-emerald-300/70 bg-emerald-900 ${disabled ? 'cursor-not-allowed opacity-40' : ''}`}>
|
||||||
|
<div className="flex items-center justify-between gap-1 text-sm font-semibold">
|
||||||
|
<span className="min-w-0 truncate">{control.name}</span>
|
||||||
|
<span className="shrink-0 font-mono text-emerald-100">{value}</span>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
ref={trackRef}
|
||||||
|
role="slider"
|
||||||
|
aria-label={control.name}
|
||||||
|
aria-valuemin={minimum}
|
||||||
|
aria-valuemax={maximum}
|
||||||
|
aria-valuenow={value}
|
||||||
|
aria-disabled={disabled}
|
||||||
|
tabIndex={disabled ? -1 : 0}
|
||||||
|
onPointerDown={handlePointerDown}
|
||||||
|
onPointerMove={handlePointerMove}
|
||||||
|
onPointerUp={handlePointerEnd}
|
||||||
|
onPointerCancel={handlePointerEnd}
|
||||||
|
onLostPointerCapture={(event) => {
|
||||||
|
if (pointerIdRef.current === event.pointerId) pointerIdRef.current = null;
|
||||||
|
}}
|
||||||
|
onKeyDown={handleKeyDown}
|
||||||
|
onContextMenu={(event) => event.preventDefault()}
|
||||||
|
style={{ touchAction: 'none' }}
|
||||||
|
className="mobile-touch-control mobile-drag-control relative mt-0.5 h-6 w-full rounded-full border border-emerald-100/80 bg-emerald-950 shadow-inner focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-emerald-200"
|
||||||
|
>
|
||||||
|
{/* An inset track gives the thumb room to remain entirely inside the
|
||||||
|
card at both endpoints without browser-specific range styling. */}
|
||||||
|
<div className="pointer-events-none absolute inset-1">
|
||||||
|
<div
|
||||||
|
className="absolute inset-y-0 left-0 rounded-full bg-emerald-400"
|
||||||
|
style={{ width: `${valuePercent}%` }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div
|
||||||
|
className="pointer-events-none absolute top-1/2 h-3.5 w-3.5 -translate-x-1/2 -translate-y-1/2 rounded-full border border-emerald-950 bg-emerald-200 shadow"
|
||||||
|
style={{ left: `clamp(0.4375rem, ${valuePercent}%, calc(100% - 0.4375rem))` }}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ToggleControl({ peripheralId, control, disabled, send, value }) {
|
||||||
|
const enabled = value === true;
|
||||||
|
|
||||||
|
const toggle = () => {
|
||||||
|
if (disabled) return;
|
||||||
|
send(peripheralId, control.id, !enabled);
|
||||||
|
triggerTouchHaptic('button');
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-pressed={enabled}
|
||||||
|
disabled={disabled}
|
||||||
|
onClick={toggle}
|
||||||
|
className={`${CARD_CLASS} ${DISABLED_CLASS} flex min-h-12 w-full items-center justify-between gap-1 font-semibold ${enabled ? 'border-emerald-300/70 bg-emerald-800 text-emerald-50' : 'border-amber-300/70 bg-amber-900 text-amber-50'}`}
|
||||||
|
>
|
||||||
|
<span className="min-w-0 truncate">{control.name}</span>
|
||||||
|
<span className="shrink-0 text-xs">{enabled ? 'On' : 'Off'}</span>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function MomentaryControl({ peripheralId, control, disabled, send, value }) {
|
||||||
|
const pressed = value === true;
|
||||||
|
const pressedRef = useRef(false);
|
||||||
|
const pointerIdRef = useRef(null);
|
||||||
|
|
||||||
|
const release = useCallback(() => {
|
||||||
|
if (!pressedRef.current) return;
|
||||||
|
pressedRef.current = false;
|
||||||
|
pointerIdRef.current = null;
|
||||||
|
// Always pair a successful press with false, including cancellation,
|
||||||
|
// permission loss, and replacement of the Accessories view.
|
||||||
|
send(peripheralId, control.id, false);
|
||||||
|
}, [control.id, peripheralId, send]);
|
||||||
|
|
||||||
|
const press = useCallback(() => {
|
||||||
|
if (disabled || pressedRef.current) return;
|
||||||
|
pressedRef.current = true;
|
||||||
|
send(peripheralId, control.id, true);
|
||||||
|
}, [control.id, disabled, peripheralId, send]);
|
||||||
|
|
||||||
|
useEffect(() => release, [release]);
|
||||||
|
useEffect(() => {
|
||||||
|
if (disabled) release();
|
||||||
|
}, [disabled, release]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
aria-pressed={pressed}
|
||||||
|
disabled={disabled}
|
||||||
|
onPointerDown={(event) => {
|
||||||
|
if (disabled || pointerIdRef.current != null) return;
|
||||||
|
event.preventDefault();
|
||||||
|
pointerIdRef.current = event.pointerId;
|
||||||
|
event.currentTarget.setPointerCapture?.(event.pointerId);
|
||||||
|
press();
|
||||||
|
}}
|
||||||
|
onPointerUp={(event) => {
|
||||||
|
if (pointerIdRef.current !== event.pointerId) return;
|
||||||
|
release();
|
||||||
|
triggerTouchHaptic('button');
|
||||||
|
}}
|
||||||
|
onPointerCancel={release}
|
||||||
|
onLostPointerCapture={release}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if ((event.key === ' ' || event.key === 'Enter') && !event.repeat) {
|
||||||
|
event.preventDefault();
|
||||||
|
press();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
onKeyUp={(event) => {
|
||||||
|
if (event.key === ' ' || event.key === 'Enter') {
|
||||||
|
event.preventDefault();
|
||||||
|
release();
|
||||||
|
triggerTouchHaptic('button');
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
onContextMenu={(event) => event.preventDefault()}
|
||||||
|
className={`${CARD_CLASS} ${DISABLED_CLASS} flex min-h-12 w-full items-center justify-center text-center font-semibold ${pressed ? 'border-fuchsia-200 bg-fuchsia-600 text-white' : 'border-fuchsia-300/70 bg-fuchsia-900 text-fuchsia-50'}`}
|
||||||
|
>
|
||||||
|
{control.name}
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function NumberControl({ peripheralId, control, disabled, send, value: storedValue }) {
|
||||||
|
const minimum = integerBound(control.min, 0);
|
||||||
|
const maximum = integerBound(control.max, minimum);
|
||||||
|
const initialValue = Number.isInteger(storedValue)
|
||||||
|
? clampInteger(storedValue, minimum, maximum)
|
||||||
|
: minimum;
|
||||||
|
const [value, setValue] = useState(String(initialValue));
|
||||||
|
const lastSentRef = useRef(initialValue);
|
||||||
|
|
||||||
|
const commit = () => {
|
||||||
|
const next = clampInteger(value, minimum, maximum);
|
||||||
|
setValue(String(next));
|
||||||
|
if (disabled || next === lastSentRef.current) return;
|
||||||
|
lastSentRef.current = next;
|
||||||
|
send(peripheralId, control.id, next);
|
||||||
|
triggerTouchHaptic('button');
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<label className={`${CARD_CLASS} flex min-h-12 items-center gap-1 border-indigo-300/70 bg-indigo-900`}>
|
||||||
|
<span className="min-w-0 flex-1 truncate text-sm font-semibold">{control.name}</span>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
inputMode="numeric"
|
||||||
|
min={minimum}
|
||||||
|
max={maximum}
|
||||||
|
step="1"
|
||||||
|
value={value}
|
||||||
|
disabled={disabled}
|
||||||
|
aria-label={`${control.name}, ${minimum} to ${maximum}`}
|
||||||
|
onChange={(event) => setValue(event.target.value)}
|
||||||
|
onBlur={commit}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if (event.key === 'Enter') {
|
||||||
|
event.preventDefault();
|
||||||
|
commit();
|
||||||
|
event.currentTarget.blur();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className={`mobile-touch-control h-9 w-[45%] min-w-16 rounded-lg border border-indigo-200/70 bg-indigo-950 px-1.5 text-right text-base text-white outline-none focus-visible:ring-2 focus-visible:ring-indigo-200 ${DISABLED_CLASS}`}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function TextControl({ peripheralId, control, disabled, send, value: storedValue }) {
|
||||||
|
const maximumLength = Math.max(1, integerBound(control.maxLength, 1));
|
||||||
|
const initialValue = typeof storedValue === 'string'
|
||||||
|
? trimUnicode(storedValue, maximumLength)
|
||||||
|
: '';
|
||||||
|
const [value, setValue] = useState(initialValue);
|
||||||
|
const lastSentRef = useRef(initialValue);
|
||||||
|
|
||||||
|
const commit = () => {
|
||||||
|
const next = trimUnicode(value, maximumLength);
|
||||||
|
setValue(next);
|
||||||
|
if (disabled || next === lastSentRef.current) return;
|
||||||
|
lastSentRef.current = next;
|
||||||
|
send(peripheralId, control.id, next);
|
||||||
|
triggerTouchHaptic('button');
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<label className={`${CARD_CLASS} flex min-h-12 items-center gap-1 border-sky-300/70 bg-sky-900`}>
|
||||||
|
<span className="min-w-0 flex-1 truncate text-sm font-semibold">{control.name}</span>
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
value={value}
|
||||||
|
disabled={disabled}
|
||||||
|
aria-label={`${control.name}, maximum ${maximumLength} characters`}
|
||||||
|
onChange={(event) => setValue(trimUnicode(event.target.value, maximumLength))}
|
||||||
|
onBlur={commit}
|
||||||
|
onKeyDown={(event) => {
|
||||||
|
if (event.key === 'Enter') {
|
||||||
|
event.preventDefault();
|
||||||
|
commit();
|
||||||
|
event.currentTarget.blur();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className={`mobile-touch-control h-9 w-[55%] min-w-20 rounded-lg border border-sky-200/70 bg-sky-950 px-1.5 text-base text-white outline-none focus-visible:ring-2 focus-visible:ring-sky-200 ${DISABLED_CLASS}`}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export default function AccessoryControlField(props) {
|
||||||
|
switch (props.control?.type) {
|
||||||
|
case 'slider':
|
||||||
|
return <SliderControl {...props} />;
|
||||||
|
case 'button':
|
||||||
|
return props.control.mode === 'momentary'
|
||||||
|
? <MomentaryControl {...props} />
|
||||||
|
: <ToggleControl {...props} />;
|
||||||
|
case 'number':
|
||||||
|
return <NumberControl {...props} />;
|
||||||
|
case 'text':
|
||||||
|
return <TextControl {...props} />;
|
||||||
|
default:
|
||||||
|
// roverd validates the four-type contract before publishing metadata.
|
||||||
|
// Returning nothing remains a defensive boundary for stale servers.
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
// Rover Accessory Controls
|
||||||
|
// Purpose: Renders every generic control advertised by a selected rover as one ordered control surface.
|
||||||
|
// Scope: Reusable content only; mobile and desktop parents own placement, expansion, and visibility.
|
||||||
|
import { useCallback } from 'react';
|
||||||
|
import { useControlActions, useControlSelector } from '../../controls/index.js';
|
||||||
|
import useCanControlRover from '../../hooks/useCanControlRover.js';
|
||||||
|
import AccessoryControlField from './AccessoryControlField.jsx';
|
||||||
|
import useRoverAccessories from './useRoverAccessories.js';
|
||||||
|
|
||||||
|
const EMPTY_ACCESSORY_VALUES = Object.freeze({});
|
||||||
|
|
||||||
|
export default function RoverAccessoryControls({
|
||||||
|
roverId,
|
||||||
|
headerAction = null,
|
||||||
|
plainCenteredHeadings = false,
|
||||||
|
className = '',
|
||||||
|
}) {
|
||||||
|
const { peripherals } = useRoverAccessories(roverId);
|
||||||
|
const canControl = useCanControlRover(roverId);
|
||||||
|
const { setPeripheralControl } = useControlActions();
|
||||||
|
const values = useControlSelector(
|
||||||
|
(control) => control.state.peripheralValues?.[String(roverId)] || EMPTY_ACCESSORY_VALUES,
|
||||||
|
);
|
||||||
|
const send = useCallback(
|
||||||
|
(peripheralId, controlId, value) => setPeripheralControl(peripheralId, controlId, value),
|
||||||
|
[setPeripheralControl],
|
||||||
|
);
|
||||||
|
|
||||||
|
if (peripherals.length === 0) return null;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
className={`mobile-touch-control min-h-0 overflow-y-auto overscroll-contain text-slate-100 ${className}`.trim()}
|
||||||
|
aria-label="Rover accessories"
|
||||||
|
>
|
||||||
|
{peripherals.map((peripheral, peripheralIndex) => {
|
||||||
|
return (
|
||||||
|
<section key={peripheral.id} className="mb-0.5 flex flex-col gap-0.5 last:mb-0">
|
||||||
|
{/* The firmware's array order is authoritative. Mapping directly over
|
||||||
|
it keeps physical authoring order intact across every UI host.
|
||||||
|
Every peripheral keeps its heading even when it is the only
|
||||||
|
device, because its firmware-provided name identifies which
|
||||||
|
physical accessory owns the controls below it. */}
|
||||||
|
<div
|
||||||
|
className={`flex min-h-8 items-center gap-1 px-1 text-xs font-semibold text-white ${plainCenteredHeadings ? '' : 'bg-black/60'}`.trim()}
|
||||||
|
>
|
||||||
|
{/* Desktop already supplies one continuous HUD background, so
|
||||||
|
its title needs neither a second tone nor left alignment.
|
||||||
|
Mobile keeps the ordinary heading because it also carries
|
||||||
|
the Back action on the opposite side. */}
|
||||||
|
<h3 className={`min-w-0 flex-1 truncate ${plainCenteredHeadings ? 'text-center' : ''}`.trim()}>
|
||||||
|
{peripheral.name}
|
||||||
|
</h3>
|
||||||
|
{peripheralIndex === 0 ? headerAction : null}
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-0.5">
|
||||||
|
{peripheral.controls.map((control) => (
|
||||||
|
<AccessoryControlField
|
||||||
|
key={control.id}
|
||||||
|
peripheralId={peripheral.id}
|
||||||
|
control={control}
|
||||||
|
value={values[peripheral.id]?.[control.id]}
|
||||||
|
disabled={!roverId || !canControl}
|
||||||
|
send={send}
|
||||||
|
/>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
// Rover Accessories Selector
|
||||||
|
// Purpose: Provides the ordered generic-control inventory advertised by one rover.
|
||||||
|
// Scope: Selects public roster metadata only; placement and visibility remain parent-UI decisions.
|
||||||
|
import { useMemo } from 'react';
|
||||||
|
import { useSessionSelector } from '../../context/SessionContext.jsx';
|
||||||
|
|
||||||
|
export default function useRoverAccessories(roverId) {
|
||||||
|
const rosterEntry = useSessionSelector((state) => {
|
||||||
|
if (!roverId) return null;
|
||||||
|
const roster = Array.isArray(state.session?.roster) ? state.session.roster : [];
|
||||||
|
return roster.find((entry) => String(entry.id) === String(roverId)) || null;
|
||||||
|
});
|
||||||
|
const advertisedPeripherals = rosterEntry?.peripherals;
|
||||||
|
|
||||||
|
const peripherals = useMemo(() => {
|
||||||
|
if (!Array.isArray(advertisedPeripherals)) return [];
|
||||||
|
// A peripheral with no generic controls may still provide a standardized
|
||||||
|
// camera, headlight, or laser backend. Those roles use their established
|
||||||
|
// HUD controls and must not create an empty Accessories surface.
|
||||||
|
return advertisedPeripherals.filter(
|
||||||
|
(peripheral) => Array.isArray(peripheral?.controls) && peripheral.controls.length > 0,
|
||||||
|
);
|
||||||
|
}, [advertisedPeripherals]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
peripherals,
|
||||||
|
hasAccessories: peripherals.length > 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -66,6 +66,7 @@ const CONTROL_ACTION_NAMES = [
|
|||||||
'sendSong',
|
'sendSong',
|
||||||
'startHorn',
|
'startHorn',
|
||||||
'stopHorn',
|
'stopHorn',
|
||||||
|
'setPeripheralControl',
|
||||||
'setMicPttActive',
|
'setMicPttActive',
|
||||||
];
|
];
|
||||||
|
|
||||||
@@ -724,6 +725,29 @@ export function ControlSystemProvider({ children }) {
|
|||||||
dispatch({ type: 'control/set-mic-ptt', payload: Boolean(active) });
|
dispatch({ type: 'control/set-mic-ptt', payload: Boolean(active) });
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
|
const setPeripheralControl = useCallback(
|
||||||
|
(peripheralId, controlId, value) => {
|
||||||
|
const sent = pipeline.sendPeripheralControl(peripheralId, controlId, value);
|
||||||
|
if (sent) {
|
||||||
|
// The generic protocol is currently command-only. Recording the value
|
||||||
|
// here lets every renderer instance share the browser's latest intent
|
||||||
|
// without pretending that it is device-reported telemetry.
|
||||||
|
dispatch({
|
||||||
|
type: 'control/set-peripheral-value',
|
||||||
|
payload: {
|
||||||
|
roverId: pipeline.roverId,
|
||||||
|
peripheralId,
|
||||||
|
controlId,
|
||||||
|
value,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
recordControlIntent();
|
||||||
|
}
|
||||||
|
return sent;
|
||||||
|
},
|
||||||
|
[pipeline, recordControlIntent],
|
||||||
|
);
|
||||||
|
|
||||||
const actionImplementations = useMemo(
|
const actionImplementations = useMemo(
|
||||||
() => ({
|
() => ({
|
||||||
setMode,
|
setMode,
|
||||||
@@ -751,6 +775,7 @@ export function ControlSystemProvider({ children }) {
|
|||||||
sendSong,
|
sendSong,
|
||||||
startHorn,
|
startHorn,
|
||||||
stopHorn,
|
stopHorn,
|
||||||
|
setPeripheralControl,
|
||||||
setMicPttActive,
|
setMicPttActive,
|
||||||
}),
|
}),
|
||||||
[
|
[
|
||||||
@@ -779,6 +804,7 @@ export function ControlSystemProvider({ children }) {
|
|||||||
sendSong,
|
sendSong,
|
||||||
startHorn,
|
startHorn,
|
||||||
stopHorn,
|
stopHorn,
|
||||||
|
setPeripheralControl,
|
||||||
setMicPttActive,
|
setMicPttActive,
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -44,6 +44,11 @@ export function useCommandPipeline(options = {}) {
|
|||||||
return rosterEntry.horn;
|
return rosterEntry.horn;
|
||||||
}, [rosterEntry]);
|
}, [rosterEntry]);
|
||||||
|
|
||||||
|
const peripherals = useMemo(
|
||||||
|
() => (Array.isArray(rosterEntry?.peripherals) ? rosterEntry.peripherals : []),
|
||||||
|
[rosterEntry],
|
||||||
|
);
|
||||||
|
|
||||||
const headlightState = useMemo(() => rosterEntry?.headlight?.state ?? null, [rosterEntry]);
|
const headlightState = useMemo(() => rosterEntry?.headlight?.state ?? null, [rosterEntry]);
|
||||||
const laserState = useMemo(() => rosterEntry?.laser?.state ?? null, [rosterEntry]);
|
const laserState = useMemo(() => rosterEntry?.laser?.state ?? null, [rosterEntry]);
|
||||||
const emitCommand = useCallback(
|
const emitCommand = useCallback(
|
||||||
@@ -208,6 +213,22 @@ export function useCommandPipeline(options = {}) {
|
|||||||
[emitCommand, roverId],
|
[emitCommand, roverId],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const sendPeripheralControl = useCallback(
|
||||||
|
(peripheralId, controlId, value) => {
|
||||||
|
if (!roverId || !peripheralId || !controlId) return null;
|
||||||
|
const peripheral = { id: peripheralId, control: controlId, value };
|
||||||
|
// Peripheral commands deliberately use the same command envelope as all
|
||||||
|
// other rover actuation. This keeps turn authorization, acknowledgements,
|
||||||
|
// and rover WebSocket routing in the server's existing command boundary.
|
||||||
|
emitCommand({
|
||||||
|
type: 'peripheral',
|
||||||
|
data: { peripheral },
|
||||||
|
});
|
||||||
|
return peripheral;
|
||||||
|
},
|
||||||
|
[emitCommand, roverId],
|
||||||
|
);
|
||||||
|
|
||||||
const sendSong = useCallback(
|
const sendSong = useCallback(
|
||||||
(notes = [], options = {}) => {
|
(notes = [], options = {}) => {
|
||||||
if (!roverId) return null;
|
if (!roverId) return null;
|
||||||
@@ -244,6 +265,7 @@ export function useCommandPipeline(options = {}) {
|
|||||||
laser,
|
laser,
|
||||||
laserState,
|
laserState,
|
||||||
horn,
|
horn,
|
||||||
|
peripherals,
|
||||||
emitCommand,
|
emitCommand,
|
||||||
enableSensorStream,
|
enableSensorStream,
|
||||||
sendDriveDirect,
|
sendDriveDirect,
|
||||||
@@ -253,6 +275,7 @@ export function useCommandPipeline(options = {}) {
|
|||||||
sendHeadlight,
|
sendHeadlight,
|
||||||
sendLaser,
|
sendLaser,
|
||||||
sendHorn,
|
sendHorn,
|
||||||
|
sendPeripheralControl,
|
||||||
sendSong,
|
sendSong,
|
||||||
runMacroSteps,
|
runMacroSteps,
|
||||||
}),
|
}),
|
||||||
@@ -265,6 +288,7 @@ export function useCommandPipeline(options = {}) {
|
|||||||
laser,
|
laser,
|
||||||
laserState,
|
laserState,
|
||||||
horn,
|
horn,
|
||||||
|
peripherals,
|
||||||
emitCommand,
|
emitCommand,
|
||||||
enableSensorStream,
|
enableSensorStream,
|
||||||
sendDriveDirect,
|
sendDriveDirect,
|
||||||
@@ -274,6 +298,8 @@ export function useCommandPipeline(options = {}) {
|
|||||||
sendHeadlight,
|
sendHeadlight,
|
||||||
sendLaser,
|
sendLaser,
|
||||||
sendHorn,
|
sendHorn,
|
||||||
|
sendPeripheralControl,
|
||||||
|
sendSong,
|
||||||
runMacroSteps,
|
runMacroSteps,
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -69,6 +69,10 @@ export const initialControlState = {
|
|||||||
macros: DEFAULT_MACROS,
|
macros: DEFAULT_MACROS,
|
||||||
keymap: DEFAULT_KEYMAP,
|
keymap: DEFAULT_KEYMAP,
|
||||||
inputs: {},
|
inputs: {},
|
||||||
|
// Generic accessory controls do not currently report state back from roverd.
|
||||||
|
// Keep the last browser-issued value per rover/device/control so closing a
|
||||||
|
// drawer or changing responsive layouts does not make the UI lie about it.
|
||||||
|
peripheralValues: {},
|
||||||
};
|
};
|
||||||
|
|
||||||
export function controlReducer(state, action) {
|
export function controlReducer(state, action) {
|
||||||
@@ -226,6 +230,27 @@ export function controlReducer(state, action) {
|
|||||||
active: Boolean(action.payload),
|
active: Boolean(action.payload),
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
case 'control/set-peripheral-value': {
|
||||||
|
const roverId = String(action.payload?.roverId || '');
|
||||||
|
const peripheralId = String(action.payload?.peripheralId || '');
|
||||||
|
const controlId = String(action.payload?.controlId || '');
|
||||||
|
if (!roverId || !peripheralId || !controlId) return state;
|
||||||
|
const roverValues = state.peripheralValues?.[roverId] || {};
|
||||||
|
const peripheralValues = roverValues[peripheralId] || {};
|
||||||
|
return {
|
||||||
|
...state,
|
||||||
|
peripheralValues: {
|
||||||
|
...(state.peripheralValues || {}),
|
||||||
|
[roverId]: {
|
||||||
|
...roverValues,
|
||||||
|
[peripheralId]: {
|
||||||
|
...peripheralValues,
|
||||||
|
[controlId]: action.payload.value,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
default:
|
default:
|
||||||
return state;
|
return state;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -87,10 +87,6 @@ function DriverPageContent({ layout, oldDesktop }) {
|
|||||||
},
|
},
|
||||||
[saveQuickstartSettings],
|
[saveQuickstartSettings],
|
||||||
);
|
);
|
||||||
const openHelpFromQuickstart = useCallback(() => {
|
|
||||||
setQuickstartVisible(false);
|
|
||||||
setHelpVisible(true);
|
|
||||||
}, []);
|
|
||||||
return (
|
return (
|
||||||
<ControlSystemProvider>
|
<ControlSystemProvider>
|
||||||
{/*
|
{/*
|
||||||
@@ -127,7 +123,6 @@ function DriverPageContent({ layout, oldDesktop }) {
|
|||||||
layout={layout}
|
layout={layout}
|
||||||
showOnLoad={quickstartSettings?.showOnLoad !== false}
|
showOnLoad={quickstartSettings?.showOnLoad !== false}
|
||||||
onToggleShowOnLoad={setQuickstartShowOnLoad}
|
onToggleShowOnLoad={setQuickstartShowOnLoad}
|
||||||
onOpenHelp={openHelpFromQuickstart}
|
|
||||||
onClose={closeQuickstart}
|
onClose={closeQuickstart}
|
||||||
/>
|
/>
|
||||||
</ControlSystemProvider>
|
</ControlSystemProvider>
|
||||||
|
|||||||
+60
-27
@@ -11,26 +11,44 @@ export const HELP_CONTENT = {
|
|||||||
type: 'list',
|
type: 'list',
|
||||||
title: 'Chat and nicknames',
|
title: 'Chat and nicknames',
|
||||||
items: [
|
items: [
|
||||||
'Set a nickname in the user list panel, on the bottom left of the page below the rover video.',
|
'Chat and nickname controls are in the Chat/Rovers tab.',
|
||||||
{ segments: ['Toggle chat focus with ', { action: 'chatFocus' }, '. Press ', { action: 'chatFocus'}, ' again to send.'] },
|
{ segments: ['Open the HUD chat composer with ', { action: 'chatFocus' }, '. Press ', { action: 'chatFocus'}, ' again to send.'] },
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
type: 'list',
|
type: 'list',
|
||||||
title: 'Driving the rover',
|
title: 'Driving the rover',
|
||||||
items: [
|
items: [
|
||||||
{ segments: ['Press the "Start Driving" button onscreen, or press ' , { action: 'driveMacro' }, ' on your keyboard to put the rover into driving mode.'] },
|
{ segments: ['Click "Your rover is docked", or press ', { action: 'driveMacro' }, ', to undock.'] },
|
||||||
'Refer to the controls for the controls for the rover.'
|
'Drive with the movement keybindings.',
|
||||||
|
'Rover controls dim while another person has the turn.',
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'list',
|
||||||
|
title: 'Video HUD',
|
||||||
|
items: [
|
||||||
|
'Top left shows the rover name and turns.',
|
||||||
|
'Top right shows battery and rover status.',
|
||||||
|
'Bottom left contains horn, headlight, and laser controls.',
|
||||||
|
'Bottom right contains camera tilt and chat.',
|
||||||
|
'Use the arrows to open and close pods and their expansions.',
|
||||||
|
],
|
||||||
|
},
|
||||||
|
{
|
||||||
|
type: 'list',
|
||||||
|
title: 'Page layout',
|
||||||
|
items: [
|
||||||
|
'Room, Activities, and VIP are in the left sidebar.',
|
||||||
|
'Chat/Rovers, Help, and Settings are in the right sidebar.',
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
type: 'list',
|
type: 'list',
|
||||||
title: 'Docking the rover',
|
title: 'Docking the rover',
|
||||||
items: [
|
items: [
|
||||||
'If the rover shows "Docking in Progress", it is already auto-seeking the dock.',
|
{ segments: ['Click "Dock rover", or press ', { action: 'dockMacro' }, '.'] },
|
||||||
'To dock manually, enter Docking Assist from the drive panel.',
|
'Click "Rover is docking itself" to resume driving.',
|
||||||
{ segments: ['Press "Enter Docking Assist", or press ', { action: 'dockMacro' }, '.'] },
|
|
||||||
'In assist mode, camera tilts down and driving speed is limited for precise alignment.',
|
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
],
|
],
|
||||||
@@ -56,8 +74,8 @@ export const HELP_CONTENT = {
|
|||||||
id: 'macros',
|
id: 'macros',
|
||||||
title: 'Rover modes & chat',
|
title: 'Rover modes & chat',
|
||||||
items: [
|
items: [
|
||||||
{ action: 'driveMacro', label: 'Drive macro' },
|
{ action: 'driveMacro', label: 'Undock / resume driving' },
|
||||||
{ action: 'dockMacro', label: 'Docking assist toggle' },
|
{ action: 'dockMacro', label: 'Dock rover' },
|
||||||
{ action: 'chatFocus', label: 'Chat focus' },
|
{ action: 'chatFocus', label: 'Chat focus' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
@@ -119,27 +137,35 @@ export const HELP_CONTENT = {
|
|||||||
type: 'list',
|
type: 'list',
|
||||||
title: 'Chat and nicknames',
|
title: 'Chat and nicknames',
|
||||||
items: [
|
items: [
|
||||||
'Set a nickname in the user list panel below.',
|
'Chat and nickname controls are in the Chat tab.',
|
||||||
'Tap in the chat box to send messages in the chat.'
|
'Tap the chat box to send a message.',
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
type: 'list',
|
type: 'list',
|
||||||
title: 'Driving the rover',
|
title: 'Driving the rover',
|
||||||
items: [
|
items: [
|
||||||
{ segments: ['Press the "Start Driving" button onscreen to put the rover into driving mode.'] },
|
'Tap "Your rover is docked" to undock.',
|
||||||
'Look below the rover video. Use the joystick column to move the rover, and hold the aux buttons in the other control column.'
|
'Hold and drag on the drive pad.',
|
||||||
|
'Choose Precision, Normal, or Turbo above the drive pad.',
|
||||||
|
'Use the other column for rover controls.',
|
||||||
|
'Rover controls dim while another person has the turn.',
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
type: 'list',
|
type: 'list',
|
||||||
title: 'Docking the rover',
|
title: 'Docking the rover',
|
||||||
items: [
|
items: [
|
||||||
'If you see "Docking in Progress", the rover is currently auto-seeking the dock.',
|
'Tap "Dock and charge" when finished.',
|
||||||
{ segments: ['For manual docking, press "Enter Docking Assist".'] },
|
|
||||||
'Assist mode tilts camera down and limits speed for precise alignment.',
|
|
||||||
],
|
],
|
||||||
}
|
},
|
||||||
|
{
|
||||||
|
type: 'list',
|
||||||
|
title: 'More controls',
|
||||||
|
items: [
|
||||||
|
'Chat, Activities, VIP, Room Controls, Help, and Settings are below the rover controls.',
|
||||||
|
],
|
||||||
|
},
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
'mobile-landscape': {
|
'mobile-landscape': {
|
||||||
@@ -148,28 +174,35 @@ export const HELP_CONTENT = {
|
|||||||
type: 'list',
|
type: 'list',
|
||||||
title: 'Chat and nicknames',
|
title: 'Chat and nicknames',
|
||||||
items: [
|
items: [
|
||||||
'Scroll down to see more of the page.',
|
'Chat and nickname controls are in the Chat tab.',
|
||||||
'Set a nickname in the user list panel below.',
|
'Tap the chat box to send a message.',
|
||||||
'Tap in the chat box to send messages in the chat.'
|
|
||||||
]
|
]
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
type: 'list',
|
type: 'list',
|
||||||
title: 'Driving the rover',
|
title: 'Driving the rover',
|
||||||
items: [
|
items: [
|
||||||
{ segments: ['Press the "Start Driving" button, or the "Drive" button to put the rover into driving mode.'] },
|
'Tap "Your rover is docked" to undock.',
|
||||||
'Use the joystick column beside the video feed to move the rover, and hold the aux buttons in the other control column.'
|
'Hold and drag on the drive pad.',
|
||||||
|
'Choose Precision, Normal, or Turbo above the drive pad.',
|
||||||
|
'Use the other column for rover controls.',
|
||||||
|
'Rover controls dim while another person has the turn.',
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
type: 'list',
|
type: 'list',
|
||||||
title: 'Docking the rover',
|
title: 'Docking the rover',
|
||||||
items: [
|
items: [
|
||||||
'If you see "Docking in Progress", the rover is currently auto-seeking the dock.',
|
'Tap "Dock and charge" when finished.',
|
||||||
{ segments: ['For manual docking, press "Enter Docking Assist" (or "Dock" button).'] },
|
|
||||||
'Assist mode tilts camera down and limits speed for precise alignment.',
|
|
||||||
],
|
],
|
||||||
}
|
},
|
||||||
|
{
|
||||||
|
type: 'list',
|
||||||
|
title: 'More controls',
|
||||||
|
items: [
|
||||||
|
'Chat, Activities, VIP, Room Controls, Help, and Settings are below the rover controls.',
|
||||||
|
],
|
||||||
|
},
|
||||||
],
|
],
|
||||||
// aside: [
|
// aside: [
|
||||||
// {
|
// {
|
||||||
|
|||||||
@@ -21,6 +21,7 @@ import { SettingsProvider } from './settings/index.js'
|
|||||||
import DeterrenceChaos from './components/DeterrenceChaos/index.jsx'
|
import DeterrenceChaos from './components/DeterrenceChaos/index.jsx'
|
||||||
import AnalyticsReporter from './analytics/AnalyticsReporter.jsx'
|
import AnalyticsReporter from './analytics/AnalyticsReporter.jsx'
|
||||||
import PtzAppRoot from './ptz/PtzAppRoot.jsx'
|
import PtzAppRoot from './ptz/PtzAppRoot.jsx'
|
||||||
|
import InitialSessionOverlay from './components/InitialSessionOverlay/index.jsx'
|
||||||
|
|
||||||
// The reporting route includes the charting and CSV libraries. Loading that
|
// The reporting route includes the charting and CSV libraries. Loading that
|
||||||
// bundle only when `/reports` is visited keeps ordinary rover-control sessions
|
// bundle only when `/reports` is visited keeps ordinary rover-control sessions
|
||||||
@@ -31,6 +32,11 @@ createRoot(document.getElementById('root')).render(
|
|||||||
<StrictMode>
|
<StrictMode>
|
||||||
<SocketProvider>
|
<SocketProvider>
|
||||||
<SessionProvider>
|
<SessionProvider>
|
||||||
|
{/* Every route depends on the first authoritative session snapshot.
|
||||||
|
Mounting this opaque layer at the shared provider boundary prevents
|
||||||
|
incomplete route-specific placeholders from flashing while still
|
||||||
|
allowing every application tree to initialize underneath it. */}
|
||||||
|
<InitialSessionOverlay />
|
||||||
<TelemetryProvider>
|
<TelemetryProvider>
|
||||||
<SettingsProvider>
|
<SettingsProvider>
|
||||||
<ChatProvider>
|
<ChatProvider>
|
||||||
|
|||||||
Reference in New Issue
Block a user