nucleuskit-toolkit 2.2.2__tar.gz → 2.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 (80) hide show
  1. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/PKG-INFO +3 -3
  2. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/README.md +1 -1
  3. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/__init__.py +1 -1
  4. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/mqtt/mqtt_controller.py +133 -25
  5. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/pages/mqtt_controller_page.py +58 -16
  6. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit.egg-info/PKG-INFO +3 -3
  7. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit.egg-info/SOURCES.txt +1 -0
  8. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit.egg-info/requires.txt +1 -1
  9. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/pyproject.toml +2 -2
  10. nucleuskit_toolkit-2.3.0/tests/test_mqtt_controller.py +63 -0
  11. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/tests/test_plot_style.py +2 -3
  12. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/tests/test_ui_pages.py +6 -6
  13. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/LICENSE +0 -0
  14. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/__main__.py +0 -0
  15. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/app.py +0 -0
  16. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/camera/__init__.py +0 -0
  17. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/camera/processing.py +0 -0
  18. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/config.py +0 -0
  19. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/hermes/__init__.py +0 -0
  20. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/hermes/constants.py +0 -0
  21. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/hermes/realtime/__init__.py +0 -0
  22. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/hermes/realtime/proxy.py +0 -0
  23. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/logging_utils.py +0 -0
  24. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/mqtt/__init__.py +0 -0
  25. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/pipeline.py +0 -0
  26. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/position/__init__.py +0 -0
  27. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/position/gps_processor.py +0 -0
  28. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/session_job.py +0 -0
  29. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/shimmer/__init__.py +0 -0
  30. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/shimmer/constants.py +0 -0
  31. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/shimmer/realtime/__init__.py +0 -0
  32. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/shimmer/realtime/proxy.py +0 -0
  33. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/tools/__init__.py +0 -0
  34. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/tools/eeg_regression.py +0 -0
  35. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/tools/recording_merger.py +0 -0
  36. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/__init__.py +0 -0
  37. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/icons.py +0 -0
  38. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/main_window.py +0 -0
  39. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/offline_job.py +0 -0
  40. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/pages/__init__.py +0 -0
  41. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/pages/about_page.py +0 -0
  42. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/pages/channel_fixer_page.py +0 -0
  43. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/pages/channel_gain_page.py +0 -0
  44. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/pages/eeg_regression_page.py +0 -0
  45. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/pages/offline_page.py +0 -0
  46. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/pages/playback_helpers.py +0 -0
  47. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/pages/playback_page.py +0 -0
  48. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/pages/ppg_fixer_page.py +0 -0
  49. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/pages/realtime_viewer_page.py +0 -0
  50. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/pages/recording_merge_page.py +0 -0
  51. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/pages/revert_original_page.py +0 -0
  52. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/pages/settings_page.py +0 -0
  53. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/pages/tools_menu_page.py +0 -0
  54. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/plot_style.py +0 -0
  55. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/realtime_eeg_plot.py +0 -0
  56. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/realtime_hermes_motion_plot.py +0 -0
  57. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/realtime_nlms_config_dialog.py +0 -0
  58. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/realtime_shimmer_plot.py +0 -0
  59. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/resources/__init__.py +0 -0
  60. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/resources/branding/__init__.py +0 -0
  61. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/resources/branding/logo.png +0 -0
  62. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/session_inspect.py +0 -0
  63. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/theme.py +0 -0
  64. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit/ui/widgets.py +0 -0
  65. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit.egg-info/dependency_links.txt +0 -0
  66. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit.egg-info/entry_points.txt +0 -0
  67. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/nucleuskit_toolkit.egg-info/top_level.txt +0 -0
  68. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/setup.cfg +0 -0
  69. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/tests/test_config.py +0 -0
  70. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/tests/test_hermes_ble_stream.py +0 -0
  71. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/tests/test_imports.py +0 -0
  72. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/tests/test_logging_redirect.py +0 -0
  73. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/tests/test_offline_job.py +0 -0
  74. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/tests/test_open_core_references.py +0 -0
  75. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/tests/test_pipeline_cancel.py +0 -0
  76. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/tests/test_playback_plot.py +0 -0
  77. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/tests/test_realtime_scan.py +0 -0
  78. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/tests/test_release_pip.py +0 -0
  79. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/tests/test_session_inspect.py +0 -0
  80. {nucleuskit_toolkit-2.2.2 → nucleuskit_toolkit-2.3.0}/tests/test_session_video_rotation.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: nucleuskit-toolkit
3
- Version: 2.2.2
3
+ Version: 2.3.0
4
4
  Summary: Nucleus-Kit offline processing toolkit (Hermes EEG/EMG, Shimmer PPG/EDA)
5
5
  Author: RE-AK Technologies Inc.
6
6
  License-Expression: GPL-3.0-or-later
@@ -21,7 +21,7 @@ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
21
21
  Requires-Python: >=3.10
22
22
  Description-Content-Type: text/markdown
23
23
  License-File: LICENSE
24
- Requires-Dist: re-ak-core<1.1,>=1.0.2
24
+ Requires-Dist: re-ak-core<1.2,>=1.1.0
25
25
  Requires-Dist: numpy>=2.5
26
26
  Requires-Dist: pandas>=2.3
27
27
  Requires-Dist: scipy<1.18,>=1.17
@@ -155,7 +155,7 @@ python3 -m venv .venv
155
155
  .venv/bin/python -m pytest
156
156
  ```
157
157
 
158
- The re-ak-core clone satisfies Nucleus-Kit's `re-ak-core>=1.0.2,<1.1` requirement, so pip keeps it instead of
158
+ The re-ak-core clone satisfies Nucleus-Kit's `re-ak-core>=1.1.0,<1.2` requirement, so pip keeps it instead of
159
159
  downloading the published one. To reproduce the tested environment exactly, install `requirements.txt` instead of the
160
160
  `[dev,gui]` extras (it needs re-ak-core on PyPI).
161
161
 
@@ -114,7 +114,7 @@ python3 -m venv .venv
114
114
  .venv/bin/python -m pytest
115
115
  ```
116
116
 
117
- The re-ak-core clone satisfies Nucleus-Kit's `re-ak-core>=1.0.2,<1.1` requirement, so pip keeps it instead of
117
+ The re-ak-core clone satisfies Nucleus-Kit's `re-ak-core>=1.1.0,<1.2` requirement, so pip keeps it instead of
118
118
  downloading the published one. To reproduce the tested environment exactly, install `requirements.txt` instead of the
119
119
  `[dev,gui]` extras (it needs re-ak-core on PyPI).
120
120
 
@@ -1,3 +1,3 @@
1
1
  """Nucleus-Kit offline processing toolkit (``python -m nucleuskit_toolkit``)."""
2
2
 
3
- __version__ = "2.2.2"
3
+ __version__ = "2.3.0"
@@ -2,7 +2,13 @@
2
2
  MQTT controller for Vizia Mobile Android devices.
3
3
 
4
4
  Connects to a user-configured MQTT broker and drives recording sessions via
5
- the Vizia Mobile MQTT interface (see doc/mqtt_interface.md for the full contract).
5
+ the Vizia Mobile MQTT interface (see doc/mqtt_interface.md; source of truth:
6
+ viziaMobile2/MQTT_INTERFACE.md, contract v1).
7
+
8
+ Devices are discovered on ``{experimentId}/+/status`` when an experiment id is given, and on the legacy
9
+ shared ``vizia/status`` topic (phones without an experiment, local brokers only). Commands go to each
10
+ device's own control topic: ``{experimentId}/{recorderId}/control`` or, legacy, ``{recorderId}/control/``.
11
+ The broker address may be a URL (``mqtt://``, ``mqtts://``, ``ws://``, ``wss://``) for TLS / WebSocket.
6
12
 
7
13
  Thread-safety: paho-mqtt runs its own network loop in a background thread.
8
14
  All public methods are safe to call from any thread. GUI consumers should
@@ -17,6 +23,7 @@ import threading
17
23
  import time
18
24
  from dataclasses import dataclass, field
19
25
  from typing import Callable
26
+ from urllib.parse import urlparse
20
27
 
21
28
  DEFAULT_BROKER_PORT = 1883
22
29
  DEFAULT_STATUS_TOPIC = "vizia/status"
@@ -24,6 +31,42 @@ DEFAULT_COMMAND_TOPIC_SUFFIX = "control/"
24
31
 
25
32
  TARGET_ALL = "__ALL__"
26
33
 
34
+ _DEFAULT_PORTS = {"mqtt": 1883, "mqtts": 8883, "ws": 80, "wss": 443}
35
+
36
+
37
+ @dataclass(frozen=True)
38
+ class BrokerEndpoint:
39
+ scheme: str
40
+ host: str
41
+ port: int
42
+ path: str | None = None
43
+
44
+ @property
45
+ def tls(self) -> bool:
46
+ return self.scheme in ("mqtts", "wss")
47
+
48
+ @property
49
+ def websocket(self) -> bool:
50
+ return self.scheme in ("ws", "wss")
51
+
52
+
53
+ def parse_broker(address: str, fallback_port: int = DEFAULT_BROKER_PORT) -> BrokerEndpoint:
54
+ """Parse a broker URL, or a bare host / IP (plain TCP on ``fallback_port``)."""
55
+ text = address.strip()
56
+ if "://" not in text:
57
+ host, _, port = text.partition(":")
58
+ if not host:
59
+ raise ValueError("broker host required")
60
+ return BrokerEndpoint("mqtt", host, int(port) if port else fallback_port)
61
+ parsed = urlparse(text)
62
+ scheme = parsed.scheme.lower()
63
+ if scheme not in _DEFAULT_PORTS or not parsed.hostname:
64
+ raise ValueError(f"unsupported broker address: {address!r}")
65
+ path = None
66
+ if scheme in ("ws", "wss"):
67
+ path = parsed.path if parsed.path not in ("", "/") else "/mqtt"
68
+ return BrokerEndpoint(scheme, parsed.hostname, parsed.port or _DEFAULT_PORTS[scheme], path)
69
+
27
70
 
28
71
  @dataclass
29
72
  class DeviceStatus:
@@ -31,6 +74,11 @@ class DeviceStatus:
31
74
  recording: bool = False
32
75
  battery: int = -1
33
76
  last_seen: float = field(default_factory=time.time)
77
+ experiment_id: str | None = None
78
+ """Experiment of the device's topics; None for legacy topics."""
79
+ control_topic: str = ""
80
+ session_id: str | None = None
81
+ headset_connected: bool | None = None
34
82
 
35
83
 
36
84
  class MqttController:
@@ -40,14 +88,20 @@ class MqttController:
40
88
  Parameters
41
89
  ----------
42
90
  broker_host : str
43
- IP address or hostname of the MQTT broker.
91
+ Broker URL (``mqtt://``, ``mqtts://``, ``ws://``, ``wss://``) or bare IP / hostname.
44
92
  broker_port : int
45
- TCP port of the broker (default 1883).
93
+ TCP port for a bare IP / hostname (default 1883).
46
94
  status_topic : str
47
- Topic on which devices publish status packets (default "vizia/status").
95
+ Legacy shared status topic (default "vizia/status"); empty to listen only to the experiment.
48
96
  command_topic_suffix : str
49
- Suffix appended after ``{recorderId}/`` when publishing commands
97
+ Legacy suffix appended after ``{recorderId}/`` when publishing commands
50
98
  (default "control/").
99
+ experiment_id : str | None
100
+ Experiment whose devices to discover on ``{experimentId}/+/status``.
101
+ username, password : str | None
102
+ Broker login (per-device or per-controller account).
103
+ ca_file : str | None
104
+ CA certificate for TLS (the RE-AK private CA); None = system CAs.
51
105
  on_log : Callable[[str], None] | None
52
106
  Called from the paho network thread with human-readable log lines.
53
107
  on_device_update : Callable[[DeviceStatus], None] | None
@@ -64,15 +118,24 @@ class MqttController:
64
118
  broker_port: int = DEFAULT_BROKER_PORT,
65
119
  status_topic: str = DEFAULT_STATUS_TOPIC,
66
120
  command_topic_suffix: str = DEFAULT_COMMAND_TOPIC_SUFFIX,
121
+ experiment_id: str | None = None,
122
+ username: str | None = None,
123
+ password: str | None = None,
124
+ ca_file: str | None = None,
67
125
  on_log: Callable[[str], None] | None = None,
68
126
  on_device_update: Callable[[DeviceStatus], None] | None = None,
69
127
  on_connected: Callable[[], None] | None = None,
70
128
  on_disconnected: Callable[[], None] | None = None,
71
129
  ) -> None:
72
- self._broker_host = broker_host.strip()
73
- self._broker_port = broker_port
74
- self._status_topic = status_topic
130
+ self._endpoint = parse_broker(broker_host, broker_port)
131
+ self._broker_host = self._endpoint.host
132
+ self._broker_port = self._endpoint.port
133
+ self._status_topic = status_topic.strip()
75
134
  self._command_topic_suffix = command_topic_suffix
135
+ self._experiment_id = (experiment_id or "").strip() or None
136
+ self._username = username or None
137
+ self._password = password or None
138
+ self._ca_file = ca_file or None
76
139
  self._on_log = on_log
77
140
  self._on_device_update = on_device_update
78
141
  self._on_connected = on_connected
@@ -106,13 +169,21 @@ class MqttController:
106
169
  "Install with: pip install 'nucleuskit-toolkit[gui]'"
107
170
  ) from exc
108
171
 
109
- self._log(f"Connecting to broker {self._broker_host}:{self._broker_port} …")
172
+ ep = self._endpoint
173
+ self._log(f"Connecting to broker {ep.scheme}://{ep.host}:{ep.port} …")
110
174
 
111
175
  client = mqtt.Client(
112
176
  client_id=f"nucleuskit-{int(time.time())}",
113
177
  protocol=mqtt.MQTTv311,
114
178
  clean_session=True,
179
+ transport="websockets" if ep.websocket else "tcp",
115
180
  )
181
+ if ep.websocket:
182
+ client.ws_set_options(path=ep.path or "/mqtt")
183
+ if ep.tls:
184
+ client.tls_set(ca_certs=self._ca_file)
185
+ if self._username:
186
+ client.username_pw_set(self._username, self._password)
116
187
  client.on_connect = self._on_mqtt_connect
117
188
  client.on_disconnect = self._on_mqtt_disconnect
118
189
  client.on_message = self._on_mqtt_message
@@ -166,14 +237,59 @@ class MqttController:
166
237
  self._log("[WARN] No devices discovered yet — command not sent.")
167
238
  return
168
239
  for did in targets:
169
- topic = f"{did}/{self._command_topic_suffix}"
240
+ topic = self.control_topic(did)
170
241
  self._client.publish(topic, payload, qos=0)
171
242
  self._log(f"→ [{label}] → {topic}")
172
243
  else:
173
- topic = f"{device_id}/{self._command_topic_suffix}"
244
+ topic = self.control_topic(device_id)
174
245
  self._client.publish(topic, payload, qos=0)
175
246
  self._log(f"→ [{label}] → {topic}")
176
247
 
248
+ def status_subscriptions(self) -> list[str]:
249
+ """Topics on which device status packets are received."""
250
+ topics = []
251
+ if self._experiment_id:
252
+ topics.append(f"{self._experiment_id}/+/status")
253
+ if self._status_topic:
254
+ topics.append(self._status_topic)
255
+ return topics
256
+
257
+ def control_topic(self, device_id: str) -> str:
258
+ """Control topic of a discovered device (experiment-scoped or legacy)."""
259
+ with self._devices_lock:
260
+ known = self._devices.get(device_id)
261
+ if known is not None and known.control_topic:
262
+ return known.control_topic
263
+ if self._experiment_id:
264
+ return f"{self._experiment_id}/{device_id}/control"
265
+ return f"{device_id}/{self._command_topic_suffix}"
266
+
267
+ def _parse_status(self, topic: str, payload: bytes) -> DeviceStatus:
268
+ data = json.loads(payload.decode("utf-8"))
269
+ if not isinstance(data, dict):
270
+ raise ValueError("status payload is not a JSON object")
271
+ parts = topic.split("/")
272
+ if self._experiment_id and len(parts) == 3 and parts[0] == self._experiment_id and parts[2] == "status":
273
+ device_id = parts[1]
274
+ if data.get("id") not in (None, device_id):
275
+ raise ValueError(f"id {data.get('id')!r} does not match topic recorder {device_id!r}")
276
+ experiment = self._experiment_id
277
+ control = f"{experiment}/{device_id}/control"
278
+ else:
279
+ device_id = str(data.get("id", "device"))
280
+ experiment = None
281
+ control = f"{device_id}/{self._command_topic_suffix}"
282
+ return DeviceStatus(
283
+ device_id=device_id,
284
+ recording=bool(data.get("recording", False)),
285
+ battery=int(data.get("battery", -1)),
286
+ last_seen=time.time(),
287
+ experiment_id=experiment,
288
+ control_topic=control,
289
+ session_id=data.get("sessionId"),
290
+ headset_connected=data.get("headsetConnected"),
291
+ )
292
+
177
293
  def _log(self, msg: str) -> None:
178
294
  if self._on_log is not None:
179
295
  self._on_log(msg)
@@ -186,8 +302,9 @@ class MqttController:
186
302
  if rc == mqtt.CONNACK_ACCEPTED:
187
303
  self._connected = True
188
304
  self._log(f"✓ Connected to {self._broker_host}:{self._broker_port}")
189
- self._log(f" Subscribing to status topic: {self._status_topic}")
190
- client.subscribe(self._status_topic, qos=0)
305
+ for topic in self.status_subscriptions():
306
+ self._log(f" Subscribing to status topic: {topic}")
307
+ client.subscribe(topic, qos=0)
191
308
  self._log(" Ready — waiting for device status packets …")
192
309
  if self._on_connected:
193
310
  self._on_connected()
@@ -213,21 +330,12 @@ class MqttController:
213
330
 
214
331
  def _on_mqtt_message(self, client, userdata, msg) -> None: # type: ignore[no-untyped-def]
215
332
  try:
216
- payload = msg.payload.decode("utf-8")
217
- data = json.loads(payload)
218
- device_id = str(data.get("id", "device"))
219
- recording = bool(data.get("recording", False))
220
- battery = int(data.get("battery", -1))
333
+ status = self._parse_status(msg.topic, msg.payload)
334
+ device_id, recording, battery = status.device_id, status.recording, status.battery
221
335
 
222
336
  with self._devices_lock:
223
337
  existing = self._devices.get(device_id)
224
338
  is_new = existing is None
225
- status = DeviceStatus(
226
- device_id=device_id,
227
- recording=recording,
228
- battery=battery,
229
- last_seen=time.time(),
230
- )
231
339
  self._devices[device_id] = status
232
340
 
233
341
  if is_new:
@@ -239,7 +347,7 @@ class MqttController:
239
347
  if self._on_device_update:
240
348
  self._on_device_update(status)
241
349
 
242
- except (json.JSONDecodeError, KeyError, ValueError) as exc:
350
+ except (json.JSONDecodeError, KeyError, ValueError, TypeError, UnicodeDecodeError) as exc:
243
351
  self._log(f"[WARN] Malformed status packet on {msg.topic}: {exc}")
244
352
 
245
353
  def _on_mqtt_log(self, client, userdata, level, buf) -> None: # type: ignore[no-untyped-def]
@@ -36,6 +36,9 @@ _KEY_HOST = "broker/host"
36
36
  _KEY_PORT = "broker/port"
37
37
  _KEY_STATUS_TOPIC = "broker/status_topic"
38
38
  _KEY_CMD_SUFFIX = "broker/command_suffix"
39
+ _KEY_EXPERIMENT = "broker/experiment_id"
40
+ _KEY_USERNAME = "broker/username"
41
+ _KEY_CA_FILE = "broker/ca_file"
39
42
 
40
43
 
41
44
  class _MqttBridge(QObject):
@@ -106,19 +109,44 @@ class MqttControllerPage(QWidget):
106
109
  form = QFormLayout(group)
107
110
 
108
111
  self._host_edit = QLineEdit()
109
- self._host_edit.setPlaceholderText("e.g. 192.168.1.100")
110
- self._host_edit.setToolTip("IP address or hostname of the MQTT broker.")
111
- form.addRow("Host:", self._host_edit)
112
+ self._host_edit.setPlaceholderText("e.g. mqtts://192.168.1.100:8883 or 192.168.1.100")
113
+ self._host_edit.setToolTip(
114
+ "Broker URL (mqtt://, mqtts:// for TLS, ws://, wss://) or a bare IP / hostname (plain TCP)."
115
+ )
116
+ form.addRow("Broker:", self._host_edit)
112
117
 
113
118
  self._port_spin = QSpinBox()
114
119
  self._port_spin.setRange(1, 65535)
115
120
  self._port_spin.setValue(DEFAULT_BROKER_PORT)
121
+ self._port_spin.setToolTip("Port used with a bare IP / hostname.")
116
122
  form.addRow("Port:", self._port_spin)
117
123
 
124
+ self._experiment_edit = QLineEdit()
125
+ self._experiment_edit.setPlaceholderText("experiment UUID (optional)")
126
+ self._experiment_edit.setToolTip(
127
+ "Discover the phones of this experiment on {experimentId}/+/status.\n"
128
+ "Leave empty for phones without an experiment (legacy topics, local broker)."
129
+ )
130
+ form.addRow("Experiment:", self._experiment_edit)
131
+
132
+ self._username_edit = QLineEdit()
133
+ self._username_edit.setPlaceholderText("optional")
134
+ form.addRow("Username:", self._username_edit)
135
+
136
+ self._password_edit = QLineEdit()
137
+ self._password_edit.setEchoMode(QLineEdit.EchoMode.Password)
138
+ self._password_edit.setPlaceholderText("optional (not saved)")
139
+ form.addRow("Password:", self._password_edit)
140
+
141
+ self._ca_edit = QLineEdit()
142
+ self._ca_edit.setPlaceholderText("CA certificate file for TLS (optional)")
143
+ self._ca_edit.setToolTip("PEM file of the CA that signed the broker certificate (RE-AK private CA).")
144
+ form.addRow("CA file:", self._ca_edit)
145
+
118
146
  self._status_topic_edit = QLineEdit()
119
147
  self._status_topic_edit.setPlaceholderText(DEFAULT_STATUS_TOPIC)
120
148
  self._status_topic_edit.setToolTip(
121
- "Topic on which Vizia devices publish status packets.\n"
149
+ "Legacy shared status topic (phones without an experiment).\n"
122
150
  "Default: vizia/status"
123
151
  )
124
152
  form.addRow("Status topic:", self._status_topic_edit)
@@ -126,7 +154,7 @@ class MqttControllerPage(QWidget):
126
154
  self._cmd_suffix_edit = QLineEdit()
127
155
  self._cmd_suffix_edit.setPlaceholderText(DEFAULT_COMMAND_TOPIC_SUFFIX)
128
156
  self._cmd_suffix_edit.setToolTip(
129
- "Suffix appended after {recorderId}/ when publishing commands.\n"
157
+ "Legacy: suffix appended after {recorderId}/ when publishing commands.\n"
130
158
  "Default: control/"
131
159
  )
132
160
  form.addRow("Command suffix:", self._cmd_suffix_edit)
@@ -236,6 +264,9 @@ class MqttControllerPage(QWidget):
236
264
  self._port_spin.setValue(int(s.value(_KEY_PORT, DEFAULT_BROKER_PORT)))
237
265
  self._status_topic_edit.setText(s.value(_KEY_STATUS_TOPIC, "", type=str))
238
266
  self._cmd_suffix_edit.setText(s.value(_KEY_CMD_SUFFIX, "", type=str))
267
+ self._experiment_edit.setText(s.value(_KEY_EXPERIMENT, "", type=str))
268
+ self._username_edit.setText(s.value(_KEY_USERNAME, "", type=str))
269
+ self._ca_edit.setText(s.value(_KEY_CA_FILE, "", type=str))
239
270
 
240
271
  def _save_settings(self) -> None:
241
272
  s = QSettings(_SETTINGS_ORG, _SETTINGS_APP)
@@ -243,13 +274,16 @@ class MqttControllerPage(QWidget):
243
274
  s.setValue(_KEY_PORT, self._port_spin.value())
244
275
  s.setValue(_KEY_STATUS_TOPIC, self._status_topic_edit.text().strip())
245
276
  s.setValue(_KEY_CMD_SUFFIX, self._cmd_suffix_edit.text().strip())
277
+ s.setValue(_KEY_EXPERIMENT, self._experiment_edit.text().strip())
278
+ s.setValue(_KEY_USERNAME, self._username_edit.text().strip())
279
+ s.setValue(_KEY_CA_FILE, self._ca_edit.text().strip())
246
280
 
247
281
  # ── Connection actions ───────────────────────────────────────────────
248
282
 
249
283
  def _on_connect_clicked(self) -> None:
250
284
  host = self._host_edit.text().strip()
251
285
  if not host:
252
- QMessageBox.warning(self, "Host required", "Enter the broker IP address or hostname.")
286
+ QMessageBox.warning(self, "Broker required", "Enter the broker URL, IP address or hostname.")
253
287
  return
254
288
 
255
289
  port = self._port_spin.value()
@@ -266,16 +300,24 @@ class MqttControllerPage(QWidget):
266
300
  self._device_combo.addItem("All devices", TARGET_ALL)
267
301
  self._device_status_label.setText("")
268
302
 
269
- self._controller = MqttController(
270
- broker_host=host,
271
- broker_port=port,
272
- status_topic=status_topic,
273
- command_topic_suffix=cmd_suffix,
274
- on_log=self._bridge.log_line.emit,
275
- on_device_update=self._bridge.device_updated.emit,
276
- on_connected=self._bridge.connected.emit,
277
- on_disconnected=self._bridge.disconnected.emit,
278
- )
303
+ try:
304
+ self._controller = MqttController(
305
+ broker_host=host,
306
+ broker_port=port,
307
+ status_topic=status_topic,
308
+ command_topic_suffix=cmd_suffix,
309
+ experiment_id=self._experiment_edit.text().strip() or None,
310
+ username=self._username_edit.text().strip() or None,
311
+ password=self._password_edit.text() or None,
312
+ ca_file=self._ca_edit.text().strip() or None,
313
+ on_log=self._bridge.log_line.emit,
314
+ on_device_update=self._bridge.device_updated.emit,
315
+ on_connected=self._bridge.connected.emit,
316
+ on_disconnected=self._bridge.disconnected.emit,
317
+ )
318
+ except ValueError as exc:
319
+ QMessageBox.warning(self, "Invalid broker address", str(exc))
320
+ return
279
321
 
280
322
  self._connect_btn.setEnabled(False)
281
323
  self._status_label.setText("Connecting …")
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: nucleuskit-toolkit
3
- Version: 2.2.2
3
+ Version: 2.3.0
4
4
  Summary: Nucleus-Kit offline processing toolkit (Hermes EEG/EMG, Shimmer PPG/EDA)
5
5
  Author: RE-AK Technologies Inc.
6
6
  License-Expression: GPL-3.0-or-later
@@ -21,7 +21,7 @@ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
21
21
  Requires-Python: >=3.10
22
22
  Description-Content-Type: text/markdown
23
23
  License-File: LICENSE
24
- Requires-Dist: re-ak-core<1.1,>=1.0.2
24
+ Requires-Dist: re-ak-core<1.2,>=1.1.0
25
25
  Requires-Dist: numpy>=2.5
26
26
  Requires-Dist: pandas>=2.3
27
27
  Requires-Dist: scipy<1.18,>=1.17
@@ -155,7 +155,7 @@ python3 -m venv .venv
155
155
  .venv/bin/python -m pytest
156
156
  ```
157
157
 
158
- The re-ak-core clone satisfies Nucleus-Kit's `re-ak-core>=1.0.2,<1.1` requirement, so pip keeps it instead of
158
+ The re-ak-core clone satisfies Nucleus-Kit's `re-ak-core>=1.1.0,<1.2` requirement, so pip keeps it instead of
159
159
  downloading the published one. To reproduce the tested environment exactly, install `requirements.txt` instead of the
160
160
  `[dev,gui]` extras (it needs re-ak-core on PyPI).
161
161
 
@@ -65,6 +65,7 @@ tests/test_config.py
65
65
  tests/test_hermes_ble_stream.py
66
66
  tests/test_imports.py
67
67
  tests/test_logging_redirect.py
68
+ tests/test_mqtt_controller.py
68
69
  tests/test_offline_job.py
69
70
  tests/test_open_core_references.py
70
71
  tests/test_pipeline_cancel.py
@@ -1,4 +1,4 @@
1
- re-ak-core<1.1,>=1.0.2
1
+ re-ak-core<1.2,>=1.1.0
2
2
  numpy>=2.5
3
3
  pandas>=2.3
4
4
  scipy<1.18,>=1.17
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "nucleuskit-toolkit"
7
- version = "2.2.2"
7
+ version = "2.3.0"
8
8
  description = "Nucleus-Kit offline processing toolkit (Hermes EEG/EMG, Shimmer PPG/EDA)"
9
9
  readme = "README.md"
10
10
  license = "GPL-3.0-or-later"
@@ -24,7 +24,7 @@ classifiers = [
24
24
  "Topic :: Scientific/Engineering :: Medical Science Apps.",
25
25
  ]
26
26
  dependencies = [
27
- "re-ak-core>=1.0.2,<1.1",
27
+ "re-ak-core>=1.1.0,<1.2",
28
28
  "numpy>=2.5",
29
29
  "pandas>=2.3",
30
30
  "scipy>=1.17,<1.18",
@@ -0,0 +1,63 @@
1
+ """MQTT controller: broker addresses, experiment-scoped discovery and per-device control topics (contract v1)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import json
6
+ from types import SimpleNamespace
7
+
8
+ import pytest
9
+ from nucleuskit_toolkit.mqtt.mqtt_controller import MqttController, parse_broker
10
+
11
+
12
+ def test_parse_broker_urls_and_bare_hosts():
13
+ assert parse_broker("192.168.1.10") == parse_broker("mqtt://192.168.1.10:1883")
14
+ assert parse_broker("192.168.1.10", fallback_port=1884).port == 1884
15
+ tls = parse_broker("mqtts://broker.example")
16
+ assert tls.port == 8883 and tls.tls and not tls.websocket
17
+ wss = parse_broker("wss://broker.example/live")
18
+ assert wss.port == 443 and wss.path == "/live" and wss.websocket
19
+ assert parse_broker("ws://h:9001").path == "/mqtt"
20
+ with pytest.raises(ValueError):
21
+ parse_broker("http://host")
22
+ with pytest.raises(ValueError):
23
+ parse_broker("")
24
+
25
+
26
+ def _message(controller: MqttController, topic: str, payload: dict) -> None:
27
+ controller._on_mqtt_message(None, None, SimpleNamespace(topic=topic, payload=json.dumps(payload).encode()))
28
+
29
+
30
+ def test_experiment_discovery_and_control_topics():
31
+ c = MqttController("mqtts://broker.example", experiment_id="exp-1")
32
+ assert c.status_subscriptions() == ["exp-1/+/status", "vizia/status"]
33
+ _message(c, "exp-1/rec-01/status", {"v": 1, "id": "rec-01", "recording": True, "battery": 80, "sessionId": "s1"})
34
+ _message(c, "vizia/status", {"id": "old-phone", "recording": False, "battery": 50})
35
+ devices = {d.device_id: d for d in c.discovered_devices}
36
+ assert devices["rec-01"].experiment_id == "exp-1" and devices["rec-01"].session_id == "s1"
37
+ assert c.control_topic("rec-01") == "exp-1/rec-01/control"
38
+ assert c.control_topic("old-phone") == "old-phone/control/"
39
+ assert c.control_topic("never-seen") == "exp-1/never-seen/control"
40
+
41
+
42
+ def test_status_id_must_match_topic():
43
+ c = MqttController("127.0.0.1", experiment_id="exp-1")
44
+ _message(c, "exp-1/rec-01/status", {"id": "someone-else", "recording": True})
45
+ assert c.discovered_devices == []
46
+
47
+
48
+ def test_legacy_only_controller_is_unchanged():
49
+ c = MqttController("127.0.0.1")
50
+ assert c.status_subscriptions() == ["vizia/status"]
51
+ _message(c, "vizia/status", {"id": "rec-02", "recording": True, "battery": 70})
52
+ assert c.control_topic("rec-02") == "rec-02/control/"
53
+
54
+
55
+ def test_publish_goes_to_each_device_topic():
56
+ c = MqttController("127.0.0.1", experiment_id="exp-1")
57
+ _message(c, "exp-1/a/status", {"id": "a", "recording": False})
58
+ _message(c, "vizia/status", {"id": "b", "recording": False})
59
+ sent = []
60
+ c._client = SimpleNamespace(publish=lambda topic, payload, qos: sent.append(topic))
61
+ c._connected = True
62
+ c.send_start_recording()
63
+ assert sorted(sent) == ["b/control/", "exp-1/a/control"]
@@ -10,12 +10,11 @@ pytest.importorskip("pyqtgraph")
10
10
  from nucleuskit_toolkit.ui import plot_style # noqa: E402
11
11
  from nucleuskit_toolkit.ui.theme import apply_theme # noqa: E402
12
12
  from PySide6.QtGui import QColor # noqa: E402
13
- from PySide6.QtWidgets import QApplication # noqa: E402
14
13
 
15
14
 
16
15
  @pytest.fixture(scope="module")
17
- def app():
18
- return QApplication.instance() or QApplication([])
16
+ def app(qapp):
17
+ return qapp
19
18
 
20
19
 
21
20
  def _contrast(a: str, b: str) -> float:
@@ -11,27 +11,27 @@ pytest.importorskip("pyqtgraph")
11
11
 
12
12
  from nucleuskit_toolkit.ui import plot_style # noqa: E402
13
13
  from nucleuskit_toolkit.ui.theme import apply_theme # noqa: E402
14
- from PySide6.QtWidgets import QApplication # noqa: E402
15
14
 
16
15
 
17
16
  @pytest.fixture(scope="module")
18
- def app():
19
- instance = QApplication.instance() or QApplication([])
20
- apply_theme(instance, "dark")
21
- return instance
17
+ def app(qapp):
18
+ apply_theme(qapp, "dark")
19
+ return qapp
22
20
 
23
21
 
24
22
  @pytest.fixture
25
23
  def page(app):
26
24
  """An OfflinePage whose inspector thread is stopped afterwards.
27
25
 
28
- The app stops it on aboutToQuit, which never fires in tests; a thread still running at exit makes Qt abort.
26
+ The app stops it on aboutToQuit, which fires only when the session-wide ``qapp`` is shut down; a thread still
27
+ running at exit makes Qt abort.
29
28
  """
30
29
  from nucleuskit_toolkit.ui.pages.offline_page import OfflinePage
31
30
 
32
31
  instance = OfflinePage()
33
32
  yield instance
34
33
  instance._stop_inspector()
34
+ instance.deleteLater()
35
35
 
36
36
 
37
37
  def test_process_page_has_no_run_summary_and_run_sits_in_step_2(page) -> None: