Debian Codegraph @

DisplayCAL/patterngenerators.py

raw
1 """Pattern generator clients and servers for HTTP and TCP devices.
2
3 It supports sending RGB patterns, managing connections, and handling events for
4 various pattern generator devices.
5 """
6
7 from __future__ import annotations
8
9 import contextlib
10 import errno
11 import http.client
12 import json
13 import select
14 import struct
15 import sys
16 import threading
17 import urllib.parse
18 from socket import (
19 AF_INET,
20 SHUT_RDWR,
21 SO_BROADCAST,
22 SO_REUSEADDR,
23 SOCK_DGRAM,
24 SOCK_STREAM,
25 SOL_SOCKET,
26 gethostbyname,
27 gethostname,
28 socket,
29 timeout,
30 )
31 from socketserver import TCPServer, ThreadingMixIn
32 from time import sleep
33 from typing import TYPE_CHECKING, Any, Callable, TextIO
34
35 from DisplayCAL import localization as lang
36 from DisplayCAL import webwin
37 from DisplayCAL.network import get_network_addr
38 from DisplayCAL.util_http import encode_multipart_formdata
39
40 if TYPE_CHECKING:
41 from http.client import HTTPResponse
42 from urllib.request import Request
43
44
45 _lock = threading.RLock()
46
47
48 PRISMA_DEFAULT_PORT = 80
49 RESOLVE_LS_DEFAULT_BITS = 8
50 RESOLVE_DEFAULT_PORT = 20002
51 RESOLVE_DEFAULT_BITS = 10
52
53
54 def _eintr_retry(func: Callable, *args) -> Any: # noqa: ANN401
55 """Restart a system call interrupted by EINTR.
56
57 Args:
58 func (Callable): The function to call.
59 *args: Arguments to pass to the function.
60
61 Returns:
62 Any: The result of the function call.
63 """
64 while True:
65 try:
66 return func(*args)
67 except OSError as e:
68 if e.args[0] != errno.EINTR:
69 raise
70
71
72 def _shutdown(sock: socket, addr: str) -> None:
73 """Shutdown and close a socket.
74
75 Args:
76 sock (socket): The socket to shut down and close.
77 addr (str): The address associated with the socket, for logging.
78 """
79 try:
80 # Will fail if the socket isn't connected, i.e. if there
81 # was an error during the call to connect()
82 sock.shutdown(SHUT_RDWR)
83 except OSError as exception:
84 if exception.errno != errno.ENOTCONN:
85 print(f"PatternGenerator: SHUT_RDWR for {addr[:2]}:{exception} failed:")
86 sock.close()
87
88
89 class GenHTTPPatternGeneratorClient:
90 """Generic pattern generator client using HTTP REST interface.
91
92 Args:
93 host (str): The hostname or IP address of the pattern generator server.
94 port (int): The port number to connect to.
95 bits (int): Number of bits per channel.
96 use_video_levels (bool, optional): Use video levels for RGB values.
97 Defaults to False.
98 logfile (None | TextIO, optional): A file-like object to log messages.
99 Defaults to None.
100 """
101
102 def __init__(
103 self,
104 host: str,
105 port: int,
106 bits: int,
107 use_video_levels: bool = False,
108 logfile: None | TextIO = None,
109 ) -> None:
110 self.host = host
111 self.port = port
112 self.bits = bits
113 self.use_video_levels = use_video_levels
114 self.logfile = logfile
115
116 def wait(self) -> None:
117 """Wait for the pattern generator server to be available."""
118 self.connect()
119
120 def __del__(self) -> None:
121 """Clean up the connection and socket."""
122 self.disconnect_client()
123
124 def _request(
125 self,
126 method: str,
127 url: str,
128 params: None | bytes | str = None,
129 headers: None | dict = None,
130 validate: None | str | dict = None,
131 ) -> str | dict:
132 """Make an HTTP request to the pattern generator server.
133
134 Args:
135 method (str): The HTTP method to use (e.g., 'GET', 'POST').
136 url (str): The URL to request.
137 params (None | bytes | str, optional): The request body for POST
138 requests. Defaults to None.
139 headers (None | dict, optional): Additional headers to include in
140 the request. Defaults to None.
141 validate (None | str | dict, optional): Expected response format or
142 value. Defaults to None.
143
144 Returns:
145 str | dict: The response from the server, validated against the
146 expected format or value.
147 """
148 try:
149 self.conn.request(method, url, params, headers or {})
150 resp = self.conn.getresponse()
151 except (OSError, http.client.HTTPException) as exception:
152 # TODO: What is the point of having the except clause here?
153 raise exception
154 else:
155 if resp.status == http.client.OK:
156 return self._validate(resp, url, validate)
157 raise http.client.HTTPException(f"{resp.status} {resp.reason}")
158
159 def _shutdown(self) -> None:
160 """Shutdown the pattern generator device connection."""
161 # Override this method in subclass!
162
163 def _validate(self, resp: HTTPResponse, url: str, validate: str | dict) -> None:
164 """Validate the response from the server.
165
166 Args:
167 resp (HTTPResponse): The HTTP response object.
168 url (str): The URL that was requested.
169 validate (str | dict): The expected response format or value.
170 """
171 # Override this method in subclass!
172
173 def connect(self) -> None:
174 """Connect to the pattern generator server."""
175 self.ip = gethostbyname(self.host)
176 self.conn = http.client.HTTPConnection(self.ip, self.port)
177 try:
178 self.conn.connect()
179 except (OSError, http.client.HTTPException):
180 del self.conn
181 raise
182
183 def disconnect_client(self) -> None:
184 """Disconnect the current client and clean up resources."""
185 self.listening = False
186 if hasattr(self, "conn"):
187 self._shutdown()
188 self.conn.close()
189 del self.conn
190
191 def send(
192 self,
193 rgb: tuple[float, float, float] = (0, 0, 0),
194 bgrgb: tuple[float, float, float] = (0, 0, 0),
195 bits: None | int = None,
196 use_video_levels: None | bool = None,
197 x: float = 0,
198 y: float = 0,
199 w: float = 1,
200 h: float = 1,
201 ) -> None:
202 """Send an RGB color to the pattern generator.
203
204 Args:
205 rgb (tuple[float, float, float], optional): RGB color values in the
206 range 0..1. Defaults to (0, 0, 0).
207 bgrgb (tuple[float, float, float], optional): Background RGB color
208 values in the range 0..1. Defaults to (0, 0, 0).
209 bits (None | int, optional): Number of bits per channel. Defaults
210 to None.
211 use_video_levels (None | bool, optional): Use video levels for RGB
212 values. Defaults to None.
213 x (float, optional): X position of the rectangle. Defaults to 0.
214 y (float, optional): Y position of the rectangle. Defaults to 0.
215 w (float, optional): Width of the rectangle. Defaults to 1.
216 h (float, optional): Height of the rectangle. Defaults to 1.
217 """
218 rgb, bgrgb, bits = self._get_rgb(rgb, bgrgb, bits, use_video_levels)
219 # Override this method in subclass!
220 # raise NotImplementedError
221
222
223 class GenTCPSockPatternGeneratorServer:
224 """Generic pattern generator server using TCP sockets.
225
226 Args:
227 port (int): The port number to listen on.
228 bits (int): Number of bits per channel.
229 use_video_levels (bool, optional): Use video levels for RGB values.
230 Defaults to False.
231 logfile (None | TextIO, optional): A file-like object to log messages.
232 Defaults to None.
233 """
234
235 def __init__(
236 self,
237 port: int,
238 bits: int,
239 use_video_levels: bool = False,
240 logfile: None | TextIO = None,
241 ) -> None:
242 self.port = port
243 self.bits = bits
244 self.use_video_levels = use_video_levels
245 self.socket = socket(AF_INET, SOCK_STREAM)
246 self.socket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
247 self.socket.settimeout(1)
248 self.socket.bind(("", port))
249 self.socket.listen(1)
250 self.listening = False
251 self.logfile = logfile
252
253 def wait(self) -> None:
254 """Wait for a client to connect."""
255 self.listening = True
256 if self.logfile:
257 try:
258 host = get_network_addr()
259 except OSError:
260 host = gethostname()
261 self.logfile.write(
262 "{} {}:{}\n".format(lang.getstr("connection.waiting"), host, self.port)
263 )
264 while self.listening:
265 try:
266 self.conn, addr = self.socket.accept()
267 except timeout:
268 continue
269 self.conn.settimeout(1)
270 break
271 if self.listening:
272 print(lang.getstr("connection.established"))
273
274 def __del__(self) -> None:
275 """Clean up the connection and socket."""
276 self.disconnect_client()
277 self.socket.close()
278
279 def _get_rgb(
280 self,
281 rgb: tuple[float, float, float],
282 bgrgb: tuple[float, float, float],
283 bits: None | int = None,
284 use_video_levels: None | bool = None,
285 ) -> tuple[int, int, int]:
286 """The RGB range should be 0..1.
287
288 Args:
289 rgb (tuple[float, float, float]): RGB color values in the range
290 0..1.
291 bgrgb (tuple[float, float, float]): Background RGB color values in
292 the range 0..1.
293 bits (int, optional): Number of bits per channel. Defaults to None.
294 use_video_levels (bool, optional): Use video levels for RGB values.
295 Defaults to None.
296
297 Returns:
298 tuple[int, int, int]: A tuple containing the RGB and BGRGB values
299 encoded for the TCP socket interface, and the number of bits
300 per channel.
301 """
302 if not bits:
303 bits = self.bits
304 if use_video_levels is None:
305 use_video_levels = self.use_video_levels
306 bitv = 2**bits - 1
307 if use_video_levels:
308 minv = 16.0 / 255.0
309 maxv = 235.0 / 255.0 - minv
310 if bits > 8:
311 # For video encoding the extra bits of precision are created by
312 # bit shifting rather than scaling, so we need to scale the fp
313 # value to account for this.
314 minv = (minv * 255.0 * (1 << (bits - 8))) / bitv
315 maxv = (maxv * 255.0 * (1 << (bits - 8))) / bitv
316 else:
317 minv = 0.0
318 maxv = 1.0
319 rgb = [round(minv * bitv + v * bitv * maxv) for v in rgb]
320 bgrgb = [round(minv * bitv + v * bitv * maxv) for v in bgrgb]
321 return rgb, bgrgb, bits
322
323 def disconnect_client(self) -> None:
324 """Disconnect the current client and clean up resources."""
325 self.listening = False
326 if hasattr(self, "conn"):
327 try:
328 self.conn.shutdown(SHUT_RDWR)
329 except OSError as exception:
330 if exception.errno != errno.ENOTCONN:
331 print(
332 "Warning - could not shutdown pattern generator connection:",
333 exception,
334 )
335 self.conn.close()
336 del self.conn
337
338 def send(
339 self,
340 rgb: tuple[float, float, float] = (0, 0, 0),
341 bgrgb: tuple[float, float, float] = (0, 0, 0),
342 use_video_levels: None | bool = None,
343 x: float = 0,
344 y: float = 0,
345 w: float = 1,
346 h: float = 1,
347 ) -> None:
348 """Send an RGB color to the pattern generator.
349
350 Args:
351 rgb (tuple, optional): RGB color values in the range 0..1. Defaults
352 to (0, 0, 0).
353 bgrgb (tuple, optional): Background RGB color values in the range
354 0..1. Defaults to (0, 0, 0).
355 use_video_levels (None | bool, optional): Use video levels for RGB
356 values. Defaults to None.
357 x (float, optional): X position of the rectangle. Defaults to 0.
358 y (float, optional): Y position of the rectangle. Defaults to 0.
359 w (float, optional): Width of the rectangle. Defaults to 1.
360 h (float, optional): Height of the rectangle. Defaults to 1.
361 """
362 for server, bits in (
363 (ResolveLSPatternGeneratorServer, 8),
364 (ResolveCMPatternGeneratorServer, 10),
365 ):
366 server.__dict__["send"](
367 self, rgb, bgrgb, bits, use_video_levels, x, y, w, h
368 )
369
370
371 class PrismaPatternGeneratorClient(GenHTTPPatternGeneratorClient):
372 """Prisma HTTP REST interface.
373
374 Args:
375 host (str): The hostname or IP address of the Prisma device.
376 port (int, optional): The port number to connect to. Defaults to 80.
377 use_video_levels (bool, optional): Use video levels for RGB values.
378 Defaults to False.
379 logfile (file-like object, optional): A file-like object to log
380 messages. Defaults to None.
381 """
382
383 def __init__(
384 self,
385 host: str,
386 port: int = PRISMA_DEFAULT_PORT,
387 use_video_levels: bool = False,
388 logfile: None | TextIO = None,
389 ) -> None:
390 GenHTTPPatternGeneratorClient.__init__(
391 self, host, port, 8, use_video_levels=use_video_levels, logfile=logfile
392 )
393 self.prod_prisma = 2
394 self.oem_qinc = 1024
395 self.prod_oem = struct.pack("<I", self.prod_prisma) + struct.pack(
396 "<I", self.oem_qinc
397 )
398 # UDP discovery of Prisma devices in local network
399 self._cast_sockets = {}
400 self._threads = []
401 self.broadcast_request_port = 7737
402 self.broadcast_response_port = 7747
403 self.debug = 0
404 self.listening = False
405 self._event_handlers = {"on_client_added": []}
406 self.broadcast_ip = "255.255.255.255"
407 self.prismas = {}
408 self._size = 10
409 self._enable_processing = True
410
411 def listen(self) -> None:
412 """Start listening for Prisma devices on the local network."""
413 self.listening = True
414 port = self.broadcast_response_port
415 if (self.broadcast_ip, port) in self._cast_sockets:
416 return
417 sock = socket(AF_INET, SOCK_DGRAM)
418 sock.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
419 sock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
420 sock.settimeout(0)
421 try:
422 sock.bind(("", port))
423 thread = threading.Thread(
424 target=self._cast_receive_handler,
425 name=(
426 "PrismaPatternGeneratorClient.BroadcastHandler["
427 f"{self.broadcast_ip}:{port}]"
428 ),
429 args=(sock, self.broadcast_ip, port),
430 )
431 self._threads.append(thread)
432 thread.start()
433 except OSError as exception:
434 print(f"PrismaPatternGeneratorClient: UDP Port {port:d}: {exception:s}")
435
436 def _cast_receive_handler(self, sock: socket, host: str, port: int) -> None:
437 """Receive broadcast messages from Prisma devices.
438
439 Args:
440 sock (socket): The UDP socket to listen on.
441 host (str): The host IP address.
442 port (int): The port number to listen on.
443 """
444 cast = "broadcast"
445 if self.debug:
446 print(
447 "PrismaPatternGeneratorClient: Entering receiver thread for "
448 f"{cast:s} port {port:d}"
449 )
450 self._cast_sockets[(host, port)] = sock
451 while getattr(self, "listening", False):
452 try:
453 data, addr = sock.recvfrom(4096)
454 except timeout as exception:
455 print(
456 "PrismaPatternGeneratorClient: In receiver thread for "
457 f"{cast:s} port {port:d}:",
458 exception,
459 )
460 continue
461 except OSError as exception:
462 if exception.errno == errno.EWOULDBLOCK:
463 sleep(0.05)
464 continue
465 if exception.errno != errno.ECONNRESET or self.debug:
466 print(
467 "PrismaPatternGeneratorClient: In receiver thread for "
468 f"{cast:s} port {port:d}:",
469 exception,
470 )
471 break
472 else:
473 with _lock:
474 if self.debug:
475 print(
476 "PrismaPatternGeneratorClient: Received "
477 f"{cast} from {addr[0]}:{addr[1]}: {data}"
478 )
479 if data.startswith(self.prod_oem):
480 name = data[8:32].rstrip(b"\0")
481 serial = data[32:].rstrip(b"\0")
482 self.prismas[addr[0]] = {"serial": serial, "name": name}
483 self._dispatch_event(
484 "on_client_added", (addr, self.prismas[addr[0]])
485 )
486 self._cast_sockets.pop((host, port))
487 _shutdown(sock, (host, port))
488 if self.debug:
489 print(
490 f"PrismaPatternGeneratorClient: Exiting {cast:s} "
491 f"receiver thread for port {port:d}"
492 )
493
494 def announce(self) -> None:
495 """Anounce ourselves."""
496 port = self.broadcast_request_port
497 sock = socket(AF_INET, SOCK_DGRAM)
498 sock.setsockopt(SOL_SOCKET, SO_BROADCAST, 1)
499 sock.settimeout(1)
500 sock.connect((self.broadcast_ip, port))
501 addr = sock.getsockname()
502 if self.debug:
503 print(
504 "PrismaPatternGeneratorClient: Sending broadcast from "
505 f"{addr[0]}:{addr[1]} to port {port:d}"
506 )
507 sock.sendall(self.prod_oem)
508 sock.close()
509
510 def bind(self, event_name: str, handler: Callable) -> None:
511 """Bind a handler to an event.
512
513 Args:
514 event_name (str): The name of the event to bind to.
515 handler (Callable): The handler to bind to the event.
516 """
517 if event_name not in self._event_handlers:
518 self._event_handlers[event_name] = []
519 self._event_handlers[event_name].append(handler)
520
521 def unbind(
522 self, event_name: str, handler: None | Callable = None
523 ) -> None | Callable:
524 """Unbind (remove) a handler from an event.
525
526 If handler is None, remove all handlers for the event.
527
528 Args:
529 event_name (str): The name of the event to unbind from.
530 handler (None | Callable, optional): The handler to remove. If
531 None, remove all handlers for the event. Defaults to None.
532
533 Returns:
534 None | Callable: The removed handler if it was found, or None if no
535 handler was found for the event.
536 """
537 if event_name not in self._event_handlers:
538 return None
539
540 if handler in self._event_handlers[event_name]:
541 self._event_handlers[event_name].remove(handler)
542 return handler
543
544 return self._event_handlers.pop(event_name)
545
546 def _dispatch_event(self, event_name: str, event_data: None | Any = None) -> None: # noqa: ANN401
547 """Dispatch events.
548
549 Args:
550 event_name (str): The name of the event to dispatch.
551 event_data (any, optional): Data associated with the event.
552 Defaults to None.
553 """
554 if self.debug:
555 print("PrismaPatternGeneratorClient: Dispatching", event_name)
556 for handler in self._event_handlers.get(event_name, []):
557 handler(event_data)
558
559 def _get_rgb(
560 self,
561 rgb: tuple[float, float, float],
562 bgrgb: tuple[float, float, float],
563 bits: int = 8,
564 use_video_levels: None | bool = None,
565 ) -> tuple[int, int, int]:
566 """The RGB range should be 0..1.
567
568 Args:
569 rgb (tuple[float, float, float]): RGB color values in the range
570 0..1.
571 bgrgb (tuple[float, float, float]): Background RGB color values in
572 the range 0..1.
573 bits (int, optional): Number of bits per channel. Defaults to 8.
574 use_video_levels (bool, optional): Use video levels for RGB values.
575 Defaults to None.
576
577 Returns:
578 tuple[int, int, int]: A tuple containing the RGB and BGRGB values
579 encoded for the Prisma HTTP REST interface, and the number of
580 bits per channel.
581 """
582 rgb, bgrgb, bits = GenTCPSockPatternGeneratorServer._get_rgb(
583 self, rgb, bgrgb, 8, use_video_levels
584 )
585 # Encode RGB values for Prisma HTTP REST interface
586 # See prisma-sdk/prisma.cpp, PrismaIo::wincolor
587 rgb = [round(v) for v in rgb]
588 bgrgb = [round(v) for v in bgrgb]
589 rgb = (rgb[0] & 0xFF) << 16 | (rgb[1] & 0xFF) << 8 | (rgb[2] & 0xFF) << 0
590 bgrgb = (
591 (bgrgb[0] & 0xFF) << 16 | (bgrgb[1] & 0xFF) << 8 | (bgrgb[2] & 0xFF) << 0
592 )
593 return rgb, bgrgb, bits
594
595 def invoke(
596 self,
597 api: str,
598 method: None | str = None,
599 params: None | dict = None,
600 validate: None | str | dict = None,
601 ) -> str | dict:
602 """Invoke a method on the Prisma device.
603
604 Args:
605 api (str): The API endpoint to call.
606 method (None | str, optional): The method to invoke. Defaults to
607 None.
608 params (None | dict, optional): Parameters to pass to the method.
609 Defaults to None.
610 validate (None | str | dict, optional): Expected response format or
611 value.
612
613 Returns:
614 str | dict: The response from the server, validated against the
615 expected format or value.
616 """
617 url = "/" + api
618 if method:
619 url += "?m=" + method
620 if params:
621 url += "&" + urllib.parse.unquote_plus(urllib.parse.urlencode(params))
622 if not validate:
623 validate = {method: "Ok"}
624 return self._request("GET", url, validate=validate)
625
626 def _shutdown(self) -> None:
627 """Shutdown the Prisma device connection."""
628 with contextlib.suppress(Exception):
629 self.invoke("window", "off", {"sz": 10})
630
631 def _validate(
632 self, resp: HTTPResponse, url: str, validate: str | dict
633 ) -> str | dict:
634 """Validate the response from the server.
635
636 Args:
637 resp (HTTPResponse): The HTTP response object.
638 url (str): The URL that was requested.
639 validate (str | dict): The expected response format or value.
640
641 Raises:
642 http.client.HTTPException: If the response does not match the
643 expected format or value.
644
645 Returns:
646 str | dict: The validated response data, either as a dictionary or
647 raw string.
648 """
649 raw = resp.read()
650 if isinstance(validate, dict):
651 data = json.loads(raw)
652 components = urllib.parse.urlparse(url)
653 # api = components.path[1:]
654 query = urllib.parse.parse_qs(components.query)
655 if b"m" in query:
656 method = query[b"m"][0]
657 if data.get(method) == "Error" and "msg" in data:
658 raise http.client.HTTPException(f"{self.host}: {data['msg']}")
659 for key in validate:
660 value = validate[key]
661 if key not in data:
662 raise http.client.HTTPException(
663 lang.getstr(
664 "response.invalid.missing_key", (self.host, key, raw)
665 )
666 )
667 if value is not None and data[key] != value:
668 raise http.client.HTTPException(
669 lang.getstr(
670 "response.invalid.value", (self.host, key, value, raw)
671 )
672 )
673 data["raw"] = raw
674 return data
675 if validate and raw != validate:
676 raise http.client.HTTPException(
677 lang.getstr("response.invalid", (self.host, raw))
678 )
679 return raw
680
681 def disable_processing(self, size: int = 10) -> None:
682 """Disable processing on the Prisma device.
683
684 Args:
685 size (int, optional): The size of the window to set. Defaults to
686 10.
687 """
688 self.enable_processing(False, size)
689
690 def enable_processing(self, enable: bool = True, size: int = 10) -> None:
691 """Enable or disable processing on the Prisma device.
692
693 Args:
694 enable (bool, optional): If True, processing is enabled; if False,
695 it is disabled. Defaults to True.
696 size (int, optional): The size of the window to set. Defaults to
697 10.
698 """
699 win = 1 if enable else 2
700 self.invoke("Window", f"win{win}", {"sz": size})
701
702 def get_config(self) -> dict:
703 """Get the current configuration of the Prisma device.
704
705 Returns:
706 dict: A dictionary containing the current configuration settings.
707 """
708 return self.invoke("Prisma", "settings", validate={"v": None, "settings": "Ok"})
709
710 def get_installed_3dluts(self) -> dict:
711 """Get a list of installed 3D LUTs.
712
713 Returns:
714 dict: A dictionary containing the list of installed 3D LUTs.
715 """
716 return self.invoke("Cube", "list", validate={"list": "Ok", "v": None})
717
718 def load_preset(self, presetname: str) -> None:
719 """Load a preset by name.
720
721 Args:
722 presetname (str): The name of the preset to load.
723 """
724 return self.invoke(
725 "Prisma", "loadPreset", {"n": presetname}, validate={"v": None}
726 )
727
728 def load_3dlut_file(self, path: str, filename: str) -> None:
729 """Load a 3D LUT file.
730
731 Args:
732 path (str): The path to the 3D LUT file.
733 filename (str): The name of the 3D LUT file to upload.
734 """
735 with open(path, "rb") as lut3d:
736 data = lut3d.read()
737 files = [("cubeFile", filename, data)]
738 content_type, params = encode_multipart_formdata([], files)
739 headers = {"Content-Type": content_type, "Content-Length": str(len(params))}
740 # Upload 3D LUT
741 self._request("POST", "/fwupload", params, headers)
742
743 def remove_3dlut(self, filename: str) -> None:
744 """Remove a 3D LUT by name.
745
746 Args:
747 filename (str): The name of the 3D LUT file to remove.
748 """
749 self.invoke("Cube", "remove", {"n": filename})
750
751 def set_3dlut(self, filename: str) -> None:
752 """Set the 3D LUT by name.
753
754 Args:
755 filename (str): The name of the 3D LUT file to set.
756 """
757 # Select 3D LUT
758 self.invoke("Prisma", "setCube", {"n": filename, "f": "null"})
759
760 def set_prismavue(self, value: str) -> None:
761 """Set the PrismaVue mode.
762
763 Args:
764 value (str): The PrismaVue mode to set. Can be "on", "off", or
765 "null".
766 """
767 self.invoke("Prisma", "setPrismaVue", {"a": value, "t": "null"})
768
769 def send(
770 self,
771 rgb: tuple[float, float, float] = (0, 0, 0),
772 bgrgb: tuple[float, float, float] = (0, 0, 0),
773 bits: None | int = None,
774 use_video_levels: None | bool = None,
775 x: float = 0,
776 y: float = 0,
777 w: float = 1,
778 h: float = 1,
779 ) -> None:
780 """Send an RGB color to the pattern generator.
781
782 The RGB range should be 0..1.
783
784 Args:
785 rgb (tuple[float, float, float], optional): RGB color values in the
786 range 0..1.
787 bgrgb (tuple[float, float, float], optional): Background RGB color
788 values in the range 0..1.
789 bits (None | int, optional): Number of bits per channel. Defaults
790 to None.
791 use_video_levels (None | bool, optional): Use video levels for RGB
792 values. Defaults to None.
793 x (float, optional): X position of the rectangle. Defaults to 0.
794 y (float, optional): Y position of the rectangle. Defaults to 0.
795 w (float, optional): Width of the rectangle. Defaults to 1.
796 h (float, optional): Height of the rectangle. Defaults to 1.
797 """
798 rgb, bgrgb, bits = self._get_rgb(rgb, bgrgb, bits, use_video_levels)
799 self.invoke("Window", "color", {"bg": bgrgb, "fg": rgb})
800 size = (w + h) / 2.0 * 100
801 if size != self._size:
802 self._size = size
803 self.enable_processing(self._enable_processing, size)
804
805
806 class ResolveLSPatternGeneratorServer(GenTCPSockPatternGeneratorServer):
807 """Resolve LS pattern generator server using TCP sockets.
808
809 Args:
810 port (int): The port number to listen on. Defaults to 20002.
811 bits (int): Number of bits per channel. Defaults to 8.
812 use_video_levels (bool): Use video levels for RGB values. Defaults to
813 False.
814 logfile (None | TextIO, optional): A file-like object to log messages.
815 Defaults to None.
816 """
817
818 def __init__(
819 self,
820 port: int = RESOLVE_DEFAULT_PORT,
821 bits: int = RESOLVE_LS_DEFAULT_BITS,
822 use_video_levels: bool = False,
823 logfile: None | TextIO = None,
824 ) -> None:
825 GenTCPSockPatternGeneratorServer.__init__(
826 self, port, bits, use_video_levels, logfile
827 )
828
829 def send(
830 self,
831 rgb: tuple[float, float, float] = (0, 0, 0),
832 bgrgb: tuple[float, float, float] = (0, 0, 0),
833 bits: None | int = None,
834 use_video_levels: None | bool = None,
835 x: float = 0,
836 y: float = 0,
837 w: float = 1,
838 h: float = 1,
839 ) -> None:
840 """Send an RGB color to the pattern generator.
841
842 The RGB range should be 0..1.
843
844 Args:
845 rgb (tuple, optional): RGB color values in the range 0..1.
846 bgrgb (tuple, optional): Background RGB color values in the range 0..1.
847 bits (None | int, optional): Number of bits per channel. Defaults
848 to None.
849 use_video_levels (None | bool, optional): Use video levels for RGB
850 values. Defaults to None.
851 x (float, optional): X position of the rectangle. Defaults to 0.
852 y (float, optional): Y position of the rectangle. Defaults to 0.
853 w (float, optional): Width of the rectangle. Defaults to 1.
854 h (float, optional): Height of the rectangle. Defaults to 1.
855 """
856 rgb, bgrgb, bits = self._get_rgb(rgb, bgrgb, bits, use_video_levels)
857 xml = (
858 '<?xml version="1.0" encoding="UTF-8" ?><calibration><shapes>'
859 "<rectangle>"
860 f'<color red="{rgb[0]:d}" green="{rgb[1]:d}" blue="{rgb[2]:d}" />'
861 f'<geometry x="{x:.4f}" y="{y:.4f}" cx="{w:.4f}" cy="{h:.4f}" />'
862 "</rectangle>"
863 "</shapes></calibration>"
864 )
865 self.conn.sendall(struct.pack(">I", len(xml)) + xml.encode("utf-8"))
866
867
868 class ResolveCMPatternGeneratorServer(GenTCPSockPatternGeneratorServer):
869 """Resolve Colorimeter pattern generator server using TCP sockets.
870
871 Args:
872 port (int, optional): The port number to listen on. Defaults to 20002.
873 bits (int, optional): Number of bits per channel. Defaults to 10.
874 use_video_levels (bool, optional): Use video levels for RGB values.
875 Defaults to False.
876 logfile (None | TextIO, optional): A file-like object to log messages.
877 Defaults to None.
878 """
879
880 def __init__(
881 self,
882 port: int = RESOLVE_DEFAULT_PORT,
883 bits: int = RESOLVE_DEFAULT_BITS,
884 use_video_levels: bool = False,
885 logfile: None | TextIO = None,
886 ) -> None:
887 GenTCPSockPatternGeneratorServer.__init__(
888 self, port, bits, use_video_levels, logfile
889 )
890
891 def send(
892 self,
893 rgb: tuple[float, float, float] = (0, 0, 0),
894 bgrgb: tuple[float, float, float] = (0, 0, 0),
895 bits: None | int = None,
896 use_video_levels: None | bool = None,
897 x: float = 0,
898 y: float = 0,
899 w: float = 1,
900 h: float = 1,
901 ) -> None:
902 """Send an RGB color to the pattern generator.
903
904 The RGB range should be 0..1.
905
906 Args:
907 rgb (tuple, optional): RGB color values in the range 0..1.
908 bgrgb (tuple, optional): Background RGB color values in the range
909 0..1.
910 bits (None | int, optional): Number of bits per channel. Defaults
911 to None.
912 use_video_levels (None | bool, optional): Use video levels for RGB
913 values. Defaults to None.
914 x (float, optional): X position of the rectangle. Defaults to 0.
915 y (float, optional): Y position of the rectangle. Defaults to 0.
916 w (float, optional): Width of the rectangle. Defaults to 1.
917 h (float, optional): Height of the rectangle. Defaults to 1.
918 """
919 rgb, bgrgb, bits = self._get_rgb(rgb, bgrgb, bits, use_video_levels)
920 xml = (
921 '<?xml version="1.0" encoding="utf-8"?><calibration>'
922 f'<color red="{rgb[0]:d}" green="{rgb[1]:d}" '
923 f'blue="{rgb[2]:d}" bits="{bits:d}"/>'
924 f'<background red="{bgrgb[0]:d}" green="{bgrgb[1]:d}" '
925 f'blue="{bgrgb[2]:d}" bits="{bits:d}"/>'
926 f'<geometry x="{x:.4f}" y="{y:.4f}" cx="{w:.4f}" cy="{h:.4f}"/>'
927 "</calibration>"
928 )
929 self.conn.sendall(struct.pack(">I", len(xml)) + xml.encode("utf-8"))
930
931
932 class WebWinHTTPPatternGeneratorServer(ThreadingMixIn, TCPServer):
933 """WebWin pattern generator server using HTTP REST interface.
934
935 Args:
936 port (int): The port number to listen on.
937 logfile (None | TextIO, optional): A file-like object to log messages.
938 Defaults to None.
939 """
940
941 def __init__(self, port: int, logfile: None | TextIO = None) -> None:
942 # Handle each HTTP client request in its own thread so multiple
943 # remote browser devices can stay connected simultaneously.
944 self.daemon_threads = True
945 self.block_on_close = False
946 self.port = port
947 TCPServer.__init__(self, ("", port), webwin.WebWinHTTPRequestHandler)
948 self.timeout = 1
949 self.patterngenerator = self
950 self._listening = threading.Event()
951 self._pattern_lock = threading.Lock()
952 self._pattern_changed = threading.Condition(self._pattern_lock)
953 self._pattern_seq = 0
954 self.logfile = logfile
955 self.pattern = "#808080|#808080|0|0|1|1"
956
957 def disconnect_client(self) -> None:
958 """Disconnect the current client and clean up resources."""
959 self.listening = False
960
961 def handle_error(self, request: Request, client_address: str) -> None:
962 """Handle errors that occur during request processing.
963
964 Args:
965 request (Request): The request object that caused the error.
966 client_address (str): The address of the client that made the
967 request.
968 """
969 print(
970 "Exception happened during processing of request from "
971 f"{client_address}:{sys.exc_info()[1]}:"
972 )
973
974 @property
975 def listening(self) -> bool:
976 """Check if the server is currently listening for requests.
977
978 Returns:
979 bool: True if the server is listening, False otherwise.
980 """
981 return self._listening.is_set()
982
983 @listening.setter
984 def listening(self, value: bool) -> None:
985 """Set the listening state of the server.
986
987 Args:
988 value (bool): If True, the server starts listening for requests.
989 If False, it stops listening and cleans up any existing
990 connections.
991 """
992 if value:
993 self._listening.set()
994 return
995 self._listening.clear()
996 with self._pattern_changed:
997 # Wake any long-poll requests so they can terminate quickly.
998 self._pattern_changed.notify_all()
999 if hasattr(self, "conn"):
1000 self.shutdown_request(self.conn)
1001 del self.conn
1002 if hasattr(self, "_thread") and self._thread.is_alive():
1003 self.shutdown()
1004
1005 def send(
1006 self,
1007 rgb: tuple[float, float, float] = (0, 0, 0),
1008 bgrgb: tuple[float, float, float] = (0, 0, 0),
1009 bits: None | int = None,
1010 use_video_levels: None | bool = None,
1011 x: float = 0,
1012 y: float = 0,
1013 w: float = 1,
1014 h: float = 1,
1015 ) -> None:
1016 """Send an RGB color to the pattern generator. The RGB range should be 0..1.
1017
1018 Args:
1019 rgb (tuple[float, float, float], optional): RGB color values in the
1020 range 0..1.
1021 bgrgb (tuple[float, float, float], optional): Background RGB color
1022 values in the range 0..1.
1023 bits (None | int, optional): Number of bits per channel. Defaults
1024 to None.
1025 use_video_levels (None | bool, optional): Use video levels for RGB
1026 values. Defaults to None.
1027 x (float, optional): X position of the rectangle. Defaults to 0.
1028 y (float, optional): Y position of the rectangle. Defaults to 0.
1029 w (float, optional): Width of the rectangle. Defaults to 1.
1030 h (float, optional): Height of the rectangle. Defaults to 1.
1031 """
1032 # Convert normalized RGB values to 8-bit CSS hex colors.
1033 pattern = [
1034 "#{:02x}{:02x}{:02x}".format(
1035 *tuple(max(0, min(255, round(v * 255))) for v in rgb)
1036 ),
1037 "#{:02x}{:02x}{:02x}".format(
1038 *tuple(max(0, min(255, round(v * 255))) for v in bgrgb)
1039 ),
1040 f"{x:.4f}|{y:.4f}|{w:.4f}|{h:.4f}",
1041 ]
1042 with self._pattern_changed:
1043 self.pattern = "|".join(pattern)
1044 self._pattern_seq += 1
1045 self._pattern_changed.notify_all()
1046
1047 def wait_for_pattern_change(self, curpat: str, timeout: float = 25.0) -> str:
1048 """Return current pattern, waiting until it changes or times out."""
1049 with self._pattern_changed:
1050 current = self.pattern
1051 start_seq = self._pattern_seq
1052 if self._listening.is_set() and current == curpat:
1053 self._pattern_changed.wait_for(
1054 lambda: (
1055 not self._listening.is_set()
1056 or self._pattern_seq != start_seq
1057 or self.pattern != curpat
1058 ),
1059 timeout=timeout,
1060 )
1061 current = self.pattern
1062 return current
1063
1064 def serve_forever(self, poll_interval: float = 0.5) -> None:
1065 """Handle one request at a time until shutdown.
1066
1067 Polls for shutdown every poll_interval seconds. Ignores
1068 self.timeout. If you need to do periodic tasks, do them in
1069 another thread.
1070 """
1071 try:
1072 while self._listening.is_set():
1073 # XXX: Consider using another file descriptor or
1074 # connecting to the socket to wake this up instead of
1075 # polling. Polling reduces our responsiveness to a
1076 # shutdown request and wastes cpu at all other times.
1077 r, w, e = _eintr_retry(select.select, [self], [], [], poll_interval)
1078 if self in r:
1079 self._handle_request_noblock()
1080 except Exception as exception:
1081 print(
1082 "Exception in WebWinHTTPPatternGeneratorServer.serve_forever:",
1083 exception,
1084 )
1085 self._listening.clear()
1086
1087 def shutdown(self) -> None:
1088 """Stop the serve_forever loop.
1089
1090 Blocks until the loop has finished. This must be called while
1091 serve_forever() is running in another thread.
1092 """
1093 self._listening.clear()
1094 while self._thread.is_alive():
1095 sleep(0.05)
1096
1097 def wait(self) -> None:
1098 """Wait for a client to connect and process the request."""
1099 self.listening = True
1100 if self.logfile:
1101 try:
1102 host = get_network_addr()
1103 except OSError:
1104 host = gethostname()
1105 self.logfile.write(
1106 "{} {}:{}\n".format(lang.getstr("webserver.waiting"), host, self.port)
1107 )
1108 self.socket.settimeout(1)
1109 while self.listening:
1110 try:
1111 self.conn, addr = self.get_request()
1112 except timeout:
1113 continue
1114 self.conn.settimeout(1)
1115 break
1116 self.socket.settimeout(None)
1117 if not self.listening:
1118 return
1119 try:
1120 self.process_request(self.conn, addr)
1121 except Exception:
1122 self.handle_error(self.conn, addr)
1123 self.disconnect_client()
1124 else:
1125 self._thread = threading.Thread(
1126 target=self.serve_forever,
1127 name="WebWinHTTPPatternGeneratorServerThread",
1128 )
1129 self._thread.start()
1130 print(lang.getstr("connection.established"))
1131
1132
1133 if __name__ == "__main__":
1134 patterngenerator = GenTCPSockPatternGeneratorServer()