walkingpad-controller 0.5.0__tar.gz → 0.6.0__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 (45) hide show
  1. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/PKG-INFO +16 -1
  2. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/README.md +15 -0
  3. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/pyproject.toml +1 -1
  4. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/src/walkingpad_controller/__init__.py +1 -1
  5. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/src/walkingpad_controller/const.py +18 -3
  6. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/src/walkingpad_controller/controller.py +3 -0
  7. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/src/walkingpad_controller/ftms.py +249 -20
  8. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/src/walkingpad_controller/models.py +7 -0
  9. walkingpad_controller-0.6.0/tests/test_ftms_stop.py +310 -0
  10. walkingpad_controller-0.6.0/tests/test_protocol_detection.py +41 -0
  11. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/.gitignore +0 -0
  12. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/LICENSE +0 -0
  13. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/docs/ftms-protocol-reference.md +0 -0
  14. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/docs/ks-fit-reverse-engineering.md +0 -0
  15. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/docs/sperax-p3max-protocol.md +0 -0
  16. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/src/walkingpad_controller/sperax.py +0 -0
  17. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/src/walkingpad_controller/wilink.py +0 -0
  18. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/commands/__init__.py +0 -0
  19. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/commands/_common.py +0 -0
  20. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/commands/test_connect.py +0 -0
  21. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/commands/test_disconnect.py +0 -0
  22. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/commands/test_observe.py +0 -0
  23. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/commands/test_pause.py +0 -0
  24. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/commands/test_reset.py +0 -0
  25. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/commands/test_resume.py +0 -0
  26. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/commands/test_set_inclination.py +0 -0
  27. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/commands/test_set_speed.py +0 -0
  28. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/commands/test_start.py +0 -0
  29. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/commands/test_stop.py +0 -0
  30. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/commands/test_switch_mode.py +0 -0
  31. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/commands/test_update_state.py +0 -0
  32. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/probe_disconnect.py +0 -0
  33. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/probe_keepalive.py +0 -0
  34. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/probe_lib_stability.py +0 -0
  35. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/probe_preworkout.py +0 -0
  36. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/probe_preworkout2.py +0 -0
  37. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/probe_setup_killer.py +0 -0
  38. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/probe_setup_step.py +0 -0
  39. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/stress_dynamic.py +0 -0
  40. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/stress_real_device.py +0 -0
  41. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/stress_start_stop.py +0 -0
  42. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/stress_traced.py +0 -0
  43. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/test_real_device.py +0 -0
  44. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/test_sperax_codec.py +0 -0
  45. {walkingpad_controller-0.5.0 → walkingpad_controller-0.6.0}/tests/watch_ble.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: walkingpad-controller
3
- Version: 0.5.0
3
+ Version: 0.6.0
4
4
  Summary: Python library for controlling KingSmith WalkingPad treadmills over BLE (FTMS and legacy WiLink protocols)
5
5
  Project-URL: Homepage, https://github.com/mcdax/walkingpad-controller
6
6
  Project-URL: Repository, https://github.com/mcdax/walkingpad-controller
@@ -162,6 +162,8 @@ For advanced use, you can use the protocol controllers directly:
162
162
 
163
163
  ### FTMS Protocol (tested)
164
164
  - KingSmith KS-Z1D (BLE name: `KS-HD-Z1D`) — confirmed working
165
+ - KingSmith KS-Z1E (BLE name: `KS-HD-Z1E`) — tested by community, see [#7](https://github.com/mcdax/walkingpad-controller/issues/7)
166
+ - KingSmith R3 (BLE name: `KS-AP-RQ3`, model `KS-R3Q`) — tested: connect, start, set_speed, pause, stop. Rejects STOP while the belt moves, so `stop()` pauses first (see Known Behavior)
165
167
  - KingSmith MC-21 (BLE names: `KS-MC21-*`, `KS-SMC21C-*`, `ZP-ZEALR1-*`) — confirmed working as of v0.4.1, requires the vendor pre-amble described below
166
168
  - Other KingSmith devices with BLE names starting with `KS-HD-` are expected to work via the same FTMS / supplement-service code path
167
169
 
@@ -175,6 +177,19 @@ For advanced use, you can use the protocol controllers directly:
175
177
  ### FTMS Cold Start
176
178
  KingSmith FTMS devices require a `START_OR_RESUME` command before the belt will accept speed commands. The library handles this automatically: it sends START, waits for the belt to report speed > 0 via treadmill data notifications, then waits an additional stabilization period before sending `SET_TARGET_SPEED`. This avoids the BLE disconnects that occur when speed commands are sent too early during motor startup.
177
179
 
180
+ ### STOP While Running
181
+ The KingSmith R3 (`KS-AP-*`) answers FTMS `STOP` with `OPERATION_FAILED` while the belt is moving, and the belt keeps running. KS Fit never sends STOP to a moving belt: it pauses, then ends the session. For devices listed in `FTMS_PAUSE_BEFORE_STOP_PREFIXES` (currently only `KS-AP-`, verified on the R3), `stop()` does the same:
182
+
183
+ 1. It sends PAUSE whatever the cached speed is, because the cached value may be stale or lag a remote start.
184
+ 2. It waits for Treadmill Data received *after* the PAUSE to report 0 km/h.
185
+ 3. Only then does it send STOP.
186
+
187
+ If the link drops, telemetry stops arriving, or the belt is still moving at the timeout, STOP is not sent, `stop()` returns `False`, and the log says which case it was. Other FTMS devices keep the plain STOP behaviour.
188
+
189
+ The R3 also rejects both PAUSE and STOP during the 3-2-1 countdown after a START, and the belt then starts anyway. The firmware can't be halted during the countdown. If STOP is rejected at 0 km/h, `stop()` watches for the belt to start for a few seconds and pauses it as soon as it moves (on the R3 that takes about a second at 1 km/h). It then ends the session as above. If the belt stays at rest, there was no session to end and `stop()` returns `False`.
190
+
191
+ Multi-step commands (`start`, `stop`, `set_target_speed`, …) are serialised within a controller, and so are Control Point acknowledgements. `pause()` only waits for an in-flight Control Point write, so it can still halt the belt while `start()` is waiting for it to move.
192
+
178
193
  ### BLE Connection Drops
179
194
  KingSmith FTMS devices may occasionally drop the connection after a cold start. The library stores the pending target speed and re-applies it after reconnection.
180
195
 
@@ -133,6 +133,8 @@ For advanced use, you can use the protocol controllers directly:
133
133
 
134
134
  ### FTMS Protocol (tested)
135
135
  - KingSmith KS-Z1D (BLE name: `KS-HD-Z1D`) — confirmed working
136
+ - KingSmith KS-Z1E (BLE name: `KS-HD-Z1E`) — tested by community, see [#7](https://github.com/mcdax/walkingpad-controller/issues/7)
137
+ - KingSmith R3 (BLE name: `KS-AP-RQ3`, model `KS-R3Q`) — tested: connect, start, set_speed, pause, stop. Rejects STOP while the belt moves, so `stop()` pauses first (see Known Behavior)
136
138
  - KingSmith MC-21 (BLE names: `KS-MC21-*`, `KS-SMC21C-*`, `ZP-ZEALR1-*`) — confirmed working as of v0.4.1, requires the vendor pre-amble described below
137
139
  - Other KingSmith devices with BLE names starting with `KS-HD-` are expected to work via the same FTMS / supplement-service code path
138
140
 
@@ -146,6 +148,19 @@ For advanced use, you can use the protocol controllers directly:
146
148
  ### FTMS Cold Start
147
149
  KingSmith FTMS devices require a `START_OR_RESUME` command before the belt will accept speed commands. The library handles this automatically: it sends START, waits for the belt to report speed > 0 via treadmill data notifications, then waits an additional stabilization period before sending `SET_TARGET_SPEED`. This avoids the BLE disconnects that occur when speed commands are sent too early during motor startup.
148
150
 
151
+ ### STOP While Running
152
+ The KingSmith R3 (`KS-AP-*`) answers FTMS `STOP` with `OPERATION_FAILED` while the belt is moving, and the belt keeps running. KS Fit never sends STOP to a moving belt: it pauses, then ends the session. For devices listed in `FTMS_PAUSE_BEFORE_STOP_PREFIXES` (currently only `KS-AP-`, verified on the R3), `stop()` does the same:
153
+
154
+ 1. It sends PAUSE whatever the cached speed is, because the cached value may be stale or lag a remote start.
155
+ 2. It waits for Treadmill Data received *after* the PAUSE to report 0 km/h.
156
+ 3. Only then does it send STOP.
157
+
158
+ If the link drops, telemetry stops arriving, or the belt is still moving at the timeout, STOP is not sent, `stop()` returns `False`, and the log says which case it was. Other FTMS devices keep the plain STOP behaviour.
159
+
160
+ The R3 also rejects both PAUSE and STOP during the 3-2-1 countdown after a START, and the belt then starts anyway. The firmware can't be halted during the countdown. If STOP is rejected at 0 km/h, `stop()` watches for the belt to start for a few seconds and pauses it as soon as it moves (on the R3 that takes about a second at 1 km/h). It then ends the session as above. If the belt stays at rest, there was no session to end and `stop()` returns `False`.
161
+
162
+ Multi-step commands (`start`, `stop`, `set_target_speed`, …) are serialised within a controller, and so are Control Point acknowledgements. `pause()` only waits for an in-flight Control Point write, so it can still halt the belt while `start()` is waiting for it to move.
163
+
149
164
  ### BLE Connection Drops
150
165
  KingSmith FTMS devices may occasionally drop the connection after a cold start. The library stores the pending target speed and re-applies it after reconnection.
151
166
 
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "walkingpad-controller"
7
- version = "0.5.0"
7
+ version = "0.6.0"
8
8
  description = "Python library for controlling KingSmith WalkingPad treadmills over BLE (FTMS and legacy WiLink protocols)"
9
9
  readme = "README.md"
10
10
  license = "MIT"
@@ -36,7 +36,7 @@ from .models import DeviceCapabilities, SpeedRange, TreadmillStatus
36
36
  from .sperax import SperaxController
37
37
  from .wilink import WiLinkController
38
38
 
39
- __version__ = "0.5.0"
39
+ __version__ = "0.6.0"
40
40
 
41
41
  __all__ = [
42
42
  # Main controller
@@ -263,11 +263,26 @@ class TreadmillDataFlags:
263
263
  # - KS-SMC21C-* : "C" variant of the MC-21 family.
264
264
  # - ZP-ZEALR1-* : Zeal-branded OEM variant of the MC-21 (KS Fit's isMC21
265
265
  # getter matches all three).
266
- FTMS_NAME_PREFIXES = ("KS-HD-", "KS-MC21-", "KS-SMC21C-", "ZP-ZEALR1-")
266
+ # - KS-AP-* : KingSmith R3 (e.g. KS-AP-RQ3, model KS-R3Q). FTMS plus the
267
+ # supplement service; rejects STOP while the belt is moving.
268
+ FTMS_NAME_PREFIXES = ("KS-HD-", "KS-MC21-", "KS-SMC21C-", "ZP-ZEALR1-", "KS-AP-")
269
+
270
+ # FTMS devices whose firmware answers STOP with OPERATION_FAILED while the
271
+ # belt is moving and keeps the belt running. On these, FTMSController.stop()
272
+ # sends PAUSE first and only sends STOP once Treadmill Data received after
273
+ # the PAUSE reports 0 km/h (what KS Fit does). Other FTMS devices keep the
274
+ # plain STOP behaviour.
275
+ #
276
+ # Verified: KS-AP-RQ3 (KingSmith R3, model KS-R3Q, firmware V74.02.23).
277
+ FTMS_PAUSE_BEFORE_STOP_PREFIXES = ("KS-AP-",)
267
278
 
268
279
  # BLE name prefixes for the Sperax / wi-linktech (WLT6200) vendor protocol.
269
- # The P3 Max advertises as "SPERAX_P3MAX".
270
- SPERAX_NAME_PREFIXES = ("SPERAX_",)
280
+ # The P3 Max advertises as "SPERAX_P3MAX". Keep this specific rather than a
281
+ # bare "SPERAX_" prefix: other Sperax-branded pads (e.g. the RM-01, which
282
+ # advertises as "SPERAX_RM-01_...") speak FTMS, not the WLT6200 vendor
283
+ # protocol. A too-broad prefix would misroute them to Sperax and break them;
284
+ # names that don't match here fall through to service-probe detection.
285
+ SPERAX_NAME_PREFIXES = ("SPERAX_P3MAX",)
271
286
 
272
287
  # Default connection parameters.
273
288
  # KingSmith FTMS firmware can be left in a bad state for several seconds
@@ -439,6 +439,9 @@ class WalkingPadController:
439
439
  """Stop the treadmill — full session end. Counters reset.
440
440
 
441
441
  On FTMS this sends `STOP_OR_PAUSE` with the STOP parameter (0x01).
442
+ On devices that reject STOP while the belt moves (KingSmith R3,
443
+ `KS-AP-*`) it pauses first and sends STOP only once fresh telemetry
444
+ confirms 0 km/h.
442
445
  For most user-facing UIs you probably want `pause()` instead — that
443
446
  matches the phone-app and physical-remote behaviour where pressing
444
447
  the stop button leaves the session live and resumable.
@@ -23,6 +23,7 @@ Protocol reference:
23
23
  from __future__ import annotations
24
24
 
25
25
  import asyncio
26
+ import enum
26
27
  import logging
27
28
  import struct
28
29
  import time
@@ -37,6 +38,7 @@ from .const import (
37
38
  FITNESS_MACHINE_STATUS_UUID,
38
39
  FTMS_CONTROL_POINT_UUID,
39
40
  FTMS_FEATURE_UUID,
41
+ FTMS_PAUSE_BEFORE_STOP_PREFIXES,
40
42
  KINGSMITH_VENDOR_PREAMBLE_PAYLOAD,
41
43
  KINGSMITH_VENDOR_PREAMBLE_UUID,
42
44
  SOFTWARE_REVISION_UUID,
@@ -67,6 +69,15 @@ _CP_TO_STATUS_ACK: dict[int, int] = {
67
69
  }
68
70
 
69
71
 
72
+ class _Standstill(enum.Enum):
73
+ """Outcome of waiting for the belt to come to rest."""
74
+
75
+ CONFIRMED = "confirmed"
76
+ STILL_MOVING = "still_moving"
77
+ NO_TELEMETRY = "no_telemetry"
78
+ DISCONNECTED = "disconnected"
79
+
80
+
70
81
  class FTMSController:
71
82
  """Controller for KingSmith FTMS treadmills.
72
83
 
@@ -108,6 +119,33 @@ class FTMSController:
108
119
  # resume" from "session ended, counters reset on next start".
109
120
  self._paused: bool = False
110
121
 
122
+ # Serialises multi-step operations (start / stop / set speed /
123
+ # inclination / reset) so e.g. a SET_TARGET_SPEED can't land between
124
+ # stop()'s PAUSE and STOP. pause() deliberately does not take it: it
125
+ # is the halt path and must never queue behind a multi-step
126
+ # operation that is waiting on the belt.
127
+ self._op_lock = asyncio.Lock()
128
+ # Serialises Control Point write-and-wait, which shares a single
129
+ # response slot (`_cp_response_event` / `_cp_response_data`).
130
+ self._cp_lock = asyncio.Lock()
131
+
132
+ # Treadmill Data bookkeeping for standstill confirmation: a counter
133
+ # bumped on every frame plus an event to wake waiters. Speed in
134
+ # `_status` can be stale (e.g. carried over from before a
135
+ # reconnect); only frames counted after a command prove anything.
136
+ self._treadmill_data_seq = 0
137
+ self._treadmill_data_event = asyncio.Event()
138
+ # Count of FM Status STOPPED_OR_PAUSED + STOP events (session end).
139
+ self._session_end_events = 0
140
+ # How long stop() waits for the belt to come to rest after PAUSE.
141
+ self._standstill_timeout = 15.0
142
+ # How many PAUSE -> standstill -> STOP cycles stop() tries on
143
+ # pause-before-stop devices before giving up.
144
+ self._stop_attempts = 2
145
+ # After STOP is rejected at 0 km/h, how long stop() watches for the
146
+ # belt to start (R3 start countdown is ~4 s; see stop()).
147
+ self._countdown_grace = 6.0
148
+
111
149
  @property
112
150
  def connected(self) -> bool:
113
151
  """Return whether the device is connected."""
@@ -195,6 +233,13 @@ class FTMSController:
195
233
 
196
234
  _LOGGER.info("FTMS: Connected to %s", ble_device.address)
197
235
 
236
+ name = (ble_device.name or "").upper()
237
+ self._capabilities.pause_before_stop = name.startswith(
238
+ FTMS_PAUSE_BEFORE_STOP_PREFIXES
239
+ )
240
+ if self._capabilities.pause_before_stop:
241
+ _LOGGER.info("FTMS: %s needs PAUSE before STOP", ble_device.name)
242
+
198
243
  # Discover services so we can detect supplement / vendor pre-amble
199
244
  # characteristics. Local (BlueZ-cached) — no extra GATT round-trips.
200
245
  await self._discover_services()
@@ -253,6 +298,9 @@ class FTMSController:
253
298
  # Re-arm the first-event skip so the next connection's stale
254
299
  # 2ADA replay is also dropped.
255
300
  self._machine_status_first_event_skipped = False
301
+ # Wake anything waiting on telemetry so it sees the disconnect
302
+ # instead of sitting out its timeout.
303
+ self._treadmill_data_event.set()
256
304
  for cb in self._disconnect_callbacks:
257
305
  try:
258
306
  cb()
@@ -418,6 +466,8 @@ class FTMSController:
418
466
  # Instantaneous Speed - always present (UINT16, 0.01 km/h)
419
467
  speed_raw = struct.unpack_from("<H", data, offset)[0]
420
468
  self._status.speed = speed_raw / 100.0
469
+ self._treadmill_data_seq += 1
470
+ self._treadmill_data_event.set()
421
471
  # Belt state derivation:
422
472
  # speed > 0 -> ACTIVE
423
473
  # speed = 0 + paused -> PAUSED (session alive, awaiting resume)
@@ -594,6 +644,7 @@ class FTMSController:
594
644
  if data[1] == FTMSStopPauseParam.STOP:
595
645
  _LOGGER.info("FTMS: Treadmill stopped by user")
596
646
  self._paused = False
647
+ self._session_end_events += 1
597
648
  # Treadmill Data with speed=0 will follow shortly and
598
649
  # set belt_state = STOPPED via the speed-0 + ~paused
599
650
  # branch; no need to write it here.
@@ -667,8 +718,18 @@ class FTMSController:
667
718
  ) -> bool:
668
719
  """Write a command to the FTMS Control Point and wait for response.
669
720
 
721
+ Writes are serialised: the response slot is shared, so a second
722
+ command must not clear or consume the first one's acknowledgement.
723
+
670
724
  Returns True if the command was acknowledged with success.
671
725
  """
726
+ async with self._cp_lock:
727
+ return await self._write_control_point_locked(opcode, params, timeout)
728
+
729
+ async def _write_control_point_locked(
730
+ self, opcode: FTMSOpcode, params: bytes, timeout: float
731
+ ) -> bool:
732
+ """Body of `_write_control_point`; caller holds `_cp_lock`."""
672
733
  if not self._client or not self._client.is_connected:
673
734
  _LOGGER.warning("FTMS: Not connected, cannot send command")
674
735
  return False
@@ -811,6 +872,10 @@ class FTMSController:
811
872
  Returns:
812
873
  True if the belt is running. False if the connection was lost.
813
874
  """
875
+ async with self._op_lock:
876
+ return await self._start_locked()
877
+
878
+ async def _start_locked(self) -> bool:
814
879
  if not self._has_control:
815
880
  await self._request_control()
816
881
 
@@ -889,16 +954,175 @@ class FTMSController:
889
954
  return False
890
955
 
891
956
  async def stop(self) -> bool:
892
- """Stop the treadmill."""
893
- if not self._has_control:
894
- await self._request_control()
895
- return await self._write_control_point(
957
+ """Stop the treadmill — end the session.
958
+
959
+ On most FTMS devices this sends STOP directly. Devices listed in
960
+ ``FTMS_PAUSE_BEFORE_STOP_PREFIXES`` (the KingSmith R3) answer STOP
961
+ with OPERATION_FAILED while the belt is moving and keep it running.
962
+ For those, mirror KS Fit: send PAUSE, wait for Treadmill Data
963
+ received *after* the PAUSE to report 0 km/h, then send STOP. The
964
+ cached speed is never trusted for this decision; it may be stale or
965
+ lag a physical/remote start.
966
+
967
+ Returns:
968
+ True if the session was ended. False if STOP was rejected or
969
+ not sent because standstill could not be confirmed (in that
970
+ case the belt has been asked to pause, but its state may be
971
+ unknown — see the log).
972
+ """
973
+ async with self._op_lock:
974
+ if not self._has_control:
975
+ await self._request_control()
976
+ if not self._capabilities.pause_before_stop:
977
+ return await self._send_stop()
978
+
979
+ for attempt in range(1, self._stop_attempts + 1):
980
+ if not await self._pause_until_standstill():
981
+ return False
982
+ seq = self._treadmill_data_seq
983
+ if await self._send_stop():
984
+ return True
985
+ if not self.connected:
986
+ _LOGGER.warning("FTMS: connection lost while sending STOP")
987
+ return False
988
+ # The R3 rejects both PAUSE and STOP at 0 km/h in two
989
+ # states: no session at all, and the 3-2-1 countdown after
990
+ # a START (from us, the remote or the app). In the
991
+ # countdown case the belt starts a moment later anyway and
992
+ # cannot be halted before it does, so watch for motion and
993
+ # pause it as soon as it moves.
994
+ if attempt == self._stop_attempts:
995
+ break
996
+ outcome = await self._wait_for_motion(seq, self._countdown_grace)
997
+ if outcome is _Standstill.DISCONNECTED:
998
+ _LOGGER.warning(
999
+ "FTMS: connection lost after STOP was rejected; belt "
1000
+ "state unknown"
1001
+ )
1002
+ return False
1003
+ if outcome is not _Standstill.STILL_MOVING:
1004
+ _LOGGER.warning(
1005
+ "FTMS: STOP rejected and the belt stayed at rest "
1006
+ "(no active session?)"
1007
+ )
1008
+ return False
1009
+ _LOGGER.warning(
1010
+ "FTMS: belt started after STOP was rejected (start "
1011
+ "countdown); pausing it (attempt %d/%d)",
1012
+ attempt + 1,
1013
+ self._stop_attempts,
1014
+ )
1015
+ _LOGGER.warning("FTMS: STOP rejected; session not ended")
1016
+ return False
1017
+
1018
+ async def _send_stop(self) -> bool:
1019
+ """Send STOP; also accept the FM Status session-end event as success.
1020
+
1021
+ The R3 occasionally drops the Control Point indication even though
1022
+ the command took effect, while still emitting FM Status ``02 01``.
1023
+ """
1024
+ ends_before = self._session_end_events
1025
+ if await self._write_control_point(
896
1026
  FTMSOpcode.STOP_OR_PAUSE,
897
1027
  bytes([FTMSStopPauseParam.STOP]),
898
- )
1028
+ ):
1029
+ return True
1030
+ if self._session_end_events != ends_before:
1031
+ _LOGGER.info(
1032
+ "FTMS: STOP not acknowledged on the Control Point, but FM "
1033
+ "Status reported the session ended"
1034
+ )
1035
+ return True
1036
+ return False
1037
+
1038
+ async def _pause_until_standstill(self) -> bool:
1039
+ """Send PAUSE and wait for fresh telemetry to confirm 0 km/h.
1040
+
1041
+ PAUSE is sent regardless of the cached speed. A rejected or
1042
+ unacknowledged PAUSE is not fatal on its own (the belt may already
1043
+ be paused, or the indication was dropped): the decision rests on
1044
+ Treadmill Data received after the PAUSE.
1045
+ """
1046
+ seq = self._treadmill_data_seq
1047
+ if not await self._write_control_point(
1048
+ FTMSOpcode.STOP_OR_PAUSE,
1049
+ bytes([FTMSStopPauseParam.PAUSE]),
1050
+ ):
1051
+ _LOGGER.info(
1052
+ "FTMS: PAUSE not acknowledged; checking telemetry before STOP"
1053
+ )
1054
+ outcome = await self._wait_for_standstill(seq, self._standstill_timeout)
1055
+ if outcome is _Standstill.CONFIRMED:
1056
+ return True
1057
+ if outcome is _Standstill.DISCONNECTED:
1058
+ _LOGGER.warning(
1059
+ "FTMS: connection lost while waiting for the belt to stop "
1060
+ "after PAUSE; belt state unknown, STOP not sent"
1061
+ )
1062
+ elif outcome is _Standstill.NO_TELEMETRY:
1063
+ _LOGGER.warning(
1064
+ "FTMS: no Treadmill Data within %.0fs of PAUSE; belt state "
1065
+ "unknown, STOP not sent",
1066
+ self._standstill_timeout,
1067
+ )
1068
+ else:
1069
+ _LOGGER.warning(
1070
+ "FTMS: belt still reports %.1f km/h %.0fs after PAUSE; STOP "
1071
+ "not sent",
1072
+ self._status.speed,
1073
+ self._standstill_timeout,
1074
+ )
1075
+ return False
1076
+
1077
+ async def _wait_for_motion(self, after_seq: int, timeout: float) -> _Standstill:
1078
+ """Wait for a Treadmill Data frame newer than ``after_seq`` with speed > 0.
1079
+
1080
+ Returns STILL_MOVING if the belt moved, CONFIRMED if it stayed at
1081
+ rest until the timeout, or DISCONNECTED.
1082
+ """
1083
+ loop = asyncio.get_running_loop()
1084
+ deadline = loop.time() + timeout
1085
+ while True:
1086
+ if not self.connected:
1087
+ return _Standstill.DISCONNECTED
1088
+ if self._treadmill_data_seq > after_seq and self._status.speed > 0:
1089
+ return _Standstill.STILL_MOVING
1090
+ remaining = deadline - loop.time()
1091
+ if remaining <= 0:
1092
+ return _Standstill.CONFIRMED
1093
+ self._treadmill_data_event.clear()
1094
+ try:
1095
+ await asyncio.wait_for(self._treadmill_data_event.wait(), remaining)
1096
+ except asyncio.TimeoutError:
1097
+ pass
1098
+
1099
+ async def _wait_for_standstill(self, after_seq: int, timeout: float) -> _Standstill:
1100
+ """Wait for a Treadmill Data frame newer than ``after_seq`` with speed 0."""
1101
+ loop = asyncio.get_running_loop()
1102
+ deadline = loop.time() + timeout
1103
+ while True:
1104
+ if not self.connected:
1105
+ return _Standstill.DISCONNECTED
1106
+ if self._treadmill_data_seq > after_seq and self._status.speed == 0:
1107
+ return _Standstill.CONFIRMED
1108
+ remaining = deadline - loop.time()
1109
+ if remaining <= 0:
1110
+ if self._treadmill_data_seq == after_seq:
1111
+ return _Standstill.NO_TELEMETRY
1112
+ return _Standstill.STILL_MOVING
1113
+ self._treadmill_data_event.clear()
1114
+ try:
1115
+ await asyncio.wait_for(self._treadmill_data_event.wait(), remaining)
1116
+ except asyncio.TimeoutError:
1117
+ pass
899
1118
 
900
1119
  async def pause(self) -> bool:
901
- """Pause the treadmill."""
1120
+ """Pause the treadmill.
1121
+
1122
+ Not serialised behind other operations (only behind other Control
1123
+ Point writes), so it can halt the belt while e.g. start() is still
1124
+ waiting for the belt to move.
1125
+ """
902
1126
  if not self._has_control:
903
1127
  await self._request_control()
904
1128
  return await self._write_control_point(
@@ -908,9 +1132,10 @@ class FTMSController:
908
1132
 
909
1133
  async def reset(self) -> bool:
910
1134
  """Reset the fitness machine."""
911
- if not self._has_control:
912
- await self._request_control()
913
- return await self._write_control_point(FTMSOpcode.RESET)
1135
+ async with self._op_lock:
1136
+ if not self._has_control:
1137
+ await self._request_control()
1138
+ return await self._write_control_point(FTMSOpcode.RESET)
914
1139
 
915
1140
  async def set_target_speed(self, speed_kmh: float) -> bool:
916
1141
  """Set the target speed in km/h.
@@ -938,13 +1163,16 @@ class FTMSController:
938
1163
  speed_raw = int(round(speed_kmh * 100))
939
1164
  params = struct.pack("<H", speed_raw)
940
1165
 
941
- if not self._has_control:
942
- await self._request_control()
1166
+ async with self._op_lock:
1167
+ if not self._has_control:
1168
+ await self._request_control()
943
1169
 
944
- _LOGGER.debug(
945
- "FTMS: Setting target speed to %.2f km/h (raw: %d)", speed_kmh, speed_raw
946
- )
947
- return await self._write_control_point(FTMSOpcode.SET_TARGET_SPEED, params)
1170
+ _LOGGER.debug(
1171
+ "FTMS: Setting target speed to %.2f km/h (raw: %d)",
1172
+ speed_kmh,
1173
+ speed_raw,
1174
+ )
1175
+ return await self._write_control_point(FTMSOpcode.SET_TARGET_SPEED, params)
948
1176
 
949
1177
  async def set_target_inclination(self, inclination_pct: float) -> bool:
950
1178
  """Set the target inclination in percent.
@@ -958,9 +1186,10 @@ class FTMSController:
958
1186
  inclination_raw = int(round(inclination_pct * 10))
959
1187
  params = struct.pack("<h", inclination_raw)
960
1188
 
961
- if not self._has_control:
962
- await self._request_control()
1189
+ async with self._op_lock:
1190
+ if not self._has_control:
1191
+ await self._request_control()
963
1192
 
964
- return await self._write_control_point(
965
- FTMSOpcode.SET_TARGET_INCLINATION, params
966
- )
1193
+ return await self._write_control_point(
1194
+ FTMSOpcode.SET_TARGET_INCLINATION, params
1195
+ )
@@ -100,3 +100,10 @@ class DeviceCapabilities:
100
100
 
101
101
  firmware_version: str = ""
102
102
  """Firmware version reported by the Software Revision String (0x2A28)."""
103
+
104
+ pause_before_stop: bool = False
105
+ """Whether STOP must be preceded by PAUSE and a confirmed standstill.
106
+
107
+ Set from the BLE name (``FTMS_PAUSE_BEFORE_STOP_PREFIXES``) for firmware
108
+ that rejects STOP while the belt is moving.
109
+ """
@@ -0,0 +1,310 @@
1
+ """FTMSController.stop() on pause-before-stop devices (KingSmith R3).
2
+
3
+ R3 firmware (KS-AP-RQ3) answers STOP with OPERATION_FAILED while the belt is
4
+ moving and keeps running. KS Fit pauses, waits for 0 km/h, then stops. These
5
+ tests drive the controller with asynchronously delivered Treadmill Data and
6
+ check that STOP is never sent before telemetry received *after* the PAUSE
7
+ confirms standstill.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import asyncio
13
+ import logging
14
+ import struct
15
+ from types import SimpleNamespace
16
+
17
+ import pytest
18
+
19
+ from walkingpad_controller import FTMSController
20
+ from walkingpad_controller.const import FTMSOpcode, FTMSStopPauseParam
21
+
22
+ PAUSE = (FTMSOpcode.STOP_OR_PAUSE, bytes([FTMSStopPauseParam.PAUSE]))
23
+ STOP = (FTMSOpcode.STOP_OR_PAUSE, bytes([FTMSStopPauseParam.STOP]))
24
+ FRAME_GAP = 0.02 # seconds between simulated Treadmill Data frames
25
+
26
+
27
+ def treadmill_frame(kmh: float) -> bytearray:
28
+ """Minimal Treadmill Data frame: flags 0 (speed only)."""
29
+ return bytearray(struct.pack("<HH", 0, round(kmh * 100)))
30
+
31
+
32
+ class Pad:
33
+ """FTMSController wired to a fake link.
34
+
35
+ ``on_pause`` is a list of speeds the belt reports, one frame every
36
+ FRAME_GAP, after each PAUSE is written (``pause_frames``, if set, gives
37
+ one such list per PAUSE). ``stop_frames`` likewise gives the frames
38
+ played after each STOP. ``results`` maps a command to the
39
+ acknowledgement result (a list is consumed one entry per write).
40
+ """
41
+
42
+ def __init__(self, *, pause_before_stop: bool, speed: float = 3.0) -> None:
43
+ self.c = FTMSController()
44
+ self.c._has_control = True
45
+ self.c._connected = True
46
+ self.c._client = SimpleNamespace(is_connected=True) # type: ignore[assignment]
47
+ self.c._capabilities.pause_before_stop = pause_before_stop
48
+ self.c._status.speed = speed
49
+ self.c._standstill_timeout = 0.3
50
+ self.c._countdown_grace = 0.3
51
+ self.sent: list[tuple[int, bytes]] = []
52
+ # speed in _status at the moment each command was written, and how
53
+ # many frames had been delivered since the last PAUSE
54
+ self.speed_at_send: list[float] = []
55
+ self.frames_since_pause_at_send: list[int] = []
56
+ self.on_pause: list[float] = [2.0, 1.0, 0.0]
57
+ self.pause_frames: list[list[float]] = []
58
+ self.stop_frames: list[list[float]] = []
59
+ self.results: dict[tuple[int, bytes], list[bool]] = {}
60
+ self.session_end_on_stop = False
61
+ self._frames_since_pause = 0
62
+ self._tasks: list[asyncio.Task] = []
63
+ self.c._write_control_point = self._write # type: ignore[method-assign]
64
+
65
+ async def _write(self, opcode, params=b"", *args, **kwargs) -> bool:
66
+ cmd = (opcode, bytes(params))
67
+ self.sent.append(cmd)
68
+ self.speed_at_send.append(self.c._status.speed)
69
+ self.frames_since_pause_at_send.append(self._frames_since_pause)
70
+ if cmd == PAUSE:
71
+ self._frames_since_pause = 0
72
+ frames = self.pause_frames.pop(0) if self.pause_frames else list(self.on_pause)
73
+ self._tasks.append(asyncio.create_task(self._play(frames)))
74
+ if cmd == STOP:
75
+ if self.session_end_on_stop:
76
+ self.c._on_machine_status(0, bytearray([0x02, 0x01]))
77
+ if self.stop_frames:
78
+ self._tasks.append(asyncio.create_task(self._play(self.stop_frames.pop(0))))
79
+ await asyncio.sleep(0)
80
+ queue = self.results.get(cmd)
81
+ return queue.pop(0) if queue else True
82
+
83
+ async def _play(self, speeds: list[float]) -> None:
84
+ for kmh in speeds:
85
+ await asyncio.sleep(FRAME_GAP)
86
+ if not self.c.connected:
87
+ return
88
+ self._frames_since_pause += 1
89
+ self.c._on_treadmill_data(0, treadmill_frame(kmh))
90
+
91
+ def drop_link(self) -> None:
92
+ self.c._client.is_connected = False # type: ignore[union-attr]
93
+ self.c._on_disconnect(None) # type: ignore[arg-type]
94
+
95
+ def stop(self) -> bool:
96
+ async def run() -> bool:
97
+ # mark the first FM Status event as already seen so the
98
+ # simulated session-end event isn't dropped as a stale replay
99
+ self.c._machine_status_first_event_skipped = True
100
+ try:
101
+ return await self.c.stop()
102
+ finally:
103
+ for t in self._tasks:
104
+ t.cancel()
105
+
106
+ return asyncio.run(run())
107
+
108
+
109
+ # --- devices without the quirk keep the plain STOP ------------------------
110
+
111
+
112
+ def test_regular_ftms_device_sends_stop_directly_even_while_moving() -> None:
113
+ pad = Pad(pause_before_stop=False, speed=3.0)
114
+ assert pad.stop() is True
115
+ assert pad.sent == [STOP]
116
+
117
+
118
+ def test_regular_ftms_device_reports_rejected_stop() -> None:
119
+ pad = Pad(pause_before_stop=False)
120
+ pad.results[STOP] = [False]
121
+ assert pad.stop() is False
122
+ assert pad.sent == [STOP]
123
+
124
+
125
+ # --- pause-before-stop devices -------------------------------------------
126
+
127
+
128
+ def test_pauses_then_stops_only_after_fresh_zero_speed() -> None:
129
+ pad = Pad(pause_before_stop=True, speed=3.0)
130
+ assert pad.stop() is True
131
+ assert pad.sent == [PAUSE, STOP]
132
+ # STOP went out only after all three deceleration frames, the last at 0
133
+ assert pad.frames_since_pause_at_send[1] == 3
134
+ assert pad.speed_at_send[1] == 0.0
135
+
136
+
137
+ @pytest.mark.parametrize("cached", [0.0, 3.0])
138
+ def test_cached_speed_is_not_trusted(cached: float) -> None:
139
+ # A cached 0 may be stale (e.g. from before a reconnect) or lag a
140
+ # remote start; PAUSE is sent and fresh telemetry is awaited either way.
141
+ pad = Pad(pause_before_stop=True, speed=cached)
142
+ pad.on_pause = [1.0, 0.0]
143
+ assert pad.stop() is True
144
+ assert pad.sent == [PAUSE, STOP]
145
+ assert pad.frames_since_pause_at_send[1] == 2
146
+
147
+
148
+ def test_cached_zero_without_any_new_frame_does_not_send_stop(caplog) -> None:
149
+ pad = Pad(pause_before_stop=True, speed=0.0)
150
+ pad.on_pause = []
151
+ with caplog.at_level(logging.WARNING):
152
+ assert pad.stop() is False
153
+ assert pad.sent == [PAUSE]
154
+ assert "no Treadmill Data" in caplog.text
155
+
156
+
157
+ def test_belt_still_moving_at_timeout_does_not_send_stop(caplog) -> None:
158
+ pad = Pad(pause_before_stop=True)
159
+ pad.on_pause = [3.0] * 30 # keeps reporting motion past the timeout
160
+ with caplog.at_level(logging.WARNING):
161
+ assert pad.stop() is False
162
+ assert STOP not in pad.sent
163
+ assert "still reports 3.0 km/h" in caplog.text
164
+
165
+
166
+ def test_rejected_pause_with_belt_still_moving_does_not_send_stop() -> None:
167
+ pad = Pad(pause_before_stop=True)
168
+ pad.results[PAUSE] = [False]
169
+ pad.on_pause = [3.0] * 30
170
+ assert pad.stop() is False
171
+ assert pad.sent == [PAUSE]
172
+
173
+
174
+ def test_unacknowledged_pause_but_belt_stops_still_ends_session() -> None:
175
+ # e.g. the PAUSE indication was dropped, or the remote paused already
176
+ pad = Pad(pause_before_stop=True)
177
+ pad.results[PAUSE] = [False]
178
+ assert pad.stop() is True
179
+ assert pad.sent == [PAUSE, STOP]
180
+ assert pad.speed_at_send[1] == 0.0
181
+
182
+
183
+ def test_disconnect_during_deceleration(caplog) -> None:
184
+ pad = Pad(pause_before_stop=True)
185
+ pad.on_pause = [2.5, 2.0, 1.5, 1.0, 0.5, 0.0]
186
+
187
+ async def run() -> bool:
188
+ task = asyncio.create_task(pad.c.stop())
189
+ await asyncio.sleep(FRAME_GAP * 2.5)
190
+ pad.drop_link()
191
+ return await task
192
+
193
+ with caplog.at_level(logging.WARNING):
194
+ assert asyncio.run(run()) is False
195
+ assert STOP not in pad.sent
196
+ assert "connection lost" in caplog.text
197
+ assert "belt state unknown" in caplog.text
198
+
199
+
200
+ def test_no_session_pause_and_stop_rejected_returns_false(caplog) -> None:
201
+ # Verified on the R3: with no session, PAUSE -> 80 08 04 02 and
202
+ # STOP -> 80 08 04 01, and the belt stays at rest.
203
+ pad = Pad(pause_before_stop=True, speed=0.0)
204
+ pad.on_pause = [0.0, 0.0]
205
+ pad.results[PAUSE] = [False]
206
+ pad.results[STOP] = [False]
207
+ with caplog.at_level(logging.WARNING):
208
+ assert pad.stop() is False
209
+ assert pad.sent == [PAUSE, STOP]
210
+ assert "stayed at rest" in caplog.text
211
+
212
+
213
+ def test_stop_during_start_countdown_pauses_once_belt_moves() -> None:
214
+ # Verified on the R3: during the 3-2-1 countdown both PAUSE and STOP are
215
+ # rejected at 0 km/h and the belt then starts at 1.0 km/h regardless.
216
+ pad = Pad(pause_before_stop=True, speed=0.0)
217
+ pad.results[PAUSE] = [False, True]
218
+ pad.results[STOP] = [False, True]
219
+ pad.pause_frames = [[0.0], [0.5, 0.0]] # countdown frame; then ramp-down
220
+ pad.stop_frames = [[0.0, 1.0, 1.0]] # countdown ends, belt starts
221
+ assert pad.stop() is True
222
+ assert pad.sent == [PAUSE, STOP, PAUSE, STOP]
223
+ assert pad.speed_at_send[2] == 1.0 # second PAUSE once the belt moved
224
+ assert pad.speed_at_send[3] == 0.0 # final STOP only at fresh standstill
225
+
226
+
227
+ def test_stop_rejected_again_after_second_pause_gives_up(caplog) -> None:
228
+ pad = Pad(pause_before_stop=True, speed=0.0)
229
+ pad.results[PAUSE] = [False, True]
230
+ pad.results[STOP] = [False, False]
231
+ pad.pause_frames = [[0.0], [0.5, 0.0]]
232
+ pad.stop_frames = [[1.0]]
233
+ with caplog.at_level(logging.WARNING):
234
+ assert pad.stop() is False
235
+ assert pad.sent == [PAUSE, STOP, PAUSE, STOP]
236
+ assert "session not ended" in caplog.text
237
+
238
+
239
+ def test_disconnect_while_watching_for_countdown_start(caplog) -> None:
240
+ pad = Pad(pause_before_stop=True, speed=0.0)
241
+ pad.on_pause = [0.0]
242
+ pad.results[STOP] = [False]
243
+
244
+ async def run() -> bool:
245
+ task = asyncio.create_task(pad.c.stop())
246
+ await asyncio.sleep(FRAME_GAP * 3)
247
+ pad.drop_link()
248
+ return await task
249
+
250
+ with caplog.at_level(logging.WARNING):
251
+ assert asyncio.run(run()) is False
252
+ assert pad.sent == [PAUSE, STOP]
253
+ assert "connection lost" in caplog.text
254
+
255
+
256
+ def test_dropped_stop_indication_but_session_end_event_counts() -> None:
257
+ pad = Pad(pause_before_stop=True)
258
+ pad.results[STOP] = [False]
259
+ pad.session_end_on_stop = True
260
+ assert pad.stop() is True
261
+ assert pad.sent == [PAUSE, STOP]
262
+
263
+
264
+ # --- serialisation ---------------------------------------------------------
265
+
266
+
267
+ def test_set_speed_waits_for_the_whole_stop_sequence() -> None:
268
+ pad = Pad(pause_before_stop=True)
269
+
270
+ async def run() -> None:
271
+ stop = asyncio.create_task(pad.c.stop())
272
+ await asyncio.sleep(FRAME_GAP / 2) # stop() has sent PAUSE, is waiting
273
+ speed = asyncio.create_task(pad.c.set_target_speed(2.0))
274
+ assert await stop is True
275
+ assert await speed is True
276
+
277
+ asyncio.run(run())
278
+ assert [op for op, _ in pad.sent] == [
279
+ FTMSOpcode.STOP_OR_PAUSE,
280
+ FTMSOpcode.STOP_OR_PAUSE,
281
+ FTMSOpcode.SET_TARGET_SPEED,
282
+ ]
283
+ assert pad.sent[:2] == [PAUSE, STOP]
284
+
285
+
286
+ def test_control_point_acks_are_not_shared_between_concurrent_writes() -> None:
287
+ """Two commands in flight must each get their own indication."""
288
+ c = FTMSController()
289
+ c._connected = True
290
+ c._has_control = True
291
+ writes: list[bytes] = []
292
+
293
+ async def write_gatt_char(uuid, data, response=True):
294
+ writes.append(bytes(data))
295
+ # indication arrives a little later; PAUSE is rejected, speed accepted
296
+ result = 0x04 if bytes(data) == bytes([0x08, 0x02]) else 0x01
297
+ asyncio.get_running_loop().call_later(
298
+ 0.02, c._on_control_point_response, 0, bytearray([0x80, data[0], result])
299
+ )
300
+
301
+ c._client = SimpleNamespace( # type: ignore[assignment]
302
+ is_connected=True, write_gatt_char=write_gatt_char
303
+ )
304
+
305
+ async def run():
306
+ return await asyncio.gather(c.pause(), c.set_target_speed(2.0))
307
+
308
+ paused, speed = asyncio.run(run())
309
+ assert paused is False and speed is True
310
+ assert [w[0] for w in writes] == [0x08, 0x02]
@@ -0,0 +1,41 @@
1
+ """Protocol detection from the BLE name.
2
+
3
+ Guards the name-prefix routing in particular: Sperax-branded pads that
4
+ actually speak FTMS (e.g. the RM-01) must NOT be routed to the Sperax
5
+ vendor protocol just because their name starts with "SPERAX_". Only the
6
+ P3 Max (SPERAX_P3MAX) uses the WLT6200 vendor protocol.
7
+ """
8
+
9
+ from types import SimpleNamespace
10
+
11
+ import pytest
12
+
13
+ from walkingpad_controller import ProtocolType, WalkingPadController
14
+
15
+
16
+ def _controller(name: str) -> WalkingPadController:
17
+ """Build a controller with a stub BLE device carrying the given name."""
18
+ ble_device = SimpleNamespace(name=name, address="AA:BB:CC:DD:EE:FF")
19
+ return WalkingPadController(ble_device=ble_device)
20
+
21
+
22
+ @pytest.mark.parametrize(
23
+ "ble_name, expected",
24
+ [
25
+ # FTMS families, matched by name prefix.
26
+ ("KS-HD-Z1D", ProtocolType.FTMS),
27
+ ("KS-MC21-D06BFD", ProtocolType.FTMS),
28
+ ("KS-SMC21C-XXXX", ProtocolType.FTMS),
29
+ ("ZP-ZEALR1-XXXX", ProtocolType.FTMS),
30
+ ("KS-AP-RQ3", ProtocolType.FTMS),
31
+ # The P3 Max is the only Sperax vendor-protocol device.
32
+ ("SPERAX_P3MAX", ProtocolType.SPERAX),
33
+ # Sperax-branded but FTMS: must fall through to service probing,
34
+ # so the name alone leaves the protocol UNKNOWN (resolved on connect).
35
+ ("SPERAX_RM-01_AB12CD", ProtocolType.UNKNOWN),
36
+ # WiLink / other names give no definitive answer from the name.
37
+ ("KS-ST-A1P", ProtocolType.UNKNOWN),
38
+ ],
39
+ )
40
+ def test_protocol_detected_from_name(ble_name: str, expected: ProtocolType) -> None:
41
+ assert _controller(ble_name).protocol == expected