openzilo-gesture-studio 0.2.0__py3-none-any.whl
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.
- openzilo_gesture_studio/__init__.py +3 -0
- openzilo_gesture_studio/__main__.py +6 -0
- openzilo_gesture_studio/_ble_connection.py +49 -0
- openzilo_gesture_studio/acceleration.py +69 -0
- openzilo_gesture_studio/acceleration_view.py +206 -0
- openzilo_gesture_studio/audio.py +140 -0
- openzilo_gesture_studio/calibration.py +281 -0
- openzilo_gesture_studio/datasets.py +110 -0
- openzilo_gesture_studio/device.py +884 -0
- openzilo_gesture_studio/device_history.py +79 -0
- openzilo_gesture_studio/evaluation.py +187 -0
- openzilo_gesture_studio/firmware.py +73 -0
- openzilo_gesture_studio/gui.py +1375 -0
- openzilo_gesture_studio/launcher.py +28 -0
- openzilo_gesture_studio/playback.py +154 -0
- openzilo_gesture_studio/plotting.py +548 -0
- openzilo_gesture_studio/qt/__init__.py +2 -0
- openzilo_gesture_studio/qt/app.py +31 -0
- openzilo_gesture_studio/qt/charts.py +458 -0
- openzilo_gesture_studio/qt/contributors.py +130 -0
- openzilo_gesture_studio/qt/controller.py +1388 -0
- openzilo_gesture_studio/qt/dialogs.py +62 -0
- openzilo_gesture_studio/qt/i18n.py +137 -0
- openzilo_gesture_studio/qt/locales/charts_en.json +36 -0
- openzilo_gesture_studio/qt/locales/common_en.json +30 -0
- openzilo_gesture_studio/qt/locales/controllers_en.json +250 -0
- openzilo_gesture_studio/qt/locales/ota_connection_en.json +5 -0
- openzilo_gesture_studio/qt/locales/pages_en.json +174 -0
- openzilo_gesture_studio/qt/models.py +257 -0
- openzilo_gesture_studio/qt/motion.py +139 -0
- openzilo_gesture_studio/qt/pages/__init__.py +2 -0
- openzilo_gesture_studio/qt/pages/about.py +213 -0
- openzilo_gesture_studio/qt/pages/audio.py +156 -0
- openzilo_gesture_studio/qt/pages/capture.py +178 -0
- openzilo_gesture_studio/qt/pages/device.py +125 -0
- openzilo_gesture_studio/qt/pages/diagnostics.py +123 -0
- openzilo_gesture_studio/qt/pages/live.py +77 -0
- openzilo_gesture_studio/qt/pages/settings.py +39 -0
- openzilo_gesture_studio/qt/pages/tools.py +108 -0
- openzilo_gesture_studio/qt/pages/train.py +94 -0
- openzilo_gesture_studio/qt/theme.py +148 -0
- openzilo_gesture_studio/qt/tools_controller.py +362 -0
- openzilo_gesture_studio/qt/widgets.py +388 -0
- openzilo_gesture_studio/qt/window.py +421 -0
- openzilo_gesture_studio/remote_audio.py +313 -0
- openzilo_gesture_studio/ring_stream.py +54 -0
- openzilo_gesture_studio/sdk_controls.py +501 -0
- openzilo_gesture_studio/training.py +309 -0
- openzilo_gesture_studio/wire.py +23 -0
- openzilo_gesture_studio-0.2.0.dist-info/METADATA +205 -0
- openzilo_gesture_studio-0.2.0.dist-info/RECORD +55 -0
- openzilo_gesture_studio-0.2.0.dist-info/WHEEL +5 -0
- openzilo_gesture_studio-0.2.0.dist-info/entry_points.txt +4 -0
- openzilo_gesture_studio-0.2.0.dist-info/licenses/LICENSE +373 -0
- openzilo_gesture_studio-0.2.0.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
2
|
+
"""Optional connection tuning, isolated from SDK firmware/protocol handling.
|
|
3
|
+
|
|
4
|
+
CoreBluetooth's central-side latency selector is private. Keep all SDK/Bleak
|
|
5
|
+
backend access here and degrade gracefully when either implementation changes.
|
|
6
|
+
No native modules are imported, so other platforms can import Studio normally.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import sys
|
|
11
|
+
from typing import Literal
|
|
12
|
+
|
|
13
|
+
LatencyRequestStatus = Literal["not_applicable", "unavailable", "requested", "failed"]
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def request_ota_low_latency(ring: object) -> LatencyRequestStatus:
|
|
17
|
+
"""Request low latency on the existing macOS connection, once per OTA attempt.
|
|
18
|
+
|
|
19
|
+
The caller must own the BLE session on its worker thread. This neither
|
|
20
|
+
connects nor disconnects, touches GATT, nor replaces a native delegate.
|
|
21
|
+
'requested' means the void native call returned, NOT that parameters changed.
|
|
22
|
+
Do not guess the previous settings or try to restore them: Studio ends the
|
|
23
|
+
session after each OTA attempt; the OS owns the negotiated link parameters.
|
|
24
|
+
"""
|
|
25
|
+
if sys.platform != "darwin":
|
|
26
|
+
return "not_applicable"
|
|
27
|
+
try:
|
|
28
|
+
if not getattr(ring, "is_connected", False):
|
|
29
|
+
return "unavailable"
|
|
30
|
+
transport = getattr(ring, "transport", None)
|
|
31
|
+
client = getattr(transport, "_client", None)
|
|
32
|
+
if client is None or not client.is_connected:
|
|
33
|
+
return "unavailable"
|
|
34
|
+
backend = getattr(client, "_backend", None)
|
|
35
|
+
peripheral = getattr(backend, "_peripheral", None)
|
|
36
|
+
delegate = getattr(backend, "_central_manager_delegate", None)
|
|
37
|
+
manager = getattr(delegate, "central_manager", None)
|
|
38
|
+
request = getattr(manager, "setDesiredConnectionLatency_forPeripheral_", None)
|
|
39
|
+
if peripheral is None or not callable(request):
|
|
40
|
+
return "unavailable"
|
|
41
|
+
# On the tested macOS runtime bluetoothd identifies 0 as "low".
|
|
42
|
+
# It is a latency preference, NOT interval=0 or peripheral latency=0.
|
|
43
|
+
# Avoid the undocumented completion-block ABI entirely.
|
|
44
|
+
request(0, peripheral)
|
|
45
|
+
except Exception:
|
|
46
|
+
# This is an optional optimization. Actual connection/OTA failures must
|
|
47
|
+
# still be handled by the SDK; never turn this into an upgrade retry.
|
|
48
|
+
return "failed"
|
|
49
|
+
return "requested"
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
2
|
+
"""Acceleration diagnostics in the sensor frame, independent of Tk and BLE.
|
|
3
|
+
|
|
4
|
+
Raw accelerometer readings include gravity. Their direction is neither a world
|
|
5
|
+
heading nor the direction of velocity. Physical units use the reported signed
|
|
6
|
+
int16 full-scale range; no range is guessed when metadata is unavailable.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
from dataclasses import dataclass
|
|
11
|
+
import math
|
|
12
|
+
from numbers import Real
|
|
13
|
+
|
|
14
|
+
STANDARD_GRAVITY = 9.80665
|
|
15
|
+
# Display-only reference bands around 1 g, not firmware detection thresholds.
|
|
16
|
+
NARROW_MAGNITUDE_BAND = (0.97, 1.03)
|
|
17
|
+
WIDE_MAGNITUDE_BAND = (0.90, 1.10)
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def acceleration_scale(accel_range_g) -> float | None:
|
|
21
|
+
"""g per raw count, or None if full-scale metadata is unavailable/invalid."""
|
|
22
|
+
if isinstance(accel_range_g, bool) or not isinstance(accel_range_g, Real):
|
|
23
|
+
return None
|
|
24
|
+
try:
|
|
25
|
+
value = float(accel_range_g)
|
|
26
|
+
except (OverflowError, ValueError):
|
|
27
|
+
return None
|
|
28
|
+
return value / 32768.0 if math.isfinite(value) and value > 0 else None
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class AccelerationVector:
|
|
33
|
+
xyz_raw: tuple[float, float, float]
|
|
34
|
+
magnitude_raw: float
|
|
35
|
+
unit_direction: tuple[float, float, float] | None
|
|
36
|
+
magnitude_g: float | None
|
|
37
|
+
xyz_g: tuple[float, float, float] | None
|
|
38
|
+
|
|
39
|
+
@property
|
|
40
|
+
def magnitude_m_s2(self) -> float | None:
|
|
41
|
+
return None if self.magnitude_g is None else self.magnitude_g * STANDARD_GRAVITY
|
|
42
|
+
|
|
43
|
+
@property
|
|
44
|
+
def axis_angles_deg(self) -> tuple[float, float, float] | None:
|
|
45
|
+
"""Angles to sensor +X/+Y/+Z, not Euler attitude angles."""
|
|
46
|
+
if self.unit_direction is None:
|
|
47
|
+
return None
|
|
48
|
+
return tuple(math.degrees(math.acos(max(-1.0, min(1.0, v))))
|
|
49
|
+
for v in self.unit_direction)
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def acceleration_vector(xyz, *, accel_range_g=None) -> AccelerationVector:
|
|
53
|
+
"""Describe a three-axis vector without int16 squaring/overflow.
|
|
54
|
+
|
|
55
|
+
``xyz`` may also be a floating-point residual after subtracting a baseline.
|
|
56
|
+
A zero vector has no direction. Invalid/missing range metadata leaves only
|
|
57
|
+
raw units available, rather than silently assuming (for example) +/-8 g.
|
|
58
|
+
"""
|
|
59
|
+
values = tuple(xyz)
|
|
60
|
+
if len(values) != 3 or any(isinstance(v, bool) or not isinstance(v, Real)
|
|
61
|
+
or not math.isfinite(v) for v in values):
|
|
62
|
+
raise ValueError("acceleration must contain three finite numbers")
|
|
63
|
+
values = tuple(float(v) for v in values)
|
|
64
|
+
magnitude = math.hypot(*values)
|
|
65
|
+
direction = tuple(v / magnitude for v in values) if magnitude else None
|
|
66
|
+
scale = acceleration_scale(accel_range_g)
|
|
67
|
+
magnitude_g = magnitude * scale if scale is not None else None
|
|
68
|
+
xyz_g = tuple(v * scale for v in values) if scale is not None else None
|
|
69
|
+
return AccelerationVector(values, magnitude, direction, magnitude_g, xyz_g)
|
|
@@ -0,0 +1,206 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
2
|
+
"""Live acceleration diagnostics; display-only, with no new BLE consumer.
|
|
3
|
+
|
|
4
|
+
Like IMUPlot, this view is owned by the Tk thread and redrawn by Studio.poll.
|
|
5
|
+
Every received sample is retained in a bounded window, not just batch tails.
|
|
6
|
+
"""
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
|
|
11
|
+
from .acceleration import (
|
|
12
|
+
NARROW_MAGNITUDE_BAND, WIDE_MAGNITUDE_BAND, acceleration_scale, acceleration_vector,
|
|
13
|
+
)
|
|
14
|
+
from .plotting import RollingIMUBuffer, curve_points
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def reading_text(vector):
|
|
18
|
+
"""Keep diagnostic wording testable without Tk or hardware."""
|
|
19
|
+
if vector is None:
|
|
20
|
+
return ("合加速度 |a|:—;等待新的 IMU 样本", "方向:—", "幅值参考:—")
|
|
21
|
+
magnitude = f"合加速度 |a|:{vector.magnitude_raw:.2f} raw"
|
|
22
|
+
if vector.magnitude_g is None:
|
|
23
|
+
magnitude += ";量程未知,无法换算 g / m/s²"
|
|
24
|
+
gates = "幅值参考:量程未知,无法对照"
|
|
25
|
+
else:
|
|
26
|
+
magnitude += f" = {vector.magnitude_g:.4f} g = {vector.magnitude_m_s2:.4f} m/s²"
|
|
27
|
+
xyz = ", ".join(f"{v:+.4f}" for v in vector.xyz_g)
|
|
28
|
+
magnitude += f"\n分量 (X, Y, Z):({xyz}) g;|a| − 1 g = {vector.magnitude_g - 1:+.4f} g(不是去重力加速度)"
|
|
29
|
+
def inside(band):
|
|
30
|
+
return "范围内" if band[0] <= vector.magnitude_g <= band[1] else "范围外"
|
|
31
|
+
gates = (f"幅值参考:1g ±3% · 0.97–1.03 g [{inside(NARROW_MAGNITUDE_BAND)},绿线];"
|
|
32
|
+
f"1g ±10% · 0.90–1.10 g [{inside(WIDE_MAGNITUDE_BAND)},橙线](仅供观察)")
|
|
33
|
+
if vector.unit_direction is None:
|
|
34
|
+
direction = "方向:未定义(零向量)\n与 +X / +Y / +Z 的夹角:—"
|
|
35
|
+
else:
|
|
36
|
+
xyz = ", ".join(f"{v:+.4f}" for v in vector.unit_direction)
|
|
37
|
+
angles = " / ".join(f"{v:.1f}°" for v in vector.axis_angles_deg)
|
|
38
|
+
direction = f"单位方向 a/|a| (X, Y, Z):({xyz})\n与 +X / +Y / +Z 的夹角:{angles}(不是欧拉角)"
|
|
39
|
+
return magnitude, direction, gates
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
class AccelerationView:
|
|
43
|
+
"""Magnitude history and three projections of the latest unit direction."""
|
|
44
|
+
|
|
45
|
+
def __init__(self, parent):
|
|
46
|
+
import tkinter as tk
|
|
47
|
+
from tkinter import ttk
|
|
48
|
+
|
|
49
|
+
self.buffer = RollingIMUBuffer()
|
|
50
|
+
self._active = False
|
|
51
|
+
self._range_g = None
|
|
52
|
+
self._frozen = None
|
|
53
|
+
self._dirty = self._layout_dirty = True
|
|
54
|
+
self.widget = ttk.Frame(parent)
|
|
55
|
+
self.widget.columnconfigure(0, weight=1)
|
|
56
|
+
self.widget.rowconfigure(4, weight=1)
|
|
57
|
+
controls = ttk.Frame(self.widget)
|
|
58
|
+
controls.grid(row=0, column=0, sticky="ew")
|
|
59
|
+
self._pause_button = ttk.Button(controls, text="暂停显示", command=self._toggle_pause)
|
|
60
|
+
self._pause_button.pack(side="left")
|
|
61
|
+
ttk.Button(controls, text="清空", command=self.clear).pack(side="left", padx=6)
|
|
62
|
+
self._view_status = tk.StringVar(value="实时显示(含重力,未滤波)")
|
|
63
|
+
ttk.Label(controls, textvariable=self._view_status).pack(side="left")
|
|
64
|
+
self._magnitude = tk.StringVar()
|
|
65
|
+
self._direction = tk.StringVar()
|
|
66
|
+
self._gates = tk.StringVar()
|
|
67
|
+
for row, variable in enumerate((self._magnitude, self._direction, self._gates), start=1):
|
|
68
|
+
ttk.Label(self.widget, textvariable=variable, wraplength=920).grid(row=row, column=0, sticky="w", pady=2)
|
|
69
|
+
self.canvas = tk.Canvas(self.widget, background="#ffffff", highlightthickness=0,
|
|
70
|
+
width=720, height=330)
|
|
71
|
+
self.canvas.grid(row=4, column=0, sticky="nsew")
|
|
72
|
+
self._status = tk.StringVar(value="等待 IMU;量程未知")
|
|
73
|
+
ttk.Label(self.widget, textvariable=self._status, wraplength=920).grid(row=5, column=0, sticky="w")
|
|
74
|
+
ttk.Label(self.widget, text="方向基于设备上报的传感器坐标,不代表前后左右、世界航向或移动方向。\n"
|
|
75
|
+
"参考范围仅用于观察加速度幅值,不代表设备的静止、姿态融合或校准判定。",
|
|
76
|
+
wraplength=920).grid(row=6, column=0, sticky="w", pady=2)
|
|
77
|
+
self.canvas.bind("<Configure>", self._invalidate_layout)
|
|
78
|
+
self.canvas.bind("<Map>", self._invalidate_layout)
|
|
79
|
+
self._set_reading(None)
|
|
80
|
+
|
|
81
|
+
def _set_reading(self, vector):
|
|
82
|
+
for variable, text in zip((self._magnitude, self._direction, self._gates), reading_text(vector)):
|
|
83
|
+
variable.set(text)
|
|
84
|
+
|
|
85
|
+
def _invalidate_layout(self, event=None):
|
|
86
|
+
self._dirty = self._layout_dirty = True
|
|
87
|
+
|
|
88
|
+
def set_stream_state(self, payload):
|
|
89
|
+
active = payload["state"] == "active"
|
|
90
|
+
if active:
|
|
91
|
+
rate = float(payload["sample_rate_hz"])
|
|
92
|
+
scale = acceleration_scale(payload.get("accel_range_g"))
|
|
93
|
+
new_range = None if scale is None else scale * 32768.0
|
|
94
|
+
if not self._active or self.buffer.sample_rate_hz != rate or self._range_g != new_range:
|
|
95
|
+
self.buffer.set_sample_rate(rate)
|
|
96
|
+
self.clear()
|
|
97
|
+
self._range_g = new_range
|
|
98
|
+
units = f"量程 ±{new_range:g} g" if new_range is not None else "量程未知,仅显示 raw"
|
|
99
|
+
self._status.set(f"IMU 正常上报;{rate:g} Hz;{units};时间轴按采样率估算,非设备时间戳")
|
|
100
|
+
else:
|
|
101
|
+
self._range_g = None
|
|
102
|
+
self.clear()
|
|
103
|
+
self._status.set(payload.get("message", "无新 IMU 数据;旧值已清除"))
|
|
104
|
+
self._active = active
|
|
105
|
+
self._invalidate_layout()
|
|
106
|
+
|
|
107
|
+
def append_samples(self, samples):
|
|
108
|
+
if not self._active:
|
|
109
|
+
return
|
|
110
|
+
self.buffer.append_samples(samples)
|
|
111
|
+
if samples:
|
|
112
|
+
self._dirty = True
|
|
113
|
+
|
|
114
|
+
def clear(self):
|
|
115
|
+
self.buffer.clear()
|
|
116
|
+
if self._frozen is not None:
|
|
117
|
+
self._frozen = ()
|
|
118
|
+
self._set_reading(None)
|
|
119
|
+
self._invalidate_layout()
|
|
120
|
+
|
|
121
|
+
def _toggle_pause(self):
|
|
122
|
+
if self._frozen is None:
|
|
123
|
+
self._frozen = self.buffer.samples
|
|
124
|
+
self._pause_button.configure(text="恢复显示")
|
|
125
|
+
self._view_status.set("已冻结:数值、方向、曲线均为历史快照(仍收数)")
|
|
126
|
+
else:
|
|
127
|
+
self._frozen = None
|
|
128
|
+
self._pause_button.configure(text="暂停显示")
|
|
129
|
+
self._view_status.set("实时显示(含重力,未滤波)")
|
|
130
|
+
self._invalidate_layout()
|
|
131
|
+
|
|
132
|
+
def redraw(self):
|
|
133
|
+
if not self._dirty or not self.canvas.winfo_ismapped():
|
|
134
|
+
return
|
|
135
|
+
if self._frozen is not None and not self._layout_dirty:
|
|
136
|
+
return
|
|
137
|
+
samples = self.buffer.samples if self._frozen is None else self._frozen
|
|
138
|
+
vector = acceleration_vector(samples[-1][:3], accel_range_g=self._range_g) if samples else None
|
|
139
|
+
self._set_reading(vector)
|
|
140
|
+
width, height = self.canvas.winfo_width(), self.canvas.winfo_height()
|
|
141
|
+
# Clear old arrows even if a resized view is too small to draw anew.
|
|
142
|
+
self.canvas.delete("all")
|
|
143
|
+
if width < 360 or height < 180:
|
|
144
|
+
return
|
|
145
|
+
projection_height = min(150, height * 0.45)
|
|
146
|
+
self._draw_direction(vector, width, projection_height)
|
|
147
|
+
self._draw_history(samples, width, height, projection_height)
|
|
148
|
+
self._dirty = self._layout_dirty = False
|
|
149
|
+
|
|
150
|
+
def _draw_direction(self, vector, width, height):
|
|
151
|
+
c = self.canvas
|
|
152
|
+
radius = min(48, (height - 42) / 2)
|
|
153
|
+
cy = height / 2 + 7
|
|
154
|
+
for panel, (axis_x, axis_y, label) in enumerate(((0, 1, "XY"), (0, 2, "XZ"), (1, 2, "YZ"))):
|
|
155
|
+
cx = width * (panel + 0.5) / 3
|
|
156
|
+
c.create_text(cx, 12, text=f"{label} 平面 · 单位方向投影", fill="#555555")
|
|
157
|
+
c.create_oval(cx - radius, cy - radius, cx + radius, cy + radius, outline="#d0d5da")
|
|
158
|
+
c.create_line(cx - radius, cy, cx + radius, cy, fill="#aab0b6")
|
|
159
|
+
c.create_line(cx, cy + radius, cx, cy - radius, fill="#aab0b6")
|
|
160
|
+
c.create_text(cx + radius + 16, cy, text=f"+{'XYZ'[axis_x]}", fill="#555555")
|
|
161
|
+
c.create_text(cx + 10, cy - radius, text=f"+{'XYZ'[axis_y]}", anchor="w", fill="#555555")
|
|
162
|
+
if vector is not None and vector.unit_direction is not None:
|
|
163
|
+
dx, dy = vector.unit_direction[axis_x], vector.unit_direction[axis_y]
|
|
164
|
+
x, y = cx + radius * dx, cy - radius * dy
|
|
165
|
+
c.create_line(cx, cy, x, y, arrow="last", width=2.5,
|
|
166
|
+
fill="#2463c5", tags="direction")
|
|
167
|
+
c.create_oval(x - 2, y - 2, x + 2, y + 2, fill="#2463c5", outline="")
|
|
168
|
+
|
|
169
|
+
def _draw_history(self, samples, width, height, top):
|
|
170
|
+
c = self.canvas
|
|
171
|
+
scale = acceleration_scale(self._range_g)
|
|
172
|
+
values = [(math.hypot(*row[:3]) * (scale if scale is not None else 1.0),) for row in samples]
|
|
173
|
+
unit = "g" if scale is not None else "raw(量程未知)"
|
|
174
|
+
text = f"合加速度 |a| / {unit}"
|
|
175
|
+
if values:
|
|
176
|
+
low, high = min(row[0] for row in values), max(row[0] for row in values)
|
|
177
|
+
text += f";窗口最小 / 最大:{low:.4f} / {high:.4f}"
|
|
178
|
+
else:
|
|
179
|
+
low = high = 0.0
|
|
180
|
+
c.create_text(68, top + 12, text=text, anchor="w", fill="#333333")
|
|
181
|
+
if scale is not None:
|
|
182
|
+
low, high = min(low, 0.9), max(high, 1.1)
|
|
183
|
+
padding = max(0.02 if scale is not None else 1.0, (high - low) * 0.12)
|
|
184
|
+
limits = low - padding, high + padding
|
|
185
|
+
left, right, bottom = 68, width - 20, height - 30
|
|
186
|
+
top += 30
|
|
187
|
+
bounds = left, top, right, bottom
|
|
188
|
+
def y(value):
|
|
189
|
+
return bottom - (value - limits[0]) / (limits[1] - limits[0]) * (bottom - top)
|
|
190
|
+
for tick in range(5):
|
|
191
|
+
value = limits[0] + tick * (limits[1] - limits[0]) / 4
|
|
192
|
+
c.create_line(left, y(value), right, y(value), fill="#edf0f2")
|
|
193
|
+
c.create_text(left - 7, y(value), text=f"{value:.4g}", anchor="e", fill="#555555")
|
|
194
|
+
x = left + tick * (right - left) / 4
|
|
195
|
+
c.create_text(x, bottom + 14, text=f"{self.buffer.seconds * (tick / 4 - 1):.3g}s", fill="#555555")
|
|
196
|
+
if scale is not None:
|
|
197
|
+
for band, color in ((NARROW_MAGNITUDE_BAND, "#187b3c"), (WIDE_MAGNITUDE_BAND, "#c47b17")):
|
|
198
|
+
for value in band:
|
|
199
|
+
c.create_line(left, y(value), right, y(value), fill=color, dash=(4, 3), tags="threshold")
|
|
200
|
+
points = curve_points(values, 0, sample_rate_hz=self.buffer.sample_rate_hz,
|
|
201
|
+
seconds=self.buffer.seconds, bounds=bounds, limits=limits)
|
|
202
|
+
if len(points) >= 4:
|
|
203
|
+
c.create_line(*points, fill="#2463c5", width=1.5, tags="magnitude")
|
|
204
|
+
elif points:
|
|
205
|
+
x, yy = points
|
|
206
|
+
c.create_oval(x - 2, yy - 2, x + 2, yy + 2, fill="#2463c5", outline="")
|
|
@@ -0,0 +1,140 @@
|
|
|
1
|
+
# SPDX-License-Identifier: MPL-2.0
|
|
2
|
+
"""Persist complete ring recordings; no BLE, microphone, or GUI operations."""
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import io
|
|
6
|
+
import json
|
|
7
|
+
import os
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
import subprocess
|
|
10
|
+
import tempfile
|
|
11
|
+
import wave
|
|
12
|
+
|
|
13
|
+
import openzilo as sdk
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def _bounded_speex_decoder(source: bytes, options: dict) -> sdk.SpeexDecodeResult:
|
|
17
|
+
"""Keep SDK parsing/container semantics, but bound the external decoder."""
|
|
18
|
+
config = sdk.normalize_pcm_config(options.get("pcm_config"))
|
|
19
|
+
packet_count = 0
|
|
20
|
+
source_type = "ogg-speex"
|
|
21
|
+
if sdk.is_ogg_speex(source):
|
|
22
|
+
ogg = source
|
|
23
|
+
else:
|
|
24
|
+
packets = sdk.parse_packetized_speex_stream(
|
|
25
|
+
source, allow_framed_blocks=options.get("allow_framed_blocks", False),
|
|
26
|
+
)
|
|
27
|
+
source_type = "packet-speex"
|
|
28
|
+
if not packets:
|
|
29
|
+
packets = sdk.split_raw_speex_packets(
|
|
30
|
+
source, quality=options.get("quality", 3),
|
|
31
|
+
bits_size=options.get("bits_size"),
|
|
32
|
+
)
|
|
33
|
+
source_type = "raw-speex"
|
|
34
|
+
if not packets:
|
|
35
|
+
raise sdk.AudioDecodeError("Recording is not recognized as Speex")
|
|
36
|
+
packet_count = len(packets)
|
|
37
|
+
ogg = sdk.build_ogg_speex(packets, pcm_config=config)
|
|
38
|
+
|
|
39
|
+
command = [
|
|
40
|
+
"ffmpeg", "-hide_banner", "-loglevel", "error", "-f", "ogg",
|
|
41
|
+
"-i", "pipe:0", "-f", "s16le" if config.bit_depth == 16 else "u8",
|
|
42
|
+
"-ac", str(config.channels), "-ar", str(config.sample_rate), "pipe:1",
|
|
43
|
+
]
|
|
44
|
+
try:
|
|
45
|
+
completed = subprocess.run(
|
|
46
|
+
command, input=ogg, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
|
47
|
+
timeout=5, check=False,
|
|
48
|
+
)
|
|
49
|
+
except FileNotFoundError as exc:
|
|
50
|
+
raise sdk.SpeexDecoderUnavailable(
|
|
51
|
+
"ffmpeg is missing; install ffmpeg and ensure it is on PATH to decode recordings."
|
|
52
|
+
) from exc
|
|
53
|
+
except subprocess.TimeoutExpired as exc:
|
|
54
|
+
raise sdk.AudioDecodeError("ffmpeg decoding timed out after 5 seconds") from exc
|
|
55
|
+
if completed.returncode != 0:
|
|
56
|
+
detail = completed.stderr.decode("utf-8", errors="replace").strip()[:500]
|
|
57
|
+
raise sdk.AudioDecodeError(f"ffmpeg decoding failed: {detail}")
|
|
58
|
+
pcm = completed.stdout
|
|
59
|
+
if not pcm:
|
|
60
|
+
raise sdk.AudioDecodeError("ffmpeg returned no decoded audio")
|
|
61
|
+
if packet_count:
|
|
62
|
+
pcm = sdk.normalize_decoded_speex_pcm(
|
|
63
|
+
pcm, packet_count=packet_count, pcm_config=config,
|
|
64
|
+
)
|
|
65
|
+
return sdk.SpeexDecodeResult(
|
|
66
|
+
pcm_bytes=pcm, pcm_config=config, source_type=source_type,
|
|
67
|
+
source_extension="spx", packet_count=packet_count,
|
|
68
|
+
)
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _save_unique(directory: Path, suffix: str, data: bytes, *, prefix: str = "recording-") -> Path:
|
|
72
|
+
"""Exclusive creation prevents collisions and never truncates existing files."""
|
|
73
|
+
fd, name = tempfile.mkstemp(dir=directory, prefix=prefix, suffix=suffix)
|
|
74
|
+
path = Path(name)
|
|
75
|
+
try:
|
|
76
|
+
with os.fdopen(fd, "wb") as target:
|
|
77
|
+
target.write(data)
|
|
78
|
+
target.flush()
|
|
79
|
+
os.fsync(target.fileno())
|
|
80
|
+
except BaseException:
|
|
81
|
+
path.unlink(missing_ok=True)
|
|
82
|
+
raise
|
|
83
|
+
return path
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def save_recording(
|
|
87
|
+
data: bytes,
|
|
88
|
+
file_index: int,
|
|
89
|
+
directory: str | Path,
|
|
90
|
+
*,
|
|
91
|
+
metadata: dict | None = None,
|
|
92
|
+
) -> dict:
|
|
93
|
+
"""Save raw bytes first, then attempt WAV decoding with a five-second timeout.
|
|
94
|
+
|
|
95
|
+
Decode errors return a raw-only result with a warning; filesystem errors
|
|
96
|
+
propagate. Duration is taken only from a valid WAV header. Optional metadata
|
|
97
|
+
persists only an integer SDK record_time, byte count and device file index.
|
|
98
|
+
All filenames are generated locally, independently of device input.
|
|
99
|
+
"""
|
|
100
|
+
if not isinstance(data, bytes):
|
|
101
|
+
raise TypeError("data must be bytes")
|
|
102
|
+
if not data:
|
|
103
|
+
raise ValueError("Recording data must not be empty")
|
|
104
|
+
if isinstance(file_index, bool) or not isinstance(file_index, int):
|
|
105
|
+
raise ValueError("file_index must be an unsigned 32-bit integer")
|
|
106
|
+
if not 0 <= file_index <= 0xFFFFFFFF:
|
|
107
|
+
raise ValueError("file_index must be an unsigned 32-bit integer")
|
|
108
|
+
if metadata is not None and not isinstance(metadata, dict):
|
|
109
|
+
raise TypeError("metadata must be a dictionary or None")
|
|
110
|
+
|
|
111
|
+
directory = Path(directory).expanduser().resolve()
|
|
112
|
+
directory.mkdir(parents=True, exist_ok=True)
|
|
113
|
+
raw_path = _save_unique(directory, ".bin", data)
|
|
114
|
+
result = {
|
|
115
|
+
"path": str(raw_path), "raw_path": str(raw_path), "duration_s": None,
|
|
116
|
+
"bytes": len(data), "file_index": file_index, "warning": None,
|
|
117
|
+
}
|
|
118
|
+
if metadata is not None:
|
|
119
|
+
safe_metadata = {"bytes": len(data), "file_index": file_index}
|
|
120
|
+
record_time = metadata.get("record_time")
|
|
121
|
+
if type(record_time) is int:
|
|
122
|
+
safe_metadata["record_time"] = record_time
|
|
123
|
+
metadata_path = _save_unique(
|
|
124
|
+
directory, ".metadata.json", json.dumps(safe_metadata).encode("utf-8"),
|
|
125
|
+
prefix=raw_path.stem + "-",
|
|
126
|
+
)
|
|
127
|
+
result["metadata_path"] = str(metadata_path)
|
|
128
|
+
|
|
129
|
+
try:
|
|
130
|
+
wav_bytes = sdk.decode_audio_to_wav(data, speex_decoder=_bounded_speex_decoder)
|
|
131
|
+
with wave.open(io.BytesIO(wav_bytes), "rb") as decoded:
|
|
132
|
+
duration_s = decoded.getnframes() / decoded.getframerate()
|
|
133
|
+
except Exception as exc:
|
|
134
|
+
result["warning"] = f"Raw recording saved; WAV unavailable: {exc}"
|
|
135
|
+
return result
|
|
136
|
+
|
|
137
|
+
# Do not catch filesystem failures as if saving had succeeded.
|
|
138
|
+
wav_path = _save_unique(directory, ".wav", wav_bytes, prefix=raw_path.stem + "-")
|
|
139
|
+
result.update(path=str(wav_path), duration_s=duration_s)
|
|
140
|
+
return result
|