halo-emulator 2.0.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 (32) hide show
  1. halo_emulator-2.0.0/.gitignore +8 -0
  2. halo_emulator-2.0.0/PKG-INFO +21 -0
  3. halo_emulator-2.0.0/pyproject.toml +49 -0
  4. halo_emulator-2.0.0/src/halo_emulator/__init__.py +5 -0
  5. halo_emulator-2.0.0/src/halo_emulator/adapter.py +258 -0
  6. halo_emulator-2.0.0/src/halo_emulator/cli.py +164 -0
  7. halo_emulator-2.0.0/src/halo_emulator/display.py +522 -0
  8. halo_emulator-2.0.0/src/halo_emulator/emulator.py +320 -0
  9. halo_emulator-2.0.0/src/halo_emulator/event_queue.py +35 -0
  10. halo_emulator-2.0.0/src/halo_emulator/gfx_fonts.py +269 -0
  11. halo_emulator-2.0.0/src/halo_emulator/lua_runtime.py +232 -0
  12. halo_emulator-2.0.0/src/halo_emulator/recorder.py +105 -0
  13. halo_emulator-2.0.0/src/halo_emulator/stubs/__init__.py +0 -0
  14. halo_emulator-2.0.0/src/halo_emulator/stubs/bluetooth.py +62 -0
  15. halo_emulator-2.0.0/src/halo_emulator/stubs/button.py +36 -0
  16. halo_emulator-2.0.0/src/halo_emulator/stubs/compression.py +31 -0
  17. halo_emulator-2.0.0/src/halo_emulator/stubs/file_stubs.py +63 -0
  18. halo_emulator-2.0.0/src/halo_emulator/stubs/imu.py +144 -0
  19. halo_emulator-2.0.0/src/halo_emulator/stubs/microphone.py +137 -0
  20. halo_emulator-2.0.0/src/halo_emulator/stubs/sound.py +76 -0
  21. halo_emulator-2.0.0/src/halo_emulator/stubs/speaker.py +24 -0
  22. halo_emulator-2.0.0/src/halo_emulator/stubs/system.py +137 -0
  23. halo_emulator-2.0.0/src/halo_emulator/stubs/time_stubs.py +87 -0
  24. halo_emulator-2.0.0/tests/conftest.py +18 -0
  25. halo_emulator-2.0.0/tests/lua/ble_echo.lua +5 -0
  26. halo_emulator-2.0.0/tests/lua/draw_shapes.lua +6 -0
  27. halo_emulator-2.0.0/tests/lua/event_callbacks.lua +14 -0
  28. halo_emulator-2.0.0/tests/lua/hello_display.lua +4 -0
  29. halo_emulator-2.0.0/tests/test_bluetooth.py +75 -0
  30. halo_emulator-2.0.0/tests/test_display.py +97 -0
  31. halo_emulator-2.0.0/tests/test_events.py +101 -0
  32. halo_emulator-2.0.0/tests/test_firmware_parity.py +340 -0
@@ -0,0 +1,8 @@
1
+ __pycache__/
2
+ *.pyc
3
+ *.pyo
4
+ *.egg-info/
5
+ dist/
6
+ build/
7
+ .pytest_cache/
8
+ .venv/
@@ -0,0 +1,21 @@
1
+ Metadata-Version: 2.5
2
+ Name: halo-emulator
3
+ Version: 2.0.0
4
+ Summary: Emulator for the Brilliant Labs Halo smart glasses Lua runtime
5
+ Author: luke-brilliant
6
+ Classifier: License :: OSI Approved :: BSD License
7
+ Classifier: Operating System :: OS Independent
8
+ Classifier: Programming Language :: Python :: 3
9
+ Requires-Python: >=3.10
10
+ Requires-Dist: lupa<3.0,>=2.0
11
+ Requires-Dist: lz4<5.0.0,>=4.4.3
12
+ Requires-Dist: numpy<3.0.0,>=2.2.3
13
+ Requires-Dist: pillow<12.0.0,>=11.1.0
14
+ Requires-Dist: pygame<3.0.0,>=2.5.0
15
+ Provides-Extra: dev
16
+ Requires-Dist: brilliant-msg>=7.0.0; extra == 'dev'
17
+ Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
18
+ Requires-Dist: pytest>=8.0; extra == 'dev'
19
+ Provides-Extra: video
20
+ Requires-Dist: imageio-ffmpeg>=0.5.0; extra == 'video'
21
+ Requires-Dist: imageio>=2.34.0; extra == 'video'
@@ -0,0 +1,49 @@
1
+ [build-system]
2
+ requires = ["hatchling"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "halo-emulator"
7
+ version = "2.0.0"
8
+ requires-python = ">=3.10"
9
+ dependencies = [
10
+ "lupa>=2.0,<3.0",
11
+ "numpy>=2.2.3,<3.0.0",
12
+ "pillow>=11.1.0,<12.0.0",
13
+ "lz4>=4.4.3,<5.0.0",
14
+ "pygame>=2.5.0,<3.0.0",
15
+ ]
16
+ authors = [
17
+ { name = "luke-brilliant" },
18
+ ]
19
+ description = "Emulator for the Brilliant Labs Halo smart glasses Lua runtime"
20
+ classifiers = [
21
+ "Programming Language :: Python :: 3",
22
+ "License :: OSI Approved :: BSD License",
23
+ "Operating System :: OS Independent",
24
+ ]
25
+
26
+ [project.optional-dependencies]
27
+ dev = [
28
+ "pytest>=8.0",
29
+ "pytest-asyncio>=0.23",
30
+ "brilliant-msg>=7.0.0",
31
+ ]
32
+ video = [
33
+ "imageio>=2.34.0",
34
+ "imageio-ffmpeg>=0.5.0",
35
+ ]
36
+
37
+ [project.scripts]
38
+ halo-emulator = "halo_emulator.cli:main"
39
+
40
+ [tool.hatch.build.targets.wheel]
41
+ packages = ["src/halo_emulator"]
42
+
43
+ [tool.hatch.build.targets.sdist]
44
+ include = [
45
+ "/src",
46
+ "/tests",
47
+ ]
48
+
49
+ [tool.pytest.ini_options]
@@ -0,0 +1,5 @@
1
+ from halo_emulator.emulator import HaloEmulator
2
+ from halo_emulator.adapter import EmulatorBrilliantMsg
3
+ from halo_emulator.recorder import VideoRecorder
4
+
5
+ __all__ = ["HaloEmulator", "EmulatorBrilliantMsg", "VideoRecorder"]
@@ -0,0 +1,258 @@
1
+ """
2
+ EmulatorBrilliantMsg — a BrilliantMsg-compatible async adapter for HaloEmulator.
3
+
4
+ Provides the same interface as ``brilliant_msg.BrilliantMsg`` so that host-side Python
5
+ scripts can switch between real Halo hardware and the emulator by changing a
6
+ single line:
7
+
8
+ # Real hardware
9
+ from brilliant_msg import BrilliantMsg
10
+ frame = BrilliantMsg()
11
+
12
+ # Emulator
13
+ from halo_emulator import HaloEmulator, EmulatorBrilliantMsg
14
+ frame = EmulatorBrilliantMsg(HaloEmulator())
15
+
16
+ The adapter bridges the async BrilliantMsg API to HaloEmulator's synchronous,
17
+ thread-based model:
18
+
19
+ - ``send_lua()`` calls ``execute_lua()`` directly (REPL mode, no running loop).
20
+ - ``send_message()`` frames the payload and calls ``inject_bluetooth_data()``.
21
+ - ``register_data_response_handler()`` installs a listener on the Bluetooth
22
+ stub; when Lua calls ``frame.bluetooth.send()``, the listener dispatches the
23
+ data to the matching handler (same msg_code routing as BrilliantMsg).
24
+ """
25
+ from __future__ import annotations
26
+
27
+ import asyncio
28
+ import shutil
29
+ from pathlib import Path
30
+ from typing import Callable
31
+
32
+ from halo_emulator.emulator import HaloEmulator
33
+
34
+
35
+ class EmulatorBrilliantMsg:
36
+ """
37
+ BrilliantMsg-compatible adapter for HaloEmulator.
38
+
39
+ Parameters
40
+ ----------
41
+ emulator:
42
+ A ``HaloEmulator`` instance. The adapter adds a send-listener to the
43
+ emulator's Bluetooth stub on construction; you should not add another
44
+ listener independently.
45
+ """
46
+
47
+ def __init__(self, emulator: HaloEmulator) -> None:
48
+ self._emu = emulator
49
+ self._data_response_handlers: dict[int, list[tuple[object, Callable]]] = {}
50
+ # Route Lua bluetooth.send() output back to Python handlers.
51
+ # This listener is called from the Lua thread — handlers must be synchronous.
52
+ self._emu._bluetooth.add_send_listener(self._on_lua_send)
53
+
54
+ # ------------------------------------------------------------------ internal
55
+
56
+ def _on_lua_send(self, data: bytes) -> None:
57
+ """Called from the Lua thread whenever Lua calls frame.bluetooth.send()."""
58
+ if not data:
59
+ return
60
+ msg_code = data[0]
61
+ for _, handler in self._data_response_handlers.get(msg_code, []):
62
+ handler(data)
63
+
64
+ def _frame_message(self, msg_code: int, payload: bytes) -> bytes:
65
+ """Build the framed packet that data.lua expects on its receive_callback."""
66
+ total = len(payload)
67
+ return bytes([msg_code, total >> 8, total & 0xFF]) + payload
68
+
69
+ # ------------------------------------------------------------------ lifecycle
70
+
71
+ async def connect(self, initialize: bool = True) -> bool:
72
+ """
73
+ Initialize the Lua runtime (REPL mode — no script is started).
74
+
75
+ Call :meth:`upload_frame_app` + :meth:`start_frame_app` afterwards to
76
+ run a full Lua app, or use :meth:`send_lua` for direct REPL commands.
77
+ """
78
+ self._emu.connect()
79
+ return True
80
+
81
+ async def disconnect(self) -> None:
82
+ """Stop the emulator."""
83
+ self._emu.stop()
84
+
85
+ def is_connected(self) -> bool:
86
+ return self._emu._lua is not None
87
+
88
+ # ------------------------------------------------------------------ REPL mode
89
+
90
+ async def send_lua(
91
+ self,
92
+ code: str,
93
+ await_print: bool = False,
94
+ show_me: bool = False,
95
+ ) -> None:
96
+ """
97
+ Execute a Lua snippet directly.
98
+
99
+ Only valid in REPL mode (after :meth:`connect`, before
100
+ :meth:`start_frame_app`). Mirrors ``BrilliantMsg.send_lua()``.
101
+
102
+ Note: ``await_print`` is accepted for API compatibility but has no
103
+ effect — Lua ``print()`` output goes to the emulator's print_handler.
104
+ """
105
+ self._emu.execute_lua(code)
106
+
107
+ async def print_short_text(self, text: str = "") -> None:
108
+ """Display text before the main app starts (REPL mode convenience)."""
109
+ sanitized = text.replace("'", "\\'").replace("\n", "")
110
+ await self.send_lua(
111
+ f"frame.display.text('{sanitized}', 1, 1, 0xFFFFFF); frame.display.show()"
112
+ )
113
+
114
+ # ------------------------------------------------------------------ app lifecycle
115
+
116
+ async def upload_stdlua_libs(
117
+ self,
118
+ lib_names: list[str] | None = None,
119
+ minified: bool = True,
120
+ ) -> None:
121
+ """
122
+ Copy brilliant_msg standard Lua libraries into the emulator sandbox.
123
+
124
+ These are the same files uploaded to real hardware (``data.min.lua``,
125
+ ``plain_text.min.lua``, etc.). Requires ``brilliant-msg`` to be installed.
126
+ """
127
+ if lib_names is None:
128
+ lib_names = ["data"]
129
+ try:
130
+ from importlib.resources import files
131
+ pkg = files("brilliant_msg")
132
+ except ImportError as exc:
133
+ raise ImportError(
134
+ "upload_stdlua_libs() requires brilliant-msg to be installed: "
135
+ "pip install brilliant-msg"
136
+ ) from exc
137
+
138
+ for lib in lib_names:
139
+ suffix = ".min" if minified else ""
140
+ content = pkg.joinpath(f"lua/{lib}{suffix}.lua").read_text(encoding="utf-8")
141
+ dst = self._emu._sandbox_dir / f"{lib}{suffix}.lua"
142
+ dst.write_text(content, encoding="utf-8")
143
+
144
+ async def upload_frame_app(
145
+ self,
146
+ local_filename: str,
147
+ frame_filename: str = "frame_app.lua",
148
+ ) -> None:
149
+ """Copy a Lua app file into the emulator sandbox."""
150
+ shutil.copy2(local_filename, self._emu._sandbox_dir / frame_filename)
151
+
152
+ async def start_frame_app(
153
+ self,
154
+ frame_app_name: str = "frame_app",
155
+ await_print: bool = True,
156
+ ) -> None:
157
+ """
158
+ Start the Lua app in the emulator.
159
+
160
+ If ``await_print`` is True (default), waits 300 ms for the app to
161
+ register its callbacks — equivalent to waiting for the first print()
162
+ on real hardware.
163
+ """
164
+ self._emu.start(script_name=f"{frame_app_name}.lua")
165
+ if await_print:
166
+ await asyncio.sleep(0.3)
167
+
168
+ async def stop_frame_app(self, reset: bool = True) -> None:
169
+ """Stop the running Lua app."""
170
+ self._emu.stop()
171
+
172
+ # ------------------------------------------------------------------ message passing
173
+
174
+ async def send_message(
175
+ self,
176
+ msg_code: int,
177
+ payload: bytes,
178
+ show_me: bool = False,
179
+ ) -> None:
180
+ """
181
+ Send a structured message to the running Lua app.
182
+
183
+ Frames the payload exactly as ``BrilliantBle.send_message()`` does, then
184
+ injects it via ``inject_bluetooth_data()``. The entire payload is sent
185
+ as one packet (no MTU chunking) since the emulator has no BLE MTU limit.
186
+
187
+ The Lua-side ``data.lua`` library will reassemble and parse it normally.
188
+ """
189
+ packet = self._frame_message(msg_code, payload)
190
+ self._emu.inject_bluetooth_data(packet)
191
+ # Yield briefly so the Lua thread can process the data and send its ACK
192
+ await asyncio.sleep(0.05)
193
+
194
+ def register_data_response_handler(
195
+ self,
196
+ subscriber: object,
197
+ msg_codes: list[int],
198
+ handler: Callable[[bytes], None],
199
+ ) -> None:
200
+ """
201
+ Register a handler for Lua→host messages on specific msg codes.
202
+
203
+ Mirrors ``BrilliantMsg.register_data_response_handler()``. The handler
204
+ receives the full raw bytes (first byte is the msg_code, same as on
205
+ real hardware).
206
+
207
+ The handler is called synchronously from the Lua thread — it must be a
208
+ plain function, not a coroutine.
209
+ """
210
+ for code in msg_codes:
211
+ self._data_response_handlers.setdefault(code, []).append((subscriber, handler))
212
+
213
+ def unregister_data_response_handler(self, subscriber: object) -> None:
214
+ """Unregister all handlers for a subscriber."""
215
+ for code in list(self._data_response_handlers):
216
+ self._data_response_handlers[code] = [
217
+ (sub, h)
218
+ for sub, h in self._data_response_handlers[code]
219
+ if sub != subscriber
220
+ ]
221
+
222
+ # ------------------------------------------------------------------ print handler
223
+
224
+ def attach_print_response_handler(self, handler: Callable = print) -> None:
225
+ """Route Lua print() output to *handler*."""
226
+ self._emu._print_handler = handler
227
+ if self._emu._lua is not None:
228
+ self._emu._lua.globals().print = handler
229
+
230
+ def detach_print_response_handler(self) -> None:
231
+ """Stop routing Lua print() output."""
232
+ self._emu._print_handler = None
233
+
234
+ # ------------------------------------------------------------------ emulator extras
235
+
236
+ def get_framebuffer(self):
237
+ """Return the current display as a 256×256 PIL Image."""
238
+ return self._emu.get_framebuffer()
239
+
240
+ def get_bluetooth_sent(self) -> list[bytes]:
241
+ """Return all data the Lua app has sent via frame.bluetooth.send()."""
242
+ return self._emu.get_bluetooth_sent()
243
+
244
+ def inject_bluetooth_data(self, data: bytes) -> None:
245
+ """Inject raw bytes into the Lua app's receive_callback (emulator only)."""
246
+ self._emu.inject_bluetooth_data(data)
247
+
248
+ def inject_button_single(self) -> None:
249
+ self._emu.inject_button_single()
250
+
251
+ def inject_button_double(self) -> None:
252
+ self._emu.inject_button_double()
253
+
254
+ def inject_button_long(self) -> None:
255
+ self._emu.inject_button_long()
256
+
257
+ def inject_imu_tap(self) -> None:
258
+ self._emu.inject_imu_tap()
@@ -0,0 +1,164 @@
1
+ """halo-emulator CLI entry point."""
2
+ from __future__ import annotations
3
+
4
+ import argparse
5
+ import code
6
+ import os
7
+ import threading
8
+ from pathlib import Path
9
+
10
+
11
+ def _pygame_window(emulator: object, stop_event: threading.Event) -> None: # type: ignore[type-arg]
12
+ """Run a pygame window showing the emulator display.
13
+
14
+ On macOS this must run on the main thread: SDL's Cocoa backend sets the
15
+ application main menu during video init, which AppKit only permits from the
16
+ main thread. The loop exits when the window is closed or ``stop_event`` is
17
+ set (e.g. when the REPL exits).
18
+ """
19
+ os.environ.setdefault("SDL_VIDEO_WINDOW_POS", "100,100")
20
+ import pygame
21
+
22
+ pygame.display.init()
23
+ scale = 2
24
+ screen = pygame.display.set_mode((256 * scale, 256 * scale))
25
+ pygame.display.set_caption("Halo Emulator")
26
+ clock = pygame.time.Clock()
27
+
28
+ key_map = {
29
+ pygame.K_SPACE: lambda: emulator.inject_button_single(),
30
+ pygame.K_d: lambda: emulator.inject_button_double(),
31
+ pygame.K_l: lambda: emulator.inject_button_long(),
32
+ pygame.K_t: lambda: emulator.inject_imu_tap("single"),
33
+ pygame.K_2: lambda: emulator.inject_imu_tap("double"),
34
+ pygame.K_3: lambda: emulator.inject_imu_tap("triple"),
35
+ }
36
+
37
+ win_size = 256 * scale
38
+ overlay = pygame.Surface((win_size, win_size), pygame.SRCALPHA)
39
+ overlay.fill((40, 40, 40, 210))
40
+ mask = pygame.Surface((win_size, win_size), pygame.SRCALPHA)
41
+ mask.fill((255, 255, 255, 255))
42
+ pygame.draw.circle(mask, (0, 0, 0, 0), (win_size // 2, win_size // 2), win_size // 2 - 8)
43
+ overlay.blit(mask, (0, 0), special_flags=pygame.BLEND_RGBA_MIN)
44
+
45
+ while not stop_event.is_set():
46
+ for event in pygame.event.get():
47
+ if event.type == pygame.QUIT:
48
+ stop_event.set()
49
+ break
50
+ elif event.type == pygame.KEYDOWN:
51
+ inject = key_map.get(event.key)
52
+ if inject:
53
+ inject()
54
+
55
+ img = emulator.get_framebuffer() # type: ignore[union-attr]
56
+ mode = img.mode
57
+ raw = img.tobytes()
58
+ surface = pygame.image.fromstring(raw, (256, 256), mode)
59
+ scaled = pygame.transform.scale(surface, (256 * scale, 256 * scale))
60
+ screen.blit(scaled, (0, 0))
61
+ screen.blit(overlay, (0, 0))
62
+ pygame.display.flip()
63
+ clock.tick(30)
64
+
65
+ pygame.display.quit()
66
+
67
+
68
+ def main() -> None:
69
+ parser = argparse.ArgumentParser(
70
+ prog="halo-emulator",
71
+ description="Halo smart glasses Lua emulator",
72
+ )
73
+ parser.add_argument(
74
+ "app_dir",
75
+ nargs="?",
76
+ default=None,
77
+ help="Directory containing Lua app files (loaded into sandbox)",
78
+ )
79
+ parser.add_argument(
80
+ "--script",
81
+ default="main.lua",
82
+ metavar="NAME",
83
+ help="Entry-point Lua filename (default: main.lua)",
84
+ )
85
+ parser.add_argument(
86
+ "--sandbox",
87
+ default=None,
88
+ metavar="DIR",
89
+ help="Explicit sandbox directory (default: app_dir or temp dir)",
90
+ )
91
+ parser.add_argument(
92
+ "--headless",
93
+ action="store_true",
94
+ help="Skip the pygame display window",
95
+ )
96
+ parser.add_argument(
97
+ "--record",
98
+ default=None,
99
+ metavar="OUTPUT",
100
+ help=(
101
+ "Record the display to a video file. "
102
+ "Use .gif for animated GIF (no extra deps) or "
103
+ ".mp4/.webm/.avi for video (requires imageio[ffmpeg])."
104
+ ),
105
+ )
106
+ parser.add_argument(
107
+ "--fps",
108
+ type=float,
109
+ default=30.0,
110
+ metavar="N",
111
+ help="Recording frame rate (default: 30)",
112
+ )
113
+ args = parser.parse_args()
114
+
115
+ from halo_emulator import HaloEmulator
116
+
117
+ sandbox = args.sandbox or args.app_dir
118
+ emulator = HaloEmulator(sandbox_dir=sandbox)
119
+
120
+ if args.app_dir:
121
+ emulator.load_directory(args.app_dir)
122
+ emulator.start(script_name=args.script)
123
+
124
+ if args.record:
125
+ emulator.start_recording(fps=args.fps)
126
+ print(f"[halo-emulator] Recording at {args.fps:.0f} fps → {args.record}")
127
+
128
+ banner = (
129
+ "Halo Emulator — 'emulator' is in scope\n"
130
+ "Keyboard (window): SPACE=single click, D=double, L=long, "
131
+ "T=tap, 2=double tap, 3=triple tap\n"
132
+ "Python API:\n"
133
+ " emulator.inject_bluetooth_data(b'...')\n"
134
+ " emulator.inject_button_single()\n"
135
+ " emulator.inject_imu_tap('single'|'double'|'triple')\n"
136
+ " emulator.get_framebuffer().save('frame.png')\n"
137
+ " emulator.get_bluetooth_sent()\n"
138
+ " emulator.start_recording(fps=30) / emulator.stop_recording('out.mp4')\n"
139
+ )
140
+
141
+ if args.headless:
142
+ code.interact(local={"emulator": emulator}, banner=banner)
143
+ else:
144
+ # The pygame window must own the main thread (macOS Cocoa requires GUI
145
+ # init on the main thread), so the REPL runs on a background thread.
146
+ stop_event = threading.Event()
147
+
148
+ def _run_repl() -> None:
149
+ try:
150
+ code.interact(local={"emulator": emulator}, banner=banner)
151
+ finally:
152
+ stop_event.set()
153
+
154
+ repl_thread = threading.Thread(target=_run_repl, daemon=True, name="repl")
155
+ repl_thread.start()
156
+ try:
157
+ _pygame_window(emulator, stop_event)
158
+ except KeyboardInterrupt:
159
+ stop_event.set()
160
+
161
+ emulator.stop()
162
+
163
+ if args.record:
164
+ emulator.stop_recording(args.record)