-
Notifications
You must be signed in to change notification settings - Fork 1
/
bulb_cli.py
executable file
·3267 lines (2810 loc) · 121 KB
/
bulb_cli.py
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
###################################################################
#
#
# Interactive Klyqa bulb commandline client
#
#
# Company: QConnex GmbH / Klyqa
# Author: Frederick Stallmeyer
#
# E-Mail: frederick.stallmeyer@gmx.de
#
#
# nice to haves:
# - list cloud connected devices in discovery.
# - offer for selected lamps possible commands and arguments in interactive
# mode based on their lamp profile
# - Implementation for the different device config profile versions and
# check on send.
#
#
###################################################################
from dataclasses import dataclass
import dataclasses
import socket
import sys
import time
import json
import datetime
import argparse
import select
import logging
from typing import TypeVar, Any, NewType
NoneType = type(None)
import requests, uuid, json
import os.path
from threading import Thread
from collections import ChainMap
from threading import Event
from enum import Enum
import threading
import multiprocessing
import asyncio, aiofiles
import functools, traceback
import aiohttp
import copy
from asyncio.exceptions import CancelledError, TimeoutError
# DEFAULT_SEND_TIMEOUT_MS=5000000000
DEFAULT_SEND_TIMEOUT_MS=5000
LOGGER = logging.getLogger(__package__)
LOGGER.setLevel(level=logging.INFO)
formatter = logging.Formatter("%(asctime)s %(levelname)-8s - %(message)s")
logging_hdl = logging.StreamHandler()
logging_hdl.setLevel(level=logging.INFO)
logging_hdl.setFormatter(formatter)
LOGGER.addHandler(logging_hdl)
import slugify as unicode_slug
try:
from Cryptodome.Cipher import AES # provided by pycryptodome
from Cryptodome.Random import get_random_bytes # pycryptodome
except:
from Crypto.Cipher import AES # provided by pycryptodome
from Crypto.Random import get_random_bytes # pycryptodome
s = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S,%f")[:-3]
print(f"{s} start")
TypeJSON = dict[str, Any]
""" string output separator width """
sep_width = 0
AES_KEY_DEV = bytes(
[
0x00,
0x11,
0x22,
0x33,
0x44,
0x55,
0x66,
0x77,
0x88,
0x99,
0xAA,
0xBB,
0xCC,
0xDD,
0xEE,
0xFF,
]
)
SCENES = [
{
"id": 100,
"colors": ["#FFECD8", "#FFAA5B"],
"label": "Warm White",
"commands": "5ch 0 0 0 0 65535 65535 500;p 1000;",
"cwww": True,
},
{
"id": 101,
"colors": ["#FCF4DD", "#FED07A"],
"label": "Daylight",
"commands": "5ch 0 0 0 24903 40631 65535 500;p 1000;",
},
{
"id": 102,
"colors": ["#FFFFFF", "#B6DAFF"],
"label": "Cold White",
"commands": "5ch 0 0 0 65535 0 65535 500;p 1000;",
"cwww": True,
},
{
"id": 103,
"colors": ["#E06004", "#55230D"],
"label": "Night Light",
"commands": "5ch 9830 3276 0 1310 0 65535 500;p 1000;",
"cwww": True,
},
{
"id": 106,
"colors": ["#FDCB78", "#FCDA60"],
"label": "Relax",
"commands": "5ch 26214 26214 0 0 13107 65535 500;p 1000;",
},
{
"id": 109,
"colors": ["#090064", "#2E2A5A"],
"label": "TV Time",
"commands": "5ch 655 0 6553 1310 0 65535 500;p 1000;",
},
{
"id": 107,
"colors": ["#FFD1A2", "#FFEDDA"],
"label": "Comfort",
"commands": "5ch 47185 0 0 18349 0 65535 500;p 1000;",
},
{
"id": 108,
"colors": ["#EAFCFF", "#81DFF0"],
"label": "Focused",
"commands": "5ch 0 0 26214 5000 0 65535 500;p 1000;",
"cwww": True,
},
{
"id": 110,
"colors": ["#CD3700", "#CD0000", "#CD6600"],
"label": "Fireplace",
"commands": "5ch 32767 0 0 0 1500 65535 500;p 500;5ch 55535 200 0 0 2000 65535 500;p 500;",
# '5ch 32767 0 0 0 1500 65535 500;p 500;5ch 55535 200 0 0 2000 65535 500;p 500;5ch 32767 30000 0 0 1500 65535 500;p 500;5ch 25535 20000 0 0 2000 65535 500;p 500;5ch 62767 0 0 0 1500 65535 500;p 500;5ch 65535 200 0 0 2000 65535 500;p 500;5ch 32767 30000 0 0 1500 65535 500;p 500;5ch 25535 30000 0 0 2000 65535 500;p 500;',
},
{
"id": 122,
"colors": ["#12126C", "#B22222", "#D02090"],
"label": "Jazz Club",
"commands": "5ch 45746 8738 8738 0 0 65535 6100;p 5100;5ch 45232 12336 24672 0 0 65535 6100;p 5000;5ch 53436 8224 37008 0 0 65535 6100;p 5000;5ch 0 0 33896 0 0 65535 6000;p 5000;5ch 18504 15677 35728 0 0 65535 6100;p 5000;5ch 38036 0 52428 0 0 65535 6600;p 5000;5ch 45232 12336 24672 0 0 65535 6100;p 5000;",
},
{
"id": 104,
"colors": ["#B20C26", "#CC1933", "#EE6AA7"],
"label": "Romantic",
"commands": "5ch 58981 6553 16383 0 0 65535 1000;p 7400;5ch 45874 3276 9830 0 0 65535 4400;p 6600;5ch 52428 6553 13107 0 0 65535 8800;p 15200;5ch 41287 0 0 0 0 65535 4400;p 13200;",
},
{
"id": 112,
"colors": ["#FFDCE8", "#D2FFD2", "#CCFFFF"],
"label": "Gentle",
"commands": "5ch 51117 0 0 13107 0 65535 26000;p 56000;5ch 26214 26214 0 8519 0 65535 26000;p 56000;5ch 0 51117 0 13107 0 65535 26000;p 56000;5ch 0 26214 26214 8519 0 65535 26000;p 56000;5ch 0 0 51117 13107 0 65535 26000;p 56000;5ch 26214 0 26214 8519 0 65535 26000;p 56000;",
},
{
"id": 113,
"colors": ["#EEAD0E", "#FF7F24", "#CD0000"],
"label": "Summer",
"commands": "5ch 17039 25558 0 13762 0 65535 8000;p 14000;5ch 39321 7864 0 15728 0 65535 8000;p 14000;5ch 28180 17694 0 11140 0 65535 8000;p 14000;",
},
{
"id": 114,
"colors": ["#00BA0C", "#008400", "#0C4400"],
"label": "Jungle",
"commands": "5ch 0 47840 3276 0 0 65535 2600;p 2100;5ch 5898 10485 1310 0 0 65535 2300;p 4200;5ch 0 34078 0 0 0 65535 2100;p 2500;5ch 3276 17694 0 0 0 65535 4600;p 4000;5ch 9174 46529 0 0 0 65535 5500;p 6900;5ch 9830 43908 1966 0 0 65535 2700;p 4700;5ch 0 55704 0 0 0 65535 2000;p 3800;",
},
{
"id": 105,
"colors": ["#00008B", "#0000FF", "#1874ED"],
"label": "Ocean",
"commands": "5ch 1310 17694 36044 0 0 65535 2400;p 5400;5ch 655 15073 39321 0 0 65535 2100;p 5100;5ch 1310 36044 17039 0 0 65535 4200;p 5100;5ch 1966 22281 29490 0 0 65535 2800;p 5700;5ch 655 19005 34733 0 0 65535 2100;p 4900;5ch 655 26869 27524 0 0 65535 2600;p 3400;5ch 655 26869 27524 0 0 65535 2700;p 3600;5ch 1310 38010 15728 0 0 65535 4200;p 5000;",
},
# {
# "id": 111,
# "colors": ['#A31900', '#A52300', '#B71933', '#A5237F', '#B71900'],
# "label": 'Club',
# "commands":
# '5ch 41942 6553 0 1310 0 65535 600;p 800;5ch 42597 9174 0 1310 0 65535 8700;p 12000;5ch 47185 6553 13107 1310 0 65535 8700;p 12000;5ch 42597 9174 32767 1310 0 65535 300;p 400;5ch 47185 6553 0 1310 0 65535 300;p 1300;',
# },
{
"id": 115,
"colors": ["#EE4000", "#CD6600", "#FFA500"],
"label": "Fall",
"commands": "5ch 49151 1966 0 9830 0 65535 8400;p 8610;5ch 35388 13107 0 6553 0 65535 8400;p 8750;5ch 52428 0 0 10485 0 65535 8400;p 8740;5ch 39321 9174 0 12451 0 65535 500;p 840;",
},
{
"id": 116,
"colors": ["#FFF0F5", "#FF6EB4", "#FF4500"],
"label": "Sunset",
"commands": "5ch 39321 0 15073 2621 0 65535 5680;p 5880;5ch 51117 0 0 13107 0 65535 5680;p 5880;5ch 43253 11796 0 2621 0 65535 5680;p 5880;5ch 38010 0 15073 7208 0 65535 5680;p 5880;5ch 46529 0 0 3932 0 65535 5680;p 5880;5ch 41287 11140 0 7864 0 65535 5680;p 5880;",
},
{
"id": 117,
"colors": ["#FF0000", "#0000FF", "#00FF00"],
"label": "Party",
"commands": "5ch 55704 0 0 0 0 65535 132;p 272;5ch 55704 0 0 0 0 65535 132;p 272;5ch 0 55704 0 0 0 65535 132;p 272;5ch 0 55704 0 0 0 65535 132;p 272;5ch 0 0 55704 0 0 65535 132;p 272;5ch 0 0 55704 0 0 65535 132;p 272;5ch 28180 0 27524 0 0 65535 132;p 272;5ch 0 28180 27524 0 0 65535 132;p 272;",
},
{
"id": 118,
"colors": ["#F0FFF0", "#C1FFC1", "#FFE4E1"],
"label": "Spring",
"commands": "5ch 19660 15728 19660 0 0 65535 8000;p 11000;5ch 20315 26214 13107 0 0 65535 8000;p 11000;5ch 17039 19005 19005 0 0 65535 8000;p 11000;5ch 20315 14417 14417 0 0 65535 8000;p 11000;5ch 19005 18349 17694 0 0 65535 8000;p 11000;5ch 11796 30146 6553 0 0 65535 8000;p 11000;",
},
{
"id": 119,
"colors": ["#C1FFC1", "#C0FF3E", "#CAFF70"],
"label": "Forest",
"commands": "5ch 23592 22937 0 3932 0 65535 6000;p 8000;5ch 19005 23592 0 7864 0 65535 6200;p 10100;5ch 22281 21626 0 12451 0 65535 6000;p 10000;5ch 23592 22281 0 4587 0 65535 5800;p 10400;5ch 18349 27524 0 1966 0 65535 6200;p 7000;5ch 8519 25558 0 23592 0 65535 6200;p 9400;",
},
{
"id": 120,
"colors": ["#104E8B", "#00008B", "#4876FF"],
"label": "Deep Sea",
"commands": "5ch 3932 3276 59636 0 0 65535 4100;p 5100;5ch 3276 6553 53738 0 0 65535 4100;p 5000;5ch 0 0 43908 0 0 65535 4100;p 5000;5ch 655 1310 53083 0 0 65535 3600;p 5000;5ch 1310 0 53738 0 0 65535 4000;p 5000;",
},
{
"id": 121,
"colors": ["#90ee90", "#8DEEEE", "#008B45"],
"label": "Tropical",
"commands": "5ch 0 43253 0 0 36044 65535 3000;p 4000;5ch 0 0 0 0 65535 65535 2400;p 5400;5ch 0 38010 0 0 48495 65535 2600;p 3600;5ch 0 32767 0 0 0 65535 2000;p 3400;5ch 0 46529 0 0 26869 65535 3100;p 4100;5ch 0 43908 0 0 0 65535 4000;p 7000;5ch 0 49806 0 0 16383 65535 2000;p 5000;",
},
{
"id": 123,
"colors": ["#FF6AD0", "#8BFFC7", "#96A0FF"],
"label": "Magic Mood",
"commands": "5ch 65535 27242 53456 0 0 35535 2400;p 1180;5ch 30326 33924 65535 0 0 35535 2200;p 1110;5ch 65535 21331 21331 0 0 35535 2800;p 1200;5ch 35723 55535 31143 0 0 35535 2800;p 1200;5ch 38550 41120 65535 0 0 35535 2400;p 1040;5ch 65535 61423 29041 0 0 35535 2400;p 1000;",
},
{
"id": 124,
"colors": ["#FF0000", "#B953FF", "#DBFF96"],
"label": "Mystic Mountain",
"commands": "5ch 65535 0 0 0 0 35535 1400;p 980;5ch 65535 30326 52685 0 0 35535 1200;p 910;5ch 47543 21331 65535 0 0 35535 1800;p 1200;5ch 35723 65535 44461 0 0 35535 1800;p 1200;5ch 56283 65535 38550 0 0 35535 1400;p 1040;5ch 65535 29041 53456 0 0 35535 1400;p 1000;",
},
{
"id": 125,
"colors": ["#FB0000", "#FFF748", "#B97FFF"],
"label": "Cotton Candy",
"commands": "5ch 65535 0 52428 0 0 35535 1400;p 980;5ch 47545 32639 655350 0 0 35535 1200;p 910;5ch 65535 33410 33410 0 0 35535 1800;p 1200;5ch 65535 63479 18504 0 0 35535 1800;p 1200;5ch 65535 63222 16448 0 0 35535 1400;p 1040;5ch 64507 0 0 0 0 35535 1400;p 1000;",
},
{
"id": 126,
"colors": ["#8BFFE1", "#D8FA97", "#FF927F"],
"label": "Ice Cream",
"commands": "5ch 65535 0 0 0 0 35535 1400;p 980;5ch 65535 37522 32639 0 0 35535 1200;p 910;5ch 61166 54741 65535 0 0 35535 1800;p 1200;5ch 35723 65535 57825 0 0 35535 1800;p 1200;5ch 55512 64250 38807 0 0 35535 1400;p 1040;5ch 65535 56796 62709 0 0 35535 1400;p 1000;",
},
]
class AsyncIOLock:
"""AsyncIOLock"""
task: asyncio.Task
lock: asyncio.Lock
_instance = None
def __init__(self):
"""__init__"""
self.lock = asyncio.Lock()
self.task = None
async def acquire(self):
"""acquire"""
await self.lock.acquire()
self.task = asyncio.current_task()
def release(self):
"""release"""
self.lock.release()
def force_unlock(self) -> bool:
"""force_unlock"""
try:
self.task.cancel()
self.lock.release()
except:
return False
return True
@classmethod
def instance(
cls,
):
"""instance"""
if cls._instance is None:
print("Creating new instance")
cls._instance = cls.__new__(cls)
# Put any initialization here.
cls._instance.__init__()
return cls._instance
tcp_udp_port_lock = AsyncIOLock.instance()
class RefParse:
"""RefParse"""
ref = None
def __init__(self, ref):
self.ref = ref
class KlyqaBulbResponse:
"""KlyqaBulbResponse"""
type: str = ""
response_msg: dict = {}
ts: datetime.datetime = datetime.datetime.now()
def __init__(self, type = type, response_msg: dict = {}):
self.type = type
self.response_msg = response_msg
self.ts = datetime.datetime.now()
# eventually dataclass
class KlyqaBulbResponseIdent(KlyqaBulbResponse):
"""KlyqaBulbResponseIdent"""
fw_version: str = ""
sdk_version: str = ""
fw_build: str = ""
hw_version: str = ""
manufacturer_id: str = ""
product_id: str = ""
unit_id: str = ""
def __init__(
self,
fw_version: str,
fw_build: str,
hw_version: str,
manufacturer_id: str,
product_id: str,
unit_id: dict,
sdk_version: str = "", # optional due to virtual devices not having sdk version
**kwargs
):
super().__init__(**kwargs)
self.type = type
self.fw_version = fw_version
self.sdk_version = sdk_version
self.fw_build = fw_build
self.hw_version = hw_version
self.manufacturer_id = manufacturer_id
self.product_id = product_id
self.unit_id = format_uid(unit_id)
async def async_json_cache(json_data, json_file):
"""
If json data is given write it to cache json_file.
Else try to read from json_file the cache.
"""
return_json: Bulb_config = json_data
cached = False
if json_data:
"""
save the json for offline cache in dirpath where called script resides
ids: { sets }
"""
return_json = json_data
try:
s = ""
for id, sets in json_data.items():
if isinstance(sets, (datetime.datetime, datetime.date)):
sets = sets.isoformat()
s = s + '"' + id + '": ' + json.dumps(sets) + ", "
s = "{" + s[:-2] + "}"
async with aiofiles.open(
os.path.dirname(sys.argv[0]) + f"/{json_file}", mode="w"
) as f:
await f.write(s)
except Exception as e:
LOGGER.warning(f'Could not save cache for json file "{json_file}".')
else:
"""no json data, take cached json from disk if available"""
try:
async with aiofiles.open(
os.path.dirname(sys.argv[0]) + f"/{json_file}", mode="r"
) as f:
s = ""
async for i in f.readlines():
s = s + i.strip()
return_json = json.loads(s)
cached = True
except:
LOGGER.warning(f'No cache from json file "{json_file}" available.')
return (return_json, cached)
def get_fields(object):
"""get_fields"""
if hasattr(object, "__dict__"):
return object.__dict__.keys()
else:
return dir(object)
def get_obj_attrs_as_string(object) -> str:
"""get_obj_attrs_as_string"""
fields = get_fields(object)
attrs = [
a for a in fields if not a.startswith("__") and not callable(getattr(object, a))
]
return ", ".join(attrs)
def get_obj_attr_values_as_string(object) -> str:
"""get_obj_attr_values_as_string"""
fields = get_fields(object)
attrs = [
a for a in fields if not a.startswith("__") and not callable(getattr(object, a))
]
vals = []
for a in attrs:
_str = str(getattr(object, a))
vals.append(_str if _str else '""')
return ", ".join(vals)
class RGBColor:
"""RGBColor"""
r: int
g: int
b: int
def __str__(self):
return "[" + ",".join([str(self.r), str(self.g), str(self.b)]) + "]"
# return get_obj_values_as_string(self)
def __init__(self, r: int, g: int, b: int):
self.r = r
self.g = g
self.b = b
def format_uid(text: str) -> str:
return unicode_slug.slugify(text)
class KlyqaBulbResponseStatus: #(KlyqaBulbResponse):
"""Klyqa_Bulb_Response_Status"""
type: str = ""
status: str = ""
color: RGBColor = RGBColor(-1, -1, -1)
brightness: int = -1
temperature: int = -1
active_command: int = -1
active_scene: str = ""
open_slots: int
mode: str = ""
fwversion: str = ""
sdkversion: str = ""
ts: datetime.datetime = datetime.datetime.now()
def __str__(self):
"""__str__"""
return get_obj_attr_values_as_string(self)
def __init__(
self,
type: str,
status: str,
brightness: dict[str, int],
mode: str,
open_slots: int = 0,
fwversion: str = "",
sdkversion: str = "",
color: dict[str, int] = {},
temperature: int = -1,
active_command: int = 0,
active_scene: str = 0,
**kwargs,
):
"""__init__"""
# super().__init__(**kwargs)
self.type = type
self.status = status
self.color = RGBColor(color["red"], color["green"], color["blue"]) if color else {}
self.brightness = brightness["percentage"]
self.temperature = temperature
self.active_command = active_command
self.active_scene = active_scene
self.open_slots = open_slots
self.mode = mode
self.fwversion = fwversion
self.sdkversion = sdkversion
self.ts = datetime.datetime.now()
LOGGER.debug(f"save status {self}")
response_classes = {
"ident": KlyqaBulbResponseIdent,
"status": KlyqaBulbResponseStatus,
}
Bulb_config = dict
bulb_configs: dict[str, Bulb_config] = dict()
class LocalConnection:
"""LocalConnection"""
state = "WAIT_IV"
localIv = get_random_bytes(8)
sendingAES = None
receivingAES = None
address = {"ip": "", "port": -1}
connection: socket.socket = None
received_packages = []
sent_msg_answer = {}
aes_key_confirmed = False
def __init__(self):
self.state = "WAIT_IV"
self.localIv = get_random_bytes(8)
self.sendingAES = None
self.receivingAES = None
self.address = {"ip": "", "port": -1}
self.connection: socket.socket = None
self.received_packages = []
self.sent_msg_answer = {}
self.aes_key_confirmed = False
class CloudConnection:
"""CloudConnection"""
received_packages = []
connected: bool
def __init__(self):
self.connected = False
self.received_packages = []
Bulb_TCP_return = Enum("Bulb_TCP_return", "sent answered wrong_uid wrong_aes tcp_error unknown_error timeout nothing_done sent_error no_message_to_send bulb_lock_timeout err_local_iv missing_aes_key response_error")
Message_state = Enum("Message_state", "sent answered unsent")
from collections.abc import Callable
from typing import List
@dataclass
class Message:
started: datetime.datetime
msg_queue: list[tuple]
msg_queue_sent = [] #: list[str] = dataclasses.field(default_factory=list)
args: list[str]
target_uid: str
state: Message_state = Message_state.unsent
finished: datetime.datetime = None
answer: str = ""
answer_utf8: str = ""
answer_json = {}
# callback on error event or answer
callback: Callable[[Any], None] = NoneType
time_to_live_secs: int = -1
msg_counter: int = -1
def __post_init__(self):
# super().__init__(self, *args, **kwargs)
global MSG_COUNTER
self.msg_counter = MSG_COUNTER
MSG_COUNTER = MSG_COUNTER + 1
async def call_cb(self):
await self.callback(self, self.target_uid)
async def check_msg_ttl(self):
if datetime.datetime.now() - self.started > datetime.timedelta(seconds=self.time_to_live_secs):
LOGGER.debug(f"time to live {self.time_to_live_secs} seconds for message {self.msg_counter} {self.msg_queue} ended.")
if self.callback:
await self.call_cb()
return False
return True
class KlyqaBulb:
"""KlyqaBulb"""
local: LocalConnection
cloud: CloudConnection
u_id: str = "no_uid"
ident: KlyqaBulbResponseIdent = None
status: KlyqaBulbResponseStatus = None
acc_sets: dict = {}
""" account settings """
_use_lock: asyncio.Lock
_use_thread: asyncio.Task
recv_msg_unproc: list[Message]
def process_msgs(self):
for msg in self.recv_msg_unproc:
LOGGER.debug(f"updating bulb {self.u_id} entity with msg:")
self.recv_msg_unproc.remove(msg)
def get_name(self):
return (
f"{self.acc_sets['name']} ({self.u_id})"
if self.acc_sets and "name" in self.acc_sets and self.acc_sets
else self.u_id
)
async def use_lock(self, timeout=30, **kwargs):
try:
if not self._use_lock:
self._use_lock = asyncio.Lock()
LOGGER.debug(f"wait for lock... {self.get_name()}")
if await self._use_lock.acquire():
self._use_thread = asyncio.current_task()
LOGGER.debug(f"got lock... {self.get_name()}")
return True
except asyncio.TimeoutError:
LOGGER.error(f'Timeout for getting the lock for bulb "{self.get_name()}"')
except Exception as excp:
LOGGER.debug(f"different error while trying to lock.")
return False
async def use_unlock(self):
if not self._use_lock:
self._use_lock = asyncio.Lock()
if self._use_lock.locked() and self._use_thread == asyncio.current_task():
try:
self._use_lock.release()
self._use_thread = None
LOGGER.debug(f"got unlock... {self.get_name()}")
except:
pass
def __init__(self):
self.local = LocalConnection()
self.cloud = CloudConnection()
self.u_id: str = "no_uid"
self.ident: KlyqaBulbResponseIdent = None
self.status: KlyqaBulbResponseStatus = None
self.acc_sets = {}
self._use_lock = None
self._use_thread = None
self.recv_msg_unproc = []
def save_bulb_message(self, msg):
"""msg: json dict"""
if "type" in msg and msg["type"] in msg and hasattr(self, msg["type"]):
try:
LOGGER.debug(f"save bulb msg {msg} {self.ident} {self.u_id}")
if msg["type"] == "ident":
setattr(
self,
msg["type"],
response_classes[msg["type"]](**msg[msg["type"]]),
)
elif msg["type"] == "status":
setattr(self, msg["type"], response_classes[msg["type"]](**msg))
except Exception as e:
LOGGER.error(f"{traceback.format_exc()}")
LOGGER.error("Could not process bulb response: ")
LOGGER.error(str(msg))
def setTemp(self, temp: int):
temperature_enum = []
try:
temperature_enum = [
trait["value_schema"]["properties"]["colorTemperature"]["enum"]
for trait in bulb_configs[self.ident.product_id]["deviceTraits"]
if trait["trait"] == "@core/traits/color-temperature"
]
if len(temperature_enum) < 2:
raise Exception()
except:
LOGGER.error("No temperature change on the lamp available")
return False
if temp < temperature_enum[0] or temp > temperature_enum[1]:
LOGGER.error(
"Temperature for bulb out of range ["
+ temperature_enum[0]
+ ", "
+ temperature_enum[1]
+ "]."
)
return False
ReturnTuple = TypeVar("ReturnTuple", tuple[int, str], tuple[int, dict])
def send_msg(msg, bulb: KlyqaBulb):
info_str = (
'Sending in local network to "'
+ bulb.get_name()
+ '": '
+ json.dumps(json.loads(msg), sort_keys=True, indent=4)
)
LOGGER.info(info_str)
plain = msg.encode("utf-8")
while len(plain) % 16:
plain = plain + bytes([0x20])
cipher = bulb.local.sendingAES.encrypt(plain)
while True:
try:
bulb.local.connection.send(
bytes([len(cipher) // 256, len(cipher) % 256, 0, 2]) + cipher
)
return True
except socket.timeout:
LOGGER.debug("Send timed out, retrying...")
pass
return False
def color_message(red, green, blue, transition, skipWait=False):
waitTime = transition if not skipWait else 0
return (
json.dumps(
{
"type": "request",
"color": {
"red": red,
"green": green,
"blue": blue,
},
"transitionTime": transition,
}
),
waitTime,
)
def temperature_message(temperature, transition, skipWait=False):
waitTime = transition if not skipWait else 0
return (
json.dumps(
{
"type": "request",
"temperature": temperature,
"transitionTime": transition,
}
),
waitTime,
)
def percent_color_message(red, green, blue, warm, cold, transition, skipWait):
waitTime = transition if not skipWait else 0
return (
json.dumps(
{
"type": "request",
"p_color": {
"red": red,
"green": green,
"blue": blue,
"warm": warm,
"cold": cold,
# "brightness" : brightness
},
"transitionTime": transition,
}
),
waitTime,
)
def brightness_message(brightness, transition):
return (
json.dumps(
{
"type": "request",
"brightness": {
"percentage": brightness,
},
"transitionTime": transition,
}
),
transition,
)
AES_KEYs: dict[str, bytes] = {}
PRODUCT_URLS = {
"""TODO: Make permalinks for urls."""
"@klyqa.lighting.cw-ww.gu10": "https://klyqa.de/produkte/gu10-white-strahler",
"@klyqa.lighting.rgb-cw-ww.gu10": "https://klyqa.de/produkte/gu10-color-strahler",
"@klyqa.lighting.cw-ww.g95": "https://www.klyqa.de/produkte/g95-vintage-lampe",
"@klyqa.lighting.rgb-cw-ww.e14": "https://klyqa.de/produkte/e14-color-lampe",
"@klyqa.lighting.cw-ww.e14": "https://klyqa.de/produkte/gu10-white-strahler",
"@klyqa.lighting.rgb-cw-ww.e27": "https://www.klyqa.de/produkte/e27-color-lampe",
"@klyqa.lighting.cw-ww.e27": "https://klyqa.de/produkte/e27-white-lampe",
"@klyqa.cleaning.vc1": "",
}
commands_send_to_bulb = [
"request",
"ping",
"color",
"temperature",
"brightness",
"routine_list",
"routine_put",
"routine_id",
"routine_commands",
"routine_delete",
"routine_start",
"power",
"reboot",
"factory_reset",
"WW",
"daylight",
"CW",
"nightlight",
"relax",
"TVtime",
"comfort",
"focused",
"fireplace",
"club",
"romantic",
"gentle",
"summer",
"jungle",
"ocean",
"fall",
"sunset",
"party",
"spring",
"forest",
"deep_sea",
"tropical",
"magic",
"mystic",
"cotton",
"ice",
]
from typing import TypeVar
S = TypeVar("S", argparse.ArgumentParser, type(None))
class EventQueuePrinter:
"""Single event queue printer for job printing."""
event = Event()
"""event for the printer that new data is available"""
not_finished = True
print_strings = []
printer_t: Thread = None
def __init__(self):
"""start printing helper thread routine"""
self.printer_t = Thread(target=self.coroutine)
self.printer_t.start()
def stop(self):
"""stop printing helper thread"""
self.not_finished = False
self.event.set()
self.printer_t.join(timeout=5)
def coroutine(self):
"""printer thread routine, waits for data to print and/or a trigger event"""
while self.not_finished:
if not self.print_strings:
self.event.wait()
while self.print_strings and (l_str := self.print_strings.pop(0)):
print(l_str, flush=True)
def print(self, str):
"""add string to the printer"""
self.print_strings.append(str)
self.event.set()
def get_description_parser() -> argparse.ArgumentParser:
"""Make an argument parse object."""
parser = argparse.ArgumentParser(
description="Interactive klyqa bulb client (local/cloud). In default the client script tries to send the commands via local connection. Therefore a broadcast on udp port 2222 for discovering the lamps is sent in the local network. When the lamp receives the broadcast it answers via tcp on socket 3333 with a new socket tcp connection. On that tcp connection the commands are sent and the replies are received. "
)
return parser
def add_config_args(parser):
"""Add arguments to the argument parser object.
Args:
parser: Parser object
"""
parser.add_argument(
"--transitionTime", nargs=1, help="transition time in milliseconds", default=[0]
)
parser.add_argument("--myip", nargs=1, help="specify own IP for broadcast sender")
# parser.add_argument(
# "--rerun",
# help="keep rerunning command",
# action="store_const",
# const=True,
# default=False,
# )
parser.add_argument(
"--passive",
help="vApp will passively listen vor UDP SYN from devices",
action="store_const",
const=True,
default=False,
)
parser.add_argument("--aes", nargs=1, help="give aes key for the lamp")
parser.add_argument("--username", nargs=1, help="give your username")
parser.add_argument("--password", nargs=1, help="give your klyqa password")
parser.add_argument(
"--bulb_name",
nargs=1,
help="give the name of the bulb from your account settings for the command to send to",
)
parser.add_argument(
"--bulb_unitids",
nargs=1,
help="give the bulb unit id from your account settings for the command to send to",
)
parser.add_argument(
"--all",
help="send commands to all lamps",
action="store_const",
const=True,
default=False,
)
parser.add_argument(
"--discover",
help="discover lamps",
action="store_const",
const=True,
default=False,
)
parser.add_argument(
"--debug",
help="give the bulb unit id from your account settings for the command to send to",
action="store_const",
const=True,
default=False,
)
parser.add_argument(
"--selectBulb",
help="give the bulb unit id from your account settings for the command to send to",
action="store_const",
const=True,
default=False,
)
parser.add_argument(
"--force",
help="If no configs about the bulb available, send the command anyway (can be dangerous).",
action="store_const",