Repository navigation
Expand file tree
/
Copy pathtest_driver.py
More file actions
1781 lines (1615 loc) · 72.9 KB
/
Copy pathtest_driver.py
File metadata and controls
1781 lines (1615 loc) · 72.9 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
"""
Test connection script for Kodi integration driver.
:copyright: (c) 2025 by Unfolded Circle ApS.
:license: Mozilla Public License Version 2.0, see LICENSE for more details.
"""
# pylint: disable=all
# flake8: noqa
import asyncio
import datetime
import io
import json
import logging
import math
import os
import queue
import socket
import sys
import threading
import time
import tkinter as tk
from asyncio import AbstractEventLoop, Future, Queue, Task
from contextlib import suppress
from dataclasses import dataclass
from enum import StrEnum
from functools import wraps
from tkinter import ttk
from typing import Any, Callable
import aiohttp
sys.path.insert(1, "src")
import requests
from aiohttp import ClientSession, ClientWebSocketResponse, WSMsgType
from PIL import Image, ImageTk
from pyee.asyncio import AsyncIOEventEmitter
from rich import print_json
def debounce(wait: float):
"""Debounce function."""
def decorator(func):
task: Task | None = None
@wraps(func)
async def debounced(*args, **kwargs):
nonlocal task
async def call_func():
"""Call wrapped function."""
await asyncio.sleep(wait)
await func(*args, **kwargs)
if task and not task.done():
task.cancel()
task = asyncio.create_task(call_func())
return task
return debounced
return decorator
# localization_cfg = {
# "country_code": "EN",
# "language_code": "en_US",
# "measurement_unit": "METRIC",
# "time_format_24h": True,
# "time_zone": "Europe/Paris",
# }
localization_cfg = {
"country_code": "FR",
"language_code": "fr_FR",
"measurement_unit": "METRIC",
"time_format_24h": True,
"time_zone": "Europe/Paris",
}
class Events(StrEnum):
"""Internal events."""
EXITING = "EXITING"
@dataclass
class Selector:
name: str
current_option: str
options: list[str]
def get_local_ip() -> str:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
ip = s.getsockname()[0]
s.close()
return ip
def get_entity_name(entity: dict[str, Any]) -> str:
entity_id = entity.get("entity_id")
name = entity["name"].get("en", None)
if name:
return f"{name} {entity_id}"
return entity_id
def load_image_from_url(url: str, max_size=(500, 500)) -> ImageTk.PhotoImage:
# Download image
resp = requests.get(url, timeout=10)
resp.raise_for_status()
# Open image from bytes data
img = Image.open(io.BytesIO(resp.content))
# Resize image
img.thumbnail(max_size)
return ImageTk.PhotoImage(img)
if sys.platform == "win32":
_LOOP = asyncio.SelectorEventLoop()
else:
_LOOP = asyncio.new_event_loop()
asyncio.set_event_loop(_LOOP)
DRIVER_PORT = os.getenv("UC_INTEGRATION_HTTP_PORT", 9090)
DRIVER_INTERFACE = os.getenv("UC_INTEGRATION_INTERFACE", get_local_ip())
DRIVER_URL = f"ws://{DRIVER_INTERFACE}:{DRIVER_PORT}/ws"
MAIN_WS_MAX_MSG_SIZE = 8 * 1024 * 1024 # 8Mb
WS_TIMEOUT = 5
BROWSING_PAGINATION = 12
BROWSING_CELL_WIDTH = 60
class RemoteWebsocket:
def __init__(self, loop: AbstractEventLoop | None = None):
self.client_session: ClientSession | None = None
self.client_websocket: ClientWebSocketResponse | None = None
self._rx_tasks = set()
self._id = 0
self.callback_queues: dict[str, Queue[dict[str, Any]]] = {}
self.callback_tasks: dict[int, Task] = {}
self.futures: dict[int, Future[dict[str, Any]]] = {}
self._loop = loop if loop else asyncio.get_event_loop()
async def websocket_connect(self):
self.client_session = ClientSession(connector=aiohttp.TCPConnector(resolver=aiohttp.ThreadedResolver()))
async with asyncio.timeout(5):
self.client_websocket = await self.client_session.ws_connect(
DRIVER_URL,
heartbeat=5,
ssl=False,
max_msg_size=MAIN_WS_MAX_MSG_SIZE,
)
if self.client_websocket is None:
_LOG.error("Websocket connection failed")
return
self._rx_tasks.add(asyncio.create_task(self._rx_msgs_main_ws(self.client_websocket)))
# await asyncio.wait(self._rx_tasks, return_when=asyncio.FIRST_COMPLETED)
async def disconnect(self):
await self._closeout_tasks()
async def get_driver_vertion(self):
try:
response = await self.send_request_and_wait(
{"msg": "get_driver_version"},
timeout=WS_TIMEOUT,
)
return response
except asyncio.TimeoutError:
_LOG.error("Timeout while extracting driver version")
return None
async def get_entity_states(self):
try:
response = await self.send_request_and_wait(
{"msg": "get_entity_states"},
timeout=WS_TIMEOUT,
)
return response
except asyncio.TimeoutError:
_LOG.error("Timeout while extracting entities states")
return None
async def start_setup(self, reconfigure=False):
try:
response = await self.send_request_and_wait(
{"msg": "setup_driver", "msg_data": {"reconfigure": reconfigure, "setup_data": {}}},
timeout=WS_TIMEOUT,
)
return response
except asyncio.TimeoutError:
_LOG.error("Timeout while starting setup")
return None
except Exception as ex:
_LOG.error("Error while starting setup", ex)
async def subscribe_entities(self, entity_ids: list[str]):
try:
response = await self.send_request_and_wait(
{"msg": "subscribe_events", "msg_data": {"entity_ids": entity_ids}},
timeout=WS_TIMEOUT,
)
return response
except asyncio.TimeoutError:
_LOG.error("Timeout while subscribing entities")
return None
async def get_available_entities(self):
try:
response = await self.send_request_and_wait(
{"msg": "get_available_entities"},
timeout=WS_TIMEOUT,
)
return response
except asyncio.TimeoutError:
_LOG.error("Timeout while getting available entities")
return None
def subscribe_events(self, event_type: str, callback: Callable):
uid = self._id
self._id += 1
self._create_subscription_handler(uid, event_type, callback)
async def send_command(self, command: dict[str, Any]) -> dict[str, Any] | None:
# {"kind":"req","id":35,"msg":"entity_command","msg_data":{"cmd_id":"on","entity_id":"media_player.192.168.1.20","entity_type":"media_player","params":{}}}
try:
response = await self.send_request_and_wait(
{"msg": "entity_command", "msg_data": command},
timeout=WS_TIMEOUT,
)
return response
except asyncio.TimeoutError:
_LOG.error("Timeout while sending command")
return None
except Exception as ex:
_LOG.error("Command error %s", ex)
return None
async def browse_media_entity(
self,
entity_id: str,
media_id: str | None = None,
media_type: str | None = None,
paging: dict[str, Any] | None = None,
) -> dict[str, Any] | None:
return await self.browse_media(
{"entity_id": entity_id, "media_id": media_id, "media_type": media_type, "paging": paging}
)
async def search_media_entity(
self,
entity_id: str,
query: str,
media_id: str | None = None,
media_type: str | None = None,
paging: dict[str, Any] | None = None,
) -> dict[str, Any] | None:
return await self.search_media(
{"entity_id": entity_id, "query": query, "media_id": media_id, "media_type": media_type, "paging": paging}
)
async def browse_media(self, msg_data: dict[str, Any]) -> dict[str, Any] | None:
try:
_LOG.debug("Browse media: %s", msg_data)
response = await self.send_request_and_wait(
{"msg": "browse_media", "msg_data": msg_data},
timeout=WS_TIMEOUT,
)
return response
except asyncio.TimeoutError:
_LOG.error("Timeout while browsing media")
return None
except Exception as ex:
_LOG.error("Browsing error %s", ex)
return None
async def search_media(self, msg_data: dict[str, Any]) -> dict[str, Any] | None:
try:
_LOG.debug("Search media: %s", msg_data)
response = await self.send_request_and_wait(
{"msg": "search_media", "msg_data": msg_data},
timeout=WS_TIMEOUT,
)
return response
except asyncio.TimeoutError:
_LOG.error("Timeout while browsing media")
return None
except Exception as ex:
_LOG.error("Browsing error %s", ex)
return None
async def _rx_msgs_main_ws(self, web_socket: ClientWebSocketResponse) -> None:
"""Receive messages from main websocket connection."""
async for raw_msg in web_socket:
# _LOG.debug("receive: %s", raw_msg)
if raw_msg.type is not WSMsgType.TEXT:
break
self._process_text_message(raw_msg.data)
async def _handle_auth(self):
# {"kind": "event", "msg": "auth_required","msg_data": {"name":"my-integration","version":{"api":"0.5.0","driver":"1.0.0"}}}
await self._send_json(
{"kind": "resp", "req_id": self._id, "code": 200, "msg": "authentication", "msg_data": {}}
)
self._id += 1
async def _handle_request(self, msg: dict[str, Any]):
# {"kind": "req", "msg": "get_supported_entity_types"}
msg_type = msg.get("msg", "")
req_id = msg.get("id", "")
if msg_type == "get_supported_entity_types":
await self._send_json(
{
"kind": "resp",
"req_id": req_id,
"code": 200,
"msg": "supported_entity_types",
"msg_data": [
"cover",
"button",
"climate",
"light",
"media_player",
"remote",
"select",
"sensor",
"switch",
"ir_emitter",
"voice_assistant",
],
}
)
elif msg_type == "get_version":
await self._send_json(
{
"kind": "resp",
"req_id": req_id,
"code": 200,
"msg": "version",
"msg_data": {
"address": "AA:BB:CC:DD:EE:FF",
"api": "0.16.0",
"core": "0.69.1-bt",
"device_name": "Remote 3",
"hostname": "Remote3-aabbccdd.local",
"model": "UCR3",
"os": "2.8.3",
"ui": "0.69.1",
},
}
)
elif msg_type == "get_localization_cfg":
await self._send_json(
{
"kind": "resp",
"req_id": req_id,
"code": 200,
"msg": "localization_cfg",
"msg_data": localization_cfg,
}
)
elif msg_type == "get_driver_metadata":
# {"id":2,"kind":"req","msg":"get_driver_metadata"}
with open("driver.json", "r") as file:
file_content = json.load(file)
await self._send_json(
{
"kind": "resp",
"req_id": req_id,
"code": 200,
"msg": "driver_metadata",
"msg_data": json.dumps(file_content),
}
)
elif msg_type == "setup_driver":
# {"kind":"req","id":3,"msg":"setup_driver","msg_data":{"reconfigure":false,"setup_data":{}}}
await self._send_json(
{
"kind": "resp",
"req_id": req_id,
"code": 200,
"msg": "result",
"msg_data": {},
}
)
await asyncio.sleep(1)
await self._send_json(
{
"kind": "event",
"msg": "driver_setup_change",
"msg_data": {"event_type": "SETUP", "state": "SETUP"},
"cat": "DEVICE",
}
)
await asyncio.sleep(1)
await self._send_json(
{
"kind": "event",
"msg": "driver_setup_change",
"msg_data": {"event_type": "SETUP", "state": "OK"},
"cat": "DEVICE",
}
)
else:
await self._send_json(
{
"kind": "resp",
"req_id": req_id,
"code": 400,
"msg": f"{msg_type}",
"msg_data": f"Unknown message type: {msg_type}",
}
)
async def _send_json(self, msg: dict) -> None:
_LOG.debug("Send json: %s", msg)
await self.client_websocket.send_json(msg)
async def send_request_and_wait(
self,
msg: dict,
timeout: float = 5.0,
) -> dict[str, Any] | None:
"""
Envoie une requête et attend la réponse associée au req_id.
"""
req_id = self._id
self._id += 1
msg["id"] = req_id
msg["kind"] = "req"
future = self._loop.create_future()
self.futures[req_id] = future
await self._send_json(msg)
try:
response = await asyncio.wait_for(future, timeout=timeout)
return response
except asyncio.TimeoutError:
pass
finally:
try:
# Nettoyage dans tous les cas
await self.futures.pop(req_id, None)
except KeyError:
pass
def _process_text_message(self, data: str) -> None:
"""Process text message."""
msg = json.loads(data)
msg_type = msg.get("msg", "")
if msg_type == "auth_required":
asyncio.create_task(self._handle_auth())
kind = msg.get("kind", "")
if kind == "event" and (callback_queue := self.callback_queues.get(msg_type)):
callback_queue.put_nowait(msg)
elif kind == "req":
asyncio.create_task(self._handle_request(msg))
else:
uid = msg.get("req_id", None)
if uid is None:
return
if future := self.futures.get(uid):
future.set_result(msg)
@staticmethod
async def callback_handler(
handler_queue: Queue[dict[str, Any]],
callback: Callable,
future: Future[dict[str, Any]],
) -> None:
"""Handle callbacks."""
with suppress(asyncio.CancelledError):
while True:
msg = await handler_queue.get()
# payload = msg.get("payload")
try:
await callback(msg)
except Exception as ex:
_LOG.error("Exception in callback: %s", ex)
pass
if not future.done():
future.set_result(msg)
def _create_subscription_handler(self, uid: int, msg_type: str, callback: Callable) -> None:
"""Create a subscription handler for a given uid.
Create a queue to store the messages, a task to handle the messages
and a future to signal first subscription update processed.
"""
self.futures[uid] = future = self._loop.create_future()
subscription_queue: Queue[dict[str, Any]] = asyncio.Queue()
self.callback_queues[msg_type] = subscription_queue
self.callback_tasks[uid] = asyncio.create_task(self.callback_handler(subscription_queue, callback, future))
async def _delete_subscription_handler(self, uid: int, msg_type: str) -> None:
"""Delete a subscription handler for a given id."""
task = self.callback_tasks.pop(uid)
if not task.done():
task.cancel()
while not task.done():
with suppress(asyncio.CancelledError):
await task
del self.callback_queues[msg_type]
def _cancel_tasks(self) -> None:
"""Cancel all tasks."""
for callback_task in self.callback_tasks.values():
if not callback_task.done():
callback_task.cancel()
for task in self._rx_tasks:
if not task.done():
task.cancel()
for future in self.futures.values():
future.cancel()
async def close_client_session(self) -> None:
await self.client_session.close()
self.client_session = None
async def _closeout_tasks(self) -> None:
"""Cancel all tasks and close connections."""
closeout = set()
self._cancel_tasks()
if callback_tasks := set(self.callback_tasks.values()):
closeout.update(callback_tasks)
closeout.update(self._rx_tasks)
closeout.add(asyncio.create_task(self.close_client_session()))
if not closeout:
return
closeout_task = asyncio.create_task(asyncio.wait(closeout))
while not closeout_task.done():
with suppress(asyncio.CancelledError):
await asyncio.shield(closeout_task)
class BrowsingData:
window: tk.Toplevel | None = None
media_id: str | None = None
media_type: str | None = None
page: int = 1
limit: int = BROWSING_PAGINATION
count = 0
items: list[dict[str, Any]] | None = None
main: dict[str, Any] | None = None
search_mode = False
class SetupData:
window: tk.Toplevel | None = None
mapping: dict[str, ttk.Widget | tk.IntVar | tk.StringVar | tk.Widget] = {}
mapping_type: dict[str, str] = {}
data: dict[str, Any] | None = None
async def load_item_image_url(button: ttk.Button, item: dict[str, Any]):
try:
photo = load_image_from_url(item.get("thumbnail"), max_size=(BROWSING_CELL_WIDTH, BROWSING_CELL_WIDTH))
button.configure(image=photo, compound="top")
button.image = photo
except Exception as e:
_LOG.exception("Image load error %s : %s", item.get("thumbnail"), e)
class RemoteInterface(tk.Tk):
def __init__(self) -> None:
super().__init__()
self._worker: WorkerThread | None = None
self.title("Remote Interface")
# self.geometry("800x600")
self.maxsize(1920, 1080)
self._row = 0
self._ui_queue: queue.Queue[Callable[[], None]] = queue.Queue()
self._left_frame = ttk.Frame(self, width=300, height=600)
self._left_frame.pack(side="left", fill="both", padx=10, pady=5, expand=True)
self._left_frame.grid_columnconfigure(0, weight=1)
self._left_frame.grid_columnconfigure(1, weight=1)
self._left_frame.grid_columnconfigure(2, weight=1)
self._right_frame = ttk.Frame(self, width=650, height=600)
self._right_frame.pack(side="right", fill="both", padx=10, pady=5, expand=True)
tool_bar2 = ttk.Frame(self._right_frame, width=650, height=80)
label = ttk.Label(tool_bar2, text="Volume")
label.pack(anchor="w", side="left", pady=(0, 10))
self._volume_bar: tk.Scale = tk.Scale(
tool_bar2,
from_=0,
to=100,
state="disabled",
orient="horizontal",
# command=lambda event: self.media_player_command("volume", {"volume": event.widget.get()}),
)
self._volume_bar.bind(
"<ButtonRelease-1>", lambda event: self.media_player_command("volume", {"volume": event.widget.get()})
)
self._volume_bar.pack(side="right", fill="x", expand=True)
tool_bar2.pack(side="bottom", fill="x", expand=True)
tool_bar = ttk.Frame(self._right_frame, width=650, height=40)
self._title_field = ttk.Label(tool_bar, text="Title")
self._title_field.pack(anchor="w", pady=(0, 10))
self._artist = ttk.Label(tool_bar, text="Artist")
self._artist.pack(anchor="w", pady=(0, 10))
self._state = ttk.Label(tool_bar, text="State")
self._state.pack(anchor="w", pady=(0, 10))
self._progress = ttk.Progressbar(
tool_bar, orient="horizontal", length=200, mode="determinate", takefocus=True, maximum=100
)
self._progress["value"] = 0
self._progress.pack(side="left", fill="x", expand=True)
self._progress_label = ttk.Label(tool_bar, text="00:00:00")
self._progress_label.pack(side="right", fill="x", expand=True)
tool_bar.pack(side="bottom", fill="x", expand=True)
start_setup_button = ttk.Button(self._left_frame, text="Start setup", command=lambda: self.setup_open())
start_setup_button.grid(row=self._row, column=0)
self._setup_reconfigure = tk.IntVar(value=1)
reconfigure_checkbox = tk.Checkbutton(self._left_frame, variable=self._setup_reconfigure, onvalue=1, offvalue=0)
reconfigure_checkbox.grid(row=self._row, column=1, sticky="e")
label_setup = ttk.Label(self._left_frame, text="Reconfigure devices")
label_setup.grid(row=self._row, column=2, sticky="w")
self._setup_data = SetupData()
self._row += 1
reconnect_button = ttk.Button(self._left_frame, text="Reconnect driver", command=lambda: self.reconnect())
reconnect_button.grid(row=self._row, column=0)
self._media_browse_button = ttk.Button(
self._left_frame, text="Browse media", command=lambda: self.media_browse_open()
)
self._media_browse_data = BrowsingData()
self._media_browse_button.grid(row=self._row, column=1)
self._row += 1
label = ttk.Label(self._left_frame, text="Search media :")
label.grid(row=self._row, column=0)
self._media_search_text = ttk.Entry(self._left_frame)
self._media_search_text.grid(row=self._row, column=1)
self._media_search_button = ttk.Button(
self._left_frame, text="Search", command=lambda: self.media_search_open()
)
self._media_search_button.grid(row=self._row, column=2)
self._row += 1
self._media_search_window: tk.Toplevel | None = None
self._media_search_data = BrowsingData()
self._media_search_data.search_mode = True
label = ttk.Label(self._left_frame, text="Media Players")
label.grid(row=self._row, column=0, columnspan=1)
self._media_players = ttk.Combobox(self._left_frame, state="readonly")
self._media_players.bind(
"<<ComboboxSelected>>",
lambda event, cmd_id="select_option": self.change_media_player(event),
)
self._media_players.grid(row=self._row, column=1, columnspan=2)
self._row += 1
self._volume = ttk.Label(self._left_frame, text="Volume")
self._volume.grid(row=self._row, column=2) # .pack(anchor="w", pady=(0, 10))
self._row += 1
command = ttk.Button(self._left_frame, text="Off", command=lambda: self.media_player_command("off"))
command.grid(row=self._row, column=0)
self._command_on = ttk.Button(self._left_frame, text="On", command=lambda: self.media_player_command("on"))
self._command_on.grid(row=self._row, column=1)
self._input_source = ttk.Combobox(self._left_frame, state="readonly", justify="left")
self._input_source.bind(
"<<ComboboxSelected>>",
lambda event: self.select_input_source(event),
)
self._input_source.grid(row=self._row, column=2)
self._row += 1
self._command_play_pause = ttk.Button(
self._left_frame, text="Play/pause", command=lambda: self.media_player_command("play_pause")
)
self._command_stop = ttk.Button(
self._left_frame, text="Stop", command=lambda: self.media_player_command("stop")
)
self._command_stop.grid(row=self._row, column=0)
self._command_play_pause.grid(row=self._row, column=1)
self._sound_mode = ttk.Combobox(self._left_frame, state="readonly", justify="left")
self._sound_mode.bind(
"<<ComboboxSelected>>",
lambda event: self.select_sound_mode(event),
)
self._sound_mode.grid(row=self._row, column=2)
self._row += 1
command = ttk.Button(self._left_frame, text="Mute", command=lambda: self.media_player_command("mute_toggle"))
command.grid(row=self._row, column=0)
command = ttk.Button(self._left_frame, text="Vol-", command=lambda: self.media_player_command("volume_down"))
command.grid(row=self._row, column=1)
command = ttk.Button(self._left_frame, text="Vol+", command=lambda: self.media_player_command("volume_up"))
command.grid(row=self._row, column=2)
self._row += 1
command = ttk.Button(self._left_frame, text="Back", command=lambda: self.media_player_command("back"))
command.grid(row=self._row, column=0)
command = ttk.Button(self._left_frame, text="Up", command=lambda: self.media_player_command("cursor_up"))
command.grid(row=self._row, column=1)
command = ttk.Button(self._left_frame, text="Home", command=lambda: self.media_player_command("home"))
command.grid(row=self._row, column=2)
self._row += 1
command = ttk.Button(self._left_frame, text="Left", command=lambda: self.media_player_command("cursor_left"))
command.grid(row=self._row, column=0)
command = ttk.Button(self._left_frame, text="OK", command=lambda: self.media_player_command("cursor_enter"))
command.grid(row=self._row, column=1)
command = ttk.Button(self._left_frame, text="Right", command=lambda: self.media_player_command("cursor_right"))
command.grid(row=self._row, column=2)
self._row += 1
command = ttk.Button(self._left_frame, text="Down", command=lambda: self.media_player_command("cursor_down"))
command.grid(row=self._row, column=1)
self._row += 1
self._sensors: dict[str, ttk.Label] = {}
self._selectors: dict[str, ttk.Combobox] = {}
self._info_label = ttk.Label(self._left_frame, text="")
self._info_label.grid(row=self._row, column=0, columnspan=3)
self._row += 1
self._loop = asyncio.get_event_loop()
self.protocol("WM_DELETE_WINDOW", self.on_close)
self.after(50, self.poll_queue)
self._photo: tk.PhotoImage | None = None
self._artwork: ttk.Label | None = None
self._events = AsyncIOEventEmitter(asyncio.get_event_loop())
self._position = 0
self._duration = 0
self._media_position_task: Future | None = None
self._browsing_support = False
self._media_search_support = False
@property
def media_player_entity(self) -> dict[str, Any] | None:
for entity in self._worker._entities:
if entity.get("entity_type", "") != "media_player":
continue
name = get_entity_name(entity)
if self._media_players.get() == name:
return entity
return None
def set_worker(self, worker: Any) -> None:
self._worker = worker
def select_input_source(self, event: tk.Event):
self.media_player_command("select_source", {"source": event.widget.get()})
def select_sound_mode(self, event: tk.Event):
self.media_player_command("select_sound_mode", {"mode": event.widget.get()})
def media_player_command(self, cmd_id: str, params: dict[str, Any] | None = None) -> None:
_LOG.debug("Media Player Command %s", cmd_id)
if self._worker is None:
_LOG.error("Media Player Command undefined worker")
return
# entity_id = next(
# (x.get("entity_id", "") for x in self._worker._entities if x.get("entity_type", "") == "media_player")
# )
media_player_entity = self.media_player_entity
if media_player_entity is None:
_LOG.error("No Media Player entity not found for command %s (%s)", cmd_id, self._worker.entity_ids)
return
entity_id = media_player_entity.get("entity_id")
try:
if params is None:
params = {}
asyncio.run_coroutine_threadsafe(
self.send_command(
{
"cmd_id": cmd_id,
"entity_id": entity_id,
"entity_type": "media_player",
"params": params,
}
),
self._worker._loop,
)
except Exception as ex:
_LOG.exception("Send command error %s", ex)
def selector_command(self, event: Any, entity_id: str, cmd_id: str) -> None:
_LOG.debug(
"Selector Command %s",
{
"cmd_id": cmd_id,
"entity_id": entity_id,
"entity_type": "select",
"params": {"option": event.widget.get()},
},
)
if self._worker is None:
_LOG.error("Selector Command undefined worker")
return
try:
asyncio.run_coroutine_threadsafe(
self.send_command(
{
"cmd_id": cmd_id,
"entity_id": entity_id,
"entity_type": "select",
"params": {"option": event.widget.get()},
}
),
self._worker._loop,
)
except Exception as ex:
_LOG.exception("Send command error %s", ex)
async def send_command(self, command: dict[str, Any]):
try:
result = await self._worker.send_command(command)
if (code := result.get("code", None)) and code != 200:
self._info_label["text"] = f"Command failed {code}"
_LOG.error("Command error : %s", result)
self.update()
else:
self._info_label["text"] = f"Command succeeded"
_LOG.debug("Command result : %s", result)
except Exception as ex:
_LOG.exception("Send command error %s", ex)
def on_close(self):
self._events.emit(Events.EXITING)
self.destroy()
self._loop.call_soon_threadsafe(self._loop.stop)
def poll_queue(self):
try:
while True:
action = self._ui_queue.get_nowait()
action()
except Exception: # queue.Empty:
pass
self.after(50, self.poll_queue)
def load_image(self, url: str) -> None:
if self._artwork and (url is None or url == ""):
self._artwork.configure(image="")
return
try:
_LOG.debug("Loading new image from URL: %s", url)
self._photo = load_image_from_url(url)
if self._artwork is None:
self._artwork = ttk.Label(self._right_frame)
self._artwork.pack(anchor="w", side="top", fill="both", expand=True)
self._artwork.configure(image=self._photo)
self.update()
except Exception as e:
self._info_label.text = str(f"Erreur de chargement de l'image : {e}")
def set_title(self, title: str) -> None:
self._title_field["text"] = title
self.update()
def set_artist(self, artist: str) -> None:
self._artist["text"] = artist
self.update()
def set_state(self, state: str) -> None:
self._state["text"] = state
self.update()
def set_volume(self, volume: float) -> None:
self._volume["text"] = volume
self._volume_bar.set(int(volume))
self.update()
def browsing_support(self, value: bool):
self._browsing_support = value
self.update()
def media_search_support(self, value: bool):
self._media_search_support = value
self.update()
async def update_position_task(self):
while True:
await asyncio.sleep(1)
entity = self.media_player_entity
if entity is None:
_LOG.debug("Stopping update position task, no media entity")
self._media_position_task = None
return
attributes = self._worker._attributes.get(entity.get("entity_id"), {})
state = attributes.get("state", "")
if state == "PLAYING":
self._ui_queue.put(lambda: self.update_position())
else:
_LOG.debug("Stopping update position task, media is not playing")
self._media_position_task = None
return
# @debounce(1)
def update_position(self):
entity = self.media_player_entity
if entity is None:
_LOG.debug("Update position : no media entity")
return
attributes = self._worker._attributes.get(entity.get("entity_id"), {})
position = attributes.get("media_position", 0)
duration = attributes.get("media_duration", 0)
state = attributes.get("state", "")
media_position_updated_at = attributes.get("media_position_updated_at", None)
if media_position_updated_at is None:
now = datetime.datetime.now(datetime.timezone.utc)
media_position_updated_at = now.strftime("%Y-%m-%dT%H:%M:%S.%f%z")
attributes["media_position_updated_at"] = media_position_updated_at
if state == "PLAYING":
try:
offset = datetime.datetime.now(datetime.timezone.utc) - datetime.datetime.strptime(
media_position_updated_at, "%Y-%m-%dT%H:%M:%S.%f%z"
)
position += offset.total_seconds()
except Exception as ex:
_LOG.error("Update position error : %s", ex)
# position = self._position
if position < 0:
position = 0
# duration = self._duration
if duration < 0:
duration = 0
self._progress_label["text"] = (
f"{time.strftime('%H:%M:%S', time.gmtime(position))} / {time.strftime('%H:%M:%S', time.gmtime(duration))}"
)
self.update()
if duration <= 0 or duration < position:
self._progress["value"] = 0
else:
self._progress["value"] = abs(int(position * 100 / duration))
self.update()
if state == "PLAYING" and (self._media_position_task is None or self._media_position_task.done()):
self._media_position_task = asyncio.run_coroutine_threadsafe(
self.update_position_task(),
self._worker._loop,
)
def update_input_source(self):
entity_id = self._worker.get_media_player_entity_id()
attributes = self._worker.get_attributes(entity_id)
if attributes is None:
attributes = {}
if self._worker.has_feature(entity_id, "select_source"):
self._input_source.configure(state="normal")
self._input_source["values"] = attributes.get("source_list", [])
self._input_source.set(attributes.get("source", ""))
else:
self._input_source.configure(state="disabled")
self._input_source["values"] = []
def update_sound_mode(self):
entity_id = self._worker.get_media_player_entity_id()
attributes = self._worker.get_attributes(entity_id)
if attributes is None:
attributes = {}
if self._worker.has_feature(entity_id, "sound_mode"):
self._sound_mode.configure(state="normal")
self._sound_mode["values"] = attributes.get("sound_mode_list", [])
self._sound_mode.set(attributes.get("source", ""))
else:
self._sound_mode.configure(state="disabled")
self._sound_mode["values"] = []
def set_position(self, position: int) -> None:
# _LOG.debug("Setting position %s", position)
self._position = position
self.update_position()
def set_duration(self, duration: int) -> None:
# _LOG.debug("Setting duration %s", duration)
self._duration = duration
self.update_position()
def set_sensor(self, entity_id: str, name: str, value: str, state: str) -> None:
# _LOG.debug("Setting sensor %s %s", entity_id, value)
if entity_id not in self._sensors:
label = self._sensors[entity_id] = ttk.Label(self._left_frame, text="")
label.grid(row=self._row, column=0, columnspan=3, sticky="we")
self._row += 1
self._sensors[entity_id] = label
self._sensors[entity_id]["text"] = f"{name}({state}): {value}"
self.update()
def set_selector(self, entity_id: str, name: str, selector: Selector) -> None:
_LOG.debug("Setting selector %s %s", entity_id, selector)
if entity_id not in self._selectors:
label = ttk.Label(self._left_frame, text=f"{name} :", justify="left", anchor="w")
label.grid(row=self._row, column=0, sticky="we")
# self._row += 1