-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathBTScan.py
More file actions
1252 lines (1049 loc) · 55.7 KB
/
Copy pathBTScan.py
File metadata and controls
1252 lines (1049 loc) · 55.7 KB
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
#!/usr/bin/env python3
"""
BLE LED Strip Discovery and Testing Tool
Helps find commands for new LED strips to add to elkbledom.py
"""
import asyncio
import logging
from bleak import BleakScanner, BleakClient
from bleak.backends.device import BLEDevice
from bleak.exc import BleakError
import sys
import os
from typing import List, Dict, Optional, Tuple
import json
from datetime import datetime
from pathlib import Path
logging.basicConfig(level=logging.INFO)
_LOGGER = logging.getLogger(__name__)
# Load models.json to get all known commands
def load_models_json():
"""Load all known models and extract unique commands"""
# Try to find models.json in common locations
possible_paths = [
Path(__file__).parent / "custom_components" / "elkbledom" / "models.json",
Path(__file__).parent.parent / "custom_components" / "elkbledom" / "models.json",
Path("custom_components/elkbledom/models.json"),
Path("models.json"),
]
models_data = None
for path in possible_paths:
if path.exists():
print(f"Loading commands from: {path}")
with open(path, 'r', encoding="utf-8") as f:
models_data = json.load(f)
break
if not models_data:
print("Warning: models.json not found, using fallback commands")
return None
# Extract unique UUIDs
write_uuids = set()
read_uuids = set()
# Extract unique commands
turn_on_cmds = []
turn_off_cmds = []
white_cmds = []
color_temp_cmds = []
color_cmds = []
query_cmds = []
for model in models_data:
# Collect UUIDs
if 'write_uuid' in model:
write_uuids.add(model['write_uuid'])
if 'read_uuid' in model:
read_uuids.add(model['read_uuid'])
# Collect commands
if 'commands' in model:
cmds = model['commands']
# Turn on commands (no variables)
if 'turn_on' in cmds and isinstance(cmds['turn_on'], list):
cmd = [x for x in cmds['turn_on'] if isinstance(x, int)]
if cmd and cmd not in turn_on_cmds:
turn_on_cmds.append(cmd)
# Turn off commands (no variables)
if 'turn_off' in cmds and isinstance(cmds['turn_off'], list):
cmd = [x for x in cmds['turn_off'] if isinstance(x, int)]
if cmd and cmd not in turn_off_cmds:
turn_off_cmds.append(cmd)
# White commands (may have variable 'i')
if 'white' in cmds and isinstance(cmds['white'], list):
cmd = cmds['white']
if cmd and cmd not in white_cmds:
white_cmds.append(cmd)
# Color temp commands (may have variables 'w', 'c')
if 'color_temp' in cmds and isinstance(cmds['color_temp'], list):
cmd = cmds['color_temp']
if cmd and cmd not in color_temp_cmds:
color_temp_cmds.append(cmd)
# Color commands (may have variables 'r', 'g', 'b')
if 'color' in cmds and isinstance(cmds['color'], list):
cmd = cmds['color']
if cmd and cmd not in color_cmds:
color_cmds.append(cmd)
# Query commands (no variables)
if 'query' in cmds and isinstance(cmds['query'], list):
cmd = [x for x in cmds['query'] if isinstance(x, int)]
if cmd and len(cmd) > 0 and cmd not in query_cmds:
query_cmds.append(cmd)
return {
'write_uuids': list(write_uuids),
'read_uuids': list(read_uuids),
'turn_on': turn_on_cmds,
'turn_off': turn_off_cmds,
'white': white_cmds,
'color_temp': color_temp_cmds,
'color': color_cmds,
'query': query_cmds
}
# Load commands from models.json
models_commands = load_models_json()
# Known characteristics from models.json or fallback
if models_commands:
KNOWN_WRITE_UUIDS = models_commands['write_uuids']
KNOWN_READ_UUIDS = models_commands['read_uuids']
KNOWN_TURN_ON = models_commands['turn_on']
KNOWN_TURN_OFF = models_commands['turn_off']
KNOWN_WHITE = models_commands['white']
KNOWN_COLOR_TEMP = models_commands['color_temp']
# Convert color commands to lambdas
NEW_COLOR_COMMANDS = []
for cmd_template in models_commands['color']:
if 'r' in cmd_template and 'g' in cmd_template and 'b' in cmd_template:
# Create lambda from template
r_idx = cmd_template.index('r')
g_idx = cmd_template.index('g')
b_idx = cmd_template.index('b')
base_cmd = [x if isinstance(x, int) else 0 for x in cmd_template]
NEW_COLOR_COMMANDS.append(
lambda r, g, b, template=base_cmd, ri=r_idx, gi=g_idx, bi=b_idx:
[r if i == ri else g if i == gi else b if i == bi else template[i]
for i in range(len(template))]
)
# Query commands
QUERY_COMMANDS = [(cmd, f"Query from {i}") for i, cmd in enumerate(models_commands['query'])]
else:
KNOWN_WRITE_UUIDS = []
KNOWN_READ_UUIDS = []
KNOWN_TURN_ON = []
KNOWN_TURN_OFF = []
KNOWN_WHITE = []
KNOWN_COLOR_TEMP = []
NEW_COLOR_COMMANDS = []
QUERY_COMMANDS = []
print(f"ERROR: models.json not found or invalid, no commands loaded. Please ensure models.json is in the correct location.\n")
print(f"Loaded {len(KNOWN_TURN_ON)} turn_on commands from models")
print(f"Loaded {len(KNOWN_TURN_OFF)} turn_off commands from models")
print(f"Loaded {len(NEW_COLOR_COMMANDS)} color command templates from models")
print(f"Loaded {len(QUERY_COMMANDS)} query commands from models\n")
# Additional new turn on/off commands for testing (beyond models.json)
NEW_TURN_ON_COMMANDS = []
NEW_TURN_OFF_COMMANDS = []
NEW_WHITE_COMMANDS = []
NEW_COLOR_TEMP_COMMANDS = []
# Note: Commands are now loaded from models.json
# Note: Query commands are now loaded from models.json
# Note: Additional commands can be added here if needed for testing beyond models.json
class LEDStripDiscovery:
def __init__(self):
self.read_uuid: Optional[str] = None
self.write_uuid: Optional[str] = None
self.discovered_devices: List[BLEDevice] = []
self.test_results = {
'device_info': {},
'characteristics': {},
'working_commands': {
'turn_on': [],
'turn_off': [],
'color': [],
'white': [],
'color_temp': [],
'query': []
},
'custom_commands': []
}
async def scan_devices(self, duration: int = 30) -> List[BLEDevice]:
"""Scans nearby BLE devices"""
print(f"\n{'='*60}")
print(f"Scanning for Bluetooth LE devices for {duration} seconds...")
print(f"{'='*60}\n")
devices = await BleakScanner.discover(timeout=duration, scanning_mode='active')
self.discovered_devices = [d for d in devices] # Only devices with name
return self.discovered_devices
def display_devices(self) -> None:
"""Displays discovered devices"""
if not self.discovered_devices:
print("No BLE devices found")
return
print(f"\n{'='*60}")
print("BLE Devices Found:")
print(f"{'='*60}\n")
for idx, device in enumerate(self.discovered_devices, 1):
print(f"{idx}. Address: {device.address}")
print(f" Name: {device.name or 'No name'}")
print(f" RSSI: N/A dBm") # Will be shown in select_device
print(f" {'-'*56}")
async def select_device(self) -> Optional[BLEDevice]:
"""Allows user to select a device"""
self.display_devices()
if not self.discovered_devices:
return None
while True:
try:
choice = input(f"\nSelect a device (1-{len(self.discovered_devices)}) or 'q' to exit: ").strip()
if choice.lower() == 'q':
return None
idx = int(choice) - 1
if 0 <= idx < len(self.discovered_devices):
device = self.discovered_devices[idx]
print(f"\nDevice selected: {device.name} ({device.address})")
self.test_results['device_info'] = {
'name': device.name,
'address': device.address,
'rssi': 'N/A'
}
return device
else:
print("Invalid number, try again")
except ValueError:
print("Invalid input, enter a number")
async def discover_characteristics(self, device: BLEDevice) -> Dict:
"""Discovers BLE characteristics of the device"""
print(f"\n{'='*60}")
print(f"Analyzing device characteristics...")
print(f"{'='*60}\n")
characteristics = {
'write': [],
'read': [],
'notify': [],
'all': []
}
try:
async with BleakClient(device.address, timeout=20.0) as client:
print(f"Connected to {device.name}\n")
# Special login procedure for MELK and MODELX devices
# Must be done BEFORE full service discovery or device will disconnect
if device.name and (device.name.lower().startswith("melk") or device.name.lower().startswith("modelx")):
print(f"Device {device.name} requires special login procedure...")
print("Getting initial services to find write characteristic...\n")
# Force service discovery
try:
temp_services = await client.get_services()
except Exception as e:
print(f"Could not get services for login: {e}")
temp_services = client.services
write_char = None
read_char = None
for service in temp_services:
for char in service.characteristics:
if char.uuid in KNOWN_WRITE_UUIDS or 'write' in char.properties or 'write-without-response' in char.properties:
write_char = char.uuid
print(f"Found write characteristic: {write_char}")
if char.uuid in KNOWN_READ_UUIDS:
read_char = char.uuid
print(f"Found read characteristic (used as write): {read_char}")
if read_char and write_char:
break
if read_char and write_char:
break
if read_char:
self.read_uuid = read_char
print(f"Found read characteristic: {read_char}")
if write_char:
self.write_uuid = write_char
# Execute login sequence
print("Executing login commands...")
try:
await client.write_gatt_char(write_char, bytes([0x7e, 0x07, 0x83]), response=False)
print(" ✓ Sent: 7e 07 83")
await asyncio.sleep(1)
await client.write_gatt_char(write_char, bytes([0x7e, 0x04, 0x04]), response=False)
print(" ✓ Sent: 7e 04 04")
await asyncio.sleep(1)
print("✓ Login procedure completed!\n")
except Exception as e:
print(f"✗ Login procedure failed: {e}\n")
raise
else:
print("✗ Could not find write characteristic for login\n")
raise Exception("No write characteristic found for login")
# Now discover all services properly
print("Discovering all services and characteristics...\n")
for service in client.services:
print(f"Service: {service.uuid}")
for char in service.characteristics:
char_info = {
'uuid': char.uuid,
'properties': char.properties,
'service': service.uuid,
'handle': char.handle
}
characteristics['all'].append(char_info)
print(f" └─ Characteristic: {char.uuid}")
print(f" Handle: {char.handle}")
print(f" Properties: {', '.join(char.properties)}")
if 'write' in char.properties or 'write-without-response' in char.properties:
characteristics['write'].append(char_info)
print(f" ✍️ WRITE available")
if 'read' in char.properties:
characteristics['read'].append(char_info)
print(f" 📖 READ available")
if 'notify' in char.properties:
characteristics['notify'].append(char_info)
print(f" 🔔 NOTIFY available")
print()
self.test_results['characteristics'] = characteristics
except Exception as e:
print(f"Connection error: {e}")
return characteristics
return characteristics
async def select_write_characteristic(self, characteristics: Dict) -> Optional[str]:
"""Selects the write characteristic"""
print(f"\n{'='*60}")
print("WRITE Characteristic Selection")
print(f"{'='*60}\n")
# Check if there are known characteristics
write_chars = characteristics.get('write', [])
if not write_chars:
print("No write characteristics found")
return None
# Search for known characteristics
known_found = []
for char in write_chars:
if char['uuid'] in KNOWN_WRITE_UUIDS:
known_found.append(char)
if known_found:
print(f"Found {len(known_found)} known characteristics:\n")
for char in known_found:
print(f" - {char['uuid']}")
if len(known_found) == 1:
selected = known_found[0]['uuid']
print(f"\nUsing known characteristic: {selected}")
return selected
# If there are no known ones or there are multiple, show all
print(f"\nAvailable write characteristics:\n")
for idx, char in enumerate(write_chars, 1):
known = "[KNOWN]" if char['uuid'] in KNOWN_WRITE_UUIDS else ""
print(f"{idx}. {char['uuid']} {known}")
while True:
try:
choice = input(f"\nSelect characteristic (1-{len(write_chars)}): ").strip()
idx = int(choice) - 1
if 0 <= idx < len(write_chars):
selected = write_chars[idx]['uuid']
print(f"\nCharacteristic selected: {selected}")
return selected
else:
print("Invalid number")
except ValueError:
print("Invalid input")
async def select_read_characteristic(self, characteristics: Dict) -> Optional[str]:
"""Selects the read characteristic"""
print(f"\n{'='*60}")
print("READ Characteristic Selection")
print(f"{'='*60}\n")
# Check if there are known characteristics
read_chars = characteristics.get('read', [])
if not read_chars:
print("No read characteristics found")
return None
# Search for known characteristics
known_found = []
for char in read_chars:
if char['uuid'] in KNOWN_READ_UUIDS:
known_found.append(char)
if known_found:
print(f"Found {len(known_found)} known characteristics:\n")
for char in known_found:
print(f" - {char['uuid']}")
if len(known_found) == 1:
selected = known_found[0]['uuid']
print(f"\nUsing known characteristic: {selected}")
return selected
# If there are no known ones or there are multiple, show all
print(f"\nAvailable read characteristics:\n")
for idx, char in enumerate(read_chars, 1):
known = "[KNOWN]" if char['uuid'] in KNOWN_READ_UUIDS else ""
print(f"{idx}. {char['uuid']} {known}")
while True:
try:
choice = input(f"\nSelect characteristic (1-{len(read_chars)}): ").strip()
idx = int(choice) - 1
if 0 <= idx < len(read_chars):
selected = read_chars[idx]['uuid']
print(f"\nCharacteristic selected: {selected}")
return selected
else:
print("Invalid number")
except ValueError:
print("Invalid input")
async def _execute_login(self, client: BleakClient, device: BLEDevice, char_uuid: str):
"""Execute login procedure for MELK/MODELX devices"""
if device.name and (device.name.lower().startswith("melk") or device.name.lower().startswith("modelx")):
try:
print("Executing login procedure...")
await client.write_gatt_char(char_uuid, bytes([0x7e, 0x07, 0x83]), response=False)
await asyncio.sleep(1)
await client.write_gatt_char(char_uuid, bytes([0x7e, 0x04, 0x04]), response=False)
await asyncio.sleep(1)
print("Login completed!\n")
except Exception as e:
print(f"Login procedure failed: {e}\n")
async def test_command(self, client: BleakClient, char_uuid: str, command: List[int],
description: str, ask_user: bool = True, turn_on_first: List[int] = None) -> bool:
"""Tests a command on the device"""
try:
# Check if still connected
if not client.is_connected:
print(f" [ERROR] Not connected")
raise Exception("Client disconnected")
# Turn on the strip first if a working turn_on command is provided
if turn_on_first is not None:
try:
await client.write_gatt_char(char_uuid, bytes(turn_on_first), response=False)
await asyncio.sleep(0.3) # Wait for the strip to turn on
except Exception as e:
print(f" [WARNING] Could not turn on strip before test: {e}")
cmd_bytes = bytes(command)
cmd_hex = ' '.join(f'{b:02x}' for b in cmd_bytes)
print(f"\nTesting: {description}")
print(f" Command: {cmd_hex}")
await client.write_gatt_char(char_uuid, cmd_bytes, response=False)
await asyncio.sleep(0.3) # Wait a bit between commands
if ask_user:
while True:
response = input(" Did the command work? (y/n/r to relaunch): ").strip().lower()
if response == 'y':
print(" [OK] Working command registered")
return True
elif response == 'n':
print(" [FAIL] Command doesn't work")
return False
elif response == 'r':
print(" [RETRY] Relaunching command...")
if client.is_connected:
await client.write_gatt_char(char_uuid, cmd_bytes, response=False)
await asyncio.sleep(0.3)
else:
print(" [ERROR] Not connected, cannot retry")
return False
else:
print(" [WARNING] Invalid response (y/n/r)")
else:
await asyncio.sleep(0.5)
return False
except Exception as e:
print(f" [ERROR] {e}")
return False
async def test_power_commands(self, device: BLEDevice, char_uuid: str) -> None:
"""Tests on/off commands"""
print(f"\n{'='*60}")
print("TESTING ON/OFF COMMANDS")
print(f"{'='*60}\n")
max_retries = 3
for attempt in range(max_retries):
try:
async with BleakClient(device.address, timeout=20.0) as client:
print(f"Connected to {device.name}\n")
# Login for MELK/MODELX devices
await self._execute_login(client, device, char_uuid)
# STEP 1: Test TURN ON commands
print("STEP 1/3: TESTING TURN ON COMMANDS")
print("=" * 60)
print("KNOWN TURN ON COMMANDS:")
print("-" * 60)
found_turn_on = False
working_turn_on_cmd = None
for idx, cmd in enumerate(KNOWN_TURN_ON, 1):
if not client.is_connected:
print("\n[WARNING] Connection lost, stopping tests...")
break
if await self.test_command(client, char_uuid, cmd,
f"Turn on #{idx} (known)"):
self.test_results['working_commands']['turn_on'].append({
'command': cmd,
'description': f'Known turn on #{idx}',
'type': 'known'
})
found_turn_on = True
working_turn_on_cmd = cmd
print("\n[OK] Working turn on command found!\n")
break
# Test new turn on commands only if not found
if not found_turn_on and client.is_connected:
print(f"\nNEW TURN ON COMMANDS ({len(NEW_TURN_ON_COMMANDS)} commands):")
print("-" * 60)
print("Testing new commands, press Ctrl+C to skip if taking too long...\n")
for idx, cmd in enumerate(NEW_TURN_ON_COMMANDS, 1):
if not client.is_connected:
print("\n[WARNING] Connection lost, stopping tests...")
break
if await self.test_command(client, char_uuid, cmd,
f"Turn on #{idx} (new)"):
self.test_results['working_commands']['turn_on'].append({
'command': cmd,
'description': f'New turn on #{idx}',
'type': 'new'
})
found_turn_on = True
working_turn_on_cmd = cmd
print("\n[OK] Working turn on command found!\n")
break
if not found_turn_on:
print("\n[WARNING] No working turn on command found, cannot continue tests\n")
return
if not client.is_connected:
raise Exception("Connection lost during turn on tests")
# Wait a bit before turn off tests
await asyncio.sleep(1)
# STEP 2: Test TURN OFF commands
print("\nSTEP 2/3: TESTING TURN OFF COMMANDS")
print("=" * 60)
print("KNOWN TURN OFF COMMANDS:")
print("-" * 60)
found_turn_off = False
working_turn_off_cmd = None
for idx, cmd in enumerate(KNOWN_TURN_OFF, 1):
if not client.is_connected:
print("\n[WARNING] Connection lost, stopping tests...")
break
if await self.test_command(client, char_uuid, cmd,
f"Turn off #{idx} (known)"):
self.test_results['working_commands']['turn_off'].append({
'command': cmd,
'description': f'Known turn off #{idx}',
'type': 'known'
})
found_turn_off = True
working_turn_off_cmd = cmd
print("\n[OK] Working turn off command found!\n")
break
# Test new turn off commands only if not found
if not found_turn_off and client.is_connected:
print(f"\nNEW TURN OFF COMMANDS ({len(NEW_TURN_OFF_COMMANDS)} commands):")
print("-" * 60)
print("Testing new commands, press Ctrl+C to skip if taking too long...\n")
for idx, cmd in enumerate(NEW_TURN_OFF_COMMANDS, 1):
if not client.is_connected:
print("\n[WARNING] Connection lost, stopping tests...")
break
if await self.test_command(client, char_uuid, cmd,
f"Turn off #{idx} (new)"):
self.test_results['working_commands']['turn_off'].append({
'command': cmd,
'description': f'New turn off #{idx}',
'type': 'new'
})
found_turn_off = True
working_turn_off_cmd = cmd
print("\n[OK] Working turn off command found!\n")
break
if not found_turn_off:
print("\n[WARNING] No working turn off command found\n")
# STEP 3: Turn ON again to leave the strip ready for other tests
if found_turn_on and client.is_connected:
await asyncio.sleep(1)
print("\nSTEP 3/3: TURNING ON AGAIN FOR NEXT TESTS")
print("=" * 60)
try:
cmd_hex = ' '.join(f'{b:02x}' for b in working_turn_on_cmd)
print(f"Sending turn on command: {cmd_hex}")
await client.write_gatt_char(char_uuid, bytes(working_turn_on_cmd), response=False)
await asyncio.sleep(0.5)
print("[OK] Strip is now ON and ready for color/white tests\n")
except Exception as e:
print(f"[WARNING] Could not turn on strip: {e}\n")
print(f"\n{'='*60}")
print("POWER COMMAND TESTS COMPLETED")
print(f"{'='*60}\n")
# If we got here, tests completed successfully
return
except KeyboardInterrupt:
print("\n\n[INFO] Tests skipped by user")
raise
except Exception as e:
print(f"\nConnection error (attempt {attempt + 1}/{max_retries}): {e}")
if attempt < max_retries - 1:
print("Retrying in 2 seconds...")
await asyncio.sleep(2)
else:
print("\nMax retries reached, giving up on power command tests")
return
async def test_color_commands(self, device: BLEDevice, char_uuid: str) -> None:
"""Tests RGB color commands"""
print(f"\n{'='*60}")
print("TESTING RGB COLOR COMMANDS")
print(f"{'='*60}\n")
# Get working turn on command from previous tests
turn_on_cmd = None
if self.test_results['working_commands']['turn_on']:
turn_on_cmd = self.test_results['working_commands']['turn_on'][0]['command']
print(f"[INFO] Will turn on strip before each test using: {' '.join(f'{b:02x}' for b in turn_on_cmd)}\n")
# Test colors
test_colors = [
(255, 0, 0, "Red"),
(0, 255, 0, "Green"),
(0, 0, 255, "Blue"),
]
try:
async with BleakClient(device.address, timeout=20.0) as client:
print(f"Connected to {device.name}\n")
# Login for MELK/MODELX devices
await self._execute_login(client, device, char_uuid)
found_color = False
for idx, cmd_func in enumerate(NEW_COLOR_COMMANDS, 1):
if found_color:
break
print(f"\nTesting color command #{idx}:")
print("Testing all 3 colors (Red, Green, Blue)...\n")
colors_worked = 0
for r, g, b, color_name in test_colors:
cmd = cmd_func(r, g, b)
if await self.test_command(client, char_uuid, cmd,
f"Color {color_name} (R:{r}, G:{g}, B:{b})", turn_on_first=turn_on_cmd):
colors_worked += 1
# If at least 2 out of 3 colors worked, consider it a success
if colors_worked >= 2:
self.test_results['working_commands']['color'].append({
'command_template': 'lambda r, g, b: ' + str([hex(x) if isinstance(x, int) else 'r' if x == test_colors[0][0] else 'g' if x == test_colors[0][1] else 'b' for x in cmd_func(0, 0, 0)]),
'description': f'Color command #{idx}',
'test_values': test_colors,
'colors_confirmed': colors_worked
})
found_color = True
print(f"\n[OK] Working color command found ({colors_worked}/3 colors confirmed), tests completed!\n")
break
elif colors_worked > 0:
print(f"\n[WARNING] Only {colors_worked}/3 colors worked, trying next command template...\n")
else:
print("\n[FAIL] No colors worked with this command template\n")
except Exception as e:
print(f"\nError during tests: {e}")
async def test_white_commands(self, device: BLEDevice, char_uuid: str) -> None:
"""Tests white light commands"""
print(f"\n{'='*60}")
print("TESTING WHITE LIGHT COMMANDS")
print(f"{'='*60}\n")
# Get working turn on command from previous tests
turn_on_cmd = None
if self.test_results['working_commands']['turn_on']:
turn_on_cmd = self.test_results['working_commands']['turn_on'][0]['command']
print(f"[INFO] Will turn on strip before each test using: {' '.join(f'{b:02x}' for b in turn_on_cmd)}\n")
max_retries = 3
for attempt in range(max_retries):
try:
async with BleakClient(device.address, timeout=20.0) as client:
print(f"Connected to {device.name}\n")
# Login for MELK/MODELX devices
await self._execute_login(client, device, char_uuid)
# Test known commands
print("KNOWN WHITE COMMANDS:")
print("-" * 60)
found_white = False
for idx, cmd in enumerate(KNOWN_WHITE, 1):
if not client.is_connected:
print("\n[WARNING] Connection lost, stopping tests...")
break
if await self.test_command(client, char_uuid, cmd,
f"White #{idx} (known)", turn_on_first=turn_on_cmd):
self.test_results['working_commands']['white'].append({
'command': cmd,
'description': f'Known white #{idx}',
'type': 'known'
})
found_white = True
print("\n[OK] Working white command found, tests completed!\n")
break
# Test new commands only if not found
if not found_white and client.is_connected:
print(f"\nNEW WHITE COMMANDS ({len(NEW_WHITE_COMMANDS)} commands):")
print("-" * 60)
for idx, cmd_func in enumerate(NEW_WHITE_COMMANDS, 1):
if not client.is_connected:
print("\n[WARNING] Connection lost, stopping tests...")
break
cmd = cmd_func(200) # Test with brightness 200
if await self.test_command(client, char_uuid, cmd,
f"White #{idx} (brightness: 200)", turn_on_first=turn_on_cmd):
self.test_results['working_commands']['white'].append({
'command_template': f'lambda brightness: {[hex(x) if isinstance(x, int) else "brightness" for x in cmd]}',
'description': f'New white #{idx}',
'type': 'new'
})
found_white = True
print("\n[OK] Working white command found, tests completed!\n")
break
return
except KeyboardInterrupt:
print("\n\n[INFO] Tests skipped by user")
raise
except Exception as e:
print(f"\nConnection error (attempt {attempt + 1}/{max_retries}): {e}")
if attempt < max_retries - 1:
print("Retrying in 2 seconds...")
await asyncio.sleep(2)
else:
print("\nMax retries reached, skipping white command tests")
return
async def test_color_temp_commands(self, device: BLEDevice, char_uuid: str) -> None:
"""Tests color temperature commands"""
print(f"\n{'='*60}")
print("TESTING COLOR TEMPERATURE COMMANDS")
print(f"{'='*60}\n")
# Get working turn on command from previous tests
turn_on_cmd = None
if self.test_results['working_commands']['turn_on']:
turn_on_cmd = self.test_results['working_commands']['turn_on'][0]['command']
print(f"[INFO] Will turn on strip before each test using: {' '.join(f'{b:02x}' for b in turn_on_cmd)}\n")
max_retries = 3
for attempt in range(max_retries):
try:
async with BleakClient(device.address, timeout=20.0) as client:
print(f"Connected to {device.name}\n")
# Login for MELK/MODELX devices
await self._execute_login(client, device, char_uuid)
# Test known commands
print("KNOWN COLOR TEMP COMMANDS:")
print("-" * 60)
found_color_temp = False
for idx, cmd in enumerate(KNOWN_COLOR_TEMP, 1):
if not client.is_connected:
print("\n[WARNING] Connection lost, stopping tests...")
break
if await self.test_command(client, char_uuid, cmd,
f"Color temp #{idx} (known)", turn_on_first=turn_on_cmd):
self.test_results['working_commands']['color_temp'].append({
'command': cmd,
'description': f'Known color temp #{idx}',
'type': 'known'
})
found_color_temp = True
print("\n[OK] Working color temp command found, tests completed!\n")
break
# Test new commands only if not found
if not found_color_temp and client.is_connected:
print(f"\nNEW COLOR TEMP COMMANDS ({len(NEW_COLOR_TEMP_COMMANDS)} commands):")
print("-" * 60)
for idx, cmd_func in enumerate(NEW_COLOR_TEMP_COMMANDS, 1):
if not client.is_connected:
print("\n[WARNING] Connection lost, stopping tests...")
break
cmd = cmd_func(50, 50) # 50% warm, 50% cold
if await self.test_command(client, char_uuid, cmd,
f"Color temp #{idx} (50% warm/cold)", turn_on_first=turn_on_cmd):
self.test_results['working_commands']['color_temp'].append({
'command_template': f'lambda warm, cold: {[hex(x) if isinstance(x, int) else "warm" if x == 50 else "cold" for x in cmd]}',
'description': f'New color temp #{idx}',
'type': 'new'
})
found_color_temp = True
print("\n[OK] Working color temp command found, tests completed!\n")
break
return
except KeyboardInterrupt:
print("\n\n[INFO] Tests skipped by user")
raise
except Exception as e:
print(f"\nConnection error (attempt {attempt + 1}/{max_retries}): {e}")
if attempt < max_retries - 1:
print("Retrying in 2 seconds...")
await asyncio.sleep(2)
else:
print("\nMax retries reached, skipping color temp command tests")
return
async def test_query_commands(self, device: BLEDevice, char_uuid: str, read_uuid: Optional[str] = None) -> None:
"""Test query/status commands to find which one works"""
print(f"\n{'='*60}")
print("QUERY/STATUS COMMAND TESTING")
print(f"{'='*60}\n")
print(f"Testing {len(QUERY_COMMANDS)} query commands...")
print("Query commands are used to read the current state of the LED strip.")
print("(Note: Many strips don't support queries, this is optional)\n")
max_retries = 3
for attempt in range(max_retries):
try:
async with BleakClient(device.address, timeout=20.0) as client:
print(f"Connected to {device.name}\n")
# Login for MELK/MODELX devices
await self._execute_login(client, device, char_uuid)
# Enable notifications to detect responses
notification_received = False
def notification_handler(sender, data):
nonlocal notification_received
notification_received = True
print(f" ✓ Response received: {' '.join(f'{b:02x}' for b in data)}")
if read_uuid:
try:
await client.start_notify(read_uuid, notification_handler)
print(f"[INFO] Notifications enabled on {read_uuid}\n")
except Exception as e:
print(f"[WARNING] Could not enable notifications: {e}\n")
found_query = False
for idx, (cmd, description) in enumerate(QUERY_COMMANDS, 1):
if not client.is_connected:
print("\n[WARNING] Connection lost, stopping tests...")
break
notification_received = False
cmd_hex = ' '.join(f'{b:02x}' for b in cmd)
print(f"[{idx}/{len(QUERY_COMMANDS)}] Testing: {description}")
print(f" Command: {cmd_hex}")
try:
await client.write_gatt_char(char_uuid, bytes(cmd), response=False)
await asyncio.sleep(0.5) # Wait for potential response
if notification_received:
self.test_results['working_commands']['query'] = [{
'command': cmd,
'description': description,
'hex': cmd_hex
}]
found_query = True
print(f"\n[OK] Working query command found: {description}\n")
break
else:
print(" ✗ No response")
except Exception as e:
print(f" ✗ Error: {e}")
if read_uuid:
try:
await client.stop_notify(read_uuid)
except:
pass
if not found_query:
print("\n[INFO] No working query command found (device may not support status queries)")
print("[INFO] This is normal for many LED strips, they work without query support\n")
print(f"\n{'='*60}")
print("QUERY COMMAND TESTS COMPLETED")
print(f"{'='*60}\n")
return
except KeyboardInterrupt:
print("\n\n[INFO] Tests skipped by user")
raise
except Exception as e:
print(f"\nConnection error (attempt {attempt + 1}/{max_retries}): {e}")
if attempt < max_retries - 1:
print("Retrying in 2 seconds...")
await asyncio.sleep(2)
else:
print("\nMax retries reached, skipping query command tests")
return
async def test_custom_commands(self, device: BLEDevice, char_uuid: str) -> None:
"""Allows user to test their own commands"""
print(f"\n{'='*60}")
print("CUSTOM COMMAND TESTING")
print(f"{'='*60}\n")
# Get working turn on command from previous tests
turn_on_cmd = None
if self.test_results['working_commands']['turn_on']:
turn_on_cmd = self.test_results['working_commands']['turn_on'][0]['command']
print(f"[INFO] Will turn on strip before each test using: {' '.join(f'{b:02x}' for b in turn_on_cmd)}\n")
print("You can test your own commands in hexadecimal format.")
print("Example: 7e 00 04 f0 00 01 ff 00 ef")
print("Type 'q' to finish.\n")
try:
async with BleakClient(device.address, timeout=20.0) as client:
print(f"Connected to {device.name}\n")