plasma-app 2.2.4__tar.gz → 2.3.1__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 (80) hide show
  1. {plasma_app-2.2.4 → plasma_app-2.3.1}/PKG-INFO +4 -2
  2. {plasma_app-2.2.4 → plasma_app-2.3.1}/README.md +4 -2
  3. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/__init__.py +1 -1
  4. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/__main__.py +27 -1
  5. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/config.py +54 -31
  6. plasma_app-2.3.1/plasma/devices/qb2.py +332 -0
  7. plasma_app-2.3.1/plasma/devices/qb2_config.py +147 -0
  8. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/integrated_panel.py +170 -31
  9. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/plugins.py +9 -3
  10. plasma_app-2.3.1/plasma/task_buzzer.py +97 -0
  11. plasma_app-2.3.1/plasma/task_sequence.py +130 -0
  12. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma_app.egg-info/PKG-INFO +4 -2
  13. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma_app.egg-info/SOURCES.txt +3 -0
  14. plasma_app-2.2.4/plasma/devices/qb2.py +0 -85
  15. {plasma_app-2.2.4 → plasma_app-2.3.1}/LICENSE +0 -0
  16. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/__pyinstaller/__init__.py +0 -0
  17. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/__pyinstaller/hook-plasma.py +0 -0
  18. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/api.py +0 -0
  19. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/app_context.py +0 -0
  20. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/build_info.py +0 -0
  21. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/ctl.py +0 -0
  22. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/desktop_shortcut.py +0 -0
  23. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/__init__.py +0 -0
  24. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/bitalino.py +0 -0
  25. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/__init__.py +0 -0
  26. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/ble_scan.py +0 -0
  27. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/bleak_probe.py +0 -0
  28. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/bleak_reconnect_test.py +0 -0
  29. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/config.py +0 -0
  30. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/detect.py +0 -0
  31. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/device.py +0 -0
  32. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/extract/__init__.py +0 -0
  33. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/extract/__main__.py +0 -0
  34. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/extract/clocksync.py +0 -0
  35. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/extract/options.py +0 -0
  36. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/extract/pipeline.py +0 -0
  37. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/formats/__init__.py +0 -0
  38. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/gyro_bias.py +0 -0
  39. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/nus_sim.py +0 -0
  40. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/nus_stream.py +0 -0
  41. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/panels/__init__.py +0 -0
  42. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/panels/_common.py +0 -0
  43. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/panels/clocksync.py +0 -0
  44. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/panels/control.py +0 -0
  45. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/panels/downloader.py +0 -0
  46. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/panels/extractor.py +0 -0
  47. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/panels/imu.py +0 -0
  48. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/panels/sqc.py +0 -0
  49. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/panels/tools.py +0 -0
  50. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/panels/uuid_tools.py +0 -0
  51. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/panels/viewer.py +0 -0
  52. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/quaternion.py +0 -0
  53. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/records.py +0 -0
  54. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense/signal_quality.py +0 -0
  55. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense_demo/__init__.py +0 -0
  56. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense_demo/config.py +0 -0
  57. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense_demo/device.py +0 -0
  58. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense_demo/fake_stream.py +0 -0
  59. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/msense_demo/faults.py +0 -0
  60. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/obs.py +0 -0
  61. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/pupil_labs.py +0 -0
  62. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/shimmer.py +0 -0
  63. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/devices/template.py +0 -0
  64. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/journal.py +0 -0
  65. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/lsl_recorder.py +0 -0
  66. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/lsl_session.py +0 -0
  67. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/lsl_util.py +0 -0
  68. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/plot_util.py +0 -0
  69. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/resources/icons/plasma.icns +0 -0
  70. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/resources/icons/plasma.ico +0 -0
  71. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/resources/icons/plasma.png +0 -0
  72. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/resources/icons/plasma.svg +0 -0
  73. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/status.py +0 -0
  74. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma/xdf_writer.py +0 -0
  75. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma_app.egg-info/dependency_links.txt +0 -0
  76. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma_app.egg-info/entry_points.txt +0 -0
  77. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma_app.egg-info/requires.txt +0 -0
  78. {plasma_app-2.2.4 → plasma_app-2.3.1}/plasma_app.egg-info/top_level.txt +0 -0
  79. {plasma_app-2.2.4 → plasma_app-2.3.1}/pyproject.toml +0 -0
  80. {plasma_app-2.2.4 → plasma_app-2.3.1}/setup.cfg +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: plasma-app
3
- Version: 2.2.4
3
+ Version: 2.3.1
4
4
  Summary: PLASMA — Platform for LSL-based Acquisition of Sensor Metrics and Analytics
5
5
  License: MIT
6
6
  Project-URL: Homepage, https://github.com/YuyiChang/PLASMA
@@ -117,7 +117,9 @@ plugins: `msense`, `qb2`, `pupil`, `shimmer`, `obs` (and `all`).
117
117
 
118
118
  ## Known issue / future works
119
119
 
120
- - [ ] need manually set lidar ip addr
120
+ - [x] Multiple QB2 LiDARs configurable with individual addresses, optional keys,
121
+ and enable switches; point clouds share the session recording folder —
122
+ [QB2 recording & review](docs/reference/qb2-recording.md)
121
123
  - [ ] the built-in LSL→XDF recorder captures **every** stream on the default
122
124
  liblsl session, so a concurrent `pytest` run or another lab tool leaks
123
125
  into the recording; re-Initialize doesn't fully tear down old outlets.
@@ -64,7 +64,9 @@ plugins: `msense`, `qb2`, `pupil`, `shimmer`, `obs` (and `all`).
64
64
 
65
65
  ## Known issue / future works
66
66
 
67
- - [ ] need manually set lidar ip addr
67
+ - [x] Multiple QB2 LiDARs configurable with individual addresses, optional keys,
68
+ and enable switches; point clouds share the session recording folder —
69
+ [QB2 recording & review](docs/reference/qb2-recording.md)
68
70
  - [ ] the built-in LSL→XDF recorder captures **every** stream on the default
69
71
  liblsl session, so a concurrent `pytest` run or another lab tool leaks
70
72
  into the recording; re-Initialize doesn't fully tear down old outlets.
@@ -109,4 +111,4 @@ a disposable run.
109
111
  ## references
110
112
 
111
113
  - qb2: https://docs.blickfeld.com/qb2/Qb2/v1.10/guides/api.html
112
- - pupil-labs: https://pupil-labs.github.io/pl-realtime-api/dev/
114
+ - pupil-labs: https://pupil-labs.github.io/pl-realtime-api/dev/
@@ -1,4 +1,4 @@
1
- __version__ = "2.2.4"
1
+ __version__ = "2.3.1"
2
2
 
3
3
  # Short git commit hash baked in by CI (.github/workflows/build.yml) just
4
4
  # before a release build is frozen with PyInstaller — a frozen bundle ships no
@@ -6,6 +6,7 @@ import gradio as gr
6
6
  from plasma import plugins
7
7
  from plasma.app_context import app_context
8
8
  from plasma.integrated_panel import IntegratedPanel
9
+ from plasma.task_buzzer import BUZZER_JS
9
10
  from plasma.config import device_config
10
11
  from plasma import api as plasma_api
11
12
 
@@ -99,6 +100,25 @@ function refresh() {
99
100
  });
100
101
  obs.observe(document.body, {childList: true, subtree: true});
101
102
  window.addEventListener('pagehide', () => obs.disconnect(), {once: true});
103
+ """ + BUZZER_JS + """
104
+ // SPACE starts a ready task only while its controls are visible. Let
105
+ // inputs, buttons and other keyboard controls retain their native behavior.
106
+ const taskKey = (event) => {
107
+ if (event.code !== 'Space' || event.repeat || event.altKey ||
108
+ event.ctrlKey || event.metaKey || event.shiftKey) return;
109
+ if (event.target.closest('input, textarea, button, select, a, [role="tab"], [contenteditable="true"]')) return;
110
+ for (const control of document.querySelectorAll('#plasma-task-start, #plasma-focus-task-start')) {
111
+ const button = control.matches('button') ? control : control.querySelector('button');
112
+ if (button && !button.disabled && button.getClientRects().length) {
113
+ event.preventDefault();
114
+ unlockAudio();
115
+ button.click();
116
+ break;
117
+ }
118
+ }
119
+ };
120
+ document.addEventListener('keydown', taskKey);
121
+ window.addEventListener('pagehide', () => document.removeEventListener('keydown', taskKey), {once: true});
102
122
  }
103
123
  """
104
124
 
@@ -107,11 +127,15 @@ def build_blocks(ip):
107
127
  the given `IntegratedPanel`. Shared by `main()` and the screenshot-capture
108
128
  tool (`scripts/capture_screenshots.py`) so both build the identical UI.
109
129
  Does not launch the server."""
110
- with gr.Blocks(title=app_context().app_name, theme=gr.themes.Ocean(), js=js_func) as app:
130
+ with gr.Blocks(title=app_context().app_name, theme=gr.themes.Ocean(), js=js_func,
131
+ css="#plasma-focus-memo {max-height: calc(100vh - 180px); overflow-y: auto;} "
132
+ "#plasma-buzzer-event {display:none;}") as app:
111
133
  yams_title = None
112
134
  with gr.Tabs() as top_tabs:
113
135
  with gr.Tab("Session Dashboard"):
114
136
  ip.interface()
137
+ with gr.Tab("Focus"):
138
+ ip.focus_interface()
115
139
  with gr.Tab("Data Dashboard"):
116
140
  ip.visualizer_interface()
117
141
  # extra tabs contributed by enabled plugins (e.g. MSense SQC / IMU).
@@ -134,6 +158,8 @@ def build_blocks(ip):
134
158
  # pl.interface()
135
159
 
136
160
  _wire_plot_timer_gate(ip, top_tabs, yams_title)
161
+ ip.wire_session_views(top_tabs)
162
+ ip.wire_task_buzzer()
137
163
 
138
164
  # stop any live MSense stream when the last browser tab goes away — a
139
165
  # continuous stream with nobody watching just churns the BLE radio and
@@ -11,6 +11,7 @@ from plasma.app_context import app_context
11
11
  _DEFAULTS = {
12
12
  "enabled_devices": [],
13
13
  "ip_qb2_lidar": "",
14
+ "qb2_api_key": "",
14
15
  "ip_pupil_labs": "",
15
16
  "plugins": {},
16
17
  # when True, plugins.load_plugins() also registers the simulated MSense
@@ -25,6 +26,7 @@ class DeviceConfig:
25
26
  cfg = self._load()
26
27
  self._active = list(cfg["enabled_devices"])
27
28
  self.ip_lidar = cfg["ip_qb2_lidar"]
29
+ self.qb2_api_key = cfg["qb2_api_key"]
28
30
  self.ip_pupil_labs = cfg["ip_pupil_labs"]
29
31
  # env var wins so a wrapper / CI can force demo mode without touching
30
32
  # the saved file
@@ -47,6 +49,7 @@ class DeviceConfig:
47
49
  return {
48
50
  "enabled_devices": list(raw.get("enabled_devices", [])),
49
51
  "ip_qb2_lidar": raw.get("ip_qb2_lidar", ""),
52
+ "qb2_api_key": raw.get("qb2_api_key", ""),
50
53
  "ip_pupil_labs": raw.get("ip_pupil_labs", ""),
51
54
  "plugins": dict(raw.get("plugins", {})),
52
55
  "demo_mode": bool(raw.get("demo_mode", False)),
@@ -58,6 +61,7 @@ class DeviceConfig:
58
61
  return {
59
62
  "enabled_devices": [],
60
63
  "ip_qb2_lidar": "",
64
+ "qb2_api_key": "",
61
65
  "ip_pupil_labs": "",
62
66
  "plugins": {},
63
67
  "demo_mode": False,
@@ -67,14 +71,23 @@ class DeviceConfig:
67
71
  def _save(self):
68
72
  path = app_context().config_path
69
73
  os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
70
- with open(path, 'w') as f:
71
- json.dump({
72
- "enabled_devices": self._active,
73
- "ip_qb2_lidar": self.ip_lidar,
74
- "ip_pupil_labs": self.ip_pupil_labs,
75
- "plugins": self.plugins,
76
- "demo_mode": self.demo_mode,
77
- }, f, indent=2)
74
+ # Atomic replacement avoids a truncated config after interruption;
75
+ # mkstemp also keeps application keys owner-readable only (POSIX).
76
+ fd, temporary = tempfile.mkstemp(prefix=".plasma-config-", dir=os.path.dirname(path) or ".")
77
+ try:
78
+ with os.fdopen(fd, 'w') as f:
79
+ json.dump({
80
+ "enabled_devices": self._active,
81
+ "ip_qb2_lidar": self.ip_lidar,
82
+ "qb2_api_key": self.qb2_api_key,
83
+ "ip_pupil_labs": self.ip_pupil_labs,
84
+ "plugins": self.plugins,
85
+ "demo_mode": self.demo_mode,
86
+ }, f, indent=2)
87
+ os.replace(temporary, path)
88
+ finally:
89
+ if os.path.exists(temporary):
90
+ os.unlink(temporary)
78
91
 
79
92
  def refresh_defaults(self):
80
93
  """Run once from ``main()`` after ``plugins.load_plugins()``: fill the
@@ -100,24 +113,33 @@ class DeviceConfig:
100
113
  return self.plugins.get(plugin_id, {})
101
114
 
102
115
  def update_plugin_config(self, plugin_id, blob):
116
+ missing = object()
117
+ previous = self.plugins.get(plugin_id, missing)
103
118
  self.plugins[plugin_id] = blob
104
- self._save()
119
+ try:
120
+ self._save()
121
+ except Exception:
122
+ if previous is missing:
123
+ self.plugins.pop(plugin_id, None)
124
+ else:
125
+ self.plugins[plugin_id] = previous
126
+ raise
105
127
 
106
128
  # ── UI callbacks ──────────────────────────────────────────────────────────
107
129
 
108
- def _apply(self, selected, ip_lidar, ip_pupil_labs, demo_mode):
130
+ def _apply(self, selected, ip_pupil_labs, demo_mode):
109
131
  self._active = list(selected)
110
- self.ip_lidar = ip_lidar
111
132
  self.ip_pupil_labs = ip_pupil_labs
112
133
  self.demo_mode = bool(demo_mode) or bool(os.environ.get("PLASMA_DEMO"))
113
134
  self._save()
114
135
  note = " — restart PLASMA to load the simulated device" if self.demo_mode else ""
115
136
  return f"Saved — {len(self._active)} device type(s) enabled{note}"
116
137
 
117
- def _export_config(self, selected, ip_lidar, ip_pupil_labs):
138
+ def _export_config(self, selected, ip_pupil_labs):
118
139
  config = {
119
140
  "enabled_devices": selected,
120
- "ip_qb2_lidar": ip_lidar,
141
+ "ip_qb2_lidar": self.ip_lidar,
142
+ "qb2_api_key": self.qb2_api_key,
121
143
  "ip_pupil_labs": ip_pupil_labs,
122
144
  "plugins": self.plugins,
123
145
  "demo_mode": self.demo_mode,
@@ -129,7 +151,7 @@ class DeviceConfig:
129
151
 
130
152
  def _import_config(self, file):
131
153
  if file is None:
132
- return gr.update(), gr.update(), gr.update(), ""
154
+ return gr.update(), gr.update(), ""
133
155
  try:
134
156
  with open(file, 'r') as f:
135
157
  raw = json.load(f)
@@ -138,27 +160,29 @@ class DeviceConfig:
138
160
  unknown = [d for d in raw.get("enabled_devices", []) if d not in catalog]
139
161
  ip_lidar = raw.get("ip_qb2_lidar", self.ip_lidar)
140
162
  ip_pupil = raw.get("ip_pupil_labs", self.ip_pupil_labs)
141
- if "plugins" in raw:
142
- # plugin config sections re-render from get_plugin_config on the
143
- # next Configuration-tab visit
144
- self.plugins = dict(raw["plugins"])
145
- self._active = enabled
146
- self.ip_lidar = ip_lidar
147
- self.ip_pupil_labs = ip_pupil
148
- self.demo_mode = (bool(raw.get("demo_mode", self.demo_mode))
149
- or bool(os.environ.get("PLASMA_DEMO")))
150
- self._save()
151
- msg = f"Loaded — {len(enabled)} device type(s)"
163
+ qb2_api_key = raw.get("qb2_api_key", "") or ""
164
+ from plasma.devices.qb2_config import device_records
165
+ imported_plugins = dict(raw.get("plugins", self.plugins))
166
+ imported_plugins["qb2"] = {"devices": device_records(
167
+ raw.get("plugins", {}).get("qb2", {}), raw.get("ip_qb2_lidar", ""), qb2_api_key)}
168
+ self.plugins = imported_plugins
169
+ self._active = enabled
170
+ self.ip_lidar = ip_lidar
171
+ self.qb2_api_key = qb2_api_key
172
+ self.ip_pupil_labs = ip_pupil
173
+ self.demo_mode = (bool(raw.get("demo_mode", self.demo_mode))
174
+ or bool(os.environ.get("PLASMA_DEMO")))
175
+ self._save()
176
+ msg = f"Loaded — {len(enabled)} device type(s); click Reload saved LiDARs to refresh the QB2 editor"
152
177
  if unknown:
153
178
  msg += f" (skipped unknown: {', '.join(unknown)})"
154
179
  return (
155
180
  gr.update(value=enabled),
156
- gr.update(value=ip_lidar),
157
181
  gr.update(value=ip_pupil),
158
182
  msg,
159
183
  )
160
184
  except Exception as e:
161
- return gr.update(), gr.update(), gr.update(), f"Import error: {e}"
185
+ return gr.update(), gr.update(), f"Import error: {e}"
162
186
 
163
187
  # ── Gradio interface ──────────────────────────────────────────────────────
164
188
 
@@ -179,7 +203,6 @@ class DeviceConfig:
179
203
  )
180
204
 
181
205
  with gr.Accordion("Network settings", open=True):
182
- ip_lidar_txt = gr.Text(value=self.ip_lidar, label="QB2 LiDAR IP address")
183
206
  ip_pupil_txt = gr.Text(value=self.ip_pupil_labs, label="Pupil Labs IP address")
184
207
 
185
208
  with gr.Row():
@@ -192,18 +215,18 @@ class DeviceConfig:
192
215
 
193
216
  btn_apply.click(
194
217
  self._apply,
195
- inputs=[checkbox_group, ip_lidar_txt, ip_pupil_txt, demo_mode_chk],
218
+ inputs=[checkbox_group, ip_pupil_txt, demo_mode_chk],
196
219
  outputs=status,
197
220
  )
198
221
  btn_export.click(
199
222
  self._export_config,
200
- inputs=[checkbox_group, ip_lidar_txt, ip_pupil_txt],
223
+ inputs=[checkbox_group, ip_pupil_txt],
201
224
  outputs=[export_file, status],
202
225
  )
203
226
  file_import.change(
204
227
  self._import_config,
205
228
  inputs=file_import,
206
- outputs=[checkbox_group, ip_lidar_txt, ip_pupil_txt, status],
229
+ outputs=[checkbox_group, ip_pupil_txt, status],
207
230
  )
208
231
 
209
232
  # Per-plugin Configuration sections. Each owns its own Apply button
@@ -0,0 +1,332 @@
1
+ """Blickfeld QB2 capture: full frames on disk, frame IDs over LSL.
2
+
3
+ The SDK's async API lets Stop cancel a pending network read. A bounded writer
4
+ queue absorbs short disk stalls without accumulating unbounded point clouds.
5
+ """
6
+ import asyncio
7
+ from datetime import datetime, timezone
8
+ import os
9
+ from pathlib import Path
10
+ import threading
11
+ import time
12
+ import uuid
13
+
14
+ try:
15
+ import blickfeld_qb2
16
+ except ImportError:
17
+ blickfeld_qb2 = None # optional plugin dependency; keep other sensors usable
18
+ import numpy as np
19
+ from pylsl import StreamInfo, StreamOutlet, local_clock
20
+
21
+ from plasma.config import plasma_config
22
+ from plasma.devices.template import PlasmaDevice, PlasmaMemo
23
+ from plasma.devices.qb2_config import configured_devices
24
+ from plasma.lsl_util import mark_plasma_origin
25
+
26
+
27
+ class Qb2Unit(PlasmaDevice):
28
+ STREAM_NAME = "blickfield_qb2" # retain the existing stream name for consumers
29
+ FRAME_TIMEOUT_S = 10.0
30
+ STOP_TIMEOUT_S = 5.0
31
+ WRITE_QUEUE_SIZE = 8
32
+
33
+ def __init__(self, session_info, logger=None, tag="qb2 LiDAR", *,
34
+ address=None, api_key=None, device_id=None):
35
+ super().__init__(session_info, logger, tag)
36
+ self.memo = PlasmaMemo(tag)
37
+ self.addr = (address if address is not None else plasma_config.ip_lidar or "").strip()
38
+ self._api_key = (api_key if api_key is not None else plasma_config.qb2_api_key or "").strip()
39
+ self.device_id = device_id
40
+ self.stream_name = f"{self.STREAM_NAME}_{device_id}" if device_id else self.STREAM_NAME
41
+ self._loop = None
42
+ self._reader = None
43
+ self._state_lock = threading.Lock()
44
+ self._fault = None
45
+ self.outlet = None
46
+ self.out_dir = None
47
+ if not self.addr:
48
+ self._fail(ValueError("Set the QB2 LiDAR IP address in Configuration"))
49
+ return
50
+ if blickfeld_qb2 is None:
51
+ self._fail(ImportError('Install the QB2 SDK with pip install "plasma-app[qb2]"'))
52
+ return
53
+ info = StreamInfo(self.stream_name, "Image", 1, 8, "string",
54
+ f"plasma-qb2-{self.addr}-{uuid.uuid4().hex}")
55
+ info.desc().append_child_value("frame_id_encoding", "decimal uint64")
56
+ info.desc().append_child_value("timestamp_reference", "host receipt, LSL local_clock")
57
+ info.desc().append_child_value("device_address", self.addr)
58
+ info.desc().append_child_value("device_label", tag)
59
+ try:
60
+ self.outlet = StreamOutlet(mark_plasma_origin(info))
61
+ except Exception as error:
62
+ self._fail(error)
63
+ return
64
+ # Channel creation is lazy; the first frame verifies transport and auth.
65
+ self.memo.sts = "Ready"
66
+ self.memo.set_latest("Configured; connection will be checked on Start")
67
+
68
+ def lsl_streams(self):
69
+ return {self.stream_name: self.tag}
70
+
71
+ def _fail(self, error):
72
+ # Vendor exceptions can contain credentials; redact before logging/UI.
73
+ detail = str(error)
74
+ status = getattr(getattr(error, "status", None), "name", "")
75
+ if status in {"NOT_FOUND", "UNAUTHENTICATED", "PERMISSION_DENIED"}:
76
+ detail += "; check the QB2 application key and its account permissions in Configuration"
77
+ if self._api_key:
78
+ detail = detail.replace(self._api_key, "[redacted]")
79
+ self._fault = f"{type(error).__name__}: {detail}"
80
+ self.memo.sts = f"⛔ QB2 capture failed: {self._fault}"
81
+ self.memo.set_latest(self._fault)
82
+ self.info(self.memo.sts)
83
+
84
+ def start(self):
85
+ with self._state_lock:
86
+ if self._thread is not None and self._thread.is_alive():
87
+ raise RuntimeError("QB2 capture is still active; wait for Stop to finish")
88
+ if self.outlet is None:
89
+ raise RuntimeError(self._fault or "QB2 is not configured")
90
+ # Resolve at Start, after the panel injects its shared session folder.
91
+ root = self.session_dir or os.path.join(
92
+ self.session_info["log_dir"],
93
+ f"{self.session_info['participant_enc']}_{time.strftime('%y%m%d_%H%M%S')}")
94
+ self.out_dir = Path(root) / "qb2"
95
+ if self.device_id:
96
+ self.out_dir /= self.device_id
97
+ try:
98
+ self.out_dir.mkdir(parents=True, exist_ok=True)
99
+ except OSError as error:
100
+ self._fail(error)
101
+ raise
102
+ self._run_id = uuid.uuid4().hex
103
+ self._fault = None
104
+ self.frames_saved = 0
105
+ self._stop_event.clear()
106
+ self.memo.sts = "Starting..."
107
+ self.memo.set_latest(f"Connecting to {self.addr}")
108
+ self._thread = threading.Thread(target=self.streaming, daemon=True,
109
+ name="plasma-qb2")
110
+ self._thread.start()
111
+
112
+ def streaming(self):
113
+ try:
114
+ asyncio.run(self._capture())
115
+ except Exception as error:
116
+ self._fail(error)
117
+ finally:
118
+ with self._state_lock:
119
+ self._loop = None
120
+ self._reader = None
121
+ if self._fault is None:
122
+ self.memo.sts = "🟥 stopped"
123
+ self.memo.set_latest(f"Saved {self.frames_saved} frames to {self.out_dir}")
124
+
125
+ async def _capture(self):
126
+ queue = asyncio.Queue(maxsize=self.WRITE_QUEUE_SIZE)
127
+ reader_done = asyncio.Event()
128
+ loop = asyncio.get_running_loop()
129
+
130
+ async def receive():
131
+ try:
132
+ args = {"fqdn_or_ip": self.addr, "secure": True}
133
+ if self._api_key:
134
+ args["token"] = blickfeld_qb2.TokenFactory(
135
+ application_key_secret=self._api_key)
136
+ if self._stop_event.is_set():
137
+ return
138
+ with blickfeld_qb2.Channel(**args) as channel:
139
+ stream = blickfeld_qb2.core_processing.services.PointCloud(channel).async_stream()
140
+ try:
141
+ while not self._stop_event.is_set():
142
+ try:
143
+ response = await asyncio.wait_for(
144
+ stream.__anext__(), timeout=self.FRAME_TIMEOUT_S)
145
+ except StopAsyncIteration:
146
+ raise RuntimeError("Point-cloud stream ended unexpectedly") from None
147
+ except asyncio.TimeoutError:
148
+ raise TimeoutError(
149
+ f"No QB2 frame received for {self.FRAME_TIMEOUT_S:g} seconds; "
150
+ "check power, network, and application key") from None
151
+ if self._stop_event.is_set():
152
+ break
153
+ unix_now, lsl_now = time.time(), local_clock()
154
+ frame = response.frame
155
+ payload = {
156
+ "frame": frame,
157
+ "unix_time": unix_now,
158
+ "datetime": datetime.fromtimestamp(
159
+ unix_now, timezone.utc).isoformat(timespec="milliseconds"),
160
+ "lsl_time": lsl_now,
161
+ "device_id": self.device_id,
162
+ "device_address": self.addr,
163
+ }
164
+ try:
165
+ queue.put_nowait((payload, lsl_now))
166
+ except asyncio.QueueFull:
167
+ raise RuntimeError(
168
+ "QB2 disk writer cannot keep up (frame queue full); "
169
+ "capture halted to avoid silent data loss") from None
170
+ self.memo.sts = "🟢"
171
+ finally:
172
+ await stream.aclose()
173
+ except asyncio.CancelledError:
174
+ if not self._stop_event.is_set():
175
+ raise
176
+ finally:
177
+ reader_done.set()
178
+
179
+ async def write():
180
+ while not (reader_done.is_set() and queue.empty()):
181
+ try:
182
+ payload, lsl_now = await asyncio.wait_for(queue.get(), timeout=0.1)
183
+ except asyncio.TimeoutError:
184
+ continue
185
+ # Keep disk I/O off the event loop so network reads and Stop
186
+ # stay responsive. Only one write is in flight at a time.
187
+ path = await asyncio.to_thread(self._save_frame, payload)
188
+ self.frames_saved += 1
189
+ # Publish only after a complete file exists. Strings preserve
190
+ # uint64 frame IDs, which the old int32 outlet could overflow.
191
+ self.outlet.push_sample([str(payload["frame"].id)], timestamp=lsl_now)
192
+ self.memo.set_latest(
193
+ f"frame ID = {payload['frame'].id}; {self.frames_saved} saved → {path.name}")
194
+
195
+ reader = asyncio.create_task(receive())
196
+ writer = asyncio.create_task(write())
197
+ with self._state_lock:
198
+ self._loop, self._reader = loop, reader
199
+ if self._stop_event.is_set():
200
+ reader.cancel()
201
+ reader_done.set()
202
+ try:
203
+ done, _ = await asyncio.wait((reader, writer), return_when=asyncio.FIRST_COMPLETED)
204
+ if writer in done:
205
+ # A writer failure must interrupt a stalled network read.
206
+ await writer
207
+ try:
208
+ await reader
209
+ finally:
210
+ # Drain already accepted frames even on timeout/network failure.
211
+ await writer
212
+ finally:
213
+ for task in (reader, writer):
214
+ if not task.done():
215
+ task.cancel()
216
+ await asyncio.gather(reader, writer, return_exceptions=True)
217
+
218
+ def _save_frame(self, payload):
219
+ frame_id = int(payload["frame"].id)
220
+ path = self.out_dir / f"frame_{self._run_id}_{self.frames_saved:08d}_{frame_id}.npy"
221
+ partial = path.with_suffix(".npy.partial")
222
+ try:
223
+ with partial.open("xb") as handle:
224
+ np.save(handle, payload, allow_pickle=True)
225
+ os.replace(partial, path)
226
+ except BaseException:
227
+ partial.unlink(missing_ok=True)
228
+ raise
229
+ return path
230
+
231
+ def stop(self):
232
+ self.request_stop()
233
+ self.wait_stopped(self.STOP_TIMEOUT_S)
234
+
235
+ def request_stop(self):
236
+ """Signal without joining, so all LiDARs receive Stop immediately."""
237
+ self._stop_event.set()
238
+ with self._state_lock:
239
+ loop, reader = self._loop, self._reader
240
+ if loop is not None and reader is not None:
241
+ try:
242
+ loop.call_soon_threadsafe(reader.cancel)
243
+ except RuntimeError: # event loop finished while Stop acquired lock
244
+ pass
245
+
246
+ def wait_stopped(self, timeout):
247
+ thread = self._thread
248
+ if thread is not None and thread is not threading.current_thread():
249
+ thread.join(timeout=max(0, timeout))
250
+ if thread.is_alive():
251
+ self.memo.sts = "⛔ QB2 stop unconfirmed; capture worker still active"
252
+ raise RuntimeError("QB2 Stop timed out; wait for pending disk I/O before restarting")
253
+ if self._fault is None:
254
+ self.memo.sts = "🟥 stopped"
255
+
256
+ def disconnect(self):
257
+ self.stop()
258
+ # Drop the native outlet only after its producer has exited.
259
+ self.outlet = None
260
+
261
+
262
+ class Qb2(PlasmaDevice):
263
+ """One catalog plugin with independently monitored physical LiDAR units."""
264
+
265
+ def __init__(self, session_info, logger=None, tag="qb2 LiDAR"):
266
+ super().__init__(session_info, logger, tag)
267
+ self.units = {}
268
+ self.memo = {}
269
+ try:
270
+ records = configured_devices(plasma_config)
271
+ except ValueError as error:
272
+ memo = PlasmaMemo(tag)
273
+ memo.sts = "⛔ Invalid QB2 device settings"
274
+ memo.set_latest(str(error))
275
+ self.memo[tag] = memo
276
+ return
277
+ for row in records:
278
+ if not row["enabled"]:
279
+ continue
280
+ identity = row["id"]
281
+ unit = Qb2Unit(session_info, logger, f"{row['name']} [{row['address']}]",
282
+ address=row["address"], api_key=row["api_key"], device_id=identity)
283
+ self.units[identity] = unit
284
+ self.memo[identity] = unit.memo
285
+ if not self.units:
286
+ memo = PlasmaMemo(tag)
287
+ memo.sts = "Ready"
288
+ memo.set_latest("No enabled LiDARs — add or enable devices in Configuration → QB2 LiDARs")
289
+ self.memo[tag] = memo
290
+
291
+ def lsl_streams(self):
292
+ return {unit.stream_name: identity for identity, unit in self.units.items()
293
+ if unit.outlet is not None}
294
+
295
+ def start(self):
296
+ if any(u._thread is not None and u._thread.is_alive() for u in self.units.values()):
297
+ raise RuntimeError("QB2 capture is still active; wait for Stop to finish")
298
+ # Compute one fallback path for standalone use, as the panel normally
299
+ # injects its own shared folder before this call.
300
+ root = self.session_dir or os.path.join(
301
+ self.session_info["log_dir"],
302
+ f"{self.session_info['participant_enc']}_{time.strftime('%y%m%d_%H%M%S')}")
303
+ for unit in self.units.values():
304
+ unit.session_info = self.session_info
305
+ unit.session_dir = root
306
+ unit.journal_hook = self.journal_hook
307
+ try:
308
+ unit.start()
309
+ except Exception as error:
310
+ unit._fail(error) # one broken unit must not block its peers
311
+
312
+ def stop(self):
313
+ for unit in self.units.values():
314
+ unit.request_stop()
315
+ # One total timeout, rather than N sequential five-second timeouts.
316
+ deadline = time.monotonic() + Qb2Unit.STOP_TIMEOUT_S
317
+ failed = 0
318
+ for unit in self.units.values():
319
+ try:
320
+ unit.wait_stopped(deadline - time.monotonic())
321
+ except RuntimeError:
322
+ failed += 1
323
+ if failed:
324
+ raise RuntimeError(f"QB2 Stop unconfirmed for {failed} LiDAR(s); wait for pending disk I/O")
325
+
326
+ def disconnect(self):
327
+ try:
328
+ self.stop()
329
+ finally:
330
+ for unit in self.units.values():
331
+ if unit._thread is None or not unit._thread.is_alive():
332
+ unit.outlet = None