plexus-python 0.4.5__tar.gz → 0.4.6__tar.gz

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.
Files changed (37) hide show
  1. {plexus_python-0.4.5 → plexus_python-0.4.6}/API.md +41 -5
  2. {plexus_python-0.4.5 → plexus_python-0.4.6}/PKG-INFO +19 -1
  3. {plexus_python-0.4.5 → plexus_python-0.4.6}/README.md +18 -0
  4. {plexus_python-0.4.5 → plexus_python-0.4.6}/plexus/__init__.py +1 -1
  5. {plexus_python-0.4.5 → plexus_python-0.4.6}/plexus/client.py +38 -10
  6. {plexus_python-0.4.5 → plexus_python-0.4.6}/plexus/ws.py +18 -0
  7. {plexus_python-0.4.5 → plexus_python-0.4.6}/pyproject.toml +1 -1
  8. {plexus_python-0.4.5 → plexus_python-0.4.6}/tests/test_basic.py +18 -0
  9. {plexus_python-0.4.5 → plexus_python-0.4.6}/tests/test_ws.py +46 -0
  10. plexus_python-0.4.6/uv.lock +1167 -0
  11. {plexus_python-0.4.5 → plexus_python-0.4.6}/.github/ISSUE_TEMPLATE/bug_report.yml +0 -0
  12. {plexus_python-0.4.5 → plexus_python-0.4.6}/.github/ISSUE_TEMPLATE/feature_request.yml +0 -0
  13. {plexus_python-0.4.5 → plexus_python-0.4.6}/.github/PULL_REQUEST_TEMPLATE.md +0 -0
  14. {plexus_python-0.4.5 → plexus_python-0.4.6}/.github/workflows/ci.yml +0 -0
  15. {plexus_python-0.4.5 → plexus_python-0.4.6}/.github/workflows/publish.yml +0 -0
  16. {plexus_python-0.4.5 → plexus_python-0.4.6}/.gitignore +0 -0
  17. {plexus_python-0.4.5 → plexus_python-0.4.6}/AGENTS.md +0 -0
  18. {plexus_python-0.4.5 → plexus_python-0.4.6}/CHANGELOG.md +0 -0
  19. {plexus_python-0.4.5 → plexus_python-0.4.6}/CODE_OF_CONDUCT.md +0 -0
  20. {plexus_python-0.4.5 → plexus_python-0.4.6}/CONTRIBUTING.md +0 -0
  21. {plexus_python-0.4.5 → plexus_python-0.4.6}/LICENSE +0 -0
  22. {plexus_python-0.4.5 → plexus_python-0.4.6}/SECURITY.md +0 -0
  23. {plexus_python-0.4.5 → plexus_python-0.4.6}/examples/README.md +0 -0
  24. {plexus_python-0.4.5 → plexus_python-0.4.6}/examples/basic.py +0 -0
  25. {plexus_python-0.4.5 → plexus_python-0.4.6}/examples/can.py +0 -0
  26. {plexus_python-0.4.5 → plexus_python-0.4.6}/examples/i2c_bme280.py +0 -0
  27. {plexus_python-0.4.5 → plexus_python-0.4.6}/examples/mavlink.py +0 -0
  28. {plexus_python-0.4.5 → plexus_python-0.4.6}/examples/mqtt.py +0 -0
  29. {plexus_python-0.4.5 → plexus_python-0.4.6}/plexus/buffer.py +0 -0
  30. {plexus_python-0.4.5 → plexus_python-0.4.6}/plexus/cli.py +0 -0
  31. {plexus_python-0.4.5 → plexus_python-0.4.6}/plexus/config.py +0 -0
  32. {plexus_python-0.4.5 → plexus_python-0.4.6}/scripts/plexus.service +0 -0
  33. {plexus_python-0.4.5 → plexus_python-0.4.6}/scripts/scan_buses.py +0 -0
  34. {plexus_python-0.4.5 → plexus_python-0.4.6}/scripts/setup.sh +0 -0
  35. {plexus_python-0.4.5 → plexus_python-0.4.6}/tests/test_buffer.py +0 -0
  36. {plexus_python-0.4.5 → plexus_python-0.4.6}/tests/test_config.py +0 -0
  37. {plexus_python-0.4.5 → plexus_python-0.4.6}/tests/test_retry.py +0 -0
@@ -98,7 +98,7 @@ x-api-key: plx_xxxxx
98
98
  | ------------ | ------ | -------- | ---------------------------------------------- |
99
99
  | `metric` | string | Yes | Metric name (e.g., `temperature`, `motor.rpm`) |
100
100
  | `value` | any | Yes | See supported value types below |
101
- | `timestamp` | float | No | Unix timestamp (seconds). Defaults to now |
101
+ | `timestamp` | float | No | Unix timestamp in seconds (or ms if ≥ 1e12). Omit to use device time. Over WebSocket, the Python SDK applies a server-synced clock correction when omitted — see [Clock correction](#clock-correction). |
102
102
  | `source_id` | string | Yes | Your source identifier |
103
103
  | `tags` | object | No | Key-value labels |
104
104
  | `session_id` | string | No | Group data into sessions |
@@ -168,18 +168,22 @@ Devices authenticate using an API key. The `source_id` in the request is the dev
168
168
  // Server → Device
169
169
  {
170
170
  "type": "authenticated",
171
- "source_id": "drone-01"
171
+ "source_id": "drone-01",
172
+ "server_time_ms": 1746100800000
172
173
  }
173
174
 
174
175
  // Server → Device (collision case)
175
176
  {
176
177
  "type": "authenticated",
177
- "source_id": "drone-01_2"
178
+ "source_id": "drone-01_2",
179
+ "server_time_ms": 1746100800000
178
180
  }
179
181
  ```
180
182
 
181
183
  The SDK **adopts** whatever `source_id` the server returns and uses it for all subsequent frames, heartbeats, and reconnects. It also persists the assigned name locally so reconnects go straight to the claimed slot.
182
184
 
185
+ `server_time_ms` is the gateway's current Unix time in milliseconds. The Python SDK uses it to compute a clock offset (`server_time - device_time`) that is applied to every SDK-generated timestamp for the lifetime of the connection. This corrects for devices that boot without NTP or have an unreliable RTC — a common condition on embedded Linux. See [Clock correction](#clock-correction) for details and limitations.
186
+
183
187
  `install_id` is a stable per-installation UUID, generated on the device's first run and saved to `~/.plexus/config.json`. It lets the server distinguish a rebooting device from a new device trying to claim an existing name. Legacy SDKs that omit `install_id` continue to work as before (the server passes the declared `source_id` through unchanged).
184
188
 
185
189
  ### Message Types (Dashboard → Device)
@@ -354,6 +358,9 @@ func main() {
354
358
  #include <WiFi.h>
355
359
  #include <HTTPClient.h>
356
360
 
361
+ // Call configTime(0, 0, "pool.ntp.org") in setup() before sending.
362
+ // time(nullptr) returns 0 until NTP sync completes — omit the timestamp
363
+ // field entirely if you cannot guarantee NTP sync at send time.
357
364
  void sendToPlexus(const char* metric, float value) {
358
365
  HTTPClient http;
359
366
  http.begin("https://plexus-gateway.fly.dev/ingest");
@@ -363,7 +370,7 @@ void sendToPlexus(const char* metric, float value) {
363
370
  String payload = "{\"points\":[{";
364
371
  payload += "\"metric\":\"" + String(metric) + "\",";
365
372
  payload += "\"value\":" + String(value) + ",";
366
- payload += "\"timestamp\":" + String(millis() / 1000.0) + ",";
373
+ payload += "\"timestamp\":" + String(time(nullptr)) + ",";
367
374
  payload += "\"source_id\":\"esp32-001\"";
368
375
  payload += "}]}";
369
376
 
@@ -469,10 +476,39 @@ class MySensor(BaseSensor):
469
476
  | 404 | Resource not found |
470
477
  | 410 | Resource expired |
471
478
 
479
+ ## Clock correction
480
+
481
+ Embedded devices commonly boot with a wrong system clock — no hardware RTC, NTP unreachable on first boot, or a fresh OS image whose filesystem timestamp is months in the past. Without correction, all telemetry lands at the wrong place on the timeline.
482
+
483
+ The Python SDK corrects for this automatically over WebSocket. On every connection the gateway returns `server_time_ms` in the `authenticated` frame. The SDK computes `offset = server_time - device_time` and adds it to every timestamp it generates. Data lands at the right time on the dashboard regardless of what the device clock says.
484
+
485
+ **When the correction applies:**
486
+
487
+ The offset is applied when `timestamp` is omitted (the SDK generates the time). If you pass an explicit `timestamp`, it is used as-is — the SDK cannot tell whether your value is a wall-clock time or a hardware-relative counter, so it leaves it alone.
488
+
489
+ ```python
490
+ px.send("temperature", 72.5) # SDK picks time → correction applied
491
+ px.send("temperature", 72.5, timestamp=t) # your timestamp → used as-is, no correction
492
+ ```
493
+
494
+ **When to pass an explicit timestamp:**
495
+ - You have a reliable wall-clock source (GPS, trusted hardware RTC, host NTP)
496
+ - You are replaying or backfilling historical data
497
+ - Your sensor provides its own wall-clock timestamp
498
+
499
+ **When to omit timestamp:**
500
+ - The device may have booted without NTP (Raspberry Pi, Jetson, field robots without network on first boot)
501
+ - You have no reliable external time source
502
+
503
+ **Known limitations:**
504
+ - The clock offset refreshes only on WebSocket reconnect. A device with a drifting RTC that stays connected for many days will accumulate uncorrected drift between reconnects proportional to the drift rate.
505
+ - HTTP transport (`transport="http"`) does not receive clock sync — timestamps default to the device clock uncorrected.
506
+ - `send_batch()` takes one shared `timestamp` for the whole batch, not per-point. For per-point timestamps, call `send()` in a loop.
507
+
472
508
  ## Best Practices
473
509
 
474
510
  - **Batch points** - Send up to 100 points per request for HTTP
475
- - **Use timestamps** - Always include accurate timestamps
511
+ - **Omit timestamp when unsure** - The Python SDK applies server-synced clock correction when `timestamp` is omitted over WebSocket; only pass an explicit timestamp when you have a reliable wall-clock source
476
512
  - **Consistent source_id** - Use the same ID for each physical device/source
477
513
  - **Use tags** - Label data for filtering (e.g., `{"location": "lab"}`)
478
514
  - **Use sessions** - Group related data for easier analysis
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: plexus-python
3
- Version: 0.4.5
3
+ Version: 0.4.6
4
4
  Summary: Thin Python SDK for Plexus — send telemetry in one line
5
5
  Project-URL: Homepage, https://plexus.dev
6
6
  Project-URL: Documentation, https://docs.plexus.dev
@@ -136,6 +136,24 @@ px.buffer_size()
136
136
  px.flush_buffer()
137
137
  ```
138
138
 
139
+ ## Timestamps and clock correction
140
+
141
+ By default — `px.send("temp", 72.5)` with no `timestamp` argument — the SDK picks the time itself. Over WebSocket, it synchronizes with the gateway clock on every connection, so data lands at the right place on the timeline even if the device's system clock is wrong (no NTP on first boot, stale RTC, fresh OS image).
142
+
143
+ ```python
144
+ px.send("temperature", 72.5) # SDK picks time; gateway-synced over WS
145
+ px.send("temperature", 72.5, timestamp=t) # your timestamp, used as-is, no correction
146
+ ```
147
+
148
+ **Pass an explicit timestamp when** you have a reliable external time source (GPS, trusted RTC, host NTP) or are replaying historical data with known timestamps.
149
+
150
+ **Omit timestamp when** the device may have booted without NTP — which is the default on Raspberry Pi, Jetson, and most embedded Linux boards without a network connection at first boot.
151
+
152
+ **Known limits:**
153
+ - Clock sync refreshes on WebSocket (re)connect. A device with a drifting RTC that stays connected for many days accumulates uncorrected drift between reconnects.
154
+ - HTTP-only transport (`transport="http"`) does not receive clock sync — timestamps default to the uncorrected device clock.
155
+ - `send_batch()` shares one timestamp across the whole batch. For per-point timestamps, call `send()` in a loop.
156
+
139
157
  ## Transport
140
158
 
141
159
  By default the SDK connects over a **WebSocket** to `/ws/device` on the gateway — same wire protocol as the C SDK. This gives you:
@@ -102,6 +102,24 @@ px.buffer_size()
102
102
  px.flush_buffer()
103
103
  ```
104
104
 
105
+ ## Timestamps and clock correction
106
+
107
+ By default — `px.send("temp", 72.5)` with no `timestamp` argument — the SDK picks the time itself. Over WebSocket, it synchronizes with the gateway clock on every connection, so data lands at the right place on the timeline even if the device's system clock is wrong (no NTP on first boot, stale RTC, fresh OS image).
108
+
109
+ ```python
110
+ px.send("temperature", 72.5) # SDK picks time; gateway-synced over WS
111
+ px.send("temperature", 72.5, timestamp=t) # your timestamp, used as-is, no correction
112
+ ```
113
+
114
+ **Pass an explicit timestamp when** you have a reliable external time source (GPS, trusted RTC, host NTP) or are replaying historical data with known timestamps.
115
+
116
+ **Omit timestamp when** the device may have booted without NTP — which is the default on Raspberry Pi, Jetson, and most embedded Linux boards without a network connection at first boot.
117
+
118
+ **Known limits:**
119
+ - Clock sync refreshes on WebSocket (re)connect. A device with a drifting RTC that stays connected for many days accumulates uncorrected drift between reconnects.
120
+ - HTTP-only transport (`transport="http"`) does not receive clock sync — timestamps default to the uncorrected device clock.
121
+ - `send_batch()` shares one timestamp across the whole batch. For per-point timestamps, call `send()` in a loop.
122
+
105
123
  ## Transport
106
124
 
107
125
  By default the SDK connects over a **WebSocket** to `/ws/device` on the gateway — same wire protocol as the C SDK. This gives you:
@@ -10,5 +10,5 @@ Plexus — thin Python SDK for sending telemetry to the Plexus gateway.
10
10
  from plexus.client import Plexus
11
11
  from plexus.ws import WebSocketTransport
12
12
 
13
- __version__ = "0.4.5"
13
+ __version__ = "0.4.6"
14
14
  __all__ = ["Plexus", "WebSocketTransport"]
@@ -140,6 +140,7 @@ class Plexus:
140
140
  self.transport = transport
141
141
  self._ws_url = (ws_url or get_gateway_ws_url())
142
142
  self._ws = None # lazily constructed in _ensure_ws()
143
+ self._clock_offset_ms: int = 0
143
144
 
144
145
  # Pluggable buffer backend for failed sends
145
146
  if persistent_buffer:
@@ -175,17 +176,16 @@ class Plexus:
175
176
  self._session.headers["User-Agent"] = f"plexus-python/{__version__}"
176
177
  return self._session
177
178
 
178
- @staticmethod
179
- def _normalize_ts_ms(timestamp: Optional[float] = None) -> int:
179
+ def _normalize_ts_ms(self, timestamp: Optional[float] = None) -> int:
180
180
  """Normalize a timestamp to milliseconds.
181
181
 
182
182
  Accepts:
183
- - None: returns current time in ms
184
- - float seconds (e.g. time.time()): converts to ms
185
- - int/float ms: returned as-is
183
+ - None: returns current time in ms, corrected by server clock offset
184
+ - float seconds (e.g. time.time()): converts to ms (no offset applied)
185
+ - int/float ms: returned as-is (no offset applied)
186
186
  """
187
187
  if timestamp is None:
188
- return int(time.time() * 1000)
188
+ return int(time.time() * 1000) + self._clock_offset_ms
189
189
  # Heuristic: values < 1e12 are seconds
190
190
  if timestamp > 0 and timestamp < 1e12:
191
191
  return int(timestamp * 1000)
@@ -258,6 +258,30 @@ class Plexus:
258
258
  point = self._make_point(metric, value, timestamp, tags, data_class)
259
259
  return self._send_points([point])
260
260
 
261
+ def event(
262
+ self,
263
+ name: str,
264
+ data: FlexValue,
265
+ timestamp: Optional[float] = None,
266
+ tags: Optional[Dict[str, str]] = None,
267
+ ) -> bool:
268
+ """
269
+ Send a named event with text or structured data.
270
+
271
+ Args:
272
+ name: Event type (e.g., "fault", "state_change", "log")
273
+ data: Text or JSON-serializable value (string, dict, list, bool, number)
274
+ timestamp: Unix timestamp. If not provided, uses current time.
275
+ tags: Optional key-value tags
276
+
277
+ Example:
278
+ px.event("fault", "E-stop triggered")
279
+ px.event("state_change", {"from": "IDLE", "to": "RUNNING"})
280
+ px.event("sensor_error", {"sensor": "imu", "code": 42}, tags={"motor": "A"})
281
+ """
282
+ point = self._make_point(name, data, timestamp, tags, data_class="event")
283
+ return self._send_points([point])
284
+
261
285
  def send_batch(
262
286
  self,
263
287
  points: List[Tuple[str, FlexValue]],
@@ -283,8 +307,8 @@ class Plexus:
283
307
  ("position", {"x": 1.0, "y": 2.0}),
284
308
  ])
285
309
  """
286
- ts = timestamp if timestamp is not None else time.time()
287
- data_points = [self._make_point(m, v, ts, tags) for m, v in points]
310
+ ts_ms = self._normalize_ts_ms(timestamp)
311
+ data_points = [self._make_point(m, v, ts_ms, tags) for m, v in points]
288
312
  return self._send_points(data_points)
289
313
 
290
314
  def _ensure_ws(self):
@@ -300,10 +324,14 @@ class Plexus:
300
324
  install_id=get_install_id(),
301
325
  agent_version=__version__,
302
326
  on_source_id_assigned=self._on_source_id_assigned,
327
+ on_clock_synced=self._on_clock_synced,
303
328
  )
304
329
  self._ws.start()
305
330
  return self._ws
306
331
 
332
+ def _on_clock_synced(self, offset_ms: int) -> None:
333
+ self._clock_offset_ms = offset_ms
334
+
307
335
  def _on_source_id_assigned(self, assigned: str) -> None:
308
336
  """Callback from WebSocketTransport when the gateway returns an
309
337
  auto-suffixed source_id. Persists it so subsequent runs (and the HTTP
@@ -555,7 +583,7 @@ class Plexus:
555
583
  "source_id": self.source_id,
556
584
  "status": "started",
557
585
  "tags": tags,
558
- "timestamp": time.time(),
586
+ "timestamp": (int(time.time() * 1000) + self._clock_offset_ms) / 1000,
559
587
  },
560
588
  timeout=self.timeout,
561
589
  )
@@ -573,7 +601,7 @@ class Plexus:
573
601
  "run_id": run_id,
574
602
  "source_id": self.source_id,
575
603
  "status": "ended",
576
- "timestamp": time.time(),
604
+ "timestamp": (int(time.time() * 1000) + self._clock_offset_ms) / 1000,
577
605
  },
578
606
  timeout=self.timeout,
579
607
  )
@@ -25,6 +25,7 @@ Runs the read loop on a background daemon thread so callers can stay sync.
25
25
 
26
26
  from __future__ import annotations
27
27
 
28
+ import atexit
28
29
  import json
29
30
  import logging
30
31
  import os
@@ -108,6 +109,7 @@ class WebSocketTransport:
108
109
  platform: str = "python-sdk",
109
110
  auto_reconnect: bool = True,
110
111
  on_source_id_assigned: Optional[Callable[[str], None]] = None,
112
+ on_clock_synced: Optional[Callable[[int], None]] = None,
111
113
  ):
112
114
  if not api_key:
113
115
  raise ValueError("api_key required")
@@ -122,6 +124,7 @@ class WebSocketTransport:
122
124
  self.platform = platform
123
125
  self.auto_reconnect = auto_reconnect
124
126
  self._on_source_id_assigned = on_source_id_assigned
127
+ self._on_clock_synced = on_clock_synced
125
128
 
126
129
  self._commands: Dict[str, _RegisteredCommand] = {}
127
130
  self._ws: Optional[websocket.WebSocket] = None
@@ -130,6 +133,7 @@ class WebSocketTransport:
130
133
  self._stop = threading.Event()
131
134
  self._thread: Optional[threading.Thread] = None
132
135
  self._backoff_attempt = 0
136
+ self._clock_offset_ms: int = 0
133
137
 
134
138
  # ------------------------------------------------------------------ public
135
139
 
@@ -155,6 +159,7 @@ class WebSocketTransport:
155
159
  target=self._run, name="plexus-ws", daemon=True
156
160
  )
157
161
  self._thread.start()
162
+ atexit.register(self.stop)
158
163
 
159
164
  def stop(self, timeout: float = 2.0) -> None:
160
165
  self._stop.set()
@@ -175,6 +180,10 @@ class WebSocketTransport:
175
180
  def is_authenticated(self) -> bool:
176
181
  return self._authenticated.is_set()
177
182
 
183
+ @property
184
+ def clock_offset_ms(self) -> int:
185
+ return self._clock_offset_ms
186
+
178
187
  def send_points(self, points: List[Dict[str, Any]]) -> bool:
179
188
  """Send a telemetry frame. Returns False if the socket is not
180
189
  authenticated — caller is expected to fall back to HTTP."""
@@ -250,6 +259,15 @@ class WebSocketTransport:
250
259
  if msg.get("type") != "authenticated":
251
260
  raise RuntimeError(f"auth failed: {msg}")
252
261
 
262
+ server_ts = msg.get("server_time_ms")
263
+ if isinstance(server_ts, (int, float)) and server_ts > 0:
264
+ self._clock_offset_ms = int(server_ts) - int(time.time() * 1000)
265
+ if self._on_clock_synced is not None:
266
+ try:
267
+ self._on_clock_synced(self._clock_offset_ms)
268
+ except Exception as e:
269
+ logger.debug("on_clock_synced callback raised: %s", e)
270
+
253
271
  # The gateway may return a different source_id if the desired name
254
272
  # was already claimed by another install — adopt the assigned value
255
273
  # so all subsequent frames (heartbeats, future reconnects) use it.
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "plexus-python"
7
- version = "0.4.5"
7
+ version = "0.4.6"
8
8
  description = "Thin Python SDK for Plexus — send telemetry in one line"
9
9
  readme = "README.md"
10
10
  license = "Apache-2.0"
@@ -1,5 +1,7 @@
1
1
  """Basic tests for plexus-python."""
2
2
 
3
+ import time
4
+
3
5
  from plexus import __version__
4
6
  from plexus.client import Plexus
5
7
  from plexus.config import DEFAULT_CONFIG
@@ -41,3 +43,19 @@ def test_make_point_with_tags():
41
43
  point = px._make_point("temperature", 72.5, tags={"sensor": "A1"})
42
44
 
43
45
  assert point["tags"] == {"sensor": "A1"}
46
+
47
+
48
+ def test_normalize_ts_ms_applies_clock_offset():
49
+ px = Plexus(api_key="test", endpoint="http://localhost")
50
+ px._clock_offset_ms = 5000
51
+ before = int(time.time() * 1000)
52
+ ts = px._normalize_ts_ms(None)
53
+ after = int(time.time() * 1000)
54
+ assert before + 5000 <= ts <= after + 5000
55
+
56
+
57
+ def test_normalize_ts_ms_ignores_offset_for_supplied_timestamp():
58
+ px = Plexus(api_key="test", endpoint="http://localhost")
59
+ px._clock_offset_ms = 5000
60
+ ts = px._normalize_ts_ms(1_700_000_000.0)
61
+ assert ts == 1_700_000_000_000
@@ -61,6 +61,7 @@ class _StubGateway:
61
61
  await ws.send(json.dumps({
62
62
  "type": "authenticated",
63
63
  "source_id": returned_source_id,
64
+ "server_time_ms": int(time.time() * 1000),
64
65
  }))
65
66
  try:
66
67
  async for raw in ws:
@@ -332,3 +333,48 @@ def test_ensure_device_path():
332
333
  assert _ensure_device_path("wss://foo") == "wss://foo/ws/device"
333
334
  assert _ensure_device_path("wss://foo/") == "wss://foo/ws/device"
334
335
  assert _ensure_device_path("wss://foo/ws/device") == "wss://foo/ws/device"
336
+
337
+
338
+ def test_clock_offset_computed_from_authenticated_frame():
339
+ # Stub sends a server_time_ms that is 30 seconds ahead of real time.
340
+ # The transport's clock_offset_ms should be close to +30_000.
341
+ fake_offset_ms = 30_000
342
+
343
+ class _OffsetStubGateway(_StubGateway):
344
+ async def _handler(self, ws, path="/ws/device"):
345
+ self._ws = ws
346
+ raw = await ws.recv()
347
+ msg = json.loads(raw)
348
+ self.auth_frame = msg
349
+ returned_source_id = self.assigned_source_id or msg.get("source_id")
350
+ await ws.send(json.dumps({
351
+ "type": "authenticated",
352
+ "source_id": returned_source_id,
353
+ "server_time_ms": int(time.time() * 1000) + fake_offset_ms,
354
+ }))
355
+ try:
356
+ async for raw in ws:
357
+ self.received.append(json.loads(raw))
358
+ except websockets.ConnectionClosed:
359
+ return
360
+
361
+ g = _OffsetStubGateway()
362
+ g.start()
363
+ try:
364
+ seen: List[int] = []
365
+ t = WebSocketTransport(
366
+ api_key="plx_test_abc",
367
+ source_id="drone-001",
368
+ ws_url=_url(g.port),
369
+ on_clock_synced=lambda offset: seen.append(offset),
370
+ )
371
+ t.start()
372
+ try:
373
+ assert t.wait_authenticated(timeout=3)
374
+ assert abs(t.clock_offset_ms - fake_offset_ms) < 500
375
+ assert len(seen) == 1
376
+ assert abs(seen[0] - fake_offset_ms) < 500
377
+ finally:
378
+ t.stop()
379
+ finally:
380
+ g.stop()