heystella 0.1.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.
@@ -0,0 +1,20 @@
1
+ ._*
2
+ .DS_Store
3
+ __pycache__/
4
+ *.egg-info/
5
+ *.pyc
6
+ .venv/
7
+ dist/
8
+
9
+ # dasm output
10
+ *.bin
11
+ *.lst
12
+ *.sym
13
+
14
+ # PlatformIO / ESP-IDF
15
+ .pio/
16
+ build/
17
+ sdkconfig.old
18
+
19
+ # speech models are large downloads, never commit them
20
+ models/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 michael-borck
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,106 @@
1
+ Metadata-Version: 2.5
2
+ Name: heystella
3
+ Version: 0.1.0
4
+ Summary: Voice control for the Atari 2600. Say a word and the console sees a joystick move.
5
+ Project-URL: Homepage, https://github.com/retroverse-studios/hey-stella
6
+ Project-URL: Repository, https://github.com/retroverse-studios/hey-stella
7
+ Project-URL: Issues, https://github.com/retroverse-studios/hey-stella/issues
8
+ Author: Michael Borck
9
+ License-Expression: MIT
10
+ License-File: LICENSE
11
+ Keywords: accessibility,atari,atari-2600,joystick,retro,speech-recognition,stella,voice-control
12
+ Classifier: Development Status :: 3 - Alpha
13
+ Classifier: Environment :: Console
14
+ Classifier: Intended Audience :: End Users/Desktop
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.11
18
+ Classifier: Programming Language :: Python :: 3.12
19
+ Classifier: Programming Language :: Python :: 3.13
20
+ Classifier: Topic :: Games/Entertainment
21
+ Classifier: Topic :: Multimedia :: Sound/Audio :: Speech
22
+ Classifier: Topic :: System :: Hardware
23
+ Requires-Python: >=3.11
24
+ Provides-Extra: all
25
+ Requires-Dist: pynput>=1.7; extra == 'all'
26
+ Requires-Dist: pyserial>=3.5; extra == 'all'
27
+ Requires-Dist: sounddevice>=0.4; extra == 'all'
28
+ Requires-Dist: vosk>=0.3.44; extra == 'all'
29
+ Provides-Extra: keys
30
+ Requires-Dist: pynput>=1.7; extra == 'keys'
31
+ Provides-Extra: serial
32
+ Requires-Dist: pyserial>=3.5; extra == 'serial'
33
+ Provides-Extra: voice
34
+ Requires-Dist: sounddevice>=0.4; extra == 'voice'
35
+ Requires-Dist: vosk>=0.3.44; extra == 'voice'
36
+ Description-Content-Type: text/markdown
37
+
38
+ # Hey Stella
39
+
40
+ Voice control for the Atari 2600. Say "left" and the console sees a joystick pushed left.
41
+
42
+ This package is the host program. It listens to a microphone, recognises the words in a game profile, and turns them into joystick actions. Those go to the Stella emulator as key presses, or to a small build-it-yourself dongle that plugs into a real console's joystick port.
43
+
44
+ **Early software.** It works with typed input and recorded speech. It has not been tried with a live microphone yet, no dongle has been built, and nothing has touched a real console. Expect rough edges and please report them.
45
+
46
+ ## Install
47
+
48
+ ```
49
+ pipx install "heystella[all]"
50
+ ```
51
+
52
+ or with pip:
53
+
54
+ ```
55
+ pip install "heystella[all]"
56
+ ```
57
+
58
+ Python 3.11 or newer. The extras are optional:
59
+
60
+ | Extra | Adds | For |
61
+ | --- | --- | --- |
62
+ | `voice` | vosk, sounddevice | Speech recognition from a microphone |
63
+ | `keys` | pynput | Pressing keys in the Stella emulator |
64
+ | `serial` | pyserial | Talking to the dongle over USB |
65
+
66
+ A plain `pip install heystella` has no dependencies and can still run profiles from typed input. On Linux the microphone needs PortAudio, for example `sudo apt install libportaudio2`.
67
+
68
+ ## Use
69
+
70
+ ```
71
+ heystella --list # the game profiles that come with it
72
+ heystella pitfall --input text # type phrases, see what the joystick does
73
+ heystella pitfall # speak, see what the joystick does
74
+ heystella pitfall --backend keys # speak, and press keys in Stella
75
+ heystella pitfall --backend serial:/dev/ttyACM0 # speak, and drive the dongle
76
+ heystella my-game.toml --input wav:take.wav # test your own profile against a recording
77
+ ```
78
+
79
+ The first spoken run downloads a 40MB speech model to `~/.cache/vosk`. After that everything runs offline.
80
+
81
+ ## Game profiles
82
+
83
+ A profile is a short TOML file that says what each spoken word does in one game.
84
+
85
+ ```toml
86
+ [game]
87
+ title = "Space Invaders"
88
+
89
+ [profile]
90
+ author = "your-name"
91
+ mode = "joystick"
92
+
93
+ [words]
94
+ left = { hold = ["left"] }
95
+ right = { hold = ["right"] }
96
+ stop = { release = "all" }
97
+ fire = { tap = ["fire"], aliases = ["shoot"] }
98
+ ```
99
+
100
+ Five starter profiles are included. To write your own, pass the path to your `.toml` file in place of a profile name.
101
+
102
+ ## More
103
+
104
+ The hardware design, the token protocol for homebrew games, a test ROM and the project plan are in the repository.
105
+
106
+ MIT licence. Atari and Atari 2600 are trademarks of their owner. Stella is also the name of an emulator, which this project works with and is not part of. No connection to either.
@@ -0,0 +1,69 @@
1
+ # Hey Stella
2
+
3
+ Voice control for the Atari 2600. Say "left" and the console sees a joystick pushed left.
4
+
5
+ This package is the host program. It listens to a microphone, recognises the words in a game profile, and turns them into joystick actions. Those go to the Stella emulator as key presses, or to a small build-it-yourself dongle that plugs into a real console's joystick port.
6
+
7
+ **Early software.** It works with typed input and recorded speech. It has not been tried with a live microphone yet, no dongle has been built, and nothing has touched a real console. Expect rough edges and please report them.
8
+
9
+ ## Install
10
+
11
+ ```
12
+ pipx install "heystella[all]"
13
+ ```
14
+
15
+ or with pip:
16
+
17
+ ```
18
+ pip install "heystella[all]"
19
+ ```
20
+
21
+ Python 3.11 or newer. The extras are optional:
22
+
23
+ | Extra | Adds | For |
24
+ | --- | --- | --- |
25
+ | `voice` | vosk, sounddevice | Speech recognition from a microphone |
26
+ | `keys` | pynput | Pressing keys in the Stella emulator |
27
+ | `serial` | pyserial | Talking to the dongle over USB |
28
+
29
+ A plain `pip install heystella` has no dependencies and can still run profiles from typed input. On Linux the microphone needs PortAudio, for example `sudo apt install libportaudio2`.
30
+
31
+ ## Use
32
+
33
+ ```
34
+ heystella --list # the game profiles that come with it
35
+ heystella pitfall --input text # type phrases, see what the joystick does
36
+ heystella pitfall # speak, see what the joystick does
37
+ heystella pitfall --backend keys # speak, and press keys in Stella
38
+ heystella pitfall --backend serial:/dev/ttyACM0 # speak, and drive the dongle
39
+ heystella my-game.toml --input wav:take.wav # test your own profile against a recording
40
+ ```
41
+
42
+ The first spoken run downloads a 40MB speech model to `~/.cache/vosk`. After that everything runs offline.
43
+
44
+ ## Game profiles
45
+
46
+ A profile is a short TOML file that says what each spoken word does in one game.
47
+
48
+ ```toml
49
+ [game]
50
+ title = "Space Invaders"
51
+
52
+ [profile]
53
+ author = "your-name"
54
+ mode = "joystick"
55
+
56
+ [words]
57
+ left = { hold = ["left"] }
58
+ right = { hold = ["right"] }
59
+ stop = { release = "all" }
60
+ fire = { tap = ["fire"], aliases = ["shoot"] }
61
+ ```
62
+
63
+ Five starter profiles are included. To write your own, pass the path to your `.toml` file in place of a profile name.
64
+
65
+ ## More
66
+
67
+ The hardware design, the token protocol for homebrew games, a test ROM and the project plan are in the repository.
68
+
69
+ MIT licence. Atari and Atari 2600 are trademarks of their owner. Stella is also the name of an emulator, which this project works with and is not part of. No connection to either.
@@ -0,0 +1 @@
1
+ """Hey Stella host: listens for words and drives an Atari 2600 joystick port."""
@@ -0,0 +1,184 @@
1
+ """Command line for the Hey Stella host.
2
+
3
+ python -m heystella pitfall listen on the microphone, print actions
4
+ python -m heystella pitfall --input text type phrases instead of speaking
5
+ python -m heystella pitfall --backend keys press keys in the Stella emulator
6
+ python -m heystella pitfall --backend serial:/dev/tty.usbmodem101
7
+ python -m heystella pitfall --input wav:take.wav run a recording and report latency
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import argparse
13
+ import queue
14
+ import sys
15
+ import threading
16
+ import time
17
+ import wave
18
+
19
+ from . import backends
20
+ from .engine import Engine
21
+ from .profiles import PROFILE_DIR, ProfileError, load, profile_paths
22
+ from .recognise import SAMPLE_RATE
23
+
24
+ CHUNK = SAMPLE_RATE // 20 # 50 ms of audio
25
+ DONE = object()
26
+
27
+
28
+ def version() -> str:
29
+ from importlib.metadata import PackageNotFoundError, version as installed
30
+
31
+ try:
32
+ return installed("heystella")
33
+ except PackageNotFoundError:
34
+ return "(running from a checkout)"
35
+
36
+
37
+ def warn_missing(listener) -> None:
38
+ if listener.missing:
39
+ print("These words are not in the speech model and will never be heard: " + ", ".join(listener.missing))
40
+
41
+
42
+ def run_live(engine: Engine, items: queue.Queue, to_phrases) -> None:
43
+ """Take microphone audio or typed lines from a queue until it ends."""
44
+ ending = False
45
+ while True:
46
+ deadline = engine.next_deadline()
47
+ if ending and deadline is None:
48
+ return
49
+ wait = 0.05 if deadline is None else max(0.0, min(0.05, deadline - time.monotonic()))
50
+ try:
51
+ item = items.get(timeout=wait)
52
+ except queue.Empty:
53
+ item = None
54
+ if item is DONE:
55
+ ending = True
56
+ elif item is not None:
57
+ for phrase in to_phrases(item):
58
+ if engine.say(phrase):
59
+ print(f"heard: {phrase}")
60
+ else:
61
+ print(f"not in this profile: {phrase}")
62
+ engine.tick()
63
+
64
+
65
+ def run_text(engine: Engine) -> None:
66
+ items: queue.Queue = queue.Queue()
67
+
68
+ def read_lines():
69
+ for line in sys.stdin:
70
+ if line.strip():
71
+ items.put(line.strip().lower())
72
+ items.put(DONE)
73
+
74
+ threading.Thread(target=read_lines, daemon=True).start()
75
+ print("Type a phrase and press Return. Ctrl-D to finish.")
76
+ run_live(engine, items, lambda line: [line])
77
+
78
+
79
+ def run_mic(engine: Engine, listener) -> None:
80
+ import sounddevice
81
+
82
+ items: queue.Queue = queue.Queue()
83
+ stream = sounddevice.RawInputStream(
84
+ samplerate=SAMPLE_RATE, blocksize=CHUNK, dtype="int16", channels=1,
85
+ callback=lambda data, frames, when, status: items.put(bytes(data)),
86
+ )
87
+ with stream:
88
+ print("Listening. Ctrl-C to stop.")
89
+ run_live(engine, items, listener.accept)
90
+
91
+
92
+ def run_wav(engine: Engine, listener, path: str) -> None:
93
+ """Play a recording through the recogniser, using the audio's own clock."""
94
+ with wave.open(path, "rb") as wav:
95
+ if (wav.getframerate(), wav.getnchannels(), wav.getsampwidth()) != (SAMPLE_RATE, 1, 2):
96
+ sys.exit(f"{path} must be 16 kHz, mono, 16-bit. Convert it first.")
97
+ audio = wav.readframes(wav.getnframes())
98
+ audio += bytes(SAMPLE_RATE * 2) # a second of silence so the last word is finished off
99
+ for start in range(0, len(audio), CHUNK * 2):
100
+ for phrase in listener.accept(audio[start:start + CHUNK * 2]):
101
+ print(f"{listener.heard_s:7.2f}s heard: {phrase}")
102
+ engine.say(phrase)
103
+ engine.tick()
104
+ if listener.latencies:
105
+ print("\nSeconds from the end of a word to acting on it:")
106
+ for phrase, seconds in listener.latencies:
107
+ print(f" {phrase:<16} {seconds:5.2f}")
108
+ values = sorted(s for _, s in listener.latencies)
109
+ print(f" median {values[len(values) // 2]:.2f}, worst {values[-1]:.2f}, {len(values)} phrases")
110
+
111
+
112
+ def main(argv=None) -> int:
113
+ parser = argparse.ArgumentParser(prog="heystella", description="Voice control for the Atari 2600.")
114
+ parser.add_argument("profile", nargs="?", help="profile name such as pitfall, or a path to a .toml file")
115
+ parser.add_argument("--backend", default="print", help="print, keys, or serial:<device>. Default print")
116
+ parser.add_argument("--input", default="mic", help="mic, text, or wav:<file>. Default mic")
117
+ parser.add_argument("--model", help="Vosk model name or folder. Default is the small English model")
118
+ parser.add_argument("--list", action="store_true", help="list the profiles and stop")
119
+ parser.add_argument("--version", action="version", version=f"heystella {version()}")
120
+ args = parser.parse_args(argv)
121
+
122
+ if args.list or not args.profile:
123
+ for path in profile_paths(PROFILE_DIR):
124
+ if path.stem != "_template":
125
+ print(path.stem)
126
+ if not args.list:
127
+ print("\nPick one, for example: heystella pitfall --input text")
128
+ return 0
129
+
130
+ try:
131
+ profile = load(args.profile)
132
+ except ProfileError as error:
133
+ print(error)
134
+ return 1
135
+ print(f"{profile.title}: {', '.join(profile.phrases)}")
136
+
137
+ try:
138
+ listener = None
139
+ clock = time.monotonic
140
+ if args.input != "text":
141
+ from .recognise import VoskListener
142
+
143
+ listener = VoskListener(profile.phrases, args.model)
144
+ warn_missing(listener)
145
+ if args.input.startswith("wav:"):
146
+ clock = lambda: listener.heard_s # noqa: E731
147
+
148
+ if args.backend == "print" and args.input.startswith("wav:"):
149
+ backend = backends.PrintBackend(out=lambda text: print(f"{clock():7.2f}s{text}"))
150
+ else:
151
+ backend = backends.make(args.backend, profile.port)
152
+ engine = Engine(profile, backend, clock)
153
+ except ImportError as error:
154
+ extra = {"vosk": "voice", "sounddevice": "voice", "pynput": "keys", "serial": "serial"}.get(error.name or "", "all")
155
+ print(f"That needs an extra package ({error.name}). Install it with: pip install 'heystella[{extra}]'")
156
+ return 1
157
+ except (ValueError, OSError) as error:
158
+ # An unknown backend name, or a serial device that would not open.
159
+ print(error)
160
+ return 1
161
+
162
+ try:
163
+ if args.input == "text":
164
+ run_text(engine)
165
+ elif args.input == "mic":
166
+ run_mic(engine, listener)
167
+ elif args.input.startswith("wav:"):
168
+ run_wav(engine, listener, args.input.split(":", 1)[1])
169
+ else:
170
+ print(f"unknown input {args.input!r}. Use mic, text or wav:<file>")
171
+ return 1
172
+ except KeyboardInterrupt:
173
+ print()
174
+ except ImportError as error:
175
+ print(f"That needs an extra package ({error.name}). Install it with: pip install 'heystella[voice]'")
176
+ return 1
177
+ finally:
178
+ engine.release_all()
179
+ backend.close()
180
+ return 0
181
+
182
+
183
+ if __name__ == "__main__":
184
+ sys.exit(main())
@@ -0,0 +1,168 @@
1
+ """Where joystick states and tokens go: the screen, an emulator, or the dongle.
2
+
3
+ Every backend has set_state(mask), send_token(token), idle(now) and close().
4
+ The mask uses the bits in engine.py: up 1, down 2, left 4, right 8, fire 16.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import time
10
+
11
+ from .engine import DOWN, FIRE, LEFT, RIGHT, UP, lines_of
12
+
13
+
14
+ def nibble_mask(nibble: int) -> int:
15
+ """Direction lines for one half of a token. See docs/token-spec.md."""
16
+ mask = 0
17
+ if nibble & 8:
18
+ mask |= RIGHT
19
+ if nibble & 4:
20
+ mask |= LEFT
21
+ if nibble & 2:
22
+ mask |= DOWN
23
+ if nibble & 1:
24
+ mask |= UP
25
+ return mask
26
+
27
+
28
+ def token_timeline(token: int) -> list[tuple[int, int]]:
29
+ """The joystick states that send one token, as (milliseconds, mask) steps."""
30
+ steps = []
31
+ at = 0
32
+ for nibble in (token >> 4, token & 0x0F):
33
+ lines = nibble_mask(nibble)
34
+ steps.append((at, lines)) # directions first
35
+ steps.append((at + 5, lines | FIRE)) # then fire, the "read now" signal
36
+ steps.append((at + 55, lines)) # fire off before the directions move
37
+ steps.append((at + 60, 0))
38
+ at += 110
39
+ return steps
40
+
41
+
42
+ class PrintBackend:
43
+ """Shows what would be sent. For trying a profile with nothing plugged in."""
44
+
45
+ def __init__(self, out=print):
46
+ self.out = out
47
+
48
+ def set_state(self, mask: int) -> None:
49
+ self.out(" joystick: " + (" + ".join(lines_of(mask)) or "released"))
50
+
51
+ def send_token(self, token: int) -> None:
52
+ self.out(f" token: ${token:02X}")
53
+
54
+ def idle(self, now: float) -> None:
55
+ pass
56
+
57
+ def close(self) -> None:
58
+ pass
59
+
60
+
61
+ class RecordBackend:
62
+ """Remembers everything it is sent. For tests."""
63
+
64
+ def __init__(self):
65
+ self.states: list[int] = []
66
+ self.tokens: list[int] = []
67
+
68
+ def set_state(self, mask: int) -> None:
69
+ self.states.append(mask)
70
+
71
+ def send_token(self, token: int) -> None:
72
+ self.tokens.append(token)
73
+
74
+ def idle(self, now: float) -> None:
75
+ pass
76
+
77
+ def close(self) -> None:
78
+ pass
79
+
80
+
81
+ class KeysBackend:
82
+ """Presses keys in whichever window has focus. Meant for the Stella emulator.
83
+
84
+ The keys are Stella 7's defaults: arrows and Space for the left joystick,
85
+ Y H G J and F for the right. macOS asks for Accessibility permission the
86
+ first time.
87
+ """
88
+
89
+ def __init__(self, port: str = "left"):
90
+ from pynput.keyboard import Controller, Key
91
+
92
+ self.keyboard = Controller()
93
+ if port == "left":
94
+ self.keys = {UP: Key.up, DOWN: Key.down, LEFT: Key.left, RIGHT: Key.right, FIRE: Key.space}
95
+ else:
96
+ self.keys = {UP: "y", DOWN: "h", LEFT: "g", RIGHT: "j", FIRE: "f"}
97
+ self.mask = 0
98
+
99
+ def set_state(self, mask: int) -> None:
100
+ for bit, key in self.keys.items():
101
+ if mask & bit and not self.mask & bit:
102
+ self.keyboard.press(key)
103
+ elif self.mask & bit and not mask & bit:
104
+ self.keyboard.release(key)
105
+ self.mask = mask
106
+
107
+ def send_token(self, token: int) -> None:
108
+ # The dongle does this timing in firmware. Here the computer does it, which
109
+ # is accurate enough for an emulator.
110
+ self.set_state(0)
111
+ time.sleep(0.1)
112
+ start = time.monotonic()
113
+ for at_ms, mask in token_timeline(token):
114
+ time.sleep(max(0.0, start + at_ms / 1000 - time.monotonic()))
115
+ self.set_state(mask)
116
+
117
+ def idle(self, now: float) -> None:
118
+ pass
119
+
120
+ def close(self) -> None:
121
+ self.set_state(0)
122
+
123
+
124
+ class SerialBackend:
125
+ """Sends J and T commands to the dongle. See docs/token-spec.md."""
126
+
127
+ KEEPALIVE_S = 1.0
128
+
129
+ def __init__(self, device: str, baud: int = 115200):
130
+ import serial
131
+
132
+ self.port = serial.Serial(device, baud, timeout=0.2, write_timeout=0.5)
133
+ self.mask = 0
134
+ self.last_sent = 0.0
135
+
136
+ def _send(self, line: str) -> None:
137
+ # No flush here. Waiting for the bytes to drain can block the whole loop
138
+ # if the dongle stops reading, and a stuck host is worse than a late byte.
139
+ self.port.write((line + "\n").encode("ascii"))
140
+ self.last_sent = time.monotonic()
141
+
142
+ def set_state(self, mask: int) -> None:
143
+ self.mask = mask
144
+ self._send(f"J{mask:02X}")
145
+
146
+ def send_token(self, token: int) -> None:
147
+ self._send(f"T{token:02X}")
148
+
149
+ def idle(self, now: float) -> None:
150
+ # The dongle lets go of everything if it hears nothing for 5 seconds, so
151
+ # repeat the state while anything is held.
152
+ if self.mask and time.monotonic() - self.last_sent >= self.KEEPALIVE_S:
153
+ self._send(f"J{self.mask:02X}")
154
+
155
+ def close(self) -> None:
156
+ self._send("J00")
157
+ self.port.close()
158
+
159
+
160
+ def make(spec: str, port: str = "left"):
161
+ """Build a backend from a command-line value: print, keys, or serial:/dev/..."""
162
+ if spec == "print":
163
+ return PrintBackend()
164
+ if spec == "keys":
165
+ return KeysBackend(port)
166
+ if spec.startswith("serial:"):
167
+ return SerialBackend(spec.split(":", 1)[1])
168
+ raise ValueError(f"unknown backend {spec!r}. Use print, keys or serial:<device>")
@@ -0,0 +1,103 @@
1
+ """Turns spoken phrases into joystick states over time.
2
+
3
+ The engine knows nothing about audio or hardware. Give it a profile, a backend
4
+ and a clock. Call say() when a phrase is heard and tick() often.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import time
10
+ from typing import Callable
11
+
12
+ from .profiles import Profile
13
+
14
+ UP, DOWN, LEFT, RIGHT, FIRE = 1, 2, 4, 8, 16
15
+ LINE_BITS = {"up": UP, "down": DOWN, "left": LEFT, "right": RIGHT, "fire": FIRE}
16
+ OPPOSITE = {"left": "right", "right": "left", "up": "down", "down": "up"}
17
+
18
+
19
+ def mask_of(lines) -> int:
20
+ mask = 0
21
+ for line in lines:
22
+ mask |= LINE_BITS[line]
23
+ return mask
24
+
25
+
26
+ def lines_of(mask: int) -> list[str]:
27
+ return [name for name, bit in LINE_BITS.items() if mask & bit]
28
+
29
+
30
+ class Engine:
31
+ def __init__(self, profile: Profile, backend, clock: Callable[[], float] = time.monotonic):
32
+ self.profile = profile
33
+ self.backend = backend
34
+ self.clock = clock
35
+ self.held: set[str] = set()
36
+ # Timed presses as (start, end, lines), in the order they were asked for.
37
+ self.pulses: list[tuple[float, float, tuple[str, ...]]] = []
38
+ self.last_mask = 0
39
+
40
+ def say(self, phrase: str) -> bool:
41
+ """Act on a phrase. Returns False if the profile does not know it."""
42
+ entry = self.profile.spoken.get(phrase)
43
+ if entry is None:
44
+ return False
45
+ now = self.clock()
46
+ if "token" in entry:
47
+ self.backend.send_token(entry["token"])
48
+ elif "tap" in entry:
49
+ ms = entry.get("ms", self.profile.tap_ms)
50
+ self.pulses.append((now, now + ms / 1000, tuple(entry["tap"])))
51
+ elif "hold" in entry:
52
+ for line in entry["hold"]:
53
+ self.held.discard(OPPOSITE.get(line, ""))
54
+ self.held.add(line)
55
+ elif "release" in entry:
56
+ if entry["release"] == "all":
57
+ self.held.clear()
58
+ self.pulses.clear()
59
+ else:
60
+ self.held.difference_update(entry["release"])
61
+ elif "sequence" in entry:
62
+ at = now
63
+ for step in entry["sequence"]:
64
+ if "wait" in step:
65
+ at += step["wait"] / 1000
66
+ else:
67
+ end = at + step["ms"] / 1000
68
+ self.pulses.append((at, end, tuple(step["press"])))
69
+ at = end
70
+ self.tick()
71
+ return True
72
+
73
+ def mask(self, now: float) -> int:
74
+ pressed = set(self.held)
75
+ for start, end, lines in self.pulses:
76
+ if start <= now < end:
77
+ # A timed press wins over a held opposite, and a later press over an
78
+ # earlier one. Left and right are never down together.
79
+ for line in lines:
80
+ pressed.discard(OPPOSITE.get(line, ""))
81
+ pressed.update(lines)
82
+ return mask_of(pressed)
83
+
84
+ def tick(self) -> None:
85
+ """Send the current state to the backend if it has changed."""
86
+ now = self.clock()
87
+ self.pulses = [p for p in self.pulses if p[1] > now]
88
+ mask = self.mask(now)
89
+ if mask != self.last_mask:
90
+ self.backend.set_state(mask)
91
+ self.last_mask = mask
92
+ self.backend.idle(now)
93
+
94
+ def next_deadline(self) -> float | None:
95
+ """When tick() next needs to run, or None if nothing is scheduled."""
96
+ now = self.clock()
97
+ times = [t for start, end, _ in self.pulses for t in (start, end) if t > now]
98
+ return min(times) if times else None
99
+
100
+ def release_all(self) -> None:
101
+ self.held.clear()
102
+ self.pulses.clear()
103
+ self.tick()