openfoci 0.1.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.
openfoci/__init__.py ADDED
@@ -0,0 +1,43 @@
1
+ """
2
+ OpenFOCI — Open-Source BLE Driver & Neurometric Telemetry Engine for FOCI Wearables.
3
+
4
+ Reviving TinyLogics FOCI / FOCI 2 biometric wearables with sovereign, local-first
5
+ Bluetooth Low Energy (BLE) diaphragmatic respiration and cognitive state tracking.
6
+ """
7
+
8
+ __version__ = "0.1.0"
9
+ __author__ = "OpenFOCI Contributors"
10
+ __license__ = "MIT"
11
+
12
+ from openfoci.protocol import (
13
+ AIRSYNC_SERVICE_UUID,
14
+ INDICATE_CHAR_UUID,
15
+ NOTIFY_CHAR_UUID,
16
+ WRITE_CHAR_UUID,
17
+ READ_CHAR_UUID,
18
+ MIND_STATES,
19
+ KTYPE_STREAKS,
20
+ compute_write_key,
21
+ battery_mv_to_percentage,
22
+ )
23
+ from openfoci.analyzer import RollingBreathAnalyzer
24
+ from openfoci.client import FociDevice, FociBleDriver
25
+ from openfoci.synthetic import run_synthetic_stream, SyntheticFociGenerator
26
+
27
+ __all__ = [
28
+ "__version__",
29
+ "AIRSYNC_SERVICE_UUID",
30
+ "INDICATE_CHAR_UUID",
31
+ "NOTIFY_CHAR_UUID",
32
+ "WRITE_CHAR_UUID",
33
+ "READ_CHAR_UUID",
34
+ "MIND_STATES",
35
+ "KTYPE_STREAKS",
36
+ "compute_write_key",
37
+ "battery_mv_to_percentage",
38
+ "RollingBreathAnalyzer",
39
+ "FociDevice",
40
+ "FociBleDriver",
41
+ "run_synthetic_stream",
42
+ "SyntheticFociGenerator",
43
+ ]
openfoci/analyzer.py ADDED
@@ -0,0 +1,120 @@
1
+ """
2
+ OpenFOCI Rolling Biometric Respiration & Coherence Signal Analyzer.
3
+
4
+ Maintains a 60-second rolling window of diaphragmatic micro-motion samples at 10 Hz.
5
+ Executes peak/trough detection, calculates breaths-per-minute (BPM), breath rhythm
6
+ fluidity / coherence index, and diaphragmatic excursion depth.
7
+ """
8
+
9
+ import time
10
+ import math
11
+ from collections import deque
12
+ from typing import Dict, Any, Optional, List
13
+
14
+ class RollingBreathAnalyzer:
15
+ """
16
+ Biological signal analyzer for waist-worn diaphragmatic micro-motion accelerometer sensors.
17
+
18
+ Provides:
19
+ - Real-time respiration rate (BPM) with biological refractory limits (7.5 - 40 BPM).
20
+ - Fluidity / Heart-Breath Coherence index (0-100%) from inter-breath interval variability.
21
+ - Diaphragmatic excursion depth (0-100%) from peak-to-trough amplitude.
22
+ - Normalized waveform buffer (-1.0 to +1.0) for live 10 Hz visualizer rendering.
23
+ """
24
+
25
+ def __init__(self, window_seconds: float = 60.0):
26
+ self.window_seconds = window_seconds
27
+ # 10 Hz * 60s = 600 samples
28
+ self.samples = deque(maxlen=int(window_seconds * 10))
29
+ self.breath_intervals = deque(maxlen=25)
30
+ self.recent_peaks = deque(maxlen=12)
31
+ self.recent_troughs = deque(maxlen=12)
32
+ self.recent_wave_samples = deque(maxlen=32)
33
+
34
+ self.last_peak_time: Optional[float] = None
35
+ self.last_signal: Optional[float] = None
36
+ self.direction = 0 # 1 = rising, -1 = falling
37
+
38
+ # Baseline biometric estimates
39
+ self.current_bpm: float = 14.0
40
+ self.current_depth: int = 70
41
+ self.current_fluidity: int = 85
42
+ self.amplitude: float = 0.5
43
+
44
+ def add_sample(self, signal_val: int, timestamp: Optional[float] = None) -> None:
45
+ """
46
+ Ingests a raw micro-motion accelerometer sample (typically sampled at 10 Hz).
47
+ """
48
+ t = timestamp or time.time()
49
+ self.samples.append((t, signal_val))
50
+
51
+ # Maintain normalized wave samples (-1.0 to +1.0) for real-time oscilloscope
52
+ norm_val = round(max(-1.0, min(1.0, signal_val / 500.0)), 3)
53
+ self.recent_wave_samples.append(norm_val)
54
+
55
+ # Peak and trough detection with refractory thresholds (1.5s to 8.0s = 7.5 to 40 bpm)
56
+ if self.last_signal is not None:
57
+ delta = signal_val - self.last_signal
58
+ if delta > 15 and self.direction <= 0:
59
+ # Trough detected (started rising)
60
+ self.direction = 1
61
+ self.recent_troughs.append((t, self.last_signal))
62
+ elif delta < -15 and self.direction >= 0:
63
+ # Peak detected (started falling)
64
+ self.direction = -1
65
+ self.recent_peaks.append((t, self.last_signal))
66
+
67
+ if self.last_peak_time is not None:
68
+ interval = t - self.last_peak_time
69
+ if 1.5 <= interval <= 8.0:
70
+ self.breath_intervals.append(interval)
71
+ inst_bpm = 60.0 / interval
72
+ # Smooth update using exponential moving average
73
+ self.current_bpm = round(0.7 * self.current_bpm + 0.3 * inst_bpm, 1)
74
+ self.last_peak_time = t
75
+
76
+ self.last_signal = signal_val
77
+
78
+ # Recalculate amplitude & depth from peak-to-trough delta
79
+ if len(self.recent_peaks) >= 2 and len(self.recent_troughs) >= 2:
80
+ avg_peak = sum(v for _, v in self.recent_peaks) / len(self.recent_peaks)
81
+ avg_trough = sum(v for _, v in self.recent_troughs) / len(self.recent_troughs)
82
+ pk_pk = max(0.0, avg_peak - avg_trough)
83
+ self.amplitude = round(min(1.0, pk_pk / 1000.0), 3)
84
+ self.current_depth = int(min(100, max(15, self.amplitude * 100)))
85
+
86
+ # Rhythm fluidity / coherence from coefficient of variation (CV) of intervals
87
+ if len(self.breath_intervals) >= 3:
88
+ avg_int = sum(self.breath_intervals) / len(self.breath_intervals)
89
+ variance = sum((x - avg_int) ** 2 for x in self.breath_intervals) / len(self.breath_intervals)
90
+ std_dev = math.sqrt(variance)
91
+ cv = (std_dev / avg_int) if avg_int > 0 else 0.5
92
+ # Low variance (smooth rhythmic breathing) yields high coherence
93
+ coherence = max(15, min(99, int((1.0 - min(1.0, cv * 2.0)) * 100)))
94
+ self.current_fluidity = coherence
95
+
96
+ def get_summary(self) -> Dict[str, Any]:
97
+ """Returns a snapshot dictionary of all computed respiratory and coherence metrics."""
98
+ return {
99
+ "respirationRate": self.current_bpm,
100
+ "breathWaveAmplitude": self.amplitude,
101
+ "inhalationExhalationRatio": 0.48,
102
+ "diaphragmaticDepth": self.current_depth,
103
+ "fluidity": self.current_fluidity,
104
+ "breathWaveSamples": list(self.recent_wave_samples) or [0.1, 0.3, 0.6, 0.4, 0.1, -0.2, -0.4, -0.1],
105
+ }
106
+
107
+ def reset(self) -> None:
108
+ """Resets the rolling window and state counters."""
109
+ self.samples.clear()
110
+ self.breath_intervals.clear()
111
+ self.recent_peaks.clear()
112
+ self.recent_troughs.clear()
113
+ self.recent_wave_samples.clear()
114
+ self.last_peak_time = None
115
+ self.last_signal = None
116
+ self.direction = 0
117
+ self.current_bpm = 14.0
118
+ self.current_depth = 70
119
+ self.current_fluidity = 85
120
+ self.amplitude = 0.5
openfoci/cli.py ADDED
@@ -0,0 +1,299 @@
1
+ """
2
+ OpenFOCI Universal Command-Line Interface.
3
+
4
+ Commands:
5
+ openfoci scan Scan for nearby FOCI BLE clips
6
+ openfoci stream Live terminal telemetry stream with ASCII biofeedback meter
7
+ openfoci daemon Run as background telemetry ingestion daemon
8
+ openfoci serve Launch the interactive Mind Orb web cockpit & SSE server
9
+ openfoci status Inspect the latest biometric snapshot and wear state
10
+ openfoci export Export recorded SQLite telemetry to CSV
11
+ """
12
+
13
+ import sys
14
+ import os
15
+ import time
16
+ import json
17
+ import signal
18
+ import argparse
19
+ import asyncio
20
+ import threading
21
+ from pathlib import Path
22
+ from datetime import datetime
23
+
24
+ from openfoci import __version__
25
+ from openfoci.protocol import AIRSYNC_SERVICE_UUID
26
+ from openfoci.client import FociDevice, FociBleDriver, HAS_BLEAK
27
+ from openfoci.synthetic import run_synthetic_stream
28
+ from openfoci.storage.json_store import JsonStorage
29
+ from openfoci.storage.sqlite_store import SqliteStorage
30
+ from openfoci.storage.csv_store import CsvStorage
31
+ from openfoci.web_server import run_web_server, FociHttpHandler
32
+
33
+ # ANSI Terminal Colors
34
+ C_RESET = "\033[0m"
35
+ C_BOLD = "\033[1m"
36
+ C_CYAN = "\033[36m"
37
+ C_GREEN = "\033[32m"
38
+ C_YELLOW = "\033[33m"
39
+ C_RED = "\033[31m"
40
+ C_MAGENTA = "\033[35m"
41
+ C_BLUE = "\033[34m"
42
+
43
+ DEFAULT_MAC = "a4:11:63:e0:7e:87"
44
+ DEFAULT_UID = 1001
45
+
46
+ async def cli_scan():
47
+ if not HAS_BLEAK:
48
+ print(f"{C_RED}Error: 'bleak' library is required for BLE scanning. Run: pip install bleak{C_RESET}")
49
+ sys.exit(1)
50
+ from bleak import BleakScanner
51
+
52
+ print(f"{C_CYAN}🔍 Scanning for nearby BLE devices (8 seconds)...{C_RESET}")
53
+ devices = await BleakScanner.discover(timeout=8.0, return_adv=True)
54
+
55
+ print("\n" + "=" * 76)
56
+ print(f"{'DEVICE NAME':<26} {'BLE ADDRESS / UUID':<36} {'RSSI':<8} {'MATCH'}")
57
+ print("=" * 76)
58
+
59
+ matches = 0
60
+ for d, adv in devices.values():
61
+ name = d.name or (adv.local_name if adv else None) or "Unknown"
62
+ rssi = adv.rssi if adv else "N/A"
63
+ is_foci = "foci" in name.lower() or (d.address and d.address.lower() == DEFAULT_MAC.lower())
64
+ match_str = f"{C_GREEN}★ FOCI DETECTED{C_RESET}" if is_foci else ""
65
+ if is_foci:
66
+ matches += 1
67
+ print(f"{name:<26} {d.address:<36} {rssi} dBm {match_str}")
68
+
69
+ print("=" * 76)
70
+ print(f"Total discovered: {len(devices)} | FOCI targets: {matches}\n")
71
+
72
+ def render_ascii_meter(value: float, max_val: float = 30.0, width: int = 16) -> str:
73
+ """Renders a smooth ASCII level meter."""
74
+ filled = int(min(width, max(0, (value / max_val) * width)))
75
+ return f"[{'█' * filled}{'░' * (width - filled)}]"
76
+
77
+ def format_state_pill(st: str) -> str:
78
+ st_upper = st.upper()
79
+ if st == "flow":
80
+ return f"{C_CYAN}{C_BOLD}{st_upper}{C_RESET}"
81
+ if st == "focus":
82
+ return f"{C_MAGENTA}{C_BOLD}{st_upper}{C_RESET}"
83
+ if st == "calm":
84
+ return f"{C_GREEN}{C_BOLD}{st_upper}{C_RESET}"
85
+ if st == "stress":
86
+ return f"{C_RED}{C_BOLD}{st_upper}{C_RESET}"
87
+ return f"{C_YELLOW}{st_upper}{C_RESET}"
88
+
89
+ async def cli_stream(args):
90
+ device = FociDevice(mac=args.device, uid=args.uid)
91
+ json_store = JsonStorage(args.json_out) if args.json_out else None
92
+ sqlite_store = SqliteStorage(args.db) if args.db else None
93
+ csv_store = CsvStorage(args.csv_out) if args.csv_out else None
94
+
95
+ def on_telemetry(snapshot):
96
+ if json_store:
97
+ json_store.save(snapshot)
98
+ if sqlite_store:
99
+ sqlite_store.save(snapshot)
100
+ if csv_store:
101
+ csv_store.save(snapshot)
102
+ FociHttpHandler.latest_snapshot = snapshot
103
+
104
+ print(f"\n{C_BOLD}🫁 OpenFOCI Telemetry Engine v{__version__}{C_RESET}")
105
+ print(f" Target Device: {device.mac} (UID {device.uid})")
106
+ print(f" Mode: {'Synthetic Simulation' if args.synthetic else 'Physical BLE Link'}")
107
+ if args.db:
108
+ print(f" SQLite Storage: {args.db}")
109
+ if args.json_out:
110
+ print(f" JSON Snapshot: {args.json_out}")
111
+ print("-" * 65)
112
+
113
+ last_render = 0.0
114
+
115
+ def on_sample(sig):
116
+ nonlocal last_render
117
+ now = time.time()
118
+ if now - last_render >= 1.0:
119
+ last_render = now
120
+ snap = device.build_snapshot()
121
+ bpm = snap["breath"]["respirationRate"]
122
+ fluidity = snap["breath"]["fluidity"]
123
+ depth = snap["breath"]["diaphragmaticDepth"]
124
+ batt = snap["batteryLevel"]
125
+ st = snap["mentalState"]
126
+ meter = render_ascii_meter(bpm, 25.0, 12)
127
+ ts = datetime.now().strftime("%H:%M:%S")
128
+ worn_icon = "✓" if snap["isWorn"] else "✗"
129
+
130
+ print(
131
+ f"[{ts}] {format_state_pill(st):<18} | "
132
+ f"Resp: {bpm:4.1f} bpm {meter} | "
133
+ f"Fluidity: {fluidity:2d}% | "
134
+ f"Depth: {depth:2d}% | "
135
+ f"Batt: {batt:2d}% [{worn_icon}]"
136
+ )
137
+
138
+ if args.synthetic:
139
+ await run_synthetic_stream(device, on_telemetry=on_telemetry, on_sample=on_sample)
140
+ else:
141
+ if not HAS_BLEAK:
142
+ print(f"{C_YELLOW}Bleak not installed. Falling back to synthetic simulation mode...{C_RESET}")
143
+ await run_synthetic_stream(device, on_telemetry=on_telemetry, on_sample=on_sample)
144
+ else:
145
+ driver = FociBleDriver(device, on_telemetry=on_telemetry, on_sample=on_sample)
146
+ await driver.run()
147
+
148
+ def cli_serve(args):
149
+ device = FociDevice(mac=args.device, uid=args.uid)
150
+ sqlite_store = SqliteStorage(args.db) if args.db else None
151
+ json_store = JsonStorage(args.json_out) if args.json_out else None
152
+
153
+ def on_telemetry(snapshot):
154
+ if sqlite_store:
155
+ sqlite_store.save(snapshot)
156
+ if json_store:
157
+ json_store.save(snapshot)
158
+ FociHttpHandler.latest_snapshot = snapshot
159
+
160
+ # Start telemetry source in background thread
161
+ def telemetry_worker():
162
+ loop = asyncio.new_event_loop()
163
+ asyncio.set_event_loop(loop)
164
+ if args.synthetic or not HAS_BLEAK:
165
+ loop.run_until_complete(run_synthetic_stream(device, on_telemetry=on_telemetry))
166
+ else:
167
+ driver = FociBleDriver(device, on_telemetry=on_telemetry)
168
+ loop.run_until_complete(driver.run())
169
+
170
+ t = threading.Thread(target=telemetry_worker, daemon=True)
171
+ t.start()
172
+
173
+ server = run_web_server(storage=sqlite_store, host="0.0.0.0", port=args.port)
174
+ url = f"http://localhost:{args.port}"
175
+ print(f"\n{C_GREEN}{C_BOLD}⚡ OpenFOCI Mind Orb Cockpit running at: {url}{C_RESET}")
176
+ print(f" REST API: {url}/api/telemetry")
177
+ print(f" SSE Stream: {url}/api/stream")
178
+ print(f" History: {url}/api/history")
179
+ print(f" Press Ctrl+C to terminate.\n")
180
+
181
+ try:
182
+ server.serve_forever()
183
+ except KeyboardInterrupt:
184
+ print("\nStopping web server...")
185
+ server.shutdown()
186
+
187
+ def cli_status(args):
188
+ json_path = Path(args.json_out)
189
+ if json_path.exists():
190
+ try:
191
+ data = json.loads(json_path.read_text(encoding="utf-8"))
192
+ print("\n" + "=" * 60)
193
+ print("🫁 OPENFOCI TELEMETRY STATUS SNAPSHOT")
194
+ print("=" * 60)
195
+ print(f" Device: {data.get('deviceName')} ({data.get('deviceId')})")
196
+ print(f" Link: {'🟢 CONNECTED' if data.get('isConnected') else '⚪ DISCONNECTED'}")
197
+ print(f" Placement: {'✓ Worn on waist' if data.get('isWorn') else '✗ Not worn / resting'}")
198
+ print(f" Battery: {data.get('batteryLevel')}% ({data.get('batteryMv', 3900)} mV)")
199
+ print(f" Mental State: {data.get('mentalState', '').upper()}")
200
+ print(f" Respiration: {data.get('breath', {}).get('respirationRate', 0)} breaths/min")
201
+ print(f" Fluidity: {data.get('breath', {}).get('fluidity', 0)}% rhythm coherence")
202
+ print(f" Depth: {data.get('breath', {}).get('diaphragmaticDepth', 0)}% diaphragmatic excursion")
203
+ print(f" Vitality: {data.get('scores', {}).get('vitalityScore', 0):+.2f} score impact")
204
+ print(f" Timestamp: {data.get('timestamp')}")
205
+ print("=" * 60 + "\n")
206
+ return
207
+ except Exception as e:
208
+ print(f"{C_RED}Error reading snapshot: {e}{C_RESET}")
209
+ return
210
+
211
+ # Check SQLite
212
+ db_path = Path(args.db)
213
+ if db_path.exists():
214
+ store = SqliteStorage(str(db_path))
215
+ latest = store.get_latest()
216
+ if latest:
217
+ print(f"\nLatest SQLite record: {latest.get('mentalState')} | {latest.get('breath', {}).get('respirationRate')} bpm")
218
+ return
219
+
220
+ print(f"{C_YELLOW}No active OpenFOCI telemetry found at {json_path} or {db_path}.{C_RESET}")
221
+
222
+ def cli_export(args):
223
+ db_path = Path(args.db)
224
+ if not db_path.exists():
225
+ print(f"{C_RED}Error: SQLite database {db_path} does not exist.{C_RESET}")
226
+ sys.exit(1)
227
+ store = SqliteStorage(str(db_path))
228
+ count = store.export_to_csv(args.out)
229
+ print(f"{C_GREEN}✓ Exported {count} telemetry records to {args.out}{C_RESET}")
230
+
231
+ def main():
232
+ parser = argparse.ArgumentParser(
233
+ prog="openfoci",
234
+ description="OpenFOCI — Open-source BLE telemetry engine and Mind Orb visualizer for FOCI wearables."
235
+ )
236
+ parser.add_argument("--version", action="version", version=f"OpenFOCI {__version__}")
237
+ subparsers = parser.add_subparsers(dest="command", help="Sub-commands")
238
+
239
+ # scan
240
+ p_scan = subparsers.add_parser("scan", help="Scan for nearby FOCI BLE clips")
241
+
242
+ # stream
243
+ p_stream = subparsers.add_parser("stream", help="Stream live telemetry to terminal")
244
+ p_stream.add_argument("--device", type=str, default=DEFAULT_MAC, help=f"BLE MAC / UUID (default: {DEFAULT_MAC})")
245
+ p_stream.add_argument("--uid", type=int, default=DEFAULT_UID, help=f"Pairing user ID (default: {DEFAULT_UID})")
246
+ p_stream.add_argument("--synthetic", action="store_true", help="Emulate FOCI clip with synthetic breathing wave")
247
+ p_stream.add_argument("--db", type=str, default="openfoci.db", help="SQLite database output path")
248
+ p_stream.add_argument("--json-out", type=str, default="foci_telemetry.json", help="JSON snapshot output path")
249
+ p_stream.add_argument("--csv-out", type=str, default="", help="CSV high-frequency log output path")
250
+
251
+ # daemon
252
+ p_daemon = subparsers.add_parser("daemon", help="Run background telemetry collection daemon")
253
+ p_daemon.add_argument("--device", type=str, default=DEFAULT_MAC, help="BLE MAC / UUID")
254
+ p_daemon.add_argument("--uid", type=int, default=DEFAULT_UID, help="Pairing user ID")
255
+ p_daemon.add_argument("--db", type=str, default="openfoci.db", help="SQLite database path")
256
+ p_daemon.add_argument("--json-out", type=str, default="foci_telemetry.json", help="JSON snapshot path")
257
+
258
+ # serve
259
+ p_serve = subparsers.add_parser("serve", help="Launch interactive Mind Orb web cockpit")
260
+ p_serve.add_argument("--port", type=int, default=8080, help="Web server port (default: 8080)")
261
+ p_serve.add_argument("--device", type=str, default=DEFAULT_MAC, help="BLE MAC / UUID")
262
+ p_serve.add_argument("--uid", type=int, default=DEFAULT_UID, help="Pairing user ID")
263
+ p_serve.add_argument("--synthetic", action="store_true", help="Run with synthetic simulated biometrics")
264
+ p_serve.add_argument("--db", type=str, default="openfoci.db", help="SQLite database path")
265
+ p_serve.add_argument("--json-out", type=str, default="foci_telemetry.json", help="JSON snapshot path")
266
+
267
+ # status
268
+ p_status = subparsers.add_parser("status", help="Inspect latest recorded telemetry snapshot")
269
+ p_status.add_argument("--json-out", type=str, default="foci_telemetry.json", help="JSON snapshot path")
270
+ p_status.add_argument("--db", type=str, default="openfoci.db", help="SQLite database path")
271
+
272
+ # export
273
+ p_export = subparsers.add_parser("export", help="Export SQLite telemetry to CSV")
274
+ p_export.add_argument("--out", type=str, required=True, help="Destination CSV file path")
275
+ p_export.add_argument("--db", type=str, default="openfoci.db", help="Source SQLite database path")
276
+
277
+ args = parser.parse_args()
278
+
279
+ if not args.command:
280
+ parser.print_help()
281
+ sys.exit(0)
282
+
283
+ if args.command == "scan":
284
+ asyncio.run(cli_scan())
285
+ elif args.command == "stream":
286
+ asyncio.run(cli_stream(args))
287
+ elif args.command == "daemon":
288
+ args.synthetic = False
289
+ args.csv_out = ""
290
+ asyncio.run(cli_stream(args))
291
+ elif args.command == "serve":
292
+ cli_serve(args)
293
+ elif args.command == "status":
294
+ cli_status(args)
295
+ elif args.command == "export":
296
+ cli_export(args)
297
+
298
+ if __name__ == "__main__":
299
+ main()