Debian Codegraph @

DisplayCAL/chromecast_pattern_generator.py

raw
1 """Control Chromecast for pattern generation.
2
3 It includes classes to send color patterns, manage connections, and interact
4 with the Chromecast's pattern generator app for use in display calibration
5 workflows.
6 """
7 # 0install: Make sure imported protobuf is from implementation to ensure
8 # correct version
9
10 from __future__ import annotations
11
12 import sys
13 from time import sleep
14 from typing import TextIO
15
16 if not getattr(sys, "frozen", False):
17 import os
18 import re
19
20 for pth in sys.path:
21 if os.path.basename(pth).startswith("protobuf-") and re.match(
22 r"sha\d+(?:new)?", os.path.basename(os.path.dirname(pth))
23 ):
24 if "google" in sys.modules:
25 del sys.modules["google"]
26 syspath = sys.path[:]
27 sys.path[:] = [pth]
28
29 sys.path[:] = syspath
30 break
31
32 from pychromecast import get_chromecasts
33 from pychromecast.controllers import BaseController
34
35 from DisplayCAL import localization as lang
36
37
38 class ChromeCastPatternGeneratorController(BaseController):
39 """Controller for the Chromecast pattern generator app."""
40
41 def __init__(self) -> None:
42 super().__init__("urn:x-cast:net.hoech.cast.patterngenerator", "B5C2CBFC")
43 self.request_id = 0
44
45 def receive_message(self, message: dict, data: dict) -> bool:
46 """Handle incoming messages from the Chromecast device.
47
48 Args:
49 message (dict): The message received from the Chromecast.
50 data (dict): Additional data associated with the message.
51
52 Returns:
53 bool: True if the message was handled, False otherwise.
54 """
55 return True # Indicate we handled this message
56
57 def send(
58 self,
59 rgb: tuple[float, float, float] = (0, 0, 0),
60 bgrgb: tuple[float, float, float] = (0, 0, 0),
61 offset_x: float = 0.5,
62 offset_y: float = 0.5,
63 h_scale: float = 1,
64 v_scale: float = 1,
65 ) -> None:
66 """Send a color pattern to the Chromecast device.
67
68 Args:
69 rgb (tuple): RGB color values (0-1 range).
70 bgrgb (tuple): Background RGB color values (0-1 range).
71 offset_x (float): Horizontal offset (0-1 range).
72 offset_y (float): Vertical offset (0-1 range).
73 h_scale (float): Horizontal scale factor.
74 v_scale (float): Vertical scale factor.
75 """
76 fg = "#{:02X}{:02X}{:02X}".format(*tuple(round(v * 255) for v in rgb))
77 bg = "#{:02X}{:02X}{:02X}".format(*tuple(round(v * 255) for v in bgrgb))
78 self.request_id += 1
79 self.send_message(
80 {
81 "requestId": self.request_id,
82 "foreground": fg,
83 "offset": [offset_x, offset_y],
84 "scale": [h_scale, v_scale],
85 "background": bg,
86 }
87 )
88
89
90 class ChromeCastPatternGenerator:
91 """Class to control a Chromecast device for pattern generation.
92
93 Args:
94 name (str): The friendly name of the Chromecast device.
95 logfile (file-like object, optional): A file-like object to log messages.
96 """
97
98 def __init__(self, name: str, logfile: None | TextIO = None) -> None:
99 self._controller = ChromeCastPatternGeneratorController()
100 self.name = name
101 self.listening = False
102 self.logfile = logfile
103
104 def disconnect_client(self) -> None:
105 """Disconnect the Chromecast client and clean up resources."""
106 self.listening = False
107 if hasattr(self, "_cc") and self._cc.app_id:
108 self._cc.quit_app()
109 if hasattr(self, "conn"):
110 del self.conn
111
112 def send(
113 self,
114 rgb: tuple[float, float, float] = (0, 0, 0),
115 bgrgb: tuple[float, float, float] = (0, 0, 0),
116 bits: None | int = None,
117 use_video_levels: None | bool = None,
118 x: float = 0,
119 y: float = 0,
120 w: float = 1,
121 h: float = 1,
122 ) -> None:
123 """Send a color pattern to the Chromecast device.
124
125 Args:
126 rgb (tuple): RGB color values (0-1 range).
127 bgrgb (tuple): Background RGB color values (0-1 range).
128 bits (int, optional): Not used in this implementation.
129 use_video_levels (bool, optional): Not used in this implementation.
130 x (float): Horizontal offset (0-1 range).
131 y (float): Vertical offset (0-1 range).
132 w (float): Width of the pattern (0-1 range).
133 h (float): Height of the pattern (0-1 range).
134 """
135 if w < 1:
136 x /= 1.0 - w
137 else:
138 x = 0
139 if h < 1:
140 y /= 1.0 - h
141 else:
142 y = 0
143 self._controller.send(rgb, bgrgb, x, y, w * 10, h * 10)
144
145 def wait(self) -> None:
146 """Wait for Chromecast to be ready and launch the pattern generator app."""
147 self.listening = True
148 if self.logfile:
149 self.logfile.write(
150 lang.getstr("connecting.to", ("Chromecast", " " + self.name)) + "\n"
151 )
152 if not hasattr(self, "_cc"):
153 # Find our ChromeCast
154 try:
155 self._cc = next(
156 cc
157 for cc in get_chromecasts()
158 if str(cc.device.friendly_name) == self.name
159 )
160 except StopIteration:
161 self.listening = False
162 raise
163 self._cc.register_handler(self._controller)
164 # Wait for ChromeCast device to be ready
165 while self.listening:
166 self._cc.wait(0.05)
167 if self._cc.status:
168 break
169 if self.listening:
170 # Launch pattern generator app
171 self._controller.launch()
172 # Wait for it
173 while (
174 self.listening and self._cc.app_id != self._controller.supporting_app_id
175 ):
176 sleep(0.05)
177 self.conn = True
178 print(lang.getstr("connection.established"))
179
180
181 if __name__ == "__main__":
182 from DisplayCAL import config
183
184 config.initcfg()
185 lang.init()
186
187 pg = ChromeCastPatternGenerator("Smörebröd")
188
189 # Find our ChromeCast and connect to it, then launch the pattern generator
190 # app on the ChromeCast device
191 pg.wait()
192
193 # Display test color (yellow window on blue background)
194 pg.send((1, 1, 0), (0, 0, 1), x=0.375, y=0.375, w=0.25, h=0.25)