armnet-busybox 0.3.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,81 @@
1
+ """BusyBox: an instrumented task box, as a state source and a success signal.
2
+
3
+ The box is a panel of buttons, switches, sliders, a knob and a wire patch field,
4
+ each read by an Arduino Nano and published over MQTT by a bridge on its own
5
+ Raspberry Pi. For armnet it does two jobs:
6
+
7
+ - **State (sidecar).** `BusyBoxRobot` reads the box beside the robot without
8
+ touching its observation contract; `BusyBoxSidecarWriter` records those
9
+ per-frame readings as a RoboCandyWrapper plugin (`candywrapper_plugins/
10
+ busybox_state/`). The box is deliberately kept out of `observation.state` so no
11
+ policy can consume it.
12
+ - **Verification.** `GoalSpec.evaluate` compares the live state against the goal
13
+ parsed from a task's language instruction, so a rollout can score itself
14
+ instead of an operator clicking success/fail in the FMS.
15
+
16
+ The calibration JSON produced by the BusyBox repo's `scripts/busybox_calibration.py`
17
+ is the contract between the two repos: it is what turns a raw
18
+ `{"values": [1, 0, 1, 1]}` in physical wiring order into "the red wire is out".
19
+ """
20
+
21
+ from .attach import busybox_from_cell, verify_success_enabled
22
+ from .calibration import BusyBoxCalibration
23
+ from .client import BusyBoxClient
24
+ from .goal import Goal, GoalSpec, GoalVerdict
25
+ from .robot import BusyBoxRobot
26
+ from .reset import (
27
+ CELL_MOTION_PLANS,
28
+ Keypoint,
29
+ MotionPlan,
30
+ execute_motion_plan,
31
+ motion_plan,
32
+ motion_plan_rail,
33
+ prepare_task_reset,
34
+ )
35
+ from .environment import BusyBoxCell, BusyBoxEnvironment
36
+ from .sidecar import BusyBoxSidecarWriter
37
+ from .state import BusyBoxState, KnobTracker, StateDecoder
38
+ from .success import (
39
+ BUTTONS_ONLY_TASK_SLUGS,
40
+ SuccessMonitor,
41
+ task_resets_itself,
42
+ )
43
+ from .tasks import (
44
+ BusyBoxTaskDefinition,
45
+ ResetDecision,
46
+ goal_for_task,
47
+ goal_from_instruction,
48
+ reset_decision_for_task,
49
+ )
50
+
51
+ __all__ = [
52
+ "BUTTONS_ONLY_TASK_SLUGS",
53
+ "BusyBoxCalibration",
54
+ "BusyBoxCell",
55
+ "BusyBoxClient",
56
+ "BusyBoxEnvironment",
57
+ "BusyBoxRobot",
58
+ "BusyBoxSidecarWriter",
59
+ "BusyBoxState",
60
+ "BusyBoxTaskDefinition",
61
+ "CELL_MOTION_PLANS",
62
+ "Goal",
63
+ "GoalSpec",
64
+ "GoalVerdict",
65
+ "KnobTracker",
66
+ "Keypoint",
67
+ "MotionPlan",
68
+ "ResetDecision",
69
+ "StateDecoder",
70
+ "SuccessMonitor",
71
+ "busybox_from_cell",
72
+ "execute_motion_plan",
73
+ "goal_for_task",
74
+ "goal_from_instruction",
75
+ "motion_plan",
76
+ "motion_plan_rail",
77
+ "prepare_task_reset",
78
+ "reset_decision_for_task",
79
+ "task_resets_itself",
80
+ "verify_success_enabled",
81
+ ]
@@ -0,0 +1,63 @@
1
+ """Building a BusyBox client from a cell's config block.
2
+
3
+ Shared by the record and eval runtimes so they attach the box the same way. The
4
+ config arrives as plain data on `ctx.cell.busybox` — armnet-runtime cannot import
5
+ this package (it must stay pydantic-only), so decoding happens here.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import logging
11
+ from typing import Any
12
+
13
+ from .calibration import BusyBoxCalibration
14
+ from .client import BusyBoxClient
15
+
16
+ logger = logging.getLogger(__name__)
17
+
18
+
19
+ def busybox_from_cell(config: dict[str, Any] | None) -> BusyBoxClient | None:
20
+ """Connect to the cell's BusyBox, or return None if it has none configured.
21
+
22
+ Raises if the box is enabled but misconfigured — a silently absent task box
23
+ would record a dataset with no BusyBox columns and score every rollout
24
+ unscorable, which is far worse to discover after a data-collection session
25
+ than at startup.
26
+ """
27
+ if not config or not config.get("enabled"):
28
+ return None
29
+
30
+ broker = config.get("broker")
31
+ if not broker:
32
+ raise ValueError(
33
+ "busybox.enabled is set but busybox.broker is missing — give the box's "
34
+ "hostname or Tailscale address in robot_cell_<name>.json"
35
+ )
36
+
37
+ raw_calibration = config.get("calibration") or {}
38
+ if not raw_calibration:
39
+ raise ValueError(
40
+ "busybox.enabled is set but busybox.calibration is empty. Run "
41
+ "scripts/busybox_calibration.py in the BusyBox repo against the "
42
+ "physical box and paste the JSON into robot_cell_<name>.json — without "
43
+ "it, readings are just anonymous numbers in wiring order."
44
+ )
45
+ calibration = BusyBoxCalibration.model_validate(raw_calibration)
46
+
47
+ client = BusyBoxClient(
48
+ broker=broker,
49
+ port=int(config.get("port", 1883)),
50
+ topic_prefix=config.get("topic_prefix") or None,
51
+ calibration=calibration,
52
+ )
53
+ client.connect()
54
+ logger.info(
55
+ "busybox: connected to %s:%s (prefix %r), %d controls",
56
+ client.broker, client.port, client.topic_prefix,
57
+ len(calibration.control_names()),
58
+ )
59
+ return client
60
+
61
+
62
+ def verify_success_enabled(config: dict[str, Any] | None) -> bool:
63
+ return bool(config and config.get("enabled") and config.get("verify_success"))
@@ -0,0 +1,141 @@
1
+ """The BusyBox calibration mapping: raw wire order -> semantic controls.
2
+
3
+ The box's MQTT bridge publishes each module's readings in physical wiring order
4
+ (D2, D3, D4, D5), so on the wire there is no such thing as "the red button" or
5
+ "the top slider" — only ``{"values": [1, 0, 1, 1]}``. The mapping produced by the
6
+ BusyBox repo's ``scripts/busybox_calibration.py`` is what turns one into the
7
+ other, and it is the entire contract between the two repos.
8
+
9
+ Nothing here assumes a polarity. The modules use ``INPUT_PULLUP`` so an idle pin
10
+ reads 1 and an actuated one reads 0, but whether a given switch was soldered such
11
+ that "on" closes the contact is a property of that physical box. Calibration
12
+ measures it; we just read what it measured.
13
+ """
14
+
15
+ from __future__ import annotations
16
+
17
+ import json
18
+ from pathlib import Path
19
+
20
+ from pydantic import BaseModel, Field, model_validator
21
+
22
+
23
+ class ButtonMapping(BaseModel):
24
+ index: int
25
+ pressed_value: int
26
+ released_value: int
27
+
28
+
29
+ class SwitchMapping(BaseModel):
30
+ index: int
31
+ on_value: int
32
+ off_value: int
33
+
34
+
35
+ class WireMapping(BaseModel):
36
+ index: int
37
+ connected_value: int
38
+ disconnected_value: int
39
+
40
+
41
+ class SliderMapping(BaseModel):
42
+ index: int
43
+ # detent (as a string, because it came from JSON) -> raw ADC reading, 0..1023
44
+ mapping: dict[str, int]
45
+
46
+ @model_validator(mode="after")
47
+ def _check_positions(self) -> "SliderMapping":
48
+ if len(self.mapping) < 2:
49
+ raise ValueError("a slider needs at least two calibrated positions")
50
+ return self
51
+
52
+ def nearest_position(self, reading: int) -> int:
53
+ """The detent whose calibrated reading is closest to `reading`."""
54
+ return int(min(self.mapping, key=lambda pos: abs(self.mapping[pos] - reading)))
55
+
56
+ def reading_for(self, position: int) -> int:
57
+ return self.mapping[str(position)]
58
+
59
+
60
+ class KnobMapping(BaseModel):
61
+ """The knob, in one of two hardware generations.
62
+
63
+ **Absolute** (current: B10K potentiometer): ``mapping`` is detent -> raw ADC
64
+ reading, exactly like a slider. A reading decodes on its own; there is no
65
+ run-time homing.
66
+
67
+ **Relative** (legacy: KY-040 encoder): the encoder counts from zero at
68
+ power-up, so a count recorded during calibration is meaningless after the
69
+ Nano resets and deliberately no origin is stored — only the step size and
70
+ direction. Absolute position comes from re-homing at run time against a
71
+ known starting detent; see `KnobTracker`.
72
+
73
+ Exactly one of ``mapping`` / ``counts_per_position`` is present; which one
74
+ tells the decoder which hardware this box has.
75
+ """
76
+
77
+ index: int = 0
78
+ mapping: dict[str, int] | None = None # absolute: detent -> ADC, 0..1023
79
+ counts_per_position: float | None = None # relative: encoder step size
80
+ direction: int = Field(default=1, description="+1 if clockwise increases the count")
81
+ positions: int = 6
82
+
83
+ @model_validator(mode="after")
84
+ def _check(self) -> "KnobMapping":
85
+ if (self.mapping is None) == (self.counts_per_position is None):
86
+ raise ValueError(
87
+ "a knob is either absolute (mapping) or relative "
88
+ "(counts_per_position) — exactly one must be present"
89
+ )
90
+ if self.mapping is not None:
91
+ if len(self.mapping) < 2:
92
+ raise ValueError("an absolute knob needs at least two calibrated positions")
93
+ self.positions = len(self.mapping)
94
+ else:
95
+ if self.counts_per_position <= 0:
96
+ raise ValueError("counts_per_position must be positive")
97
+ if self.direction not in (-1, 1):
98
+ raise ValueError("direction must be -1 or +1")
99
+ return self
100
+
101
+ @property
102
+ def is_absolute(self) -> bool:
103
+ return self.mapping is not None
104
+
105
+ def nearest_position(self, reading: int) -> int:
106
+ """The detent whose calibrated reading is closest to `reading`."""
107
+ if self.mapping is None:
108
+ raise ValueError("a relative knob has no absolute mapping")
109
+ return int(min(self.mapping, key=lambda pos: abs(self.mapping[pos] - reading)))
110
+
111
+
112
+ class BusyBoxCalibration(BaseModel):
113
+ version: int = 2
114
+ topic_prefix: str = "busybox-1"
115
+ created_at: str | None = None
116
+ buttons: dict[str, ButtonMapping] = Field(default_factory=dict)
117
+ switches: dict[str, SwitchMapping] = Field(default_factory=dict)
118
+ wires: dict[str, WireMapping] = Field(default_factory=dict)
119
+ sliders: dict[str, SliderMapping] = Field(default_factory=dict)
120
+ knob: KnobMapping | None = None
121
+
122
+ @classmethod
123
+ def from_file(cls, path: str | Path) -> "BusyBoxCalibration":
124
+ path = Path(path)
125
+ if not path.is_file():
126
+ raise FileNotFoundError(
127
+ f"no BusyBox calibration at {path}. Run scripts/busybox_calibration.py "
128
+ f"in the BusyBox repo against the physical box and copy the JSON here — "
129
+ f"without it, raw readings cannot be resolved to named controls."
130
+ )
131
+ return cls.model_validate(json.loads(path.read_text()))
132
+
133
+ def control_names(self) -> list[str]:
134
+ """Every named control, in the order they appear in an observation."""
135
+ names = [f"button_{n}" for n in sorted(self.buttons)]
136
+ names += [f"switch_{n}" for n in sorted(self.switches)]
137
+ names += [f"wire_{n}" for n in sorted(self.wires)]
138
+ names += [f"slider_{n}" for n in sorted(self.sliders)]
139
+ if self.knob is not None:
140
+ names.append("knob")
141
+ return names
@@ -0,0 +1,276 @@
1
+ """Live BusyBox state over MQTT.
2
+
3
+ The box runs its own mosquitto on its own Raspberry Pi (anonymous, no TLS), and
4
+ each module pushes a `{"values": [...]}` payload on change to
5
+ `<prefix>/<module>/state`. We subscribe and keep the most recent value per module.
6
+
7
+ This sits on a robot control loop, so `snapshot()` never blocks and never waits on
8
+ the network: it reads a cached value under a lock, in the same
9
+ most-recent-value-register spirit as the cell's teleop and rollout registers. A
10
+ box that goes offline degrades to a stale snapshot and a warning, and must never
11
+ stall recording.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ import json
17
+ import logging
18
+ import threading
19
+ import time
20
+ from typing import Any
21
+
22
+ import paho.mqtt.client as mqtt
23
+
24
+ from .calibration import BusyBoxCalibration
25
+ from .state import MODULES, BusyBoxState, Readings, StateDecoder
26
+
27
+ logger = logging.getLogger(__name__)
28
+
29
+ DEFAULT_PORT = 1883
30
+
31
+
32
+ class BusyBoxClient:
33
+ """Subscribes to a box's modules and decodes them into named control states."""
34
+
35
+ def __init__(
36
+ self,
37
+ *,
38
+ broker: str,
39
+ calibration: BusyBoxCalibration,
40
+ port: int = DEFAULT_PORT,
41
+ topic_prefix: str | None = None,
42
+ connect_timeout_s: float = 10.0,
43
+ connect_budget_s: float = 60.0,
44
+ stale_after_s: float = 5.0,
45
+ ) -> None:
46
+ self.broker = broker
47
+ self.port = port
48
+ # The bridge is deployed per unit as `--base-topic busybox-<N>`, so the
49
+ # prefix is a property of the box; the calibration file records the one it
50
+ # was taken against. Subscribing to the wrong prefix is silent — you get
51
+ # readings of None forever — so default to what calibration saw.
52
+ self.topic_prefix = topic_prefix or calibration.topic_prefix
53
+ self.calibration = calibration
54
+ self.connect_timeout_s = connect_timeout_s
55
+ self.connect_budget_s = connect_budget_s
56
+ self.stale_after_s = stale_after_s
57
+
58
+ self.decoder = StateDecoder(calibration)
59
+ self._lock = threading.RLock()
60
+ self._readings: Readings = {}
61
+ # time.monotonic() timestamps: staleness is an elapsed-time question, and
62
+ # an NTP step on the workstation must not mass-expire (or resurrect) the
63
+ # box's readings mid-episode.
64
+ self._received_at: dict[str, float] = {}
65
+ self._last_stale_warned: list[str] = []
66
+ self._client: mqtt.Client | None = None
67
+ self._connected = threading.Event()
68
+ self._connect_refused: Any = None
69
+
70
+ # ------------------------------------------------------------------ lifecycle
71
+ def connect(self) -> None:
72
+ """Connect, retrying until `connect_budget_s` is spent.
73
+
74
+ A single attempt is not enough over Tailscale. The box is reached through
75
+ a DERP relay until a direct path is negotiated, and the very first TCP
76
+ connect to a cold peer routinely takes tens of seconds — long enough that
77
+ a one-shot timeout fails the whole job before the network has finished
78
+ waking up. Every attempt after the first is fast.
79
+ """
80
+ deadline = time.monotonic() + self.connect_budget_s
81
+ attempt = 0
82
+ while True:
83
+ attempt += 1
84
+ try:
85
+ self._try_connect()
86
+ return
87
+ except (OSError, TimeoutError) as e:
88
+ self.disconnect()
89
+ if time.monotonic() >= deadline:
90
+ raise TimeoutError(
91
+ f"no MQTT connection to the BusyBox at {self.broker}:{self.port} "
92
+ f"after {attempt} attempts over {self.connect_budget_s:.0f}s "
93
+ f"({e})"
94
+ ) from e
95
+ logger.warning(
96
+ "busybox: connect attempt %d to %s:%s failed (%s); retrying",
97
+ attempt, self.broker, self.port, e,
98
+ )
99
+ time.sleep(1.0)
100
+
101
+ def _try_connect(self) -> None:
102
+ self._connect_refused = None
103
+ client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2)
104
+ client.on_connect = self._on_connect
105
+ client.on_message = self._on_message
106
+ client.reconnect_delay_set(min_delay=1, max_delay=8)
107
+ client.connect(self.broker, self.port, keepalive=30)
108
+ client.loop_start()
109
+ self._client = client
110
+
111
+ if not self._connected.wait(self.connect_timeout_s):
112
+ # Distinguish "the broker said no" from "the broker said nothing" —
113
+ # a refused CONNACK reported as a timeout sends whoever is debugging
114
+ # off to check the network instead of the broker.
115
+ if self._connect_refused is not None:
116
+ raise OSError(f"MQTT connect refused: {self._connect_refused}")
117
+ raise TimeoutError(f"no CONNACK within {self.connect_timeout_s:.0f}s")
118
+
119
+ # A wrong topic prefix produces a healthy connection and no data at all,
120
+ # which is the single easiest way to misconfigure this. Say so loudly.
121
+ deadline = time.monotonic() + self.connect_timeout_s
122
+ while time.monotonic() < deadline:
123
+ if self._modules_seen() == set(MODULES):
124
+ logger.info("busybox: all modules reporting on %r", self.topic_prefix)
125
+ return
126
+ time.sleep(0.05)
127
+ missing = sorted(set(MODULES) - self._modules_seen())
128
+ logger.warning(
129
+ "busybox: no readings from %s on prefix %r — is the bridge running, "
130
+ "and does the prefix match its --base-topic?",
131
+ ", ".join(missing), self.topic_prefix,
132
+ )
133
+
134
+ def disconnect(self) -> None:
135
+ client, self._client = self._client, None
136
+ if client is None:
137
+ return
138
+ try:
139
+ client.loop_stop()
140
+ client.disconnect()
141
+ finally:
142
+ self._connected.clear()
143
+
144
+ @property
145
+ def is_connected(self) -> bool:
146
+ return self._client is not None and self._connected.is_set()
147
+
148
+ def __enter__(self) -> "BusyBoxClient":
149
+ self.connect()
150
+ return self
151
+
152
+ def __exit__(self, *exc: object) -> None:
153
+ self.disconnect()
154
+
155
+ # --------------------------------------------------------------------- state
156
+ def raw_readings(self, *, fresh_only: bool = False) -> Readings:
157
+ """The latest values per module.
158
+
159
+ Every module heartbeats at 1 Hz — each Nano's alive beacon prints its data
160
+ line every second and the bridge republishes it unconditionally — so
161
+ silence means the box is gone, not that nobody touched it. With
162
+ `fresh_only`, modules that have stopped reporting are omitted entirely
163
+ rather than served as last-known-good: a stale reading is indistinguishable
164
+ from a live one downstream, and scoring a rollout against a box that was
165
+ unplugged a minute ago is the kind of wrong that never announces itself.
166
+ """
167
+ cutoff = time.monotonic() - self.stale_after_s
168
+ with self._lock:
169
+ return {
170
+ module: list(values)
171
+ for module, values in self._readings.items()
172
+ if not fresh_only or self._received_at.get(module, float("-inf")) >= cutoff
173
+ }
174
+
175
+ def snapshot(self) -> BusyBoxState:
176
+ """Decode the most recent readings. Cheap, non-blocking, control-loop safe.
177
+
178
+ Stale modules drop out, so their controls read as absent — which the goal
179
+ check reports as unscorable rather than as a confident verdict.
180
+ """
181
+ fresh = self.raw_readings(fresh_only=True)
182
+ self._warn_if_stale(fresh)
183
+ return self.decoder.decode(fresh)
184
+
185
+ def _warn_if_stale(self, fresh: Readings) -> None:
186
+ gone = sorted(set(self._modules_seen()) - set(fresh))
187
+ if not gone or gone == self._last_stale_warned:
188
+ self._last_stale_warned = gone
189
+ return
190
+ self._last_stale_warned = gone
191
+ logger.warning(
192
+ "busybox: no heartbeat from %s for over %.0fs — these controls will "
193
+ "read as absent (the box publishes every module at 1 Hz, so silence "
194
+ "means it is gone, not idle)",
195
+ ", ".join(gone), self.stale_after_s,
196
+ )
197
+
198
+ def begin_episode(self, knob_position: int | None = None) -> None:
199
+ """Open a new observation window.
200
+
201
+ `knob_position` is the detent the box was reset to. It only matters on
202
+ a legacy box with the relative (KY-040) knob: that encoder free-runs
203
+ from power-up, so without homing the knob has no absolute position and
204
+ any knob goal reports as unscorable rather than guessing. On a current
205
+ box with the absolute B10K pot the reading IS the position — homing is
206
+ trivially satisfied and `knob_position` is ignored.
207
+
208
+ Homing uses only a *fresh* knob reading. A cached count is worse than no
209
+ count: if the knob module went quiet because its Nano reset, the count
210
+ restarted from zero, and homing against the pre-reset value would plant
211
+ exactly the garbage origin homing exists to prevent. When homing was
212
+ asked for but cannot happen, say so loudly — the operator passed
213
+ `busybox_knob_home` expecting knob goals to be scorable, and a silent
214
+ no-op here would quietly hand every one of them back to a human.
215
+ """
216
+ self.decoder.reset_events()
217
+ if knob_position is None:
218
+ return
219
+ homed = self.decoder.home_knob(
220
+ self.raw_readings(fresh_only=True), int(knob_position)
221
+ )
222
+ if not homed:
223
+ logger.warning(
224
+ "busybox: knob homing to detent %s requested but there is no fresh "
225
+ "knob reading (module silent for over %.0fs, or never heard from) — "
226
+ "knob goals will report unscorable this episode",
227
+ knob_position, self.stale_after_s,
228
+ )
229
+
230
+ def stale_modules(self) -> list[str]:
231
+ """Modules that are silent: never heard from, or gone quiet.
232
+
233
+ Every module heartbeats at 1 Hz, so either is a fault — there is no such
234
+ thing as a legitimately idle module.
235
+ """
236
+ cutoff = time.monotonic() - self.stale_after_s
237
+ with self._lock:
238
+ seen = dict(self._received_at)
239
+ return [m for m in MODULES if seen.get(m, float("-inf")) < cutoff]
240
+
241
+ def _modules_seen(self) -> set[str]:
242
+ with self._lock:
243
+ return set(self._readings)
244
+
245
+ # ----------------------------------------------------------------- callbacks
246
+ def _on_connect(self, client: mqtt.Client, _userdata: Any, _flags: Any,
247
+ reason_code: Any, _properties: Any = None) -> None:
248
+ if getattr(reason_code, "is_failure", False) or reason_code != 0:
249
+ self._connect_refused = reason_code
250
+ logger.error("busybox: MQTT connect refused (%s)", reason_code)
251
+ return
252
+ for module in MODULES:
253
+ client.subscribe(f"{self.topic_prefix}/{module}/state", qos=0)
254
+ self._connected.set()
255
+
256
+ def _on_message(self, _client: mqtt.Client, _userdata: Any,
257
+ msg: mqtt.MQTTMessage) -> None:
258
+ module = self._module_of(msg.topic)
259
+ if module is None:
260
+ return
261
+ try:
262
+ payload = json.loads(msg.payload.decode("utf-8"))
263
+ values = [int(v) for v in payload["values"]]
264
+ except (ValueError, KeyError, TypeError) as e:
265
+ logger.warning("busybox: bad payload on %s: %s", msg.topic, e)
266
+ return
267
+ with self._lock:
268
+ self._readings[module] = values
269
+ self._received_at[module] = time.monotonic()
270
+
271
+ def _module_of(self, topic: str) -> str | None:
272
+ prefix = f"{self.topic_prefix}/"
273
+ if not topic.startswith(prefix):
274
+ return None
275
+ module = topic[len(prefix):].split("/", 1)[0]
276
+ return module if module in MODULES else None