openfoci 0.1.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.
@@ -0,0 +1,233 @@
1
+ Metadata-Version: 2.4
2
+ Name: openfoci
3
+ Version: 0.1.0
4
+ Summary: Open-source BLE driver, telemetry engine, and local-first biofeedback visualizer for FOCI wearables.
5
+ Author: OpenFOCI Contributors
6
+ License: MIT
7
+ Keywords: foci,wearable,bluetooth,ble,respiration,biofeedback,airsync,diaphragm,telemetry
8
+ Classifier: Development Status :: 4 - Beta
9
+ Classifier: Intended Audience :: Developers
10
+ Classifier: Intended Audience :: Healthcare Industry
11
+ Classifier: Intended Audience :: Science/Research
12
+ Classifier: License :: OSI Approved :: MIT License
13
+ Classifier: Operating System :: MacOS
14
+ Classifier: Operating System :: POSIX :: Linux
15
+ Classifier: Operating System :: Microsoft :: Windows
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.9
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Topic :: Scientific/Engineering :: Medical Science Apps.
22
+ Classifier: Topic :: System :: Hardware :: Hardware Drivers
23
+ Requires-Python: >=3.9
24
+ Description-Content-Type: text/markdown
25
+ Requires-Dist: bleak>=0.21.0
26
+ Provides-Extra: dev
27
+ Requires-Dist: pytest>=8.0.0; extra == "dev"
28
+ Requires-Dist: pytest-asyncio>=0.23.0; extra == "dev"
29
+ Provides-Extra: mqtt
30
+ Requires-Dist: paho-mqtt>=1.6.0; extra == "mqtt"
31
+
32
+ # OpenFOCI: Sovereign Biofeedback & Wearable Telemetry Engine
33
+
34
+ [![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
35
+ [![License: MIT](https://img.shields.io/badge/License-MIT-emerald.svg)](LICENSE)
36
+ [![Tests](https://img.shields.io/badge/tests-15%20passed-brightgreen.svg)](tests/)
37
+ [![Architecture](https://img.shields.io/badge/architecture-local--first-cyan.svg)](#architecture)
38
+ [![Hardware](https://img.shields.io/badge/hardware-Dialog%20DA14580%20ARM-indigo.svg)](docs/GATT_SPEC.md)
39
+
40
+ Open-source Bluetooth Low Energy (BLE) driver, real-time diaphragmatic respiration telemetry engine, and local-first **Mind Orb** biofeedback visualizer for **FOCI** and **FOCI 2** biometric wearables.
41
+
42
+ ---
43
+
44
+ <p align="center">
45
+ <img src="assets/mind_orb_preview.svg" alt="OpenFOCI Mind Orb and 10 Hz Oscilloscope" width="100%" />
46
+ </p>
47
+
48
+ ---
49
+
50
+ ## Right to Repair & Technical Backstory
51
+
52
+ Between 2018 and 2021, Cambridge-based startup **Tinylogics Ltd** raised over \$900,000 across [Kickstarter](https://www.kickstarter.com/projects/661527809/foci-wearable-that-boosts-your-focus) and [Indiegogo](https://www.indiegogo.com/projects/foci-2-boosts-your-focus-productivity-with-ai#/) from thousands of backers to produce **FOCI**, a waist-worn clip tracking diaphragmatic breathing patterns and cognitive state estimates (*Flow, Focus, Calm, Distraction, Fatigue*).
53
+
54
+ Following company dissolution in September 2025 ([UK Companies House #08954266](https://find-and-update.company-information.service.gov.uk/company/08954266)), the centralized authentication servers were deactivated and the mobile app (`com.tinylogics.foci`) was removed from distribution, stranding physical devices at a cloud login gate.
55
+
56
+ ### Reverse-Engineering Findings
57
+
58
+ 1. **On-Device Inference**: Digital signal processing (DSP), zero-crossing respiration rate computation, autoregressive motion parameters (AR1/AR3), and mental state classifications execute directly on the wearable's **Dialog Semiconductor DA14580 Cortex-M0 SoC**. Cloud endpoints served solely as an account/licensing check.
59
+ 2. **WeChat AirSync Profile**: The peripheral advertises standard GATT Service `0xFEE7` and uses standard AirSync framing with a 4-byte CRC32 challenge.
60
+ 3. **Cryptographic WriteKey Derivation**: Device authorization requires a 32-bit key computed from:
61
+ ```text
62
+ writeKey = MD5(UID + "3BF608C70828" + reversed_mac_hex)[:4]
63
+ ```
64
+ 4. **Hardware Interface**: The physical magnetic cradle exposes only two contacts (+5V and GND) for charging. All diagnostic and data exchange must occur over BLE.
65
+
66
+ **OpenFOCI** restores full utility to this hardware without proprietary cloud intermediaries. It negotiates the BLE authentication handshake, streams raw 10 Hz diaphragmatic waveforms, and exposes modern visualization and data interfaces.
67
+
68
+ ---
69
+
70
+ ## System Architecture
71
+
72
+ <p align="center">
73
+ <img src="assets/openfoci_architecture.svg" alt="OpenFOCI Architecture" width="100%" />
74
+ </p>
75
+
76
+ ---
77
+
78
+ ## Key Capabilities
79
+
80
+ - **Hardware BLE Driver**: Full asynchronous driver for WeChat AirSync (`0xFEE7` GATT) with 20-byte MTU slicing, challenge-response negotiation, and keepalive management.
81
+ - **10 Hz Respiration Oscilloscope**: Real-time diaphragmatic displacement capture isolating abdominal excursion from gross body motion.
82
+ - **Rolling Biometric Analyzer**: 60-second rolling window peak and trough detector computing respiration rate (BPM), rhythm regularity (fluidity/coherence percentage), and diaphragmatic excursion depth.
83
+ - **Mind Orb Visualizer**: Modern WebGL / Next.js cockpit with fluid particle physics responding dynamically to respiratory cycles and autonomic state indicators.
84
+ - **Pluggable Persistence**: Stream telemetry to SQLite databases, high-frequency CSV files, atomic JSON files, or forward to HTTP webhooks.
85
+ - **Home Assistant & MQTT Integration**: Automated MQTT discovery schema for home automation triggers based on autonomic state shifts.
86
+ - **Synthetic Simulation Engine**: Complete mathematical emulation generating realistic biological respiratory harmonics and state cycles for offline development without physical hardware.
87
+
88
+ ---
89
+
90
+ ## Quickstart
91
+
92
+ ### 1. Installation
93
+
94
+ Requires Python 3.9+ and a Bluetooth 4.0+ adapter (macOS CoreBluetooth and Linux BlueZ supported).
95
+
96
+ ```bash
97
+ git clone https://github.com/holy-script/OpenFOCI.git
98
+ cd OpenFOCI
99
+
100
+ # Install in editable mode
101
+ pip install -e .
102
+
103
+ # Install with testing dependencies
104
+ pip install -e ".[dev]"
105
+ ```
106
+
107
+ ### 2. Discover Your Clip
108
+
109
+ Ensure the clip is charged and located near your computer:
110
+
111
+ ```bash
112
+ openfoci scan
113
+ ```
114
+
115
+ Output:
116
+ ```text
117
+ Scanning for nearby BLE devices (8 seconds)...
118
+ ============================================================================
119
+ DEVICE NAME BLE ADDRESS / UUID RSSI MATCH
120
+ ============================================================================
121
+ FOCI 5C7427EA-91E6-9039-5D37-6D185EB23FC5 -61 dBm FOCI DETECTED
122
+ ============================================================================
123
+ Total discovered: 6 | FOCI targets: 1
124
+ ```
125
+
126
+ ### 3. Stream Live Biometrics in Terminal
127
+
128
+ ```bash
129
+ openfoci stream
130
+ ```
131
+
132
+ Terminal HUD:
133
+ ```text
134
+ ============================================================================
135
+ FOCI WEARABLE TELEMETRY HUD (OpenFOCI Core)
136
+ ============================================================================
137
+ Device: FOCI 78 (a4:11:63:e0:7e:87)
138
+ Connection: CONNECTED
139
+ Wearing State: Worn on waistband
140
+ Battery: 88% (3900 mV)
141
+ Mental State: FLOW (Confidence: 85%)
142
+ Respiration: 14.0 breaths/min
143
+ Fluidity: 85% coherence
144
+ Excursion: 70% diaphragmatic depth
145
+ Streak: Focus Streak (25 min)
146
+ ============================================================================
147
+ ```
148
+
149
+ ### 4. Launch the Mind Orb Cockpit
150
+
151
+ Run the local web dashboard and SSE stream:
152
+
153
+ ```bash
154
+ openfoci serve --port 8080
155
+ ```
156
+
157
+ Open [http://localhost:8080](http://localhost:8080) to inspect the live fluid Mind Orb and real-time 10 Hz oscilloscope.
158
+
159
+ ---
160
+
161
+ ## Python SDK Example
162
+
163
+ Integrate OpenFOCI directly into custom analytics, agents, or automation loops:
164
+
165
+ ```python
166
+ import asyncio
167
+ from openfoci.client import FociDevice, FociBleDriver
168
+
169
+ async def main():
170
+ device = FociDevice(mac="a4:11:63:e0:7e:87")
171
+
172
+ def handle_telemetry(snapshot):
173
+ bpm = snapshot["breath"]["respirationRate"]
174
+ coherence = snapshot["breath"]["fluidity"]
175
+ state = snapshot["mentalState"]
176
+ battery = snapshot["batteryLevel"]
177
+ print(f"[{state.upper()}] {bpm:.1f} bpm | Coherence: {coherence}% | Battery: {battery}%")
178
+
179
+ driver = FociBleDriver(device, on_telemetry=handle_telemetry)
180
+ await driver.run()
181
+
182
+ if __name__ == "__main__":
183
+ asyncio.run(main())
184
+ ```
185
+
186
+ ---
187
+
188
+ ## Project Roadmap
189
+
190
+ - [x] **Phase 1: BLE Protocol Reverse-Engineering**
191
+ - [x] AirSync GATT service (`0xFEE7`) identification and 20-byte MTU slicing
192
+ - [x] AuthRequest (`0x2711`) and CRC32 InitRequest (`0x2713`) challenge resolution
193
+ - [x] `writeKey` derivation formula extraction
194
+ - [x] Continuous `0x4E22` SendData ACK loop
195
+ - [x] **Phase 2: Local Core Driver & Web Cockpit**
196
+ - [x] Asynchronous Python driver (`openfoci.client.FociBleDriver`)
197
+ - [x] 60-second rolling breath detector and coherence scoring
198
+ - [x] Modern WebGL Mind Orb cockpit with real-time SSE stream
199
+ - [x] Terminal biofeedback meter (`openfoci stream`)
200
+ - [x] **Phase 3: Pluggable Storage & Integrations**
201
+ - [x] SQLite time-series storage with indexed timestamps
202
+ - [x] High-frequency CSV sample exporter
203
+ - [x] Atomic JSON snapshot writer for local system daemons
204
+ - [x] Webhook / REST forwarding adapter
205
+ - [x] Home Assistant MQTT auto-discovery configuration
206
+ - [x] **Phase 4: Offline Android APK Repackaging**
207
+ - [x] Smali bytecode patch on `TrackerSDK.smali` (`checkLoginStatus -> true`)
208
+ - [x] Smali bytecode patch on `AccountManager.smali` (`hasAutoLoginToken -> true`, default UID `1001`)
209
+ - [x] Smali bytecode patch on `SplashViewPagerActivity.smali` (`loginSuccessFinished()` in `onCreate`)
210
+ - [x] Automated APK patcher script (`tools/patch_apk.sh`)
211
+ - [ ] **Phase 5: PyPI Release & Multi-OS CI/CD**
212
+ - [ ] PyPI distribution package (`pip install openfoci`)
213
+ - [ ] GitHub Actions CI across macOS, Linux, and Windows
214
+ - [ ] **Phase 6: Advanced Respiratory Sinus Arrhythmia (RSA) Model**
215
+ - [ ] Temporal Convolutional Network (TCN) trained on raw 10 Hz strain data
216
+ - [ ] Autonomic nervous system tone estimation (HRV proxy)
217
+ - [ ] Personalized user calibration profiles
218
+
219
+ ---
220
+
221
+ ## Technical Specifications & References
222
+
223
+ - [GATT Specification (docs/GATT_SPEC.md)](docs/GATT_SPEC.md): Full breakdown of UUIDs, byte offsets, opcodes, and bitmasks.
224
+ - [Protocol Reverse-Engineering Dossier (docs/PROTOCOL_BREAKDOWN.md)](docs/PROTOCOL_BREAKDOWN.md): Technical analysis of packet structures, cryptographic derivations, and firmware registers.
225
+ - [Home Assistant Guide (docs/HOME_ASSISTANT.md)](docs/HOME_ASSISTANT.md): Setup instructions for MQTT telemetry streaming and biofeedback automations.
226
+
227
+ ---
228
+
229
+ ## License
230
+
231
+ This project is licensed under the **MIT License** — see [LICENSE](LICENSE) for details.
232
+
233
+ *Disclaimer: OpenFOCI is an independent open-source hardware liberation and right-to-repair research project. It is not affiliated with, endorsed by, or sponsored by Tinylogics Ltd or its successors.*
@@ -0,0 +1,202 @@
1
+ # OpenFOCI: Sovereign Biofeedback & Wearable Telemetry Engine
2
+
3
+ [![Python 3.9+](https://img.shields.io/badge/python-3.9+-blue.svg)](https://www.python.org/downloads/)
4
+ [![License: MIT](https://img.shields.io/badge/License-MIT-emerald.svg)](LICENSE)
5
+ [![Tests](https://img.shields.io/badge/tests-15%20passed-brightgreen.svg)](tests/)
6
+ [![Architecture](https://img.shields.io/badge/architecture-local--first-cyan.svg)](#architecture)
7
+ [![Hardware](https://img.shields.io/badge/hardware-Dialog%20DA14580%20ARM-indigo.svg)](docs/GATT_SPEC.md)
8
+
9
+ Open-source Bluetooth Low Energy (BLE) driver, real-time diaphragmatic respiration telemetry engine, and local-first **Mind Orb** biofeedback visualizer for **FOCI** and **FOCI 2** biometric wearables.
10
+
11
+ ---
12
+
13
+ <p align="center">
14
+ <img src="assets/mind_orb_preview.svg" alt="OpenFOCI Mind Orb and 10 Hz Oscilloscope" width="100%" />
15
+ </p>
16
+
17
+ ---
18
+
19
+ ## Right to Repair & Technical Backstory
20
+
21
+ Between 2018 and 2021, Cambridge-based startup **Tinylogics Ltd** raised over \$900,000 across [Kickstarter](https://www.kickstarter.com/projects/661527809/foci-wearable-that-boosts-your-focus) and [Indiegogo](https://www.indiegogo.com/projects/foci-2-boosts-your-focus-productivity-with-ai#/) from thousands of backers to produce **FOCI**, a waist-worn clip tracking diaphragmatic breathing patterns and cognitive state estimates (*Flow, Focus, Calm, Distraction, Fatigue*).
22
+
23
+ Following company dissolution in September 2025 ([UK Companies House #08954266](https://find-and-update.company-information.service.gov.uk/company/08954266)), the centralized authentication servers were deactivated and the mobile app (`com.tinylogics.foci`) was removed from distribution, stranding physical devices at a cloud login gate.
24
+
25
+ ### Reverse-Engineering Findings
26
+
27
+ 1. **On-Device Inference**: Digital signal processing (DSP), zero-crossing respiration rate computation, autoregressive motion parameters (AR1/AR3), and mental state classifications execute directly on the wearable's **Dialog Semiconductor DA14580 Cortex-M0 SoC**. Cloud endpoints served solely as an account/licensing check.
28
+ 2. **WeChat AirSync Profile**: The peripheral advertises standard GATT Service `0xFEE7` and uses standard AirSync framing with a 4-byte CRC32 challenge.
29
+ 3. **Cryptographic WriteKey Derivation**: Device authorization requires a 32-bit key computed from:
30
+ ```text
31
+ writeKey = MD5(UID + "3BF608C70828" + reversed_mac_hex)[:4]
32
+ ```
33
+ 4. **Hardware Interface**: The physical magnetic cradle exposes only two contacts (+5V and GND) for charging. All diagnostic and data exchange must occur over BLE.
34
+
35
+ **OpenFOCI** restores full utility to this hardware without proprietary cloud intermediaries. It negotiates the BLE authentication handshake, streams raw 10 Hz diaphragmatic waveforms, and exposes modern visualization and data interfaces.
36
+
37
+ ---
38
+
39
+ ## System Architecture
40
+
41
+ <p align="center">
42
+ <img src="assets/openfoci_architecture.svg" alt="OpenFOCI Architecture" width="100%" />
43
+ </p>
44
+
45
+ ---
46
+
47
+ ## Key Capabilities
48
+
49
+ - **Hardware BLE Driver**: Full asynchronous driver for WeChat AirSync (`0xFEE7` GATT) with 20-byte MTU slicing, challenge-response negotiation, and keepalive management.
50
+ - **10 Hz Respiration Oscilloscope**: Real-time diaphragmatic displacement capture isolating abdominal excursion from gross body motion.
51
+ - **Rolling Biometric Analyzer**: 60-second rolling window peak and trough detector computing respiration rate (BPM), rhythm regularity (fluidity/coherence percentage), and diaphragmatic excursion depth.
52
+ - **Mind Orb Visualizer**: Modern WebGL / Next.js cockpit with fluid particle physics responding dynamically to respiratory cycles and autonomic state indicators.
53
+ - **Pluggable Persistence**: Stream telemetry to SQLite databases, high-frequency CSV files, atomic JSON files, or forward to HTTP webhooks.
54
+ - **Home Assistant & MQTT Integration**: Automated MQTT discovery schema for home automation triggers based on autonomic state shifts.
55
+ - **Synthetic Simulation Engine**: Complete mathematical emulation generating realistic biological respiratory harmonics and state cycles for offline development without physical hardware.
56
+
57
+ ---
58
+
59
+ ## Quickstart
60
+
61
+ ### 1. Installation
62
+
63
+ Requires Python 3.9+ and a Bluetooth 4.0+ adapter (macOS CoreBluetooth and Linux BlueZ supported).
64
+
65
+ ```bash
66
+ git clone https://github.com/holy-script/OpenFOCI.git
67
+ cd OpenFOCI
68
+
69
+ # Install in editable mode
70
+ pip install -e .
71
+
72
+ # Install with testing dependencies
73
+ pip install -e ".[dev]"
74
+ ```
75
+
76
+ ### 2. Discover Your Clip
77
+
78
+ Ensure the clip is charged and located near your computer:
79
+
80
+ ```bash
81
+ openfoci scan
82
+ ```
83
+
84
+ Output:
85
+ ```text
86
+ Scanning for nearby BLE devices (8 seconds)...
87
+ ============================================================================
88
+ DEVICE NAME BLE ADDRESS / UUID RSSI MATCH
89
+ ============================================================================
90
+ FOCI 5C7427EA-91E6-9039-5D37-6D185EB23FC5 -61 dBm FOCI DETECTED
91
+ ============================================================================
92
+ Total discovered: 6 | FOCI targets: 1
93
+ ```
94
+
95
+ ### 3. Stream Live Biometrics in Terminal
96
+
97
+ ```bash
98
+ openfoci stream
99
+ ```
100
+
101
+ Terminal HUD:
102
+ ```text
103
+ ============================================================================
104
+ FOCI WEARABLE TELEMETRY HUD (OpenFOCI Core)
105
+ ============================================================================
106
+ Device: FOCI 78 (a4:11:63:e0:7e:87)
107
+ Connection: CONNECTED
108
+ Wearing State: Worn on waistband
109
+ Battery: 88% (3900 mV)
110
+ Mental State: FLOW (Confidence: 85%)
111
+ Respiration: 14.0 breaths/min
112
+ Fluidity: 85% coherence
113
+ Excursion: 70% diaphragmatic depth
114
+ Streak: Focus Streak (25 min)
115
+ ============================================================================
116
+ ```
117
+
118
+ ### 4. Launch the Mind Orb Cockpit
119
+
120
+ Run the local web dashboard and SSE stream:
121
+
122
+ ```bash
123
+ openfoci serve --port 8080
124
+ ```
125
+
126
+ Open [http://localhost:8080](http://localhost:8080) to inspect the live fluid Mind Orb and real-time 10 Hz oscilloscope.
127
+
128
+ ---
129
+
130
+ ## Python SDK Example
131
+
132
+ Integrate OpenFOCI directly into custom analytics, agents, or automation loops:
133
+
134
+ ```python
135
+ import asyncio
136
+ from openfoci.client import FociDevice, FociBleDriver
137
+
138
+ async def main():
139
+ device = FociDevice(mac="a4:11:63:e0:7e:87")
140
+
141
+ def handle_telemetry(snapshot):
142
+ bpm = snapshot["breath"]["respirationRate"]
143
+ coherence = snapshot["breath"]["fluidity"]
144
+ state = snapshot["mentalState"]
145
+ battery = snapshot["batteryLevel"]
146
+ print(f"[{state.upper()}] {bpm:.1f} bpm | Coherence: {coherence}% | Battery: {battery}%")
147
+
148
+ driver = FociBleDriver(device, on_telemetry=handle_telemetry)
149
+ await driver.run()
150
+
151
+ if __name__ == "__main__":
152
+ asyncio.run(main())
153
+ ```
154
+
155
+ ---
156
+
157
+ ## Project Roadmap
158
+
159
+ - [x] **Phase 1: BLE Protocol Reverse-Engineering**
160
+ - [x] AirSync GATT service (`0xFEE7`) identification and 20-byte MTU slicing
161
+ - [x] AuthRequest (`0x2711`) and CRC32 InitRequest (`0x2713`) challenge resolution
162
+ - [x] `writeKey` derivation formula extraction
163
+ - [x] Continuous `0x4E22` SendData ACK loop
164
+ - [x] **Phase 2: Local Core Driver & Web Cockpit**
165
+ - [x] Asynchronous Python driver (`openfoci.client.FociBleDriver`)
166
+ - [x] 60-second rolling breath detector and coherence scoring
167
+ - [x] Modern WebGL Mind Orb cockpit with real-time SSE stream
168
+ - [x] Terminal biofeedback meter (`openfoci stream`)
169
+ - [x] **Phase 3: Pluggable Storage & Integrations**
170
+ - [x] SQLite time-series storage with indexed timestamps
171
+ - [x] High-frequency CSV sample exporter
172
+ - [x] Atomic JSON snapshot writer for local system daemons
173
+ - [x] Webhook / REST forwarding adapter
174
+ - [x] Home Assistant MQTT auto-discovery configuration
175
+ - [x] **Phase 4: Offline Android APK Repackaging**
176
+ - [x] Smali bytecode patch on `TrackerSDK.smali` (`checkLoginStatus -> true`)
177
+ - [x] Smali bytecode patch on `AccountManager.smali` (`hasAutoLoginToken -> true`, default UID `1001`)
178
+ - [x] Smali bytecode patch on `SplashViewPagerActivity.smali` (`loginSuccessFinished()` in `onCreate`)
179
+ - [x] Automated APK patcher script (`tools/patch_apk.sh`)
180
+ - [ ] **Phase 5: PyPI Release & Multi-OS CI/CD**
181
+ - [ ] PyPI distribution package (`pip install openfoci`)
182
+ - [ ] GitHub Actions CI across macOS, Linux, and Windows
183
+ - [ ] **Phase 6: Advanced Respiratory Sinus Arrhythmia (RSA) Model**
184
+ - [ ] Temporal Convolutional Network (TCN) trained on raw 10 Hz strain data
185
+ - [ ] Autonomic nervous system tone estimation (HRV proxy)
186
+ - [ ] Personalized user calibration profiles
187
+
188
+ ---
189
+
190
+ ## Technical Specifications & References
191
+
192
+ - [GATT Specification (docs/GATT_SPEC.md)](docs/GATT_SPEC.md): Full breakdown of UUIDs, byte offsets, opcodes, and bitmasks.
193
+ - [Protocol Reverse-Engineering Dossier (docs/PROTOCOL_BREAKDOWN.md)](docs/PROTOCOL_BREAKDOWN.md): Technical analysis of packet structures, cryptographic derivations, and firmware registers.
194
+ - [Home Assistant Guide (docs/HOME_ASSISTANT.md)](docs/HOME_ASSISTANT.md): Setup instructions for MQTT telemetry streaming and biofeedback automations.
195
+
196
+ ---
197
+
198
+ ## License
199
+
200
+ This project is licensed under the **MIT License** — see [LICENSE](LICENSE) for details.
201
+
202
+ *Disclaimer: OpenFOCI is an independent open-source hardware liberation and right-to-repair research project. It is not affiliated with, endorsed by, or sponsored by Tinylogics Ltd or its successors.*
@@ -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
+ ]
@@ -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