bbr-buttonboard 0.2.0__tar.gz → 0.3.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 (29) hide show
  1. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/PKG-INFO +1 -1
  2. bbr_buttonboard-0.3.0/examples/ds_volume.py +214 -0
  3. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/src/buttonboard/__init__.py +1 -1
  4. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/src/buttonboard/client.py +16 -6
  5. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/src/buttonboard/mock.py +6 -2
  6. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/src/buttonboard/transport.py +4 -1
  7. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/tests/test_buttonboard.py +13 -0
  8. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/.gitignore +0 -0
  9. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/LICENSE +0 -0
  10. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/README.md +0 -0
  11. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/examples/ds_field.py +0 -0
  12. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/examples/ds_reef.py +0 -0
  13. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/examples/ds_reef_side.py +0 -0
  14. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/examples/ds_swerve.py +0 -0
  15. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/ftc/README.md +0 -0
  16. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/ftc/org/firstinspires/ftc/teamcode/buttonboard/ButtonBoard.java +0 -0
  17. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/ftc/org/firstinspires/ftc/teamcode/buttonboard/GamepadRumbleSink.java +0 -0
  18. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/ftc/org/firstinspires/ftc/teamcode/buttonboard/RumbleSink.java +0 -0
  19. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/ftc/org/firstinspires/ftc/teamcode/buttonboard/TriggerKnob.java +0 -0
  20. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/pyproject.toml +0 -0
  21. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/src/buttonboard/bbctl.py +0 -0
  22. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/src/buttonboard/companion.py +0 -0
  23. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/src/buttonboard/crc.py +0 -0
  24. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/src/buttonboard/display.py +0 -0
  25. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/src/buttonboard/draw.py +0 -0
  26. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/src/buttonboard/errors.py +0 -0
  27. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/src/buttonboard/leds.py +0 -0
  28. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/src/buttonboard/rumble.py +0 -0
  29. {bbr_buttonboard-0.2.0 → bbr_buttonboard-0.3.0}/src/buttonboard/sound.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: bbr-buttonboard
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Drive a BBR Button Board's LEDs, displays and bindings from the Driver Station laptop
5
5
  Project-URL: Documentation, https://buttonboard.buildingblockrobotics.com/driver-station/install.html
6
6
  Project-URL: Source, https://github.com/BuildingBlockRobotics/BBRButtonBoard
@@ -0,0 +1,214 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ Show the computer's volume on a disp2 as a bar, and light the mute key red while the sound is muted.
4
+
5
+ Built on the bbr-buttonboard library (tools/buttonboard) for a board in desk mode (PROTOCOL.md 8.9). The board
6
+ does the work itself: an enc1 whose knob sends Volume up and Volume down turns the computer's volume, and a key
7
+ that sends Mute mutes it, with no script at all. This script is the feedback. It reads the volume from the
8
+ computer, not from the knob, so the bar follows the keyboard's own volume keys and the menu bar slider too.
9
+
10
+ Set the board up in the config app first:
11
+ 1. Configure -> Mode -> Keyboard & media. Save, unplug and plug back in.
12
+ 2. Select the enc1's knob -> Knob -> Volume knob.
13
+ 3. Select the mx1's key -> Sends -> Mute. Save.
14
+
15
+ Install and run (the config website not connected to the board):
16
+
17
+ pip install bbr-buttonboard
18
+ python ds_volume.py # macOS and Linux as they are
19
+ pip install pycaw && python ds_volume.py # Windows needs pycaw to read the volume
20
+
21
+ python ds_volume.py --mock --png volume.png # no board: a made-up volume, drawn into a picture
22
+ """
23
+ import argparse
24
+ import platform
25
+ import re
26
+ import subprocess
27
+ import sys
28
+ import time
29
+
30
+ from buttonboard import Board, BoardError, MockBoard
31
+
32
+ HZ = 10
33
+ W = 160 # the disp2's panel, pixels across
34
+ BAR_X, BAR_Y, BAR_W, BAR_H = 8, 44, 144, 28
35
+ CHAR_W = 12 # the tile's font: 12 x 16 per character
36
+
37
+
38
+ def centred(text):
39
+ return (W - CHAR_W * len(text)) // 2
40
+
41
+
42
+ # ---- reading the computer's volume: (percent 0-100, muted), or None when it cannot be read ---------------------
43
+
44
+ def _run(*cmd):
45
+ return subprocess.run(cmd, capture_output=True, text=True, timeout=2).stdout
46
+
47
+
48
+ def volume_macos():
49
+ # "output volume:44, input volume:50, alert volume:100, output muted:false". An output with no volume control
50
+ # (HDMI, some USB DACs) says "missing value".
51
+ out = _run("osascript", "-e", "get volume settings")
52
+ v, m = re.search(r"output volume:(\d+)", out), re.search(r"output muted:(true|false)", out)
53
+ return (int(v.group(1)), m.group(1) == "true") if v and m else None
54
+
55
+
56
+ def volume_linux():
57
+ try: # PipeWire: "Volume: 0.50 [MUTED]"
58
+ out = _run("wpctl", "get-volume", "@DEFAULT_AUDIO_SINK@")
59
+ v = re.search(r"Volume:\s*([\d.]+)", out)
60
+ if v:
61
+ return round(float(v.group(1)) * 100), "MUTED" in out
62
+ except FileNotFoundError:
63
+ pass
64
+ # PulseAudio: "Volume: front-left: 32768 / 50% / ..." and "Mute: no"
65
+ v = re.search(r"(\d+)%", _run("pactl", "get-sink-volume", "@DEFAULT_SINK@"))
66
+ m = re.search(r"Mute:\s*(yes|no)", _run("pactl", "get-sink-mute", "@DEFAULT_SINK@"))
67
+ return (int(v.group(1)), m.group(1) == "yes") if v and m else None
68
+
69
+
70
+ def volume_windows():
71
+ from pycaw.pycaw import AudioUtilities # pip install pycaw
72
+ speakers = AudioUtilities.GetSpeakers()
73
+ ep = getattr(speakers, "EndpointVolume", None) # pycaw 2025 and later
74
+ if ep is None: # older pycaw: activate the interface by hand
75
+ from ctypes import POINTER, cast
76
+ from comtypes import CLSCTX_ALL
77
+ from pycaw.pycaw import IAudioEndpointVolume
78
+ ep = cast(speakers.Activate(IAudioEndpointVolume._iid_, CLSCTX_ALL, None), POINTER(IAudioEndpointVolume))
79
+ return round(ep.GetMasterVolumeLevelScalar() * 100), bool(ep.GetMute())
80
+
81
+
82
+ def volume_reader():
83
+ system = platform.system()
84
+ if system == "Darwin":
85
+ return volume_macos
86
+ if system == "Linux":
87
+ return volume_linux
88
+ if system == "Windows":
89
+ try:
90
+ import pycaw # noqa: F401
91
+ except ImportError:
92
+ sys.exit("Reading the volume on Windows needs pycaw: pip install pycaw")
93
+ return volume_windows
94
+ sys.exit(f"Don't know how to read the volume on {system}.")
95
+
96
+
97
+ def volume_demo(t):
98
+ """A made-up volume for --mock: up from 0 to 100, then muted for a while."""
99
+ level = min(100, int(t * 25))
100
+ return level, t > 5
101
+
102
+
103
+ # ---- the board ---------------------------------------------------------------------------------------------------
104
+
105
+ def find_panel(board, addr=None):
106
+ """The disp2 to draw on: the one at `addr`, or the first online that draws."""
107
+ for t in board.tiles():
108
+ if t["state"] == "online" and (t["addr"] == addr if addr else t["type"] == "disp2" and t.get("draw")):
109
+ if not t.get("draw"):
110
+ sys.exit(f"The tile at address {addr} cannot draw. This needs a disp2 on firmware 0.3.0 or newer.")
111
+ return t["addr"]
112
+ sys.exit(f"No {'tile at address ' + str(addr) if addr else 'disp2 that draws'} online. "
113
+ "Check its cable and its firmware, or pass --addr.")
114
+
115
+
116
+ def check_setup(board, mock=False):
117
+ """The mute key's button number, or None, and a word about anything that will not work as expected."""
118
+ if not mock and board.hello().get("usb") != "desk": # the mock is always frc
119
+ print("note: the board is not in desk mode, so the knob and the mute key will not reach the computer. "
120
+ "The display still follows the volume.", file=sys.stderr)
121
+ m = board.map_get()
122
+ hid = m.get("hid", {})
123
+ if not any(hid.get(str(e.get("cw"))) == "vol_up" for e in m.get("enc", [])):
124
+ print("note: no knob turns the volume up. In the config app select the knob and pick Volume knob.",
125
+ file=sys.stderr)
126
+ mute = next((int(b) for b, act in sorted(hid.items(), key=lambda kv: int(kv[0])) if act == "mute"), None)
127
+ if mute is None:
128
+ print("note: no key sends Mute, so no key will light. In the config app select the key and pick Mute.",
129
+ file=sys.stderr)
130
+ return mute
131
+
132
+
133
+ def draw(layers, reading):
134
+ bar, label = layers
135
+ bar.clear()
136
+ label.clear()
137
+ if reading is None:
138
+ label.text(centred("NO VOLUME"), 84, "NO VOLUME", "orange")
139
+ return
140
+ level, muted = reading
141
+ width = round((BAR_W - 4) * max(0, min(level, 100)) / 100)
142
+ if width:
143
+ bar.fill(BAR_X + 2, BAR_Y + 2, width, BAR_H - 4, "#404040" if muted else "lime")
144
+ text = f"{level}%"
145
+ label.text(centred(text), 84, text, "#808080" if muted else "white")
146
+ if muted:
147
+ label.text(centred("MUTED"), 106, "MUTED", "white", "red")
148
+
149
+
150
+ def main():
151
+ ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
152
+ ap.add_argument("--port", help="the board's serial port (default: found by USB id)")
153
+ ap.add_argument("--addr", type=int, help="the display's address (default: the first disp2)")
154
+ ap.add_argument("--mock", action="store_true", help="no board and a made-up volume: draw into memory")
155
+ ap.add_argument("--png", help="with --mock, write the finished panel to this file")
156
+ a = ap.parse_args()
157
+
158
+ if a.mock:
159
+ ticks = iter(range(10 ** 9))
160
+ read = lambda: volume_demo(next(ticks) / HZ) # noqa: E731 -- made-up time, so --mock does not wait
161
+ else:
162
+ read = volume_reader()
163
+
164
+ with (MockBoard() if a.mock else Board.open(port=a.port)) as board:
165
+ addr = find_panel(board, a.addr)
166
+ if a.mock: # the set-up the docstring asks for: a volume knob and a mute key
167
+ board.map_set(dict(board.map_get(), hid={"1": "mute", "2": "vol_up", "3": "vol_down"},
168
+ enc=[{"addr": 3, "idx": 0, "cw": 2, "ccw": 3}]))
169
+ mute_btn = check_setup(board, a.mock)
170
+ canvas = board.canvas(addr)
171
+ frame = canvas.layer()
172
+ frame.text(centred("VOLUME"), 8, "VOLUME", "white")
173
+ frame.rect(BAR_X, BAR_Y, BAR_W, BAR_H, "white")
174
+ layers = (canvas.layer(), canvas.layer())
175
+ # A tile that drops off the bus comes back blank: draw it all again, not just what changed.
176
+ board.on("tile", lambda ev: ev.get("addr") == addr and canvas.forget())
177
+ print(f"showing the volume on the display at address {addr}" + ("" if a.mock else "; Ctrl-C to stop"),
178
+ flush=True)
179
+
180
+ lit, passes = None, 0
181
+ try:
182
+ while not a.mock or passes < 80:
183
+ try:
184
+ reading = read()
185
+ except (OSError, subprocess.SubprocessError, ValueError):
186
+ reading = None
187
+ muted = bool(reading and reading[1])
188
+ try:
189
+ draw(layers, reading)
190
+ canvas.flush()
191
+ if mute_btn is not None and muted != lit:
192
+ # Red while muted. Unmuted, the key goes back to its colour from the config app.
193
+ board.led(mute_btn, "red") if muted else board.led_reset()
194
+ lit = muted
195
+ except BoardError as e: # a frame that failed did not land: start from a clear panel next time
196
+ canvas.forget()
197
+ lit = None
198
+ print(f"board: {e}", file=sys.stderr, flush=True)
199
+ passes += 1
200
+ if not a.mock:
201
+ time.sleep(1.0 / HZ)
202
+ finally:
203
+ if lit:
204
+ board.led_reset()
205
+ print(f"{passes} passes took {canvas.frames} frames on the bus", flush=True)
206
+ if a.png:
207
+ print("wrote", board.state.panel(addr).save(a.png), flush=True)
208
+
209
+
210
+ if __name__ == "__main__":
211
+ try:
212
+ main()
213
+ except KeyboardInterrupt:
214
+ pass
@@ -31,7 +31,7 @@ puts it on the glass in a single frame. `board.rumble_bind(1, 5, 0)` binds a
31
31
  legend code to that slot (§8.8), which is how a match-time `gamepad.rumble()`
32
32
  from an OpMode reaches a board that has no config channel at all.
33
33
  """
34
- __version__ = "0.2.0"
34
+ __version__ = "0.3.0"
35
35
 
36
36
  from . import rumble
37
37
  from .client import Board, FLASH_CHUNK, MAX_LINE
@@ -27,6 +27,14 @@ FLASH_READY_TIMEOUT = 4.0 # ENTER_BOOT, reset, GET_DESC until IN_BOOT
27
27
  FLASH_CHUNK_TIMEOUT = 2.0 # one WRITE and the tile's ACK
28
28
  FLASH_VERIFY_TIMEOUT = 6.0 # VERIFY, RESET, tile online again
29
29
 
30
+ # The USB personalities `usb` takes (§8.3): desk from rev 0.49, midi 0.50, sim
31
+ # 0.51. A master that predates one answers `args`, which reaches the caller
32
+ # as CommandError.
33
+ USB_MODES = ("frc", "xinput", "desk", "midi", "sim")
34
+ # Encoder and stick axes, SIM_AXES in protocol.h (§8.11): `frc` reports the
35
+ # first four, `sim` all eight.
36
+ AXES = 8
37
+
30
38
  # `busy` on a `disp` command is the auxiliary queue (§3.2), or §14.9's picture
31
39
  # flash, saying it has no room this cycle. Waiting slightly under a slot period
32
40
  # means a refused line goes out on the first cycle with room; bounded by
@@ -235,8 +243,10 @@ class Board(object):
235
243
  return self.command("stats")
236
244
 
237
245
  def usb(self, mode):
238
- if mode not in ("frc", "xinput"):
239
- raise ValueError("usb mode must be frc or xinput, not %r" % (mode,))
246
+ """Set the persisted USB personality (§8.3). It takes effect after
247
+ `save()` and a replug or `reset()`; `hello()["usbSaved"]` shows it."""
248
+ if mode not in USB_MODES:
249
+ raise ValueError("usb mode must be one of %s, not %r" % (", ".join(USB_MODES), mode))
240
250
  return self.command("usb %s" % mode)
241
251
 
242
252
  def save(self):
@@ -291,16 +301,16 @@ class Board(object):
291
301
  return self.command("unbind %d %d %d" % (btn, _int_in("addr", addr, 1, 31),
292
302
  _int_in("key", key, 0, 15)))
293
303
 
294
- # encoders, §15.7
304
+ # encoders, §15.7; axes 5-8 move only under `sim` (§8.11)
295
305
  def bind_axis(self, n):
296
- return self.command("bind axis %d" % _int_in("axis", n, 1, 4),
306
+ return self.command("bind axis %d" % _int_in("axis", n, 1, AXES),
297
307
  timeout=self.BIND_TIMEOUT)
298
308
 
299
309
  def unbind_axis(self, n):
300
- return self.command("unbind axis %d" % _int_in("axis", n, 1, 4))
310
+ return self.command("unbind axis %d" % _int_in("axis", n, 1, AXES))
301
311
 
302
312
  def enc_zero(self, n=None):
303
- return self.command("enc zero" if n is None else "enc zero %d" % _int_in("axis", n, 1, 4))
313
+ return self.command("enc zero" if n is None else "enc zero %d" % _int_in("axis", n, 1, AXES))
304
314
 
305
315
  # map, §9.5
306
316
  def map_get(self):
@@ -14,7 +14,7 @@ from __future__ import annotations
14
14
  import json
15
15
 
16
16
  from . import display, draw, rumble
17
- from .client import Board
17
+ from .client import USB_MODES, Board
18
18
  from .crc import crc16_ccitt_false
19
19
  from .transport import LoopTransport
20
20
 
@@ -61,6 +61,7 @@ class MockState(object):
61
61
  self.display = display # False emulates a board older than §14
62
62
  self.sound = sound # §16 is still reserved: no sounder tile
63
63
  self.pixel = True # §8.6 status pixel, on until turned off
64
+ self.usb_saved = "frc" # §8.3: what `usb` set; the active one stays frc
64
65
  self.playing = {} # addr -> (notes, repeat) or None
65
66
  self.volume = {} # addr -> 0-255
66
67
  self.leds = {} # ("btn", n) / ("tile", addr, i) -> line
@@ -312,7 +313,7 @@ class MockState(object):
312
313
  return {"ok": True, "product": "BBR Button Board", "fw": "0.1.0", "proto": 1,
313
314
  "serial": "MOCK", "hw": "A", "mapValid": True,
314
315
  "tiles": len(self.tiles), "mode": "run",
315
- "usb": "frc", "usbSaved": "frc", "pixel": self.pixel}
316
+ "usb": "frc", "usbSaved": self.usb_saved, "pixel": self.pixel}
316
317
 
317
318
  def _cmd_tiles(self, argv):
318
319
  return {"ok": True, "tiles": self.tiles}
@@ -437,6 +438,9 @@ class MockState(object):
437
438
  return {"ok": True}
438
439
 
439
440
  def _cmd_usb(self, argv):
441
+ if len(argv) != 1 or argv[0] not in USB_MODES:
442
+ raise _Err("args")
443
+ self.usb_saved = argv[0]
440
444
  return {"ok": True, "usb": argv[0], "pending": True}
441
445
 
442
446
  def _cmd_pixel(self, argv):
@@ -23,6 +23,9 @@ def _pyserial():
23
23
  raise BoardError("needs pyserial: python3 -m pip install pyserial")
24
24
 
25
25
  VID, PID = 0x1209, 0x0001 # §8.4, still the pid.codes test PID
26
+ # Every personality with a config channel has a PID of its own (§8.3): frc,
27
+ # then desk, midi and sim. All pid.codes test PIDs until settled (§11).
28
+ PIDS = (PID, 0x0002, 0x0003, 0x0004)
26
29
 
27
30
 
28
31
  def find_port():
@@ -32,7 +35,7 @@ def find_port():
32
35
 
33
36
  ports = list(list_ports.comports())
34
37
  for p in ports:
35
- if p.vid == VID and p.pid == PID:
38
+ if p.vid == VID and p.pid in PIDS:
36
39
  return p.device
37
40
  for p in ports:
38
41
  # Substring, not equality: iProduct is "BBR Button Board" (PROTOCOL.md
@@ -46,6 +46,19 @@ check_raises("rgb bool", ValueError, rgb, True)
46
46
  check_raises("rgb range", ValueError, rgb, (0, 300, 0))
47
47
 
48
48
  # ---- command formatting -----------------------------------------------------
49
+ board = MockBoard()
50
+ for mode in ("frc", "xinput", "desk", "midi", "sim"):
51
+ board.usb(mode)
52
+ check("usb " + mode, board.state.sent[-1], "usb " + mode)
53
+ check("usb is saved, not active", (board.hello()["usb"], board.hello()["usbSaved"]), ("frc", "sim"))
54
+ check_raises("usb unknown mode", ValueError, board.usb, "keyboard")
55
+ board.bind_axis(8)
56
+ check("axis 8 for sim", board.state.sent[-1], "bind axis 8")
57
+ board.enc_zero(5)
58
+ check("enc zero 5", board.state.sent[-1], "enc zero 5")
59
+ check_raises("axis 9", ValueError, board.bind_axis, 9)
60
+ check_raises("axis 0", ValueError, board.unbind_axis, 0)
61
+
49
62
  board = MockBoard()
50
63
  check("hello", board.hello()["product"], "BBR Button Board")
51
64
  board.led(3, "red")
File without changes