awear 0.1.0

Rust client for AWEAR EEG devices over BLE using btleplug
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
#!/usr/bin/env python3
"""
AWEAR Runner — Python parity implementation of the native Swift/Flutter Runner.
Covers the full CoreBluetooth protocol: scanning, connecting, service/characteristic
discovery, data streaming (EEG, battery, signal, misc), command TX/RX, packet
tracking, firmware update (Nordic DFU), reconnection logic, file writing (OpenBCI
CSV + binary), and all configuration/timer machinery.

Usage:
    python runner.py [--benchmark] [--device NAME] [--scan-timeout 10]
                     [--connect-timeout 30] [--save-bt-data] [--openbci]
                     [--binary] [--min-rssi -80] [--auto-start]
"""

from __future__ import annotations

import argparse
import asyncio
import csv
import enum
import hashlib
import hmac
import io
import logging
import os
import struct
import sys
import time
from collections import deque
from dataclasses import dataclass, field
from datetime import datetime, timezone
from pathlib import Path
from threading import Lock
from typing import Any, Callable, Optional

import bleak
from bleak import BleakClient, BleakScanner
from bleak.backends.characteristic import BleakGATTCharacteristic
from bleak.backends.device import BLEDevice
from bleak.backends.scanner import AdvertisementData

# ---------------------------------------------------------------------------
# Constants — UUIDs extracted from the Runner binary
# ---------------------------------------------------------------------------

AWEAR_SERVICE_UUID = "FC740001-0291-41FC-A9B0-45951B5B01D7"
AWEAR_TX_CHARACTERISTIC_UUID = "FC740002-0291-41FC-A9B0-45951B5B01D7"  # write to device
AWEAR_RX_CHARACTERISTIC_UUID = "FC740003-0291-41FC-A9B0-45951B5B01D7"  # notify from device

NORDIC_DFU_SERVICE_UUID = "8EC90001-F315-4F60-9FB8-838830DAEA50"
NORDIC_DFU_CONTROL_CHARACTERISTIC_UUID = "8EC90001-F315-4F60-9FB8-838830DAEA50"
NORDIC_DFU_PACKET_CHARACTERISTIC_UUID = "8EC90002-F315-4F60-9FB8-838830DAEA50"

AWEAR_CONNECTED_PREFIX = "AWEAR_CONNECTED:"
LUCA_MAGIC = b"LUCA"  # 0x4c554341 — LUCA protocol header signature
CHALLENGE_REPLY_PREFIX = "CRPL:"
CHALLENGE_CONSTANT = 0xD4C3B2A1  # Magic constant used in challenge-response HMAC
# 16-byte SymmetricKey extracted from Runner binary at 0x1001f7ff8
CHALLENGE_SYMMETRIC_KEY = bytes.fromhex("4ee1fbef8798e94a17bb945898c1898f")


def compute_challenge_reply(challenge_hex: str) -> str:
    """
    Compute the AWEAR challenge-response.

    Reverse-engineered from the Runner binary's AwearController:
      1. Parse the 8-char hex challenge string → uint32
      2. Byte-reverse (endian swap) → 4 bytes
      3. Append constant 0xD4C3B2A1 in little-endian → 8-byte message
      4. HMAC-SHA256(key=16-byte SymmetricKey, message=8-byte combined)
      5. Take first 8 bytes of the HMAC digest
      6. Format as uppercase hex → 16-char string
      7. Return "CRPL:<hex>"
    """
    challenge_val = int(challenge_hex, 16)
    # Byte-reverse the uint32 (ARM rev instruction)
    reversed_bytes = struct.pack(">I", challenge_val)
    constant_bytes = struct.pack("<I", CHALLENGE_CONSTANT)
    message = reversed_bytes + constant_bytes  # 8 bytes

    # HMAC-SHA256 with the static 16-byte SymmetricKey from the binary
    mac = hmac.new(CHALLENGE_SYMMETRIC_KEY, message, hashlib.sha256).digest()
    # Take first 8 bytes, format as uppercase hex
    reply_hex = mac[:8].hex().upper()
    return f"{CHALLENGE_REPLY_PREFIX}{reply_hex}"

# ---------------------------------------------------------------------------
# Default configuration (mirrors UserDefaults keys)
# ---------------------------------------------------------------------------

DEFAULTS: dict[str, Any] = {
    "AwearConnectAutomaticallyAfterStartup": False,
    "AwearReconnectAutomaticallyAfterCrash": True,
    "AwearReconnectAutomatically": True,
    "AwearConnectTimeout": 30.0,
    "AwearReconnectTimeout": 10.0,
    "AwearMaxEEGValueCheck": 8388607,  # 2^23 - 1 (24-bit signed max)
    "AwearMinEEGValueCheck": -8388608,
    "AwearDiscoveryMinSignal": -80,
    "AwearDiscoveryShowSignal": True,
    "AwearDiscoverySortBySignal": True,
    "AwearLastConnectedDeviceName": "",
    "AwearLastConnectedDevice": "",
    "SaveSettingsToICloud": False,
    "ShowLastConnectedDevice": True,
    "WarningSoundWithErrors": True,
    "SaveDataAsOpenBCI": True,
    "StartAfterConnected": False,
    "SaveBTData": False,
}

# Timer intervals (seconds) — from binary strings
SEARCH_TIMEOUT = 10.0
STALE_DEVICE_TIMEOUT = 15.0
DEVICE_CONNECTION_TIMEOUT = 30.0
DFU_CONNECTION_TIMEOUT = 60.0
STREAMING_DATA_TIMER_INTERVAL = 1.0
CHECK_DATA_TIMER_INTERVAL = 5.0
FREQUENCY_COUNTER_TIMER_INTERVAL = 1.0
BOARD_LIST_UPDATE_INTERVAL = 1.0
LAST_WARNING_SOUND_TIMEOUT = 5.0
RECONNECTION_MAX_RETRIES = 10

# ---------------------------------------------------------------------------
# Logging
# ---------------------------------------------------------------------------

log = logging.getLogger("awear.runner")


# ---------------------------------------------------------------------------
# Thread-safe array (mirrors Swift ThreadSafeArray)
# ---------------------------------------------------------------------------

class ThreadSafeArray:
    """Minimal thread-safe list used for device lists and data buffers."""

    def __init__(self) -> None:
        self._lock = Lock()
        self._items: list[Any] = []

    def append(self, item: Any) -> None:
        with self._lock:
            self._items.append(item)

    def remove(self, item: Any) -> None:
        with self._lock:
            try:
                self._items.remove(item)
            except ValueError:
                pass

    def clear(self) -> None:
        with self._lock:
            self._items.clear()

    def snapshot(self) -> list[Any]:
        with self._lock:
            return list(self._items)

    def __len__(self) -> int:
        with self._lock:
            return len(self._items)

    def __iter__(self):
        return iter(self.snapshot())


# ---------------------------------------------------------------------------
# Data types — mirror Swift enums / structs
# ---------------------------------------------------------------------------

class DeviceStatus(enum.Enum):
    DISCONNECTED = "disconnected"
    CONNECTING = "connecting"
    CONNECTED = "connected"
    READY = "ready"
    STREAMING = "streaming"
    RECONNECTING = "reconnecting"
    DFU = "dfu"


class DataPacketType(enum.IntEnum):
    """First byte of BLE notification identifies the packet type."""
    EEG = 0x01
    BATTERY = 0x02
    SIGNAL = 0x03
    MISC = 0x04


@dataclass
class DiscoveredDevice:
    name: str
    address: str
    rssi: int
    ble_device: BLEDevice
    advertisement: AdvertisementData
    last_seen: float = field(default_factory=time.monotonic)


@dataclass
class PacketStats:
    eeg_packet_count: int = 0
    battery_packet_count: int = 0
    signal_packet_count: int = 0
    misc_packet_count: int = 0
    lost_packets: int = 0
    prev_lost_packets: int = 0
    packet_counter: int = 0
    prev_packet_counter: int = 0
    frequency_counter: int = 0
    last_frequency: float = 0.0


@dataclass
class DeviceInfo:
    name: str = ""
    peripheral_uuid: str = ""
    firmware: str = ""
    bootloader: str = ""
    battery: int = -1
    signal: int = -127
    is_awear: bool = False
    is_dk: bool = False


# ---------------------------------------------------------------------------
# OpenBCI file writer
# ---------------------------------------------------------------------------

OPENBCI_HEADER = "AWEAR_OpenBCI_Header"


class FileWriter:
    """Writes EEG data to local files in OpenBCI CSV or raw binary format."""

    def __init__(self, output_dir: Path, openbci_format: bool = True) -> None:
        self.output_dir = output_dir
        self.openbci_format = openbci_format
        self._file: Optional[io.BufferedWriter | io.TextIOWrapper] = None
        self._csv_writer: Optional[csv.writer] = None
        self._filename: str = ""
        self._lock = Lock()
        self._sample_index: int = 0
        output_dir.mkdir(parents=True, exist_ok=True)

    # -- lifecycle -----------------------------------------------------------

    def open(self) -> str:
        ts = datetime.now().strftime("%Y%m%d_%H%M%S")
        if self.openbci_format:
            self._filename = f"AWEAR_{ts}.csv"
            path = self.output_dir / self._filename
            self._file = open(path, "w", newline="")
            self._csv_writer = csv.writer(self._file)
            self._write_openbci_header()
        else:
            self._filename = f"AWEAR_{ts}.bin"
            path = self.output_dir / self._filename
            self._file = open(path, "wb")
        self._sample_index = 0
        log.info("Opened data file: %s", path)
        return str(path)

    def close(self) -> None:
        with self._lock:
            if self._file:
                self._file.close()
                self._file = None
                self._csv_writer = None

    # -- writing -------------------------------------------------------------

    def write_eeg(self, channels: list[int], timestamp: Optional[float] = None) -> None:
        with self._lock:
            if self._file is None:
                return
            if self.openbci_format:
                assert self._csv_writer is not None
                row = [self._sample_index] + channels
                if timestamp is not None:
                    row.append(f"{timestamp:.6f}")
                self._csv_writer.writerow(row)
            else:
                # binary: 4-byte sample index + 3 bytes per channel (24-bit signed)
                buf = struct.pack("<I", self._sample_index & 0xFFFFFFFF)
                for ch in channels:
                    # 24-bit signed, big-endian (OpenBCI convention)
                    b = ch.to_bytes(3, byteorder="big", signed=True)
                    buf += b
                if timestamp is not None:
                    buf += struct.pack("<d", timestamp)
                self._file.write(buf)
            self._sample_index += 1

    def write_raw(self, data: bytes, timestamp: Optional[float] = None) -> None:
        """Write raw BLE payload (battery / signal / misc)."""
        with self._lock:
            if self._file is None:
                return
            if self.openbci_format:
                assert self._csv_writer is not None
                hex_str = data.hex()
                row: list[Any] = [self._sample_index, hex_str]
                if timestamp is not None:
                    row.append(f"{timestamp:.6f}")
                self._csv_writer.writerow(row)
            else:
                if timestamp is not None:
                    self._file.write(struct.pack("<d", timestamp))
                self._file.write(data)
            self._sample_index += 1

    def flush(self) -> None:
        with self._lock:
            if self._file:
                self._file.flush()

    # -- private -------------------------------------------------------------

    def _write_openbci_header(self) -> None:
        assert self._csv_writer is not None
        self._csv_writer.writerow(["%%AWEAR Raw EXG Data"])
        self._csv_writer.writerow(["%%Number of channels = 1"])
        self._csv_writer.writerow(["%%Sample Rate = 256 Hz"])
        self._csv_writer.writerow(["Sample Index", "EXG Channel 0", "Timestamp"])


# ---------------------------------------------------------------------------
# DFU (Device Firmware Update) — Nordic DFU protocol over BLE
# ---------------------------------------------------------------------------

class DFUStatus(enum.Enum):
    IDLE = "idle"
    STARTING = "starting"
    UPLOADING = "uploading"
    VALIDATING = "validating"
    COMPLETED = "completed"
    FAILED = "failed"


@dataclass
class DFUProgress:
    status: DFUStatus = DFUStatus.IDLE
    bytes_sent: int = 0
    total_bytes: int = 0
    speed_bps: float = 0.0
    avg_speed_bps: float = 0.0

    @property
    def percent(self) -> float:
        if self.total_bytes == 0:
            return 0.0
        return (self.bytes_sent / self.total_bytes) * 100.0


class DFUController:
    """
    Implements Nordic DFU (Secure) firmware update over BLE.
    Mirrors the native iOSDFULibrary integration in the Runner.
    """

    DFU_PACKET_SIZE = 20  # default BLE MTU-safe packet size

    def __init__(self, client: BleakClient) -> None:
        self._client = client
        self.progress = DFUProgress()
        self._control_char: Optional[BleakGATTCharacteristic] = None
        self._packet_char: Optional[BleakGATTCharacteristic] = None

    async def discover(self) -> bool:
        """Discover DFU service and characteristics."""
        services = self._client.services
        dfu_service = services.get_service(NORDIC_DFU_SERVICE_UUID)
        if dfu_service is None:
            log.warning("Nordic DFU service not found")
            return False
        for char in dfu_service.characteristics:
            uuid_upper = char.uuid.upper()
            if uuid_upper == NORDIC_DFU_CONTROL_CHARACTERISTIC_UUID.upper():
                self._control_char = char
            elif uuid_upper == NORDIC_DFU_PACKET_CHARACTERISTIC_UUID.upper():
                self._packet_char = char
        found = self._control_char is not None and self._packet_char is not None
        if not found:
            log.warning("DFU characteristics not fully discovered")
        return found

    async def update_firmware(
        self,
        firmware_path: str,
        on_progress: Optional[Callable[[DFUProgress], None]] = None,
    ) -> bool:
        """
        Perform OTA firmware update.
        Returns True on success, False on failure.
        """
        if self._control_char is None or self._packet_char is None:
            log.error("DFU not discovered; call discover() first")
            self.progress.status = DFUStatus.FAILED
            return False

        firmware_data = Path(firmware_path).read_bytes()
        self.progress = DFUProgress(
            status=DFUStatus.STARTING,
            total_bytes=len(firmware_data),
        )
        if on_progress:
            on_progress(self.progress)

        try:
            # Enable notifications on control characteristic
            await self._client.start_notify(
                self._control_char, self._on_dfu_control_notify
            )

            # Send init packet (start DFU)
            await self._client.write_gatt_char(
                self._control_char, bytearray([0x01, 0x04]), response=True
            )

            # Send firmware size
            size_bytes = struct.pack("<I", len(firmware_data))
            await self._client.write_gatt_char(
                self._packet_char, bytearray(size_bytes), response=False
            )

            # Wait a beat for the device to acknowledge
            await asyncio.sleep(0.1)

            # Send receive firmware image command
            await self._client.write_gatt_char(
                self._control_char, bytearray([0x03]), response=True
            )

            # Stream firmware data
            self.progress.status = DFUStatus.UPLOADING
            offset = 0
            start_time = time.monotonic()
            while offset < len(firmware_data):
                chunk = firmware_data[offset : offset + self.DFU_PACKET_SIZE]
                await self._client.write_gatt_char(
                    self._packet_char, bytearray(chunk), response=False
                )
                offset += len(chunk)
                self.progress.bytes_sent = offset
                elapsed = time.monotonic() - start_time
                if elapsed > 0:
                    self.progress.speed_bps = offset / elapsed
                    self.progress.avg_speed_bps = offset / elapsed
                if on_progress:
                    on_progress(self.progress)

            # Validate
            self.progress.status = DFUStatus.VALIDATING
            await self._client.write_gatt_char(
                self._control_char, bytearray([0x04]), response=True
            )
            await asyncio.sleep(0.5)

            # Activate and reset
            await self._client.write_gatt_char(
                self._control_char, bytearray([0x05]), response=True
            )

            self.progress.status = DFUStatus.COMPLETED
            if on_progress:
                on_progress(self.progress)
            log.info("DFU completed successfully")
            return True

        except Exception as exc:
            log.error("DFU failed: %s", exc)
            self.progress.status = DFUStatus.FAILED
            if on_progress:
                on_progress(self.progress)
            return False
        finally:
            try:
                await self._client.stop_notify(self._control_char)
            except Exception:
                pass

    def _on_dfu_control_notify(
        self, _char: BleakGATTCharacteristic, data: bytearray
    ) -> None:
        log.debug("DFU control notification: %s", data.hex())


# ---------------------------------------------------------------------------
# AwearController — core BLE protocol (mirrors Swift AwearController)
# ---------------------------------------------------------------------------

class AwearControllerDelegate:
    """Callback interface — mirrors AwearControllerDelegate protocol."""

    def on_status_update(self, status: str) -> None: ...
    def on_status_set(self, status: DeviceStatus) -> None: ...
    def on_data_update(self, key: str, value: Any) -> None: ...
    def on_data_received(self, packet_type: DataPacketType, data: bytes) -> None: ...
    def on_ready(self) -> None: ...
    def on_central_state_changed(self, state: str) -> None: ...
    def on_eeg_data(self, channels: list[int], counter: int) -> None: ...
    def on_battery_data(self, level: int) -> None: ...
    def on_signal_data(self, rssi: int) -> None: ...
    def on_misc_data(self, data: bytes) -> None: ...
    def on_disconnected(self) -> None: ...
    def on_connected(self) -> None: ...


class AwearController:
    """
    Full-parity Python implementation of the native Swift AwearController.
    Manages BLE scanning, connection, data streaming, reconnection,
    command TX/RX, firmware update, and file writing.
    """

    def __init__(self, config: Optional[dict[str, Any]] = None) -> None:
        self.config: dict[str, Any] = {**DEFAULTS, **(config or {})}
        self.delegate: Optional[AwearControllerDelegate] = None

        # -- device state (mirrors Swift properties) -------------------------
        self.device_info = DeviceInfo()
        self.status = DeviceStatus.DISCONNECTED
        self.stats = PacketStats()

        # -- discovered devices ----------------------------------------------
        self.found_devices = ThreadSafeArray()
        self._searching = False

        # -- connection ------------------------------------------------------
        self._client: Optional[BleakClient] = None
        self._scanner: Optional[BleakScanner] = None
        self._tx_char: Optional[BleakGATTCharacteristic] = None
        self._rx_char: Optional[BleakGATTCharacteristic] = None

        # -- streaming / started ---------------------------------------------
        self._started = False
        self._device_ready = False

        # -- command buffer (sendCommandAWEAR / getCommandOutputAWEAR) -------
        self._command_output: deque[str] = deque(maxlen=256)

        # -- reconnection ----------------------------------------------------
        self._reconnection_counter = 0
        self._reconnection_requested = False
        self._resume_streaming_after_reconnect = False
        self._ready_event: Optional[asyncio.Event] = None

        # -- file writing ----------------------------------------------------
        self._file_writer: Optional[FileWriter] = None

        # -- DFU -------------------------------------------------------------
        self._dfu: Optional[DFUController] = None

        # -- timers (asyncio tasks) ------------------------------------------
        self._timer_tasks: dict[str, asyncio.Task] = {}

        # -- frequency measurement -------------------------------------------
        self._freq_counter = 0
        self._last_freq_time = time.monotonic()
        self._current_frequency: float = 0.0

        # -- LUCA protocol state -------------------------------------------------
        self._luca_expecting_data = False
        self._luca_last_chunk_size = 0  # size of final chunk in current block
        self._luca_block_type = 0
        self._luca_block_counter = 0
        self._luca_eeg_buffer = bytearray()

        # -- haptics -------------------------------------------------------------
        self._haptic_engine_available = True  # simulates CoreHaptics availability

        # -- device listing notifications ------------------------------------
        self._device_listing_active = False

        # -- benchmark data collection ---------------------------------------
        self.benchmark_latencies: list[float] = []
        self._bench_mode = False

    # -----------------------------------------------------------------------
    # Properties (mirror Swift computed properties / Flutter method calls)
    # -----------------------------------------------------------------------

    @property
    def device_name(self) -> str:
        return self.device_info.name

    @property
    def device_connected(self) -> bool:
        return self.status in (
            DeviceStatus.CONNECTED,
            DeviceStatus.READY,
            DeviceStatus.STREAMING,
        )

    @property
    def device_connecting(self) -> bool:
        return self.status == DeviceStatus.CONNECTING

    @property
    def device_disconnected(self) -> bool:
        return self.status == DeviceStatus.DISCONNECTED

    @property
    def device_ready(self) -> bool:
        return self._device_ready

    @property
    def device_streaming(self) -> bool:
        return self.status == DeviceStatus.STREAMING

    @property
    def device_reconnecting(self) -> bool:
        return self.status == DeviceStatus.RECONNECTING

    @property
    def is_searching(self) -> bool:
        return self._searching

    @property
    def is_started(self) -> bool:
        return self._started

    @property
    def battery_level(self) -> int:
        return self.device_info.battery

    @property
    def signal_level(self) -> int:
        return self.device_info.signal

    @property
    def firmware_version(self) -> str:
        return self.device_info.firmware

    @property
    def bootloader_version(self) -> str:
        return self.device_info.bootloader

    @property
    def last_connected_device_name(self) -> str:
        return self.config["AwearLastConnectedDeviceName"]

    @last_connected_device_name.setter
    def last_connected_device_name(self, value: str) -> None:
        self.config["AwearLastConnectedDeviceName"] = value

    @property
    def save_bt_data(self) -> bool:
        return self.config.get("SaveBTData", False)

    @save_bt_data.setter
    def save_bt_data(self, value: bool) -> None:
        self.config["SaveBTData"] = value

    # -----------------------------------------------------------------------
    # Scanning (searchDevices / stopSearch)
    # -----------------------------------------------------------------------

    async def search_devices(self, timeout: Optional[float] = None) -> list[DiscoveredDevice]:
        """Start BLE scan for AWEAR devices. Mirrors searchDevices()."""
        if self._searching:
            log.debug("Already searching")
            return self.found_devices.snapshot()

        timeout = timeout or SEARCH_TIMEOUT
        self._searching = True
        self.found_devices.clear()
        log.info("Starting AWEAR device search (timeout=%.1fs)", timeout)

        if self.delegate:
            self.delegate.on_status_update("Searching for AWEAR devices...")

        min_rssi = self.config["AwearDiscoveryMinSignal"]

        def _detection_callback(device: BLEDevice, adv: AdvertisementData) -> None:
            # Filter by name prefix or service UUID
            name = device.name or adv.local_name or ""
            if not name:
                return
            rssi = adv.rssi if adv.rssi is not None else -127
            if rssi < min_rssi:
                return
            # Accept AWEAR devices or devices advertising the AWEAR service
            is_awear = (
                "AWEAR" in name.upper()
                or AWEAR_SERVICE_UUID.lower() in [u.lower() for u in (adv.service_uuids or [])]
            )
            if not is_awear:
                return

            # Deduplicate
            existing = [d for d in self.found_devices if d.address == device.address]
            if existing:
                existing[0].rssi = rssi
                existing[0].last_seen = time.monotonic()
                return

            disc = DiscoveredDevice(
                name=name,
                address=device.address,
                rssi=rssi,
                ble_device=device,
                advertisement=adv,
            )
            self.found_devices.append(disc)
            log.info("Found AWEAR device: %s (%s) RSSI=%d", name, device.address, rssi)

        self._scanner = BleakScanner(detection_callback=_detection_callback)
        await self._scanner.start()

        # Schedule stale device cleanup
        self._start_timer("stale_device", self._stale_device_cleanup, STALE_DEVICE_TIMEOUT)

        # Wait for scan timeout
        await asyncio.sleep(timeout)
        await self.stop_search()

        # Sort by signal if configured
        devices = self.found_devices.snapshot()
        if self.config["AwearDiscoverySortBySignal"]:
            devices.sort(key=lambda d: d.rssi, reverse=True)

        log.info("AWEAR boards found: %d", len(devices))
        if self.delegate:
            self.delegate.on_status_update(f"AWEAR devices found: {len(devices)}")
        return devices

    async def stop_search(self) -> None:
        """Stop BLE scanning. Mirrors stopSearch()."""
        if self._scanner:
            try:
                await self._scanner.stop()
            except Exception:
                pass
            self._scanner = None
        self._searching = False
        self._cancel_timer("stale_device")
        log.info("Stopped AWEAR device search")

    async def _stale_device_cleanup(self) -> None:
        """Remove devices not seen recently. Mirrors staleAwearDeviceTimer."""
        while self._searching:
            await asyncio.sleep(STALE_DEVICE_TIMEOUT)
            now = time.monotonic()
            stale = [
                d
                for d in self.found_devices
                if (now - d.last_seen) > STALE_DEVICE_TIMEOUT
            ]
            for d in stale:
                self.found_devices.remove(d)
                log.debug("Removed stale device: %s", d.name)

    # -----------------------------------------------------------------------
    # Connection (connect / disconnect)
    # -----------------------------------------------------------------------

    async def connect(self, device: str | DiscoveredDevice | BLEDevice) -> bool:
        """
        Connect to an AWEAR device by name, address, or DiscoveredDevice.
        Mirrors connect(to deviceName: String).
        """
        if self.device_connected:
            log.info("Already connected to AWEAR board: %s", self.device_info.name)
            return True

        # Resolve device
        ble_device: Optional[BLEDevice] = None
        device_name = ""

        if isinstance(device, DiscoveredDevice):
            ble_device = device.ble_device
            device_name = device.name
        elif isinstance(device, BLEDevice):
            ble_device = device
            device_name = device.name or device.address
        elif isinstance(device, str):
            device_name = device
            # Search found devices first
            for d in self.found_devices:
                if d.name == device or d.address == device:
                    ble_device = d.ble_device
                    break
            # If not found, scan briefly
            if ble_device is None:
                log.info("Device %s not in discovered list, scanning...", device)
                await self.search_devices(timeout=5.0)
                for d in self.found_devices:
                    if d.name == device or d.address == device:
                        ble_device = d.ble_device
                        break

        if ble_device is None:
            log.error("Could not find AWEAR device: %s", device)
            return False

        self._set_status(DeviceStatus.CONNECTING)
        log.info("@@@@ Bluetooth.beginConnecting-1: %s", device_name)

        connect_timeout = self.config["AwearConnectTimeout"]
        self._client = BleakClient(
            ble_device,
            disconnected_callback=self._on_disconnected_callback,
        )

        try:
            await asyncio.wait_for(
                self._client.connect(), timeout=connect_timeout
            )
        except (asyncio.TimeoutError, Exception) as exc:
            log.error("Connection failed: %s", exc)
            self._set_status(DeviceStatus.DISCONNECTED)
            self._client = None
            return False

        log.info("@@@@ Bluetooth.beginConnecting-2: connected to %s", device_name)

        # Discover services & characteristics
        if not await self._discover_services():
            await self.disconnect()
            return False

        # Store device info
        self.device_info.name = device_name
        self.device_info.peripheral_uuid = ble_device.address
        self.config["AwearLastConnectedDeviceName"] = device_name
        self.config["AwearLastConnectedDevice"] = ble_device.address

        self._set_status(DeviceStatus.CONNECTED)
        self._reconnection_counter = 0
        log.info("Connected to AWEAR board: %s", device_name)

        # Enable RX notifications and wait for the device handshake.
        # The AWEAR firmware sends an "AWEAR_CONNECTED:..." message on the
        # RX characteristic once it's ready to accept commands.  The native
        # app waits for this "awearReadyMessage" before setting deviceReady
        # and calling onReady.  Sending START before this handshake causes
        # the device to drop the connection.
        if self._rx_char:
            # Two-phase handshake:
            # Phase 1: Wait for AWEAR_CONNECTED:<challenge>
            # Phase 2: Send CRPL:<hmac>, wait for AWEAR_READY confirmation
            self._challenge_event = asyncio.Event()
            self._ready_event = asyncio.Event()
            self._pending_challenge = None

            await self._client.start_notify(self._rx_char, self._on_rx_notify)
            log.info("Notifications enabled — waiting for AWEAR_CONNECTED...")

            # Phase 1: Wait for challenge
            try:
                await asyncio.wait_for(self._challenge_event.wait(), timeout=10.0)
            except asyncio.TimeoutError:
                log.warning("AWEAR_CONNECTED not received (timeout)")

            # Phase 2: Send CRPL challenge reply
            challenge = getattr(self, "_pending_challenge", None)
            if challenge and self._client and self._client.is_connected and self._tx_char:
                reply = compute_challenge_reply(challenge)
                log.info("Sending challenge reply: %s", reply)
                await self._client.write_gatt_char(
                    self._tx_char, reply.encode("utf-8"), response=False
                )
                log.info("CRPL sent — waiting for AWEAR_READY...")

                # Wait for AWEAR_READY confirmation from device
                try:
                    await asyncio.wait_for(self._ready_event.wait(), timeout=10.0)
                except asyncio.TimeoutError:
                    log.warning("AWEAR_READY not received (timeout)")

            if not self._client or not self._client.is_connected:
                log.error("Device disconnected during handshake")
                self._set_status(DeviceStatus.DISCONNECTED)
                return False

            self._device_ready = True
            self._set_status(DeviceStatus.READY)
            log.info("Device ready — authenticated and streaming")
            if self.delegate:
                self.delegate.on_ready()

        if self.delegate:
            self.delegate.on_connected()

        # Auto-start if configured
        if self.config["StartAfterConnected"]:
            log.info("Starting after connected")
            await self.start()

        return True

    async def disconnect(self) -> None:
        """Disconnect from the AWEAR device. Mirrors disconnect()."""
        log.info("@@@@ AwearController.disconnect")
        self._cancel_all_timers()
        self._started = False
        self._device_ready = False

        if self._client and self._client.is_connected:
            try:
                if self._rx_char:
                    await self._client.stop_notify(self._rx_char)
            except Exception:
                pass
            try:
                await self._client.disconnect()
            except Exception:
                pass

        self._client = None
        self._tx_char = None
        self._rx_char = None
        self._set_status(DeviceStatus.DISCONNECTED)

        if self._file_writer:
            self._file_writer.close()
            self._file_writer = None

        log.info("@@@@ Bluetooth.disconnect: Disconnected from AWEAR board: %s",
                 self.device_info.name)
        if self.delegate:
            self.delegate.on_disconnected()

    async def _discover_services(self) -> bool:
        """Discover AWEAR service and TX/RX characteristics."""
        assert self._client is not None
        services = self._client.services
        awear_svc = services.get_service(AWEAR_SERVICE_UUID)
        if awear_svc is None:
            # Try case-insensitive
            for svc in services:
                if svc.uuid.upper() == AWEAR_SERVICE_UUID.upper():
                    awear_svc = svc
                    break
        if awear_svc is None:
            log.error("AWEAR service not found on device")
            return False

        for char in awear_svc.characteristics:
            uuid_upper = char.uuid.upper()
            log.info("  Characteristic %s properties=%s", char.uuid, char.properties)
            if uuid_upper == AWEAR_TX_CHARACTERISTIC_UUID.upper():
                self._tx_char = char
            elif uuid_upper == AWEAR_RX_CHARACTERISTIC_UUID.upper():
                self._rx_char = char

        if self._tx_char is None or self._rx_char is None:
            log.error("AWEAR TX/RX characteristics not found (tx=%s, rx=%s)",
                      self._tx_char, self._rx_char)
            return False

        log.info("Discovered AWEAR service — TX=%s RX=%s",
                 self._tx_char.uuid, self._rx_char.uuid)
        return True

    # -----------------------------------------------------------------------
    # Disconnection handling / reconnection
    # -----------------------------------------------------------------------

    def _on_disconnected_callback(self, _client: BleakClient) -> None:
        """BleakClient disconnected callback — schedules reconnection."""
        log.warning("AWEAR disconnected (callback)")
        was_connected = self.device_connected
        was_streaming = self._started
        self._device_ready = False
        self._started = False
        self._tx_char = None
        self._rx_char = None
        self._set_status(DeviceStatus.DISCONNECTED)

        if self.delegate:
            self.delegate.on_disconnected()

        if was_connected and self.config["AwearReconnectAutomatically"]:
            self._reconnection_requested = True
            self._resume_streaming_after_reconnect = was_streaming
            # Schedule reconnection on the event loop
            try:
                loop = asyncio.get_running_loop()
                loop.create_task(self._reconnect())
            except RuntimeError:
                log.warning("No running event loop for reconnection")

    async def _reconnect(self) -> None:
        """Attempt to reconnect to the last connected device."""
        if not self._reconnection_requested:
            return

        device_name = self.config.get("AwearLastConnectedDeviceName", "")
        if not device_name:
            log.warning("No last connected device name for reconnection")
            self._reconnection_requested = False
            return

        self._set_status(DeviceStatus.RECONNECTING)
        reconnect_timeout = self.config["AwearReconnectTimeout"]

        while (
            self._reconnection_requested
            and self._reconnection_counter < RECONNECTION_MAX_RETRIES
        ):
            self._reconnection_counter += 1
            log.info(
                "@@@@ Bluetooth.beginReconnecting: %s (attempt %d)",
                device_name,
                self._reconnection_counter,
            )
            if self.delegate:
                self.delegate.on_status_update(
                    f"Reconnecting to {device_name} (attempt {self._reconnection_counter})"
                )

            success = await self.connect(device_name)
            if success:
                log.info("Reconnection to AWEAR board %s successful", device_name)
                self._reconnection_requested = False
                # Resume streaming if it was active before disconnect
                if getattr(self, "_resume_streaming_after_reconnect", False):
                    self._resume_streaming_after_reconnect = False
                    log.info("Resuming streaming after reconnection")
                    await self.start()
                return

            log.info("Reconnection attempt %d failed, waiting %.1fs",
                     self._reconnection_counter, reconnect_timeout)
            await asyncio.sleep(reconnect_timeout)

        log.warning("Canceled reconnection to device %s after %d attempts",
                    device_name, self._reconnection_counter)
        self._reconnection_requested = False
        self._set_status(DeviceStatus.DISCONNECTED)

    # -----------------------------------------------------------------------
    # Start / Stop streaming (mirrors AwearController:start / :stop)
    # -----------------------------------------------------------------------

    async def start(self) -> None:
        """
        Start EEG streaming from the AWEAR device.

        After authentication (CRPL → AWEAR_READY), the device only sends
        status info (battery, RSSI). A "START" command must be sent to
        begin EEG data streaming. This only works after successful auth.
        """
        if not self.device_ready:
            log.warning("Device not ready; cannot start")
            return
        if not self._client or not self._client.is_connected:
            log.warning("Device not connected; cannot start")
            return
        log.info("AwearController:start")
        await self._send_command("START")
        log.info("START command sent to connected AWEAR board")
        self._started = True
        self._set_status(DeviceStatus.STREAMING)

        # Reset stats
        self.stats = PacketStats()
        self._freq_counter = 0
        self._last_freq_time = time.monotonic()

        # Open file writer if configured
        if self.save_bt_data:
            openbci = self.config.get("SaveDataAsOpenBCI", True)
            output_dir = Path.cwd() / "awear_data"
            self._file_writer = FileWriter(output_dir, openbci_format=openbci)
            self._file_writer.open()

        # Start timers
        self._start_timer("frequency_counter", self._frequency_counter_tick,
                          FREQUENCY_COUNTER_TIMER_INTERVAL)
        self._start_timer("check_data", self._check_data_tick,
                          CHECK_DATA_TIMER_INTERVAL)

        if self.delegate:
            self.delegate.on_status_update("Streaming started")

    async def stop(self) -> None:
        """Stop EEG streaming."""
        log.info("AwearController:stop")
        if self._client and self._client.is_connected and self._tx_char:
            await self._send_command("STOP")
            log.info("STOP command sent to connected AWEAR board")
        self._started = False
        if self.status == DeviceStatus.STREAMING:
            self._set_status(DeviceStatus.READY)

        self._cancel_timer("frequency_counter")
        self._cancel_timer("check_data")

        if self._file_writer:
            self._file_writer.flush()
            self._file_writer.close()
            self._file_writer = None

        if self.delegate:
            self.delegate.on_status_update("Streaming stopped")

    # -----------------------------------------------------------------------
    # Command TX/RX (sendCommandAWEAR / getCommandOutputAWEAR / has...)
    # -----------------------------------------------------------------------

    async def send_command(self, command: str) -> None:
        """Send a command string to the device over TX characteristic."""
        if not command:
            log.warning("sendCommandAWEAR: invalid argument")
            return
        await self._send_command(command)

    def get_command_output(self) -> Optional[str]:
        """Get next command output from buffer. Mirrors getCommandOutputAWEAR."""
        if self._command_output:
            return self._command_output.popleft()
        return None

    def has_command_output(self) -> bool:
        """Check if command output is available. Mirrors hasCommandOutputAWEAR."""
        return len(self._command_output) > 0

    async def _send_command(self, command: str) -> None:
        """Write command bytes to TX characteristic (write-without-response)."""
        if not self._client or not self._client.is_connected or not self._tx_char:
            log.warning("Cannot send command — not connected")
            return
        data = command.encode("utf-8")
        try:
            # The native app uses CBCharacteristicWriteType.withoutResponse
            # (confirmed by peripheralIsReadyToSendWriteWithoutResponse delegate).
            # Using write-with-response causes the AWEAR firmware to drop the
            # connection.
            await self._client.write_gatt_char(self._tx_char, data, response=False)
            log.debug("Sent command: %s (%d bytes, write-without-response)",
                      command, len(data))
        except Exception as exc:
            log.error("Failed to send command '%s': %s", command, exc)

    # -----------------------------------------------------------------------
    # Data reception (RX notifications)
    # -----------------------------------------------------------------------

    def _on_rx_notify(self, _char: BleakGATTCharacteristic, data: bytearray) -> None:
        """
        Handle incoming BLE notifications on the RX characteristic.

        The AWEAR device uses the LUCA protocol:
          1. Text messages: "AWEAR_CONNECTED:<hex>\n", "Unknown command:...\n", etc.
          2. LUCA header packets: 36 bytes starting with b'LUCA' (0x4c554341)
             — announces an upcoming data block with metadata
          3. Raw EEG data packets: variable length (typically 244 or 24 bytes)
             — 3 bytes per sample (24-bit signed big-endian), multiple channels

        The native Swift app routes via peripheral:didUpdateValueForCharacteristic:
        and uses the same detection logic.
        """
        recv_time = time.monotonic()

        if len(data) < 1:
            return

        # Debug: log all incoming packets to trace data flow
        if self._started:
            log.debug("RX [%d bytes] first=0x%02X last=0x%02X luca_expecting=%s",
                      len(data), data[0], data[-1], self._luca_expecting_data)

        # ----- 1. Text-based messages -----
        # All text messages from the device end with \n (0x0A).
        # LUCA headers start with b'LUCA' (0x4C) which is also printable,
        # so check for newline terminator to distinguish.
        if data[-1:] == b"\n":
            try:
                text = data.decode("utf-8", errors="ignore").strip()

                # AWEAR_CONNECTED:<challenge> — store challenge for connect() to send CRPL
                if text.startswith(AWEAR_CONNECTED_PREFIX):
                    board_info = text[len(AWEAR_CONNECTED_PREFIX):].strip()
                    log.info("Received handshake: AWEAR_CONNECTED:%s", board_info)
                    self.device_info.is_awear = True
                    self._pending_challenge = board_info if len(board_info) == 8 else None
                    # Signal that we received the challenge (connect() will send CRPL)
                    ev = getattr(self, "_challenge_event", None)
                    if ev and not ev.is_set():
                        ev.set()
                    return

                # AWEAR_READY:<crpl_echo>:<params> — device accepted our CRPL
                if text.startswith("AWEAR_READY:"):
                    parts = text.split(":")
                    log.info("Device authenticated: %s", text)
                    # Parse params: AWEAR_READY:<hmac>:<type>:<param1>:<param2>:<param3>
                    if len(parts) >= 6:
                        self._awear_packet_size = int(parts[4])  # e.g. 244
                    ev = getattr(self, "_ready_event", None)
                    if ev and not ev.is_set():
                        ev.set()
                    return

                # Battery mV: <value>
                if text.startswith("Battery mV:"):
                    try:
                        mv = int(text.split(":")[1].strip())
                        # Convert mV to rough percentage (3200-4200mV range)
                        pct = max(0, min(100, int((mv - 3200) / 10)))
                        self.device_info.battery = pct
                        log.debug("Battery: %d mV (%d%%)", mv, pct)
                        if self.delegate:
                            self.delegate.on_battery_data(pct)
                    except (ValueError, IndexError):
                        pass
                    return

                # RSSI DBm: <value>
                if text.startswith("RSSI DBm:"):
                    try:
                        rssi = int(text.split(":")[1].strip())
                        self.device_info.signal = rssi
                        log.debug("Signal: %d dBm", rssi)
                        if self.delegate:
                            self.delegate.on_signal_data(rssi)
                    except (ValueError, IndexError):
                        pass
                    return

                # Any other text message
                if text:
                    log.debug("RX text: %s", text)
                    self._command_output.append(text)
                return
            except Exception:
                pass

        # ----- 2. LUCA header packet (36 bytes, starts with b'LUCA') -----
        if len(data) >= 4 and data[:4] == LUCA_MAGIC:
            # Only process LUCA data after handshake is complete
            if self._device_ready:
                self._handle_luca_header(data, recv_time)
            return

        # ----- 3. Raw EEG / sensor data (continuation of a LUCA block) -----
        if self._luca_expecting_data and self._device_ready:
            self._handle_luca_data(data, recv_time)
            return

        # ----- 4. Fallback: legacy single-byte type routing -----
        packet_type_byte = data[0]
        try:
            ptype = DataPacketType(packet_type_byte)
        except ValueError:
            log.debug("Unknown packet: 0x%02X (%d bytes)", packet_type_byte, len(data))
            return

        if self.delegate:
            self.delegate.on_data_received(ptype, bytes(data))

        if ptype == DataPacketType.EEG:
            self._received_eeg_data(data, recv_time)
        elif ptype == DataPacketType.BATTERY:
            self._received_battery_data(data)
        elif ptype == DataPacketType.SIGNAL:
            self._received_signal_data(data)
        elif ptype == DataPacketType.MISC:
            self._received_misc_data(data)

    # -----------------------------------------------------------------------
    # LUCA protocol handlers
    # -----------------------------------------------------------------------

    def _handle_luca_header(self, data: bytearray, recv_time: float) -> None:
        """
        Parse a LUCA header packet (36 bytes).

        Format (from device captures and native binary analysis):
          [0:4]   "LUCA" magic
          [4:8]   data type (LE uint32): 1/7=EEG, 2=info, 3=signal, 4=battery
          [8:12]  sub-type / flags
          [12:20] device ID / session ID
          [20:28] reserved
          [28:32] sequence counter
          [32:34] payload size hint
          [34:36] channel/format info

        For types 2/3/4, the next notification is a text message (ends with \\n)
        which our text handler processes automatically.
        For types 1/7, the next notifications are raw binary EEG data.
        """
        if len(data) < 36:
            return

        data_type = struct.unpack_from(">I", data, 4)[0]
        seq = struct.unpack_from("<I", data, 28)[0]
        payload_hint = struct.unpack_from("<H", data, 32)[0]

        self._luca_block_type = data_type
        self._luca_block_counter = seq

        # Only collect binary data for EEG types (1 and 7).
        # Types 2/3/4 are followed by text messages handled by the text parser.
        if data_type in (1, 7):
            # If there's a previous EEG block pending, finalize it first
            if self._luca_expecting_data and self._luca_eeg_buffer:
                self._finalize_eeg_block(time.monotonic())
            self._luca_expecting_data = True
            self._luca_eeg_buffer = bytearray()
            self._luca_last_chunk_size = payload_hint  # size of the final chunk
            log.debug("LUCA EEG header: type=%d seq=%d last_chunk=%d", data_type, seq, payload_hint)
        else:
            # Non-EEG header: finalize any pending EEG block
            if self._luca_expecting_data and self._luca_eeg_buffer:
                self._finalize_eeg_block(recv_time)
            self._luca_expecting_data = False
            log.debug("LUCA info header: type=%d seq=%d", data_type, seq)

    def _handle_luca_data(self, data: bytearray, recv_time: float) -> None:
        """
        Accumulate raw EEG data chunks following a LUCA header.

        The device sends EEG data in multiple BLE notifications (typically
        several 244-byte chunks plus one shorter final chunk). The final
        chunk size matches the payload_hint from the LUCA header.
        """
        self._luca_eeg_buffer.extend(data)
        self._freq_counter += 1

        # Finalize when we receive the short final chunk
        last_chunk = getattr(self, "_luca_last_chunk_size", 0)
        if last_chunk > 0 and len(data) == last_chunk:
            self._finalize_eeg_block(recv_time)

    def _finalize_eeg_block(self, recv_time: float) -> None:
        """Parse a complete EEG data block from the accumulated buffer."""
        self._luca_expecting_data = False
        self.stats.eeg_packet_count += 1

        raw_buf = self._luca_eeg_buffer

        # The AWEAR device sends EEG data as ASCII hex text, not raw binary.
        # Each byte of actual data is encoded as 2 hex ASCII characters.
        # e.g. "32 46 43 33 46" = ASCII "2FC3F" = hex bytes.
        try:
            hex_str = raw_buf.decode("ascii").strip()
            buf = bytes.fromhex(hex_str)
        except (UnicodeDecodeError, ValueError):
            # Fallback: treat as raw binary if not valid ASCII hex
            buf = bytes(raw_buf)

        # AWEAR EEG: 1 channel, 256 Hz, 16-bit signed samples
        # 512 decoded bytes / 2 bytes per sample = 256 samples per block
        bytes_per_sample = 2
        num_samples = len(buf) // bytes_per_sample

        for s in range(num_samples):
            offset = s * bytes_per_sample
            if offset + 1 < len(buf):
                raw = struct.unpack_from(">h", buf, offset)[0]  # 16-bit signed big-endian
                channels = [raw]
            if channels:
                if self.delegate:
                    self.delegate.on_eeg_data(channels, self._luca_block_counter)
                if self._file_writer and self.save_bt_data:
                    ts = time.time() if self.config.get("AdjustTimestamp", False) else None
                    self._file_writer.write_eeg(channels, timestamp=ts)

        if self._bench_mode:
            self.benchmark_latencies.append(time.monotonic() - recv_time)

        if self.delegate:
            self.delegate.on_data_update("eeg_block", {
                "samples": num_samples,
                "block_seq": self._luca_block_counter,
                "block_bytes": len(buf),
            })

        log.debug("EEG block: %d bytes, %d samples", len(buf), num_samples)
        self._luca_eeg_buffer = bytearray()

    def _received_eeg_data(self, data: bytearray, recv_time: float) -> None:
        """
        Process legacy EEG data packet (non-LUCA fallback).
        Mirrors AwearController receivedEEGData.

        Expected format: [type(1)] [counter(1)] [ch1(3)] [ch2(3)] [ch3(3)] ...
        Each channel is 24-bit signed big-endian.
        """
        if len(data) < 2:
            return

        self.stats.eeg_packet_count += 1
        self._freq_counter += 1

        # Packet counter for loss detection
        counter = data[1]
        expected = (self.stats.prev_packet_counter + 1) & 0xFF
        if self.stats.eeg_packet_count > 1 and counter != expected:
            if counter > expected:
                lost = counter - expected
            else:
                lost = (256 - expected) + counter
            self.stats.lost_packets += lost
            log.debug("Lost EEG packets: %d (total lost: %d)", lost, self.stats.lost_packets)
        self.stats.prev_packet_counter = counter
        self.stats.packet_counter = counter

        # Parse 24-bit signed channels
        payload = data[2:]
        channels: list[int] = []
        i = 0
        while i + 2 < len(payload):
            # 24-bit big-endian signed
            raw = (payload[i] << 16) | (payload[i + 1] << 8) | payload[i + 2]
            if raw & 0x800000:  # sign extend
                raw -= 0x1000000
            channels.append(raw)
            i += 3

        # Validate EEG values
        min_val = self.config["AwearMinEEGValueCheck"]
        max_val = self.config["AwearMaxEEGValueCheck"]
        for ch_val in channels:
            if ch_val < min_val or ch_val > max_val:
                log.debug("EEG value out of range: %d", ch_val)

        # Benchmark latency tracking
        if self._bench_mode:
            self.benchmark_latencies.append(time.monotonic() - recv_time)

        # File writing
        if self._file_writer and self.save_bt_data:
            ts = time.time() if self.config.get("AdjustTimestamp", False) else None
            self._file_writer.write_eeg(channels, timestamp=ts)

        if self.delegate:
            self.delegate.on_eeg_data(channels, counter)
            self.delegate.on_data_update("eeg", channels)

    def _received_battery_data(self, data: bytearray) -> None:
        """Process battery packet. Mirrors AwearController receivedBatteryData."""
        self.stats.battery_packet_count += 1
        if len(data) >= 2:
            level = data[1]
            self.device_info.battery = level
            log.debug("AwearController receivedBatteryData: %d%%", level)
            if self.delegate:
                self.delegate.on_battery_data(level)
                self.delegate.on_data_update("battery", level)

        if self._file_writer and self.save_bt_data:
            self._file_writer.write_raw(bytes(data), timestamp=time.time())

    def _received_signal_data(self, data: bytearray) -> None:
        """Process signal (RSSI) packet. Mirrors AwearController receivedSignalData."""
        self.stats.signal_packet_count += 1
        if len(data) >= 2:
            # RSSI as signed int8
            rssi = data[1] if data[1] < 128 else data[1] - 256
            self.device_info.signal = rssi
            log.debug("AwearController receivedSignalData: %d dBm", rssi)
            if self.delegate:
                self.delegate.on_signal_data(rssi)
                self.delegate.on_data_update("signal", rssi)

        if self._file_writer and self.save_bt_data:
            self._file_writer.write_raw(bytes(data), timestamp=time.time())

    def _received_misc_data(self, data: bytearray) -> None:
        """Process misc packet. Mirrors AwearController receivedMiscData."""
        self.stats.misc_packet_count += 1
        log.debug("AwearController receivedMiscData: %d bytes", len(data))

        # Check if it's a command response (text)
        try:
            text = data[1:].decode("utf-8").strip()
            if text:
                self._command_output.append(text)
        except UnicodeDecodeError:
            pass

        if self.delegate:
            self.delegate.on_misc_data(bytes(data))
            self.delegate.on_data_update("misc", bytes(data))

        if self._file_writer and self.save_bt_data:
            self._file_writer.write_raw(bytes(data), timestamp=time.time())

    # -----------------------------------------------------------------------
    # Firmware update
    # -----------------------------------------------------------------------

    async def update_firmware(self, firmware_path: str,
                              on_progress: Optional[Callable[[DFUProgress], None]] = None) -> bool:
        """Initiate OTA firmware update. Mirrors updateFirmware(from fileURL:)."""
        if not self._client or not self._client.is_connected:
            log.error("Cannot update firmware — not connected")
            return False

        self._set_status(DeviceStatus.DFU)
        self._dfu = DFUController(self._client)

        if not await self._dfu.discover():
            log.error("DFU service discovery failed")
            self._set_status(DeviceStatus.READY if self._device_ready else DeviceStatus.CONNECTED)
            return False

        success = await self._dfu.update_firmware(firmware_path, on_progress=on_progress)
        if success:
            # Device will reboot — expect disconnect
            log.info("Firmware update complete; device will reboot")
        self._dfu = None
        return success

    # -----------------------------------------------------------------------
    # File writing (mirrors writeFileData / writeFileDataWithTimestamp)
    # -----------------------------------------------------------------------

    def write_file_data(self, data: bytes) -> None:
        """Write raw data to the current file. Mirrors writeFileData()."""
        if self._file_writer:
            self._file_writer.write_raw(data)

    def write_file_data_with_timestamp(self, data: bytes) -> None:
        """Write data with timestamp. Mirrors writeFileDataWithTimestamp()."""
        if self._file_writer:
            self._file_writer.write_raw(data, timestamp=time.time())

    # -----------------------------------------------------------------------
    # Timer machinery
    # -----------------------------------------------------------------------

    def _start_timer(self, name: str, coro_func, interval: float) -> None:
        self._cancel_timer(name)
        async def _loop():
            try:
                await coro_func()
            except asyncio.CancelledError:
                pass
        self._timer_tasks[name] = asyncio.ensure_future(_loop())

    def _cancel_timer(self, name: str) -> None:
        task = self._timer_tasks.pop(name, None)
        if task and not task.done():
            task.cancel()

    def _cancel_all_timers(self) -> None:
        for name in list(self._timer_tasks):
            self._cancel_timer(name)

    async def _frequency_counter_tick(self) -> None:
        """Measure EEG packet frequency. Mirrors frequencyCounterTimer."""
        while True:
            await asyncio.sleep(FREQUENCY_COUNTER_TIMER_INTERVAL)
            now = time.monotonic()
            elapsed = now - self._last_freq_time
            if elapsed > 0:
                self._current_frequency = self._freq_counter / elapsed
            self.stats.last_frequency = self._current_frequency
            if self._current_frequency > 0:
                log.debug("EEG packet frequency: %.1f Hz", self._current_frequency)
            else:
                log.debug("EEG packet frequency: 0")
            self._freq_counter = 0
            self._last_freq_time = now

    async def _check_data_tick(self) -> None:
        """Periodic data health check. Mirrors checkDataTimer."""
        while True:
            await asyncio.sleep(CHECK_DATA_TIMER_INTERVAL)
            if self._started and self.stats.eeg_packet_count == 0:
                log.warning("No EEG data received from AWEAR board")
                if self.delegate:
                    self.delegate.on_status_update(
                        "Warning: not received from AWEAR board"
                    )
            new_lost = self.stats.lost_packets - self.stats.prev_lost_packets
            if new_lost > 0:
                log.warning("Lost %d EEG packets since last check", new_lost)
            self.stats.prev_lost_packets = self.stats.lost_packets

    # -----------------------------------------------------------------------
    # Status management
    # -----------------------------------------------------------------------

    def _set_status(self, status: DeviceStatus) -> None:
        old = self.status
        self.status = status
        if old != status:
            log.info("AWEAR StatusSet: %s%s", old.value, status.value)
            if self.delegate:
                self.delegate.on_status_set(status)

    # -----------------------------------------------------------------------
    # Connection key (mirrors getConnectionKey)
    # -----------------------------------------------------------------------

    def get_connection_key(self) -> str:
        return self.device_info.peripheral_uuid

    # -----------------------------------------------------------------------
    # Device list for Flutter (mirrors getDevicesAWEAR / deviceListUpdatedAWEAR)
    # -----------------------------------------------------------------------

    def get_devices(self) -> list[dict[str, Any]]:
        """Return discovered devices as dicts. Mirrors getDevicesAWEAR."""
        devices = self.found_devices.snapshot()
        result = []
        for d in devices:
            result.append({
                "name": d.name,
                "address": d.address,
                "rssi": d.rssi,
            })
        log.debug("AWEAR device list data sent to Flutter")
        return result

    # -----------------------------------------------------------------------
    # Cancel in-progress connection (mirrors Bluetooth.stopConnecting)
    # -----------------------------------------------------------------------

    async def stop_connecting(self) -> None:
        """Cancel an in-progress BLE connection. Mirrors Bluetooth.stopConnecting."""
        log.info("@@@@ Bluetooth.stopConnecting")
        if self.status == DeviceStatus.CONNECTING and self._client:
            try:
                await self._client.disconnect()
            except Exception:
                pass
            self._client = None
            self._set_status(DeviceStatus.DISCONNECTED)

    # -----------------------------------------------------------------------
    # Device listing notifications (mirrors startDeviceListing / stopDeviceListing
    #   / deviceListUpdatedAWEAR)
    # -----------------------------------------------------------------------

    def start_device_listing(self) -> None:
        """Begin device listing mode. Mirrors Flutter method startDeviceListing()."""
        log.debug("Flutter method startDeviceListing() called")
        self._device_listing_active = True

    def stop_device_listing(self) -> None:
        """Stop device listing mode. Mirrors Flutter method stopDeviceListing()."""
        log.debug("Flutter method stopDeviceListing() called")
        self._device_listing_active = False

    def device_list_updated(self) -> bool:
        """
        Notify that the device list has changed. Mirrors deviceListUpdatedAWEAR().
        Returns True if listing is active and there are devices.
        """
        log.debug("Flutter method deviceListUpdatedAWEAR() called")
        return self._device_listing_active and len(self.found_devices) > 0

    # -----------------------------------------------------------------------
    # Cloud data transmission (mirrors transmit_cloud_data)
    # -----------------------------------------------------------------------

    async def transmit_cloud_data(self, collection: str, data: dict[str, Any]) -> bool:
        """
        Transmit data to the cloud (Firebase Firestore equivalent).
        Mirrors Flutter method transmit_cloud_data().

        In the native app this writes to Firestore via FirebaseFirestoreHostApi.
        Here we simulate the serialization/validation and optionally forward to
        a configurable HTTP endpoint.
        """
        log.debug("Flutter method transmit_cloud_data() called")
        if not collection or not data:
            log.error("Invalid transmit_cloud_data")
            return False

        # Validate payload (mirror native validation)
        if not isinstance(data, dict):
            log.error("Invalid transmit_cloud_data: data must be a dict")
            return False

        # Serialize to measure parity with native Firestore serialization cost
        import json
        try:
            payload = json.dumps(data, default=str)
        except (TypeError, ValueError) as exc:
            log.error("transmit_cloud_data serialization failed: %s", exc)
            return False

        cloud_endpoint = self.config.get("CloudEndpoint")
        if cloud_endpoint:
            import urllib.request
            try:
                req = urllib.request.Request(
                    cloud_endpoint,
                    data=payload.encode("utf-8"),
                    headers={"Content-Type": "application/json"},
                    method="POST",
                )
                urllib.request.urlopen(req, timeout=10)
            except Exception as exc:
                log.error("Cloud transmit failed: %s", exc)
                return False

        log.info("transmit_cloud_data: collection=%s, payload_size=%d bytes",
                 collection, len(payload))
        return True

    # -----------------------------------------------------------------------
    # Haptic feedback (mirrors triggerBreathingCycle / triggerStressVibration)
    # -----------------------------------------------------------------------

    async def trigger_breathing_cycle(self, duration: float = 4.0) -> bool:
        """
        Trigger a breathing haptic cycle. Mirrors triggerBreathingCycle().

        The native app uses CoreHaptics (CHHapticEngine) in the foreground
        and falls back to AudioServices system vibrate in the background.
        On Python/macOS we simulate the timing and computation cost.
        """
        log.info("Flutter method triggerBreathingCycle(%.1f) called", duration)

        if not self._haptic_engine_available:
            log.warning("#### No haptic engine available")
            return False

        log.info("#### Breathing haptic cycle started (%.1fs)", duration)

        # Simulate CoreHaptics event construction (mirrors CHHapticEvent creation)
        # The native code builds a CHHapticPattern with intensity/sharpness curves
        events = []
        steps = int(duration / 0.1)
        for i in range(steps):
            t = i * 0.1
            # Sinusoidal intensity curve (inhale/exhale)
            import math
            intensity = 0.5 + 0.5 * math.sin(2 * math.pi * t / duration)
            sharpness = 0.3
            events.append({
                "type": "hapticContinuous",
                "time": t,
                "duration": 0.1,
                "intensity": intensity,
                "sharpness": sharpness,
            })

        # Simulate the playback duration
        await asyncio.sleep(duration)
        log.info("Breathing haptic cycle completed")
        return True

    async def trigger_stress_vibration(self) -> bool:
        """
        Trigger stress relief vibration. Mirrors triggerStressVibration().

        Native implementation queues on stress.haptics.queue, uses
        CoreHaptics in foreground or StressVibrationBG in background.
        """
        log.info("Flutter method triggerStressVibration() called")
        log.debug("#### triggerStressVibrationBackground() start")

        # Simulate the vibration pattern (3 short bursts)
        for _ in range(3):
            await asyncio.sleep(0.2)
        log.debug("#### triggerStressVibrationBackground() done")
        return True

    # -----------------------------------------------------------------------
    # Cleanup
    # -----------------------------------------------------------------------

    async def cleanup(self) -> None:
        """Teardown — mirrors AwearController deinit."""
        log.info("AwearController deinit")
        self._reconnection_requested = False
        self._cancel_all_timers()
        if self.device_connected:
            await self.disconnect()


# ---------------------------------------------------------------------------
# Benchmark harness
# ---------------------------------------------------------------------------

class BenchmarkRunner:
    """
    End-to-end benchmark that exercises every AwearController code path
    and measures timing for comparison with the native Runner binary.
    """

    def __init__(self, controller: AwearController) -> None:
        self.ctrl = controller
        self.results: dict[str, dict[str, float]] = {}

    async def run_all(self, device_name: Optional[str] = None, duration: float = 30.0) -> dict:
        """Run the full benchmark suite."""
        log.info("=" * 60)
        log.info("AWEAR Runner Python Benchmark")
        log.info("=" * 60)

        # 1. Scan benchmark
        await self._bench("scan_devices", self._bench_scan)

        # 2. Connect benchmark
        if device_name:
            await self._bench("connect", self._bench_connect, device_name)
        elif len(self.ctrl.found_devices) > 0:
            dev = self.ctrl.found_devices.snapshot()[0]
            device_name = dev.name
            await self._bench("connect", self._bench_connect, dev)

        if not self.ctrl.device_connected:
            log.warning("No device connected — skipping connected benchmarks")
            self._print_results()
            return self.results

        # 3. Service discovery (already done in connect, measure separately)
        await self._bench("service_discovery", self._bench_service_discovery)

        # 4. Start streaming
        await self._bench("start_streaming", self._bench_start)

        # 5. Data streaming throughput
        await self._bench("data_streaming", self._bench_streaming, duration)

        # 6. Command round-trip
        await self._bench("command_roundtrip", self._bench_command)

        # 7. Stop streaming
        await self._bench("stop_streaming", self._bench_stop)

        # 8. File writing throughput (synthetic)
        await self._bench("file_write_openbci", self._bench_file_write, True)
        await self._bench("file_write_binary", self._bench_file_write, False)

        # 9. Packet parsing throughput (synthetic)
        await self._bench("packet_parse_eeg", self._bench_packet_parse)

        # 10. Haptics
        await self._bench("breathing_cycle", self._bench_breathing_cycle)
        await self._bench("stress_vibration", self._bench_stress_vibration)

        # 11. Cloud data transmission (synthetic)
        await self._bench("transmit_cloud_data", self._bench_cloud_transmit)

        # 12. Device listing API
        await self._bench("device_listing_api", self._bench_device_listing)

        # 13. Disconnect
        await self._bench("disconnect", self._bench_disconnect)

        # 14. Reconnection
        if device_name:
            await self._bench("reconnection", self._bench_reconnect, device_name)
            if self.ctrl.device_connected:
                await self.ctrl.disconnect()

        self._print_results()
        return self.results

    async def _bench(self, name: str, func, *args) -> None:
        log.info("--- Benchmark: %s ---", name)
        t0 = time.monotonic()
        try:
            result = await func(*args)
        except Exception as exc:
            log.error("Benchmark %s failed: %s", name, exc)
            result = {"error": str(exc)}
        elapsed = time.monotonic() - t0
        entry = {"elapsed_s": round(elapsed, 6)}
        if isinstance(result, dict):
            entry.update(result)
        self.results[name] = entry
        log.info("  %s: %.4fs %s", name, elapsed,
                 " ".join(f"{k}={v}" for k, v in entry.items() if k != "elapsed_s"))

    # -- individual benchmarks -----------------------------------------------

    async def _bench_scan(self) -> dict:
        devices = await self.ctrl.search_devices(timeout=SEARCH_TIMEOUT)
        return {"devices_found": len(devices)}

    async def _bench_connect(self, device) -> dict:
        ok = await self.ctrl.connect(device)
        return {"success": ok}

    async def _bench_service_discovery(self) -> dict:
        # Services already discovered on connect; just verify presence
        has_tx = self.ctrl._tx_char is not None
        has_rx = self.ctrl._rx_char is not None
        return {"tx_found": has_tx, "rx_found": has_rx}

    async def _bench_start(self) -> dict:
        await self.ctrl.start()
        return {"started": self.ctrl.is_started}

    async def _bench_streaming(self, duration: float) -> dict:
        self.ctrl._bench_mode = True
        self.ctrl.benchmark_latencies.clear()
        initial_count = self.ctrl.stats.eeg_packet_count

        await asyncio.sleep(duration)

        total_packets = self.ctrl.stats.eeg_packet_count - initial_count
        lost = self.ctrl.stats.lost_packets
        freq = self.ctrl._current_frequency
        latencies = list(self.ctrl.benchmark_latencies)
        self.ctrl._bench_mode = False

        avg_latency = sum(latencies) / len(latencies) if latencies else 0
        max_latency = max(latencies) if latencies else 0
        min_latency = min(latencies) if latencies else 0
        p95_latency = sorted(latencies)[int(len(latencies) * 0.95)] if latencies else 0

        return {
            "total_packets": total_packets,
            "lost_packets": lost,
            "frequency_hz": round(freq, 2),
            "avg_latency_us": round(avg_latency * 1e6, 2),
            "min_latency_us": round(min_latency * 1e6, 2),
            "max_latency_us": round(max_latency * 1e6, 2),
            "p95_latency_us": round(p95_latency * 1e6, 2),
            "throughput_pps": round(total_packets / duration, 2) if duration > 0 else 0,
        }

    async def _bench_command(self) -> dict:
        if not self.ctrl._tx_char:
            return {"error": "no TX characteristic"}
        t0 = time.monotonic()
        await self.ctrl.send_command("PING")
        # Wait for response (up to 2s)
        for _ in range(200):
            if self.ctrl.has_command_output():
                break
            await asyncio.sleep(0.01)
        rtt = time.monotonic() - t0
        resp = self.ctrl.get_command_output()
        return {"rtt_ms": round(rtt * 1000, 2), "response": resp or "timeout"}

    async def _bench_stop(self) -> dict:
        await self.ctrl.stop()
        return {"stopped": not self.ctrl.is_started}

    async def _bench_file_write(self, openbci: bool) -> dict:
        """Synthetic file write benchmark — 10000 EEG samples."""
        n = 10_000
        output_dir = Path.cwd() / "awear_benchmark_data"
        fw = FileWriter(output_dir, openbci_format=openbci)
        fw.open()
        channels = [100000, -200000, 350000, -450000, 500000, -600000, 700000, -800000]
        t0 = time.monotonic()
        for i in range(n):
            fw.write_eeg(channels, timestamp=time.time())
        fw.flush()
        elapsed = time.monotonic() - t0
        fw.close()
        return {
            "samples": n,
            "throughput_sps": round(n / elapsed, 2),
            "format": "openbci" if openbci else "binary",
        }

    async def _bench_packet_parse(self) -> dict:
        """Synthetic EEG packet parsing benchmark — 100000 packets."""
        n = 100_000
        # Build a realistic 26-byte EEG packet: type(1) + counter(1) + 8ch * 3bytes
        channels_raw = b""
        for val in [100000, -200000, 350000, -450000, 500000, -600000, 700000, -800000]:
            channels_raw += val.to_bytes(3, "big", signed=True)
        base_packet = bytearray([0x01, 0x00]) + bytearray(channels_raw)

        t0 = time.monotonic()
        ctrl = self.ctrl
        ctrl._bench_mode = False  # don't append latencies for synthetic
        old_delegate = ctrl.delegate
        ctrl.delegate = None  # disable callbacks for raw speed
        old_writer = ctrl._file_writer
        ctrl._file_writer = None

        for i in range(n):
            pkt = bytearray(base_packet)
            pkt[1] = i & 0xFF
            ctrl._received_eeg_data(pkt, time.monotonic())

        elapsed = time.monotonic() - t0
        ctrl.delegate = old_delegate
        ctrl._file_writer = old_writer
        return {
            "packets": n,
            "throughput_pps": round(n / elapsed, 2),
            "parse_us_per_packet": round((elapsed / n) * 1e6, 2),
        }

    async def _bench_breathing_cycle(self) -> dict:
        ok = await self.ctrl.trigger_breathing_cycle(duration=1.0)
        return {"success": ok}

    async def _bench_stress_vibration(self) -> dict:
        ok = await self.ctrl.trigger_stress_vibration()
        return {"success": ok}

    async def _bench_cloud_transmit(self) -> dict:
        """Synthetic cloud data serialization benchmark — 1000 payloads."""
        n = 1_000
        sample_data = {
            "timestamp": time.time(),
            "eeg_channels": [100000, -200000, 350000, -450000],
            "battery": 85,
            "signal": -45,
            "device": "AWEAR_TEST",
            "session_id": "bench-001",
        }
        t0 = time.monotonic()
        for _ in range(n):
            await self.ctrl.transmit_cloud_data("benchmark", sample_data)
        elapsed = time.monotonic() - t0
        return {
            "payloads": n,
            "throughput_pps": round(n / elapsed, 2),
        }

    async def _bench_device_listing(self) -> dict:
        """Exercise device listing API cycle."""
        self.ctrl.start_device_listing()
        updated = self.ctrl.device_list_updated()
        devices = self.ctrl.get_devices()
        self.ctrl.stop_device_listing()
        return {"devices": len(devices), "updated": updated}

    async def _bench_disconnect(self) -> dict:
        await self.ctrl.disconnect()
        return {"disconnected": self.ctrl.device_disconnected}

    async def _bench_reconnect(self, device_name: str) -> dict:
        t0 = time.monotonic()
        ok = await self.ctrl.connect(device_name)
        elapsed = time.monotonic() - t0
        return {"success": ok, "reconnect_time_s": round(elapsed, 4)}

    # -- reporting -----------------------------------------------------------

    def _print_results(self) -> None:
        print("\n" + "=" * 70)
        print("BENCHMARK RESULTS — Python AWEAR Runner")
        print("=" * 70)
        for name, metrics in self.results.items():
            elapsed = metrics.get("elapsed_s", 0)
            detail = ", ".join(
                f"{k}={v}" for k, v in metrics.items() if k != "elapsed_s"
            )
            print(f"  {name:30s}  {elapsed:10.4f}s  {detail}")
        print("=" * 70)


# ---------------------------------------------------------------------------
# Main — CLI entry point
# ---------------------------------------------------------------------------

async def main() -> None:
    parser = argparse.ArgumentParser(
        description="AWEAR Runner — Python BLE parity benchmark"
    )
    parser.add_argument("--benchmark", action="store_true", help="Run benchmark suite")
    parser.add_argument("--device", type=str, default=None, help="Device name to connect to")
    parser.add_argument("--scan-timeout", type=float, default=SEARCH_TIMEOUT,
                        help="Scan timeout in seconds")
    parser.add_argument("--connect-timeout", type=float, default=DEVICE_CONNECTION_TIMEOUT,
                        help="Connection timeout in seconds")
    parser.add_argument("--stream-duration", type=float, default=30.0,
                        help="Streaming benchmark duration in seconds")
    parser.add_argument("--save-bt-data", action="store_true",
                        help="Save BT data to file during streaming")
    parser.add_argument("--openbci", action="store_true", default=True,
                        help="Save in OpenBCI CSV format (default)")
    parser.add_argument("--binary", action="store_true",
                        help="Save in binary format instead of OpenBCI")
    parser.add_argument("--min-rssi", type=int, default=-80,
                        help="Minimum RSSI for device discovery")
    parser.add_argument("--auto-start", action="store_true",
                        help="Auto-start streaming after connection")
    parser.add_argument("--verbose", "-v", action="store_true", help="Verbose logging")
    args = parser.parse_args()

    level = logging.DEBUG if args.verbose else logging.INFO
    logging.basicConfig(
        level=level,
        format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
        datefmt="%H:%M:%S",
    )

    config = {
        **DEFAULTS,
        "AwearConnectTimeout": args.connect_timeout,
        "AwearDiscoveryMinSignal": args.min_rssi,
        "StartAfterConnected": args.auto_start,
        "SaveBTData": args.save_bt_data,
        "SaveDataAsOpenBCI": not args.binary,
    }

    controller = AwearController(config=config)

    try:
        if args.benchmark:
            bench = BenchmarkRunner(controller)
            await bench.run_all(device_name=args.device, duration=args.stream_duration)
        else:
            # Interactive mode: scan → connect → stream
            devices = await controller.search_devices(timeout=args.scan_timeout)
            if not devices:
                print("No AWEAR devices found.")
                return

            target = args.device
            if not target:
                print("\nDiscovered devices:")
                for i, d in enumerate(devices):
                    print(f"  [{i}] {d.name} ({d.address}) RSSI={d.rssi}")
                choice = input("\nSelect device [0]: ").strip()
                idx = int(choice) if choice else 0
                target = devices[idx]

            ok = await controller.connect(target)
            if not ok:
                print("Connection failed.")
                return

            print(f"\nConnected to {controller.device_name}")
            print("Streaming... (Ctrl+C to stop)")
            await controller.start()

            try:
                while True:
                    await asyncio.sleep(1.0)
                    freq = controller._current_frequency
                    pkts = controller.stats.eeg_packet_count
                    lost = controller.stats.lost_packets
                    batt = controller.battery_level
                    sig = controller.signal_level
                    print(
                        f"\r  Freq={freq:.1f}Hz  Packets={pkts}  "
                        f"Lost={lost}  Battery={batt}%  Signal={sig}dBm",
                        end="", flush=True,
                    )
            except KeyboardInterrupt:
                print("\nStopping...")

            await controller.stop()
    finally:
        await controller.cleanup()


if __name__ == "__main__":
    asyncio.run(main())