-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplugin.py
More file actions
1065 lines (898 loc) · 37.5 KB
/
plugin.py
File metadata and controls
1065 lines (898 loc) · 37.5 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
"""
<plugin key="LyrionMusicServer" name="Lyrion Music Server" author="MadPatrick" version="2.1.7" wikilink="https://lyrion.org" externallink="https://github.com/MadPatrick/domoticz_Lyrion">
<description>
<h2><br/>Lyrion Music Server Plugin</h2>
<p>Version 2.1.7</p>
<p>Detects players, creates devices, and provides:</p>
<ul>
<li>Power / Play / Pause / Stop</li>
<li>Volume (Dimmer)</li>
<li>Track info (Text)</li>
<li>Playlists (Selector) - per player (player-specific list)</li>
<li>Sync / Unsync</li>
<li>Favorites (Selector)</li>
<li>Display text (via Actions device)</li>
<li>Shuffle (Selector)</li>
<li>Repeat (Selector)</li>
</ul>
<br/><span style="font-weight: bold;">Lyrion Server settings</span>
</description>
<params>
<param field="Address" label="Server IP" width="200px" required="true" default="192.168.1.6"/>
<param field="Port" label="Port" width="100px" required="true" default="9000"/>
<param field="Username" label="Username" width="150px">
<description>
<br/><span style="color: yellow;">Login settings. Only needed when applicable</span>
</description>
</param>
<param field="Password" label="Password" width="150px" password="true">
</param>
<param field="Mode1" label="Polling interval (On)" width="100px" default="10">
<description>
<br/>
</description>
<options>
<option label="20 sec" value="20"/>
<option label="5 sec" value="5"/>
<option label="10 sec" value="10" default="true"/>
<option label="30 sec" value="30"/>
<option label="60 sec" value="60"/>
</options>
</param>
<param field="Mode5" label="Polling interval (Off)" width="100px" default="600">
<options>
<option label="10 sec" value="10"/>
<option label="300 sec" value="300"/>
<option label="600 sec" value="600" default="true"/>
<option label="1800 sec" value="1800"/>
<option label="3600 sec" value="3600"/>
</options>
</param>
<param field="Mode6" label="Polling interval (lists)" width="100px" default="600">
<options>
<option label="10 sec" value="10"/>
<option label="300 sec" value="300"/>
<option label="600 sec" value="600" default="true"/>
<option label="1800 sec" value="1800"/>
<option label="3600 sec" value="3600"/>
</options>
</param>
<param field="Mode2" label="Max playlists to load" width="100px" default="5"/>
<param field="Mode3" label="Debug logging" width="100px" default="No">
<options>
<option label="Off" value="False" default="true"/>
<option label="On" value="True"/>
</options>
</param>
<param field="Mode4" label="Message text" width="300px" default="Hello from Domoticz!" />
</params>
</plugin>
"""
# Lyrion Music Server Domoticz Plugin
import Domoticz
import requests
import time
import re
class LMSPlugin:
def __init__(self):
self.url = ""
self.auth = None
self.pollInterval = 30
self.offlinePollInterval = 60
self.nextPoll = 0
self.players = []
self.max_playlists = 10
self.imageID = 0
self.debug = False
# Display text settings
self.displayText = "" # Mode4: line2
self.subjectText = "Lyrion" # line1
self.displayDuration = 60
# Logging / init
self.initialized = False
# Track-change detection
self.lastTrackIndex = {}
# Server status tracking
self.server_was_online = None
self.last_success = 0
self.offline_grace = 15
self.update_notified = False
# FIX 10: bijhouden welke versiemelding al getoond is
self.last_update_version = ""
# cache per speler
self.playlist_cache = {}
self.favorites_cache = {}
# FIX 9: listPollInterval initialiseren in __init__ als veilige fallback
self.listPollInterval = 600
# Flag of er een actieve speler is (play/pause)
self.any_active = False
# ------------------------------------------------------------------
# Helpers
# ------------------------------------------------------------------
def log(self, msg):
Domoticz.Log(msg)
def debug_log(self, msg):
# FIX 5: gebruik Domoticz.Debug zodat berichten alleen zichtbaar zijn
# als Domoticz zelf in debug-mode staat
if self.debug:
Domoticz.Debug("DEBUG: " + str(msg))
def error(self, msg):
Domoticz.Error(msg)
def log_player(self, dev, action):
if not dev:
name = "Unknown"
else:
name = dev.Name.replace(" Control", "")
self.log(f"{name} | {action}")
@staticmethod
def is_main_device_name(name: str) -> bool:
return not any(x in name for x in ("Volume", "Track", "Actions", "Shuffle", "Repeat", "Playlists", "Favorites"))
def get_free_unit(self):
used = set(Devices.keys())
for u in range(1, 256):
if u not in used:
return u
return None
# ------------------------------------------------------------------
# Domoticz lifecycle
# ------------------------------------------------------------------
def onStart(self):
self.log(f"Starting Plugin version {Parameters['Version']}")
_IMAGE = "LMS"
creating_new_icon = _IMAGE not in Images
Domoticz.Image(f"{_IMAGE}.zip").Create()
if _IMAGE in Images:
self.imageID = Images[_IMAGE].ID
if creating_new_icon:
self.log("Icons created and loaded.")
else:
self.log(f"Icons found in database (ImageID={self.imageID}).")
else:
self.error(f"Unable to load icon pack '{_IMAGE}.zip'")
# Poll interval (Mode1)
try:
self.pollInterval = int(Parameters.get("Mode1", 30))
except (TypeError, ValueError):
self.log("Mode1 leeg of ongeldig, default 30s gebruikt")
self.pollInterval = 30
# Offline interval (Mode5)
# FIX 2: Parameters is read-only in Domoticz, niet naar schrijven
mode5_raw = Parameters.get("Mode5", "")
if not mode5_raw:
self.log("Mode5 is empty, fallback to 60s")
self.offlinePollInterval = 60
else:
try:
self.offlinePollInterval = int(mode5_raw)
except (TypeError, ValueError):
self.log("Mode5 invalid, fallback to 60s")
self.offlinePollInterval = 60
# List poll interval (Mode6)
try:
self.listPollInterval = int(Parameters.get("Mode6", 600))
except (TypeError, ValueError):
self.listPollInterval = 600
self.log("Mode6 invalid, fallback to 600 sec")
# Max playlists (Mode2)
try:
self.max_playlists = int(Parameters.get("Mode2", 50))
except (TypeError, ValueError):
self.max_playlists = 50
# Debug logging (Mode3)
self.debug = Parameters.get("Mode3", "False").lower() == "true"
if self.debug:
Domoticz.Debugging(1)
self.log("Debug logging enabled")
else:
Domoticz.Debugging(0)
# Display text (Mode4)
self.displayText = Parameters.get("Mode4", "")
self.log(
f"Poll interval: Online : {self.pollInterval}s | "
f"Offline : {self.offlinePollInterval}s | Lists: {self.listPollInterval}s"
)
self.log("Starting initialization ...... Please wait")
# Server URL + Auth
self.url = f"http://{Parameters['Address']}:{Parameters['Port']}/jsonrpc.js"
user = Parameters.get("Username", "")
pwd = Parameters.get("Password", "")
self.auth = (user, pwd) if user else None
Domoticz.Heartbeat(5)
self.nextPoll = time.time() + 2
def onStop(self):
self.log("Plugin stopped.")
def onHeartbeat(self):
now = time.time()
if now < self.nextPoll:
return
self.updateEverything()
active = self.any_active
interval = self.pollInterval if active else self.offlinePollInterval
self.debug_log(f"Heartbeat done, active={active}, next poll in {interval}s")
self.nextPoll = now + interval
# ------------------------------------------------------------------
# LMS JSON helper
# ------------------------------------------------------------------
def lms_query_raw(self, player, cmd_array):
data = {"id": 1, "method": "slim.request", "params": [player, cmd_array]}
try:
r = requests.post(self.url, json=data, auth=self.auth, timeout=10)
r.raise_for_status()
result = r.json().get("result")
self.debug_log(f"Query: player={player}, cmd={cmd_array}, result={result}")
self.last_success = time.time()
if self.server_was_online is not True:
if self.server_was_online is False:
self.log("Lyrion Music Server is ONLINE.")
self.server_was_online = True
return result
except Exception as e:
now = time.time()
if self.server_was_online is not False:
if now - self.last_success > self.offline_grace:
self.log("Lyrion Music Server is OFFLINE")
self.server_was_online = False
self.debug_log(f"LMS query failed: {e}")
return None
def get_serverstatus(self):
return self.lms_query_raw("", ["serverstatus", 0, 999])
def get_status(self, playerid):
return self.lms_query_raw(playerid, ["status", "-", 1, "tags:adclmntyK"])
def send_playercmd(self, playerid, cmd_array):
for attempt in range(2):
result = self.lms_query_raw(playerid, cmd_array)
if result is not None:
return result
time.sleep(0.2)
return None
# FIX 3: send_button verwijderd — werd nergens gebruikt
# ------------------------------------------------------------------
# DISPLAY TEXT
# ------------------------------------------------------------------
def send_display_text(self, playerid, line2_text):
if not playerid or not line2_text:
return
line1 = self.subjectText[:64].replace('"', "'")
line2 = line2_text[:128].replace('"', "'")
d = self.displayDuration
cmd = [
"show",
f"line1:{line1}",
f"line2:{line2}",
f"duration:{d}",
"brightness:4",
"font:large",
]
self.send_playercmd(playerid, cmd)
self.log(f"Display text sent to {playerid}: '{line1}' / '{line2}' ({d}s)")
def find_player_devices(self, mac):
main = vol = text = actions = shuffle = repeat = playlistsel = favorites = None
# Eerst op Description (ideaal)
for uid, dev in Devices.items():
if dev.Description != mac:
continue
if dev.Name.endswith("Volume"):
vol = uid
elif dev.Name.endswith("Track"):
text = uid
elif dev.Name.endswith("Actions"):
actions = uid
elif dev.Name.endswith("Shuffle"):
shuffle = uid
elif dev.Name.endswith("Repeat"):
repeat = uid
elif dev.Name.endswith("Playlists"):
playlistsel = uid
elif dev.Name.endswith("Favorites"):
favorites = uid
else:
main = uid
# Fallback: als niets gevonden, probeer naamfragment
if not main:
for uid, dev in Devices.items():
if mac not in dev.Name:
continue
if dev.Name.endswith("Volume"):
vol = uid
elif dev.Name.endswith("Track"):
text = uid
elif dev.Name.endswith("Actions"):
actions = uid
elif dev.Name.endswith("Shuffle"):
shuffle = uid
elif dev.Name.endswith("Repeat"):
repeat = uid
elif dev.Name.endswith("Playlists"):
playlistsel = uid
elif dev.Name.endswith("Favorites"):
favorites = uid
else:
main = uid
if main:
return (main, vol, text, actions, shuffle, repeat, playlistsel, favorites)
return None
def ensure_player_devices(self, name, mac):
"""Check welke devices er bestaan en maak ontbrekende aan"""
devices = self.find_player_devices(mac)
if not devices:
devices = (None, None, None, None, None, None, None, None)
main, vol, text, actions, shuffle, repeat, plsel, favsel = devices
# FIX 1: lokale used_units set zodat nieuw aangemaakte devices direct
# worden meegeteld en geen dubbele unit-nummers kunnen ontstaan
used_units = set(Devices.keys())
for u in devices:
if u is not None:
used_units.add(u)
def next_free():
u = next(i for i in range(1, 256) if i not in used_units)
used_units.add(u)
return u
# Main selector — FIX: LevelActions heeft 3 pipes voor 4 levels
if main is None:
opts_main = {
"LevelNames": "Off|Pause|Play|Stop",
"LevelActions": "|||",
"SelectorStyle": "0",
}
main_unit = next_free()
Domoticz.Device(
Name=f"{name} Control",
Unit=main_unit,
TypeName="Selector Switch",
Switchtype=18,
Options=opts_main,
Image=self.imageID,
Description=mac,
Used=1,
).Create()
main = main_unit
self.log(f"Main device created for {name}")
# Volume
if vol is None:
vol_unit = next_free()
Domoticz.Device(
Name=f"{name} Volume",
Unit=vol_unit,
TypeName="Dimmer",
Image=self.imageID,
Description=mac,
Used=1,
).Create()
vol = vol_unit
self.log(f"Volume device created for {name}")
# Track
if text is None:
text_unit = next_free()
Domoticz.Device(
Name=f"{name} Track",
Unit=text_unit,
TypeName="Text",
Image=self.imageID,
Description=mac,
Used=1,
).Create()
text = text_unit
self.log(f"Track device created for {name}")
# Actions — FIX: LevelActions heeft 3 pipes voor 4 levels
if actions is None:
opts_act = {
"LevelNames": "None|SendText|Sync to this|Unsync",
"LevelActions": "|||",
"SelectorStyle": "0",
}
act_unit = next_free()
Domoticz.Device(
Name=f"{name} Actions",
Unit=act_unit,
TypeName="Selector Switch",
Switchtype=18,
Options=opts_act,
Image=self.imageID,
Description=mac,
Used=1,
).Create()
actions = act_unit
self.log(f"Actions device created for {name}")
# Shuffle
if shuffle is None:
opts_shuffle = {"LevelNames": "Off|Songs|Albums", "LevelActions": "||", "SelectorStyle": "0"}
sh_unit = next_free()
Domoticz.Device(
Name=f"{name} Shuffle",
Unit=sh_unit,
TypeName="Selector Switch",
Switchtype=18,
Options=opts_shuffle,
Image=self.imageID,
Description=mac,
Used=1,
).Create()
shuffle = sh_unit
self.log(f"Shuffle device created for {name}")
# Repeat
if repeat is None:
opts_repeat = {"LevelNames": "Off|Track|Playlist", "LevelActions": "||", "SelectorStyle": "0"}
rep_unit = next_free()
Domoticz.Device(
Name=f"{name} Repeat",
Unit=rep_unit,
TypeName="Selector Switch",
Switchtype=18,
Options=opts_repeat,
Image=self.imageID,
Description=mac,
Used=1,
).Create()
repeat = rep_unit
self.log(f"Repeat device created for {name}")
# Playlists
if plsel is None:
opts_pl = {"LevelNames": "Select|Loading...", "LevelActions": "", "SelectorStyle": "1"}
pl_unit = next_free()
Domoticz.Device(
Name=f"{name} Playlists",
Unit=pl_unit,
TypeName="Selector Switch",
Switchtype=18,
Options=opts_pl,
Image=self.imageID,
Description=mac,
Used=1,
).Create()
plsel = pl_unit
self.log(f"Playlists device created for {name}")
# Favorites
if favsel is None:
opts_fav = {"LevelNames": "Select|Loading...", "LevelActions": "", "SelectorStyle": "1"}
fav_unit = next_free()
Domoticz.Device(
Name=f"{name} Favorites",
Unit=fav_unit,
TypeName="Selector Switch",
Switchtype=18,
Options=opts_fav,
Image=self.imageID,
Description=mac,
Used=1,
).Create()
favsel = fav_unit
self.log(f"Favorites device created for {name}")
return (main, vol, text, actions, shuffle, repeat, plsel, favsel)
# ------------------------------------------------------------------
# PLAYER-SPECIFIC PLAYLISTS
# ------------------------------------------------------------------
def get_player_playlists(self, mac):
result = self.send_playercmd(mac, ["playlists", 0, self.max_playlists])
if not result:
return []
pl_loop = result.get("playlists_loop", []) or []
playlists = []
for p in pl_loop[: self.max_playlists]:
name = p.get("playlist", "")
plid = p.get("id")
if name:
playlists.append({"id": plid, "name": name})
return playlists
def get_cached_playlists(self, mac):
now = time.time()
entry = self.playlist_cache.get(mac)
if entry and now - entry["ts"] < self.listPollInterval:
return entry["data"]
playlists = self.get_player_playlists(mac)
self.playlist_cache[mac] = {"ts": now, "data": playlists}
return playlists
def get_cached_favorites(self, mac):
now = time.time()
entry = self.favorites_cache.get(mac)
if entry and now - entry["ts"] < self.listPollInterval:
return entry["data"]
favorites = self.get_player_favorites()
self.favorites_cache[mac] = {"ts": now, "data": favorites}
return favorites
def update_player_playlist_selector(self, plsel_unit, playlists, active_playlist_name=None):
if plsel_unit not in Devices:
return
dev_pl = Devices[plsel_unit]
if not playlists:
levelnames = "Select|No playlists"
else:
levelnames = "Select|" + "|".join(p["name"] for p in playlists)
opts = {
"LevelNames": levelnames,
"LevelActions": "",
"SelectorStyle": "1",
}
if dev_pl.Options.get("LevelNames", "") != levelnames:
dev_pl.Update(nValue=0, sValue=dev_pl.sValue, Options=opts)
dev_pl = Devices[plsel_unit]
self.log(f"Playlist selector updated for '{dev_pl.Name}'.")
if active_playlist_name and playlists:
for idx, pinfo in enumerate(playlists):
if pinfo["name"] == active_playlist_name:
expected_level = (idx + 1) * 10
if dev_pl.sValue != str(expected_level):
self.log(f"Setting playlist selector '{dev_pl.Name}' to level {expected_level} for '{active_playlist_name}'")
dev_pl.Update(nValue=0, sValue=str(expected_level))
break
else:
if dev_pl.sValue != "0":
dev_pl.Update(nValue=0, sValue="0")
def play_playlist_for_player(self, mac, Level):
if Level == 0:
self.log("Playlist selection reset to 'Select'.")
return
if Level < 10:
return
playlists = self.get_cached_playlists(mac)
idx = int(Level // 10) - 1
if idx < 0 or idx >= len(playlists):
self.error("Invalid playlist index.")
return
pl = playlists[idx]
playlist_name = pl["name"]
playlist_id = pl["id"]
self.send_playercmd(mac, ["playlistcontrol", "cmd:load", f"playlist_id:{playlist_id}"])
self.log(f"Loaded playlist '{playlist_name}' (ID {playlist_id}) on player {mac}")
self.nextPoll = time.time() + 1
# ------------------------------------------------------------------
# FAVORITES
# LMS favorites zijn globaal — geen mac-parameter nodig
# ------------------------------------------------------------------
def get_player_favorites(self):
result = self.lms_query_raw("", ["favorites", "items", 0, 50])
if not result:
return []
fav_loop = result.get("loop_loop", []) or []
favorites = []
for f in fav_loop:
name = f.get("name", "")
fid = f.get("id")
# FIX 6: expliciet filteren op hasitems==0 (afspeelbare items),
# mappen hebben hasitems=1 en worden zo uitgesloten
if name and fid and f.get("hasitems") == 0:
favorites.append({"id": fid, "name": name})
return favorites
def update_favorites_selector(self, fav_unit, favorites):
if fav_unit not in Devices:
return
dev_fav = Devices[fav_unit]
if not favorites:
levelnames = "Select|Geen Favorieten"
else:
# FIX 7: bouw de lijst op en stop vóór de limiet bereikt wordt
# zodat er nooit midden in een naam of separator geknipt wordt
parts = ["Select"]
for f in favorites:
short_name = f["name"][:25]
candidate = "|".join(parts + [short_name])
if len(candidate) > 150:
break
parts.append(short_name)
levelnames = "|".join(parts)
opts = {
"LevelNames": levelnames,
"LevelActions": "",
"SelectorStyle": "1",
}
if dev_fav.Options.get("LevelNames", "") != levelnames:
self.debug_log(f"Updating Favorites list. String length: {len(levelnames)}")
dev_fav.Update(nValue=0, sValue=dev_fav.sValue, Options=opts)
# ------------------------------------------------------------------
# MAIN UPDATE LOOP
# ------------------------------------------------------------------
def updateEverything(self):
server = self.get_serverstatus()
if not server:
self.any_active = False
return
self.players = server.get("players_loop", []) or []
# LMS update melding
update_msg = server.get("newversion", "")
clean_msg = ""
if update_msg:
clean_msg = re.sub('<[^<]+?>', '', update_msg)
clean_msg = clean_msg.split('Klik op hier')[0].strip()
# FIX 10: alleen melden als het een nieuwe/andere versie is
if clean_msg and clean_msg != self.last_update_version:
try:
Domoticz.Status(f"{clean_msg}")
except Exception as e:
Domoticz.Error(f"Kon update notificatie niet versturen: {e}")
self.last_update_version = clean_msg
self.update_notified = True
else:
# Server meldt geen update meer: reset zodat een volgende
# nieuwe versie opnieuw gemeld wordt
if self.update_notified:
self.last_update_version = ""
self.update_notified = False
# Nieuwe spelers -> devices aanmaken
for p in self.players:
name = p.get("name", "Unknown")
mac = p.get("playerid", "")
if mac:
self.ensure_player_devices(name, mac)
any_active = False
# Alle spelers updaten
for p in self.players:
mac = p.get("playerid")
if not mac:
continue
devices = self.find_player_devices(mac)
if not devices:
continue
main, vol, text, actions, shuffle, repeat, plsel, favsel = devices
st = self.get_status(mac) or {}
power = int(st.get("power", 0))
mode = st.get("mode", "stop")
sel_level = {"pause": 10, "play": 20, "stop": 30}.get(mode, 0)
if power == 0:
sel_level = 0
if power == 1 and mode in ("play", "pause"):
any_active = True
remote = st.get("remote", 0)
# Main selector
if main in Devices:
dev_main = Devices[main]
n = 1 if power else 0
s = str(sel_level)
if dev_main.nValue != n or dev_main.sValue != s:
dev_main.Update(nValue=n, sValue=s)
# Volume
if vol in Devices:
dev_vol = Devices[vol]
raw = st.get("mixer volume", 0)
try:
new_sval = str(int(float(str(raw).replace("%", ""))))
except Exception:
new_sval = "0"
if dev_vol.sValue != new_sval:
self.log(f"Volume changed to : {new_sval}%")
n_val = 2 if int(new_sval) > 0 else 0
dev_vol.Update(nValue=n_val, sValue=new_sval)
# Player-specific playlists
player_pl = None
if plsel:
player_pl = self.get_cached_playlists(mac)
# Track Text
if text in Devices:
dev_text = Devices[text]
if power == 0 or mode in ["stop", "pause"]:
# FIX 4: encoding-artefact vervangen door correcte Unicode escape
label = "\U0001F514 LMS update beschikbaar" if clean_msg else ""
if dev_text.sValue != label:
dev_text.Update(nValue=0, sValue=label)
if plsel:
self.update_player_playlist_selector(plsel, player_pl, active_playlist_name=None)
else:
rm = st.get("remoteMeta", {})
pl_loop = st.get("playlist_loop", []) or []
current_title = st.get("current_title", "")
title = ""
artist = ""
station = ""
if remote == 1:
station = current_title
title = rm.get("title", "")
artist = rm.get("artist", "")
else:
if pl_loop and isinstance(pl_loop, list):
title = pl_loop[0].get("title", "")
artist = pl_loop[0].get("artist", "")
if not title:
title = current_title
lines = []
if station:
lines.append(f"📻 <b><span style='color:#969696;'>{station}</span></b>")
if artist:
lines.append(f"🎤 <span style='color:#FFD700;'>{artist}</span>")
if title and title != station:
lines.append(f"🎵 <span style='color:#FFA500 !important;'>{title}</span>")
label = "<br>".join(lines) if lines else " "
label = label[:255]
track_index = st.get("playlist_cur_index")
player_key = mac
changed = False
if track_index is not None:
if player_key not in self.lastTrackIndex or self.lastTrackIndex[player_key] != track_index:
changed = True
self.lastTrackIndex[player_key] = track_index
if dev_text.sValue != label or changed:
dev_text.Update(nValue=0, sValue=label)
# Shuffle
if shuffle in Devices:
dev_shuffle = Devices[shuffle]
try:
shuffle_state = int(st.get("playlist shuffle", 0))
except Exception:
shuffle_state = 0
level = shuffle_state * 10
if dev_shuffle.sValue != str(level):
dev_shuffle.Update(nValue=0, sValue=str(level))
# Repeat
if repeat in Devices:
dev_repeat = Devices[repeat]
try:
repeat_state = int(st.get("playlist repeat", 0))
except Exception:
repeat_state = 0
level = repeat_state * 10
if dev_repeat.sValue != str(level):
dev_repeat.Update(nValue=0, sValue=str(level))
# Playlist selector update
playlist_tracks = st.get("playlist_tracks", 0)
playlist_name = st.get("playlist_name", "")
playlist_is_active = (playlist_tracks > 1 and playlist_name not in ("", None) and remote == 0)
if plsel:
if playlist_is_active:
self.update_player_playlist_selector(plsel, player_pl, active_playlist_name=playlist_name)
else:
self.update_player_playlist_selector(plsel, player_pl, active_playlist_name=None)
if favsel:
favorites = self.get_cached_favorites(mac)
self.update_favorites_selector(favsel, favorites)
self.any_active = any_active
if not self.initialized:
self.log("Initialization complete:")
self.log(f" Players : {len(self.players)}")
self.log(f" Devices : {len(Devices)}")
self.log(f" Max playlists/player : {self.max_playlists}")
self.initialized = True
# ------------------------------------------------------------------
# COMMAND HANDLER
# ------------------------------------------------------------------
def onCommand(self, Unit, Command, Level, Hue):
if Unit not in Devices:
return
# Forceer snelle update na een commando
self.nextPoll = time.time() + 1
dev = Devices[Unit]
devname = dev.Name
mac = dev.Description
# Vroege check op lege MAC
if not mac:
self.error(f"No MAC address for device {Unit} ('{devname}'), command ignored.")
return
self.debug_log(f"onCommand: Unit={Unit}, Name={devname}, Command={Command}, Level={Level}, mac={mac}")
if "Favorites" in devname and Command == "Set Level":
if Level == 0:
dev.Update(nValue=0, sValue="0")
return
favorites = self.get_cached_favorites(mac)
svalue = str(Level)
idx = (int(svalue) // 10) - 1
if 0 <= idx < len(favorites):
fav = favorites[idx]
fav_id = fav["id"]
self.send_playercmd(mac, ["favorites", "playlist", "play", f"item_id:{fav_id}"])
self.log(f"Playing Favorite: {fav['name']}")
dev.Update(nValue=1, sValue=svalue, Options=dev.Options)
self.nextPoll = time.time() + 1
return
if "Playlists" in devname and Command == "Set Level":
if Level == 0:
dev.Update(nValue=0, sValue="0")
return
self.play_playlist_for_player(mac, Level)
return
if "Actions" in devname and Command == "Set Level":
self.handle_actions(dev, mac, Level)
return
if "Shuffle" in devname:
if Command == "Set Level":
mode = int(Level // 10)
elif Command == "Off":
mode = 0
Level = 0
else:
return
self.send_playercmd(mac, ["playlist", "shuffle", str(mode)])
nval = 1 if mode > 0 else 0
dev.Update(nValue=nval, sValue=str(Level))
mode_name = {0: "Off", 1: "Songs", 2: "Albums"}.get(mode, f"Unknown ({mode})")
self.log_player(dev, f"Shuffle {mode_name}")
return
if "Repeat" in devname:
if Command == "Set Level":
mode = int(Level // 10)
elif Command == "Off":
mode = 0
Level = 0
else:
return
self.send_playercmd(mac, ["playlist", "repeat", str(mode)])
nval = 1 if mode > 0 else 0
dev.Update(nValue=nval, sValue=str(Level))
mode_name = {0: "Off", 1: "Track", 2: "Playlist"}.get(mode, f"Unknown ({mode})")
self.log_player(dev, f"Repeat {mode_name}")
return
if Command in ["On", "Off"] and self.is_main_device_name(devname):
self.handle_power(dev, mac, Command)
return
if "Volume" in devname and Command == "Set Level":
self.handle_volume(dev, mac, Level)
return
if Command == "Set Level" and self.is_main_device_name(devname):
self.handle_main_playback(dev, mac, Level)
return
# ------------------------------------------------------------------
# Command helpers
# ------------------------------------------------------------------
def handle_volume(self, dev, mac, Level):
self.send_playercmd(mac, ["mixer", "volume", str(Level)])
dev.Update(nValue=2 if Level > 0 else 0, sValue=str(Level))
self.log_player(dev, f"Volume {Level}%")
def handle_actions(self, dev, mac, Level):
# Level 10: SendText, 20: Sync, 30: Unsync
if Level == 10:
if self.displayText:
self.send_display_text(mac, self.displayText)
else:
self.log("No display text configured in parameters (Mode4).")
dev.Update(nValue=0, sValue="0")
return
if Level == 20:
self.log(f"Syncing all players TO master: {mac}")
server = self.get_serverstatus()
if not server:
self.log("Serverstatus niet beschikbaar, sync afgebroken.")
dev.Update(nValue=0, sValue="0")
return
players = server.get("players_loop", []) or []
for p in players:
pid = p.get("playerid")
if pid and pid != mac:
self.send_playercmd(pid, ["sync", mac])
time.sleep(0.1)
dev.Update(nValue=0, sValue="0")
return
if Level == 30: