feetech-cli 0.1.4__tar.gz → 0.1.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 (26) hide show
  1. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/PKG-INFO +10 -1
  2. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/README.md +4 -0
  3. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/feetech_cli/__init__.py +1 -1
  4. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/feetech_cli/cli.py +22 -7
  5. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/feetech_cli/controller.py +55 -0
  6. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/feetech_cli/protocol.py +86 -6
  7. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/feetech_cli/tui.py +195 -7
  8. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/feetech_cli.egg-info/PKG-INFO +10 -1
  9. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/pyproject.toml +6 -1
  10. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/tests/test_cli.py +10 -0
  11. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/tests/test_controller.py +7 -0
  12. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/tests/test_protocol.py +31 -0
  13. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/tests/test_terminal.py +79 -4
  14. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/tests/test_tui.py +32 -0
  15. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/LICENSE +0 -0
  16. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/feetech_cli/devices.py +0 -0
  17. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/feetech_cli/registers.py +0 -0
  18. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/feetech_cli/simulator.py +0 -0
  19. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/feetech_cli.egg-info/SOURCES.txt +0 -0
  20. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/feetech_cli.egg-info/dependency_links.txt +0 -0
  21. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/feetech_cli.egg-info/entry_points.txt +0 -0
  22. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/feetech_cli.egg-info/requires.txt +0 -0
  23. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/feetech_cli.egg-info/top_level.txt +0 -0
  24. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/setup.cfg +0 -0
  25. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/tests/test_devices.py +0 -0
  26. {feetech_cli-0.1.4 → feetech_cli-0.1.6}/tests/test_registers.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: feetech-cli
3
- Version: 0.1.4
3
+ Version: 0.1.6
4
4
  Summary: Command line tool to inspect and configure FEETECH STS/SMS/SCS serial bus servos
5
5
  Author-email: Iori Yanokura <ab.ioryz@gmail.com>
6
6
  License-Expression: MIT
@@ -13,6 +13,11 @@ Classifier: Intended Audience :: Developers
13
13
  Classifier: Intended Audience :: Science/Research
14
14
  Classifier: Operating System :: OS Independent
15
15
  Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
16
21
  Classifier: Topic :: Scientific/Engineering
17
22
  Classifier: Topic :: System :: Hardware
18
23
  Requires-Python: >=3.9
@@ -25,6 +30,10 @@ Dynamic: license-file
25
30
 
26
31
  # feetech-cli
27
32
 
33
+ ![PyPI](https://img.shields.io/pypi/v/feetech-cli.svg)
34
+ ![Python Versions](https://img.shields.io/pypi/pyversions/feetech-cli.svg)
35
+ [![Build Status](https://github.com/iory/feetech-cli/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/iory/feetech-cli/actions)
36
+
28
37
  Command line tool to inspect and configure FEETECH STS/SMS/SCS serial bus
29
38
  servos (STS3215 and friends) — change servo ids, bus speeds, modes and limits,
30
39
  or watch a live status screen.
@@ -1,5 +1,9 @@
1
1
  # feetech-cli
2
2
 
3
+ ![PyPI](https://img.shields.io/pypi/v/feetech-cli.svg)
4
+ ![Python Versions](https://img.shields.io/pypi/pyversions/feetech-cli.svg)
5
+ [![Build Status](https://github.com/iory/feetech-cli/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/iory/feetech-cli/actions)
6
+
3
7
  Command line tool to inspect and configure FEETECH STS/SMS/SCS serial bus
4
8
  servos (STS3215 and friends) — change servo ids, bus speeds, modes and limits,
5
9
  or watch a live status screen.
@@ -7,7 +7,7 @@ from feetech_cli.protocol import FeetechStatusError
7
7
  from feetech_cli.protocol import FeetechTimeoutError
8
8
  from feetech_cli.protocol import PacketHandler
9
9
 
10
- __version__ = "0.1.4"
10
+ __version__ = "0.1.6"
11
11
 
12
12
  __all__ = [
13
13
  "FeetechServoController",
@@ -16,6 +16,7 @@ from feetech_cli.devices import default_device_dir
16
16
  from feetech_cli.devices import format_value
17
17
  from feetech_cli.devices import load_profiles
18
18
  from feetech_cli.protocol import FeetechError
19
+ from feetech_cli.protocol import describe_error
19
20
  from feetech_cli.registers import BAUDRATE_INDEX
20
21
  from feetech_cli.registers import BAUDRATE_TABLE
21
22
  from feetech_cli.registers import CENTER_POSITION
@@ -389,16 +390,30 @@ def command_scan(args, controller):
389
390
  if not profiles[servo_id].is_servo:
390
391
  print(_device_summary(controller, servo_id, profiles[servo_id]))
391
392
  continue
392
- model = controller.read_register(servo_id, "model_number")
393
- position = controller.read_register(servo_id, "present_position")
394
- voltage = controller.read_register(servo_id, "present_voltage")
395
- temperature = controller.read_register(servo_id, "present_temperature")
393
+ values = {}
394
+ error = 0
395
+ for name in (
396
+ "model_number",
397
+ "present_position",
398
+ "present_voltage",
399
+ "present_temperature",
400
+ ):
401
+ values[name], flags = controller.read_register_with_error(servo_id, name)
402
+ error |= flags
403
+ position = values["present_position"]
396
404
  degree = position_to_degree(position)
397
- print(
398
- f" id {servo_id:>3} model {model:>5} "
405
+ line = (
406
+ f" id {servo_id:>3} model {values['model_number']:>5} "
399
407
  f"position {position:>5} ({degree:+.1f} deg) "
400
- f"{voltage / 10.0:.1f}V {temperature}C"
408
+ f"{values['present_voltage'] / 10.0:.1f}V "
409
+ f"{values['present_temperature']}C"
401
410
  )
411
+ if error:
412
+ line += (
413
+ f" {Fore.RED}ALARM: {', '.join(describe_error(error))}"
414
+ f"{Style.RESET_ALL}"
415
+ )
416
+ print(line)
402
417
  return 0
403
418
 
404
419
 
@@ -461,6 +461,30 @@ class FeetechServoController:
461
461
  data = self.packet_handler.read(servo_id, register.address, register.size)
462
462
  return self._decode_register(register, data)
463
463
 
464
+ def read_register_with_error(self, servo_id, name):
465
+ """Read a named register even while the servo reports an alarm.
466
+
467
+ Parameters
468
+ ----------
469
+ servo_id : int
470
+ Servo id.
471
+ name : str
472
+ Register name, a key of
473
+ :data:`~feetech_cli.registers.CONTROL_TABLE`.
474
+
475
+ Returns
476
+ -------
477
+ tuple of (int, int)
478
+ The register value, sign decoded where applicable, and the error
479
+ byte of the status packet that carried it.
480
+ """
481
+ self._require_open()
482
+ register = _lookup(name, self.device_profile(servo_id))
483
+ error, data = self.packet_handler.read_with_error(
484
+ servo_id, register.address, register.size
485
+ )
486
+ return self._decode_register(register, data), error
487
+
464
488
  def _decode_register(self, register, data):
465
489
  """Turn the bytes of one register into its value, sign decoded."""
466
490
  value = self.packet_handler.decode(register.size, data)
@@ -678,6 +702,37 @@ class FeetechServoController:
678
702
  result[name] = None
679
703
  return result
680
704
 
705
+ def dump_with_error(self, servo_id, names):
706
+ """Read several registers, keeping their values while in alarm.
707
+
708
+ :meth:`dump` maps a register whose status packet carries an error
709
+ byte to ``None``, so a servo in alarm reads as if it were absent.
710
+ This keeps the values and reports the error bits next to them.
711
+
712
+ Parameters
713
+ ----------
714
+ servo_id : int
715
+ Servo id.
716
+ names : sequence of str
717
+ Register names to read.
718
+
719
+ Returns
720
+ -------
721
+ tuple of (dict, int)
722
+ Register name to value, ``None`` for a register that could not be
723
+ read, and the error bits of every answer OR-ed together.
724
+ """
725
+ result = {}
726
+ error = 0
727
+ for name in names:
728
+ try:
729
+ result[name], flags = self.read_register_with_error(servo_id, name)
730
+ except FeetechError:
731
+ result[name] = None
732
+ continue
733
+ error |= flags
734
+ return result, error
735
+
681
736
  # -- configuration -----------------------------------------------------
682
737
 
683
738
  def set_id(self, servo_id, new_id):
@@ -33,6 +33,10 @@ INST_SYNC_WRITE = 0x83
33
33
  #: Bytes read per call while draining stale replies off the bus.
34
34
  DRAIN_CHUNK = 256
35
35
 
36
+ #: Address of the ``id`` register, the same on every FEETECH series. Reading
37
+ #: it is how :class:`PacketHandler` finds out whether the adapter echoes.
38
+ ID_ADDRESS = 5
39
+
36
40
  #: Hardware error bits reported in the ``ERROR`` byte of a status packet.
37
41
  ERROR_BITS = (
38
42
  (0x01, "voltage"),
@@ -185,6 +189,9 @@ class PacketHandler:
185
189
  def __init__(self, port, little_endian=True):
186
190
  self.port = port
187
191
  self.little_endian = little_endian
192
+ #: Whether the adapter echoes transmissions back, ``None`` until an
193
+ #: exchange has shown it one way or the other.
194
+ self.echoes = None
188
195
 
189
196
  def encode_word(self, value):
190
197
  """Split a 16 bit value into two bytes using the bus byte order.
@@ -369,6 +376,11 @@ class PacketHandler:
369
376
  first packet read is byte for byte identical to ``sent`` it is
370
377
  discarded and the next one is read instead.
371
378
 
379
+ A genuine answer can be identical too: a PING (instruction 0x01)
380
+ answered with the voltage error flag (0x01) and no parameters
381
+ reproduces the request exactly. When no second packet follows,
382
+ :meth:`_adapter_echoes` settles which of the two it was.
383
+
372
384
  Returns
373
385
  -------
374
386
  tuple of (int, int, bytes)
@@ -381,13 +393,52 @@ class PacketHandler:
381
393
  FeetechChecksumError
382
394
  If the packet checksum did not match.
383
395
  """
384
- for _ in range(2):
385
- servo_id, error, params, raw = self._read_one_packet()
386
- if sent is not None and raw == sent:
387
- # Adapter echoed our own transmission, read the real answer.
388
- continue
396
+ servo_id, error, params, raw = self._read_one_packet()
397
+ if sent is None or raw != sent:
398
+ if sent is not None:
399
+ self.echoes = False
389
400
  return servo_id, error, params
390
- raise FeetechTimeoutError("only the transmit echo was received")
401
+ if self.echoes is not False:
402
+ try:
403
+ servo_id, error, params, _ = self._read_one_packet()
404
+ except FeetechTimeoutError:
405
+ pass
406
+ else:
407
+ self.echoes = True
408
+ return servo_id, error, params
409
+ if self._adapter_echoes(servo_id):
410
+ raise FeetechTimeoutError("only the transmit echo was received")
411
+ return servo_id, error, params
412
+
413
+ def _adapter_echoes(self, servo_id):
414
+ """Find out whether the adapter echoes transmissions.
415
+
416
+ Reads the ``id`` register of ``servo_id``. That request is a
417
+ different size from its answer, so the two can never be mistaken for
418
+ each other: if the first packet back is the request itself, the
419
+ adapter echoes.
420
+
421
+ Parameters
422
+ ----------
423
+ servo_id : int
424
+ Servo to address with the probe.
425
+
426
+ Returns
427
+ -------
428
+ bool
429
+ The cached or freshly measured :attr:`echoes`.
430
+ """
431
+ if self.echoes is None:
432
+ probe = self.build_packet(servo_id, INST_READ, [ID_ADDRESS, 1])
433
+ self._send(probe)
434
+ try:
435
+ _, _, _, raw = self._read_one_packet()
436
+ except FeetechTimeoutError:
437
+ # An echoing adapter always sends something back.
438
+ raw = None
439
+ self.echoes = raw == probe
440
+ self.port.reset_input_buffer()
441
+ return self.echoes
391
442
 
392
443
  def _read_one_packet(self):
393
444
  """Scan for a header and read a single packet off the wire.
@@ -515,6 +566,35 @@ class PacketHandler:
515
566
  )
516
567
  return answer
517
568
 
569
+ def read_with_error(self, servo_id, address, size):
570
+ """Read a register and hand back the error byte instead of raising.
571
+
572
+ A servo in alarm (over voltage, overheat, ...) still returns valid
573
+ register contents; this lets the caller show them next to the alarm.
574
+
575
+ Parameters
576
+ ----------
577
+ servo_id : int
578
+ Servo id.
579
+ address : int
580
+ Register address.
581
+ size : int
582
+ Number of bytes to read.
583
+
584
+ Returns
585
+ -------
586
+ tuple of (int, bytes)
587
+ The error byte and the register contents.
588
+ """
589
+ error, answer = self.txrx(
590
+ servo_id, INST_READ, [address & 0xFF, size & 0xFF], raise_on_error=False
591
+ )
592
+ if len(answer) != size:
593
+ raise FeetechChecksumError(
594
+ f"expected {size} bytes from address {address}, received {len(answer)}"
595
+ )
596
+ return error, answer
597
+
518
598
  def sync_read(self, servo_ids, address, size):
519
599
  """Read the same registers of several devices in one SYNC_READ.
520
600
 
@@ -1,16 +1,22 @@
1
1
  """Interactive terminal UI for inspecting and reconfiguring servos."""
2
2
 
3
+ import contextlib
3
4
  import queue
5
+ import shutil
4
6
  import sys
5
7
  import threading
6
8
  import time
7
9
 
8
10
  import readchar
11
+ from colorama import Back
9
12
  from colorama import Fore
10
13
  from colorama import Style
14
+ from readchar import config as readchar_config
11
15
 
12
16
  from feetech_cli.protocol import FeetechError
17
+ from feetech_cli.protocol import FeetechStatusError
13
18
  from feetech_cli.protocol import FeetechTimeoutError
19
+ from feetech_cli.protocol import describe_error
14
20
  from feetech_cli.registers import BAUDRATE_TABLE
15
21
  from feetech_cli.registers import CENTER_POSITION
16
22
  from feetech_cli.registers import OPERATING_MODES
@@ -19,6 +25,29 @@ from feetech_cli.registers import format_baud
19
25
  from feetech_cli.registers import format_current
20
26
  from feetech_cli.registers import position_to_degree
21
27
 
28
+ try:
29
+ import termios
30
+ except ImportError: # Windows, where readchar reads through msvcrt instead.
31
+ termios = None
32
+
33
+ #: Registers read only while the servo is in alarm, to say which limit it hit.
34
+ ALARM_LIMIT_REGISTERS = [
35
+ "min_voltage_limit",
36
+ "max_voltage_limit",
37
+ "max_temperature_limit",
38
+ ]
39
+
40
+ #: Widest the alarm banner gets, so it stays readable on a wide terminal.
41
+ ALARM_BANNER_WIDTH = 72
42
+
43
+ #: What to do about each error flag, shown under the alarm banner.
44
+ ALARM_HINTS = {
45
+ "angle": "goal position is outside the position limits",
46
+ "over-element": "the servo reports a sensor fault",
47
+ "over-current": "the output stage drew too much current, check for a stall",
48
+ "overload": "the servo is overloaded, check that the horn can move freely",
49
+ }
50
+
22
51
  #: Encoder counts moved per arrow key press, about five degrees.
23
52
  POSITION_STEP = RESOLUTION // 72
24
53
 
@@ -100,6 +129,80 @@ BUS_ERRORS = (FeetechError, OSError)
100
129
  #: discipline turns it into LF when ICRNL is set, which readchar leaves alone.
101
130
  ENTER_KEYS = (readchar.key.ENTER, "\r", "\n")
102
131
 
132
+ #: Characters that may follow ESC, ESC [ and so on in a key sequence. The same
133
+ #: decoding ``readchar.readkey`` does, see readchar/_posix_read.py.
134
+ ESCAPE_CONTINUATIONS = (
135
+ "\x4F\x5B",
136
+ "\x31\x32\x33\x35\x36",
137
+ "\x30\x31\x33\x34\x35\x37\x38\x39",
138
+ )
139
+
140
+
141
+ def _read_char():
142
+ """Read one character from stdin, raising :class:`EOFError` at its end."""
143
+ char = sys.stdin.read(1)
144
+ if not char:
145
+ raise EOFError("stdin closed")
146
+ return char
147
+
148
+
149
+ def _read_key_posix():
150
+ """Read one key press from a terminal already in non canonical mode.
151
+
152
+ Returns
153
+ -------
154
+ str
155
+ The key, a full escape sequence for arrows and the like.
156
+ """
157
+ key = _read_char()
158
+ if key in readchar_config.INTERRUPT_KEYS:
159
+ raise KeyboardInterrupt
160
+ if key != "\x1b":
161
+ return key
162
+ for continuations in ESCAPE_CONTINUATIONS:
163
+ char = _read_char()
164
+ key += char
165
+ if char not in continuations:
166
+ return key
167
+ return key + _read_char()
168
+
169
+
170
+ @contextlib.contextmanager
171
+ def key_input():
172
+ """Put the terminal in key at a time mode for as long as the screen runs.
173
+
174
+ ``readchar.readkey`` switches the terminal mode around every character
175
+ with ``TCSAFLUSH``, which throws away whatever was typed while no read was
176
+ pending: before the listener's first read, and between two reads. Keys
177
+ pressed then were lost. Switching once here, without flushing, keeps
178
+ every key.
179
+
180
+ Yields
181
+ ------
182
+ callable
183
+ Reads one key press and returns it.
184
+ """
185
+ if termios is None:
186
+ yield readchar.readkey
187
+ return
188
+ fd = sys.stdin.fileno()
189
+ try:
190
+ saved = termios.tcgetattr(fd)
191
+ except termios.error:
192
+ # Not a terminal. readchar.readkey raises the same error, which stops
193
+ # the listener just as it did before.
194
+ yield readchar.readkey
195
+ return
196
+ mode = termios.tcgetattr(fd)
197
+ mode[3] &= ~(termios.ICANON | termios.ECHO)
198
+ mode[6][termios.VMIN] = 1
199
+ mode[6][termios.VTIME] = 0
200
+ termios.tcsetattr(fd, termios.TCSANOW, mode)
201
+ try:
202
+ yield _read_key_posix
203
+ finally:
204
+ termios.tcsetattr(fd, termios.TCSADRAIN, saved)
205
+
103
206
 
104
207
  class KeyListener(threading.Thread):
105
208
  """Read key presses in the background.
@@ -109,8 +212,9 @@ class KeyListener(threading.Thread):
109
212
  the screen feel stuck.
110
213
  """
111
214
 
112
- def __init__(self):
215
+ def __init__(self, read_key=readchar.readkey):
113
216
  super().__init__()
217
+ self.read_key = read_key
114
218
  self.keys = queue.Queue()
115
219
  self.running = True
116
220
 
@@ -118,7 +222,7 @@ class KeyListener(threading.Thread):
118
222
  """Queue key presses until the listener is stopped."""
119
223
  while self.running:
120
224
  try:
121
- key = readchar.readkey()
225
+ key = self.read_key()
122
226
  except KeyboardInterrupt:
123
227
  self.keys.put("q")
124
228
  self.stop()
@@ -201,6 +305,8 @@ class ServoTui:
201
305
  self.candidate_index = 0
202
306
  self.message = ""
203
307
  self.values = {}
308
+ #: Error bits the active servo reported on its last refresh.
309
+ self.alarm = 0
204
310
  #: ``(question, action)`` while a destructive key waits for 'y'.
205
311
  self.pending_confirm = None
206
312
  #: False once the bus stops answering, until a servo is found again.
@@ -229,7 +335,18 @@ class ServoTui:
229
335
  holding down an arrow key does not flood the bus, and the screen is
230
336
  repainted only when something actually changed.
231
337
  """
232
- listener = KeyListener()
338
+ with key_input() as read_key:
339
+ self._run(read_key)
340
+
341
+ def _run(self, read_key):
342
+ """Body of :meth:`run`, with the terminal already set up for keys.
343
+
344
+ Parameters
345
+ ----------
346
+ read_key : callable
347
+ Reads one key press, from :func:`key_input`.
348
+ """
349
+ listener = KeyListener(read_key)
233
350
  listener.daemon = True
234
351
  listener.start()
235
352
  if self.connected:
@@ -289,6 +406,10 @@ class ServoTui:
289
406
  break
290
407
  try:
291
408
  self.handle_key(key)
409
+ except FeetechStatusError as error:
410
+ # The servo answered, so the bus is fine; it is in
411
+ # alarm, which the next refresh shows as well.
412
+ self.message = f"{Fore.RED}{error}{Style.RESET_ALL}"
292
413
  except BUS_ERRORS as error:
293
414
  self.lose_bus(error)
294
415
  last_probe = None
@@ -321,6 +442,7 @@ class ServoTui:
321
442
  """
322
443
  self.connected = False
323
444
  self.values = {}
445
+ self.alarm = 0
324
446
  self.pending_confirm = None
325
447
  self.message = f"{Fore.RED}Lost the servo: {error}{Style.RESET_ALL}"
326
448
  if isinstance(error, OSError):
@@ -403,17 +525,81 @@ class ServoTui:
403
525
  Maps register name to value, with ``None`` for any register that
404
526
  could not be read.
405
527
  """
406
- values = self.controller.dump(self.servo_id, STATUS_REGISTERS)
528
+ values, alarm = self.controller.dump_with_error(
529
+ self.servo_id, STATUS_REGISTERS
530
+ )
407
531
  if all(value is None for value in values.values()):
408
- # dump() turns a per register failure into None so that one odd
409
- # register cannot blank the screen. Everything failing means the
410
- # servo is gone, which the caller has to know about.
532
+ # dump_with_error() turns a per register failure into None so that
533
+ # one odd register cannot blank the screen. Everything failing
534
+ # means the servo is gone, which the caller has to know about.
411
535
  raise FeetechTimeoutError(
412
536
  f"servo {self.servo_id} stopped answering"
413
537
  )
538
+ if alarm:
539
+ limits, _ = self.controller.dump_with_error(
540
+ self.servo_id, ALARM_LIMIT_REGISTERS
541
+ )
542
+ values.update(limits)
414
543
  self.values = values
544
+ self.alarm = alarm
415
545
  return values
416
546
 
547
+ def alarm_lines(self, values):
548
+ """Build the banner shown while the servo reports an alarm.
549
+
550
+ Parameters
551
+ ----------
552
+ values : dict
553
+ Register values as returned by :meth:`read_values`.
554
+
555
+ Returns
556
+ -------
557
+ list of str
558
+ The banner and one hint per error flag.
559
+ """
560
+ width = min(shutil.get_terminal_size().columns, ALARM_BANNER_WIDTH)
561
+ style = Back.RED + Fore.WHITE + Style.BRIGHT
562
+ flags = describe_error(self.alarm)
563
+ title = f"!!! ALARM on servo {self.servo_id}: {', '.join(flags)} !!!"
564
+ lines = [style + title.center(width) + Style.RESET_ALL]
565
+ for flag in flags:
566
+ hint = self.alarm_hint(flag, values)
567
+ lines.append(f"{Fore.RED}{Style.BRIGHT} -> {hint}{Style.RESET_ALL}")
568
+ return lines
569
+
570
+ def alarm_hint(self, flag, values):
571
+ """Explain one error flag, with the reading that tripped it.
572
+
573
+ Parameters
574
+ ----------
575
+ flag : str
576
+ A name from :func:`~feetech_cli.protocol.describe_error`.
577
+ values : dict
578
+ Register values as returned by :meth:`read_values`.
579
+
580
+ Returns
581
+ -------
582
+ str
583
+ One line of advice.
584
+ """
585
+ voltage = values.get("present_voltage")
586
+ low = values.get("min_voltage_limit")
587
+ high = values.get("max_voltage_limit")
588
+ if flag == "voltage" and None not in (voltage, low, high):
589
+ return (
590
+ f"supply {voltage / 10.0:.1f} V is outside the servo's "
591
+ f"{low / 10.0:.1f}-{high / 10.0:.1f} V range, fix the power supply"
592
+ )
593
+ temperature = values.get("present_temperature")
594
+ limit = values.get("max_temperature_limit")
595
+ if flag == "overheat" and None not in (temperature, limit):
596
+ return f"{temperature} C is above the {limit} C limit, let it cool down"
597
+ if flag == "voltage":
598
+ return "supply voltage is out of range, check the power supply"
599
+ if flag == "overheat":
600
+ return "the servo is too hot, let it cool down"
601
+ return ALARM_HINTS.get(flag, f"error flag '{flag}' is set")
602
+
417
603
  def build_lines(self, values):
418
604
  """Build the screen as a list of lines.
419
605
 
@@ -441,6 +627,8 @@ class ServoTui:
441
627
  f"Bus: {self.controller.serial.port} @ {speed}bps Servos: {bus}",
442
628
  "",
443
629
  ]
630
+ if self.alarm:
631
+ lines[-1:-1] = self.alarm_lines(values)
444
632
  for index, row in enumerate(SELECTABLE_ROWS):
445
633
  text = self.render_row(row, values)
446
634
  if index == self.selected_row:
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: feetech-cli
3
- Version: 0.1.4
3
+ Version: 0.1.6
4
4
  Summary: Command line tool to inspect and configure FEETECH STS/SMS/SCS serial bus servos
5
5
  Author-email: Iori Yanokura <ab.ioryz@gmail.com>
6
6
  License-Expression: MIT
@@ -13,6 +13,11 @@ Classifier: Intended Audience :: Developers
13
13
  Classifier: Intended Audience :: Science/Research
14
14
  Classifier: Operating System :: OS Independent
15
15
  Classifier: Programming Language :: Python :: 3
16
+ Classifier: Programming Language :: Python :: 3.9
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Programming Language :: Python :: 3.13
16
21
  Classifier: Topic :: Scientific/Engineering
17
22
  Classifier: Topic :: System :: Hardware
18
23
  Requires-Python: >=3.9
@@ -25,6 +30,10 @@ Dynamic: license-file
25
30
 
26
31
  # feetech-cli
27
32
 
33
+ ![PyPI](https://img.shields.io/pypi/v/feetech-cli.svg)
34
+ ![Python Versions](https://img.shields.io/pypi/pyversions/feetech-cli.svg)
35
+ [![Build Status](https://github.com/iory/feetech-cli/actions/workflows/test.yml/badge.svg?branch=main)](https://github.com/iory/feetech-cli/actions)
36
+
28
37
  Command line tool to inspect and configure FEETECH STS/SMS/SCS serial bus
29
38
  servos (STS3215 and friends) — change servo ids, bus speeds, modes and limits,
30
39
  or watch a live status screen.
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "feetech-cli"
3
- version = "0.1.4"
3
+ version = "0.1.6"
4
4
  description = "Command line tool to inspect and configure FEETECH STS/SMS/SCS serial bus servos"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.9"
@@ -15,6 +15,11 @@ classifiers = [
15
15
  "Intended Audience :: Science/Research",
16
16
  "Operating System :: OS Independent",
17
17
  "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.9",
19
+ "Programming Language :: Python :: 3.10",
20
+ "Programming Language :: Python :: 3.11",
21
+ "Programming Language :: Python :: 3.12",
22
+ "Programming Language :: Python :: 3.13",
18
23
  "Topic :: Scientific/Engineering",
19
24
  "Topic :: System :: Hardware",
20
25
  ]
@@ -59,6 +59,16 @@ def test_scan_lists_every_servo(bus, capsys):
59
59
  assert "id 4" in out
60
60
 
61
61
 
62
+ def test_scan_shows_the_alarm_of_a_servo_over_its_voltage_limit(bus, capsys):
63
+ bus.servos[0].error = 0x01 # voltage
64
+ assert run(["scan"]) == 0
65
+ out = capsys.readouterr().out
66
+ assert "Found 2 servo(s)" in out
67
+ lines = {line.split()[1]: line for line in out.splitlines() if " id " in line}
68
+ assert "ALARM: voltage" in lines["1"]
69
+ assert "ALARM" not in lines["4"]
70
+
71
+
62
72
  def test_info_prints_the_control_table(bus, capsys):
63
73
  assert run(["info", "1"]) == 0
64
74
  out = capsys.readouterr().out
@@ -54,6 +54,13 @@ def test_scan_default_range_stops_at_16():
54
54
  assert controller.scan(max_id=20) == [1, 17]
55
55
 
56
56
 
57
+ def test_scan_finds_a_servo_in_voltage_alarm():
58
+ servo = FakeServo(1)
59
+ servo.error = 0x01 # over the voltage limit, the LED blinks
60
+ controller, _ = make_controller([servo, FakeServo(4)])
61
+ assert controller.scan() == [1, 4]
62
+
63
+
57
64
  def test_read_register_decodes_sign_magnitude():
58
65
  servo = FakeServo(1)
59
66
  servo._store("homing_offset", 0x0800 | 100) # sign bit 11 set
@@ -83,6 +83,37 @@ def test_transmit_echo_is_skipped():
83
83
  assert handler.decode(2, handler.read(1, 56, 2)) == 2048
84
84
 
85
85
 
86
+ def voltage_alarm_servo(servo_id):
87
+ """A servo whose PING answer is byte for byte the PING request."""
88
+ servo = FakeServo(servo_id)
89
+ servo.error = 0x01 # voltage, same value as INST_PING
90
+ return servo
91
+
92
+
93
+ @pytest.mark.parametrize("echo", [False, True])
94
+ def test_ping_answer_identical_to_the_request_is_not_dropped(echo):
95
+ handler = PacketHandler(FakeBus([voltage_alarm_servo(1)], echo=echo))
96
+ assert handler.ping(1) is True
97
+ assert handler.echoes is echo
98
+
99
+
100
+ @pytest.mark.parametrize("echo", [False, True])
101
+ def test_echo_detection_does_not_invent_servos(echo):
102
+ handler = PacketHandler(FakeBus([voltage_alarm_servo(1)], echo=echo))
103
+ assert handler.ping(2) is False
104
+ assert handler.ping(1) is True
105
+ assert handler.ping(3) is False
106
+
107
+
108
+ def test_echo_is_probed_only_once():
109
+ bus = FakeBus([voltage_alarm_servo(1)])
110
+ handler = PacketHandler(bus)
111
+ handler.ping(1)
112
+ handler.ping(1)
113
+ # Two pings and a single id read to learn the adapter does not echo.
114
+ assert len(bus.tx_log) == 3
115
+
116
+
86
117
  def test_timeout_when_nobody_answers():
87
118
  handler = PacketHandler(FakeBus([FakeServo(1)]))
88
119
  with pytest.raises(FeetechTimeoutError):
@@ -84,19 +84,24 @@ class Screen:
84
84
  return CURSOR_CODES.sub("", self.buffer.decode("utf-8", "replace"))
85
85
 
86
86
  def highlighted(self):
87
- """Return the id candidate currently painted green.
87
+ """Return the id candidate painted green in the most recent frame.
88
+
89
+ The last match, like :meth:`line` and :meth:`row`. :meth:`forget`
90
+ only drops what was already read: frames painted before a key press
91
+ was handled can still be waiting in the pty, and the first match then
92
+ comes from one of those.
88
93
 
89
94
  Returns
90
95
  -------
91
96
  str or None
92
97
  The highlighted text, or ``None`` when nothing is highlighted.
93
98
  """
94
- match = re.search(
99
+ hits = re.findall(
95
100
  re.escape(GREEN) + r"(\d+)" + re.escape(RESET), self.coloured
96
101
  )
97
- if match is None:
102
+ if not hits:
98
103
  return None
99
- return match.group(1)
104
+ return hits[-1]
100
105
 
101
106
  def line(self, needle):
102
107
  """Return the most recently painted line containing ``needle``.
@@ -409,3 +414,73 @@ def test_zero_key_can_be_cancelled(screen):
409
414
 
410
415
  def test_quit_key_exits_cleanly(screen):
411
416
  assert screen.close() == 0
417
+
418
+
419
+ #: Reads keys through key_input() while busy between reads, then prints them.
420
+ BUSY_READER = r"""
421
+ import sys, termios, time
422
+ from feetech_cli.tui import key_input
423
+ before = termios.tcgetattr(sys.stdin.fileno())
424
+ keys = []
425
+ with key_input() as read_key:
426
+ print("READY", flush=True)
427
+ for _ in range(4):
428
+ keys.append(read_key())
429
+ time.sleep(0.4)
430
+ after = termios.tcgetattr(sys.stdin.fileno())
431
+ # Turning ICANON back on makes BSD kernels, macOS included, set PENDIN until
432
+ # the next read reprocesses the input queue (xnu bsd/kern/tty.c, TIOCSETA).
433
+ # It is kernel bookkeeping, not a setting the screen left behind.
434
+ after[3] &= ~termios.PENDIN
435
+ before[3] &= ~termios.PENDIN
436
+ changed = [index for index in range(len(before)) if before[index] != after[index]]
437
+ print("CHANGED", changed, before, after, flush=True)
438
+ print("GOT", repr(keys), "RESTORED", not changed, flush=True)
439
+ # macOS drops unread pty output once the child side closes, so stay until the
440
+ # test has read the line and answers with a newline.
441
+ sys.stdin.readline()
442
+ """
443
+
444
+
445
+ def test_keys_typed_while_the_reader_is_busy_are_kept():
446
+ """readchar flushed input on every read, dropping keys typed in between.
447
+
448
+ The writes land while the reader sleeps, which is exactly when
449
+ ``readchar.readkey`` used to throw them away.
450
+ """
451
+ master, slave = pty.openpty()
452
+ process = subprocess.Popen(
453
+ [sys.executable, "-c", BUSY_READER],
454
+ stdin=slave, stdout=slave, stderr=slave, close_fds=True,
455
+ )
456
+ os.close(slave)
457
+ output = b""
458
+
459
+ def read_until(*needles):
460
+ """Collect the child's output until one of ``needles`` shows up."""
461
+ nonlocal output
462
+ end = time.time() + TIMEOUT
463
+ while (not any(needle in output for needle in needles)
464
+ and time.time() < end):
465
+ ready, _, _ = select.select([master], [], [], 0.05)
466
+ if ready:
467
+ output += os.read(master, 65536)
468
+
469
+ try:
470
+ read_until(b"READY")
471
+ os.write(master, b"a")
472
+ time.sleep(0.1)
473
+ os.write(master, b"b") # reader asleep
474
+ time.sleep(0.1)
475
+ os.write(master, RIGHT.encode())
476
+ time.sleep(0.1)
477
+ os.write(master, b"q")
478
+ read_until(b"RESTORED True", b"RESTORED False")
479
+ os.write(master, b"\n")
480
+ process.wait(timeout=TIMEOUT)
481
+ finally:
482
+ if process.poll() is None:
483
+ process.kill()
484
+ os.close(master)
485
+ text = output.decode("utf-8", "replace")
486
+ assert f"GOT {['a', 'b', RIGHT, 'q']!r} RESTORED True" in text, text
@@ -331,3 +331,35 @@ def test_starting_on_a_quiet_bus_does_not_claim_to_have_lost_one(tui):
331
331
  lines = "\n".join(screen.build_lines({}))
332
332
  assert "No servo is answering" in lines
333
333
  assert "Lost the servo" not in lines
334
+
335
+
336
+ def test_a_servo_in_alarm_stays_on_screen_with_the_alarm(tui):
337
+ """An over voltage servo still answers; it must not read as unplugged."""
338
+ screen, servos = tui
339
+ servos[0].error = 0x01 # voltage
340
+ values = screen.read_values()
341
+ assert screen.connected is True
342
+ assert values["present_voltage"] is not None
343
+ text = "\n".join(screen.build_lines(values))
344
+ assert "ALARM on servo 1: voltage" in text
345
+ assert "12.1 V is outside the servo's" in text
346
+ assert "No servo is answering" not in text
347
+
348
+
349
+ def test_the_alarm_clears_once_the_servo_recovers(tui):
350
+ screen, servos = tui
351
+ servos[0].error = 0x01
352
+ screen.read_values()
353
+ servos[0].error = 0
354
+ text = "\n".join(screen.build_lines(screen.read_values()))
355
+ assert "ALARM" not in text
356
+
357
+
358
+ def test_a_servo_in_alarm_is_picked_up_again(tui):
359
+ screen, servos = tui
360
+ screen.lose_bus(FeetechError("gone"))
361
+ alarmed = FakeServo(1)
362
+ alarmed.error = 0x01
363
+ screen.controller.serial.servos = [alarmed]
364
+ assert screen.rediscover() is True
365
+ assert screen.alarm == 0x01
File without changes
File without changes