Debian Codegraph @

src/arcam/fmj/__init__.py

raw
1 """Arcam AV Control"""
2
3 import asyncio
4 import enum
5 import logging
6 import re
7 from asyncio.exceptions import IncompleteReadError
8 from typing import (
9 Any,
10 SupportsBytes,
11 TypeVar,
12 Union,
13 Literal,
14 SupportsIndex,
15 )
16 from collections.abc import Iterable
17
18 import attr
19
20 PROTOCOL_STR = b"\x21"
21 PROTOCOL_ETR = b"\x0d"
22 PROTOCOL_EOF = b""
23
24 _LOGGER = logging.getLogger(__name__)
25 _WRITE_TIMEOUT = 3
26 _READ_TIMEOUT = 3
27
28
29 class ArcamException(Exception):
30 pass
31
32
33 class ConnectionFailed(ArcamException):
34 pass
35
36
37 class NotConnectedException(ArcamException):
38 pass
39
40
41 class UnsupportedZone(ArcamException):
42 pass
43
44
45 class ResponseException(ArcamException):
46 def __init__(self, ac=None, zn=None, cc=None, data=None):
47 self.ac = ac
48 self.zn = zn
49 self.cc = cc
50 self.data = data
51 super().__init__(f"'ac':{ac}, 'zn':{zn}, 'cc':{cc}, 'data':{data}")
52
53 @staticmethod
54 def from_response(response: "ResponsePacket"):
55 kwargs = {"zn": response.zn, "cc": response.cc, "data": response.data}
56 if response.ac == AnswerCodes.ZONE_INVALID:
57 return InvalidZoneException(**kwargs)
58 elif response.ac == AnswerCodes.COMMAND_NOT_RECOGNISED:
59 return CommandNotRecognised(**kwargs)
60 elif response.ac == AnswerCodes.PARAMETER_NOT_RECOGNISED:
61 return ParameterNotRecognised(**kwargs)
62 elif response.ac == AnswerCodes.COMMAND_INVALID_AT_THIS_TIME:
63 return CommandInvalidAtThisTime(**kwargs)
64 elif response.ac == AnswerCodes.INVALID_DATA_LENGTH:
65 return InvalidDataLength(**kwargs)
66 else:
67 return ResponseException(ac=response.ac, **kwargs)
68
69
70 class InvalidZoneException(ResponseException):
71 def __init__(self, zn=None, cc=None, data=None):
72 super().__init__(ac=AnswerCodes.ZONE_INVALID, zn=zn, cc=cc, data=data)
73
74
75 class CommandNotRecognised(ResponseException):
76 def __init__(self, zn=None, cc=None, data=None):
77 super().__init__(ac=AnswerCodes.COMMAND_NOT_RECOGNISED, zn=zn, cc=cc, data=data)
78
79
80 class ParameterNotRecognised(ResponseException):
81 def __init__(self, zn=None, cc=None, data=None):
82 super().__init__(
83 ac=AnswerCodes.PARAMETER_NOT_RECOGNISED, zn=zn, cc=cc, data=data
84 )
85
86
87 class CommandInvalidAtThisTime(ResponseException):
88 def __init__(self, zn=None, cc=None, data=None):
89 super().__init__(
90 ac=AnswerCodes.COMMAND_INVALID_AT_THIS_TIME, zn=zn, cc=cc, data=data
91 )
92
93
94 class InvalidDataLength(ResponseException):
95 def __init__(self, zn=None, cc=None, data=None):
96 super().__init__(ac=AnswerCodes.INVALID_DATA_LENGTH, zn=zn, cc=cc, data=data)
97
98
99 class InvalidPacket(ArcamException):
100 pass
101
102
103 class NullPacket(ArcamException):
104 pass
105
106
107 APIVERSION_450_SERIES = {"AVR380", "AVR450", "AVR750"}
108 APIVERSION_860_SERIES = {
109 "AV860",
110 "AVR850",
111 "AVR550",
112 "AVR390",
113 "SR250",
114 "RV-6",
115 "RV-9",
116 "MC-10",
117 }
118 APIVERSION_SA_SERIES = {"SA10", "SA20", "SA30", "SA750"}
119 APIVERSION_HDA_SERIES = {
120 "AVR5",
121 "AVR10",
122 "AVR20",
123 "AVR30",
124 "AV40",
125 "AVR11",
126 "AVR21",
127 "AVR31",
128 "AV41",
129 "SDP-55",
130 "SDP-58",
131 }
132 APIVERSION_HDA_PREMIUM_SERIES = {
133 "AVR10",
134 "AVR20",
135 "AVR30",
136 "AV40",
137 "AVR11",
138 "AVR21",
139 "AVR31",
140 "AV41",
141 "SDP-55",
142 "SDP-58",
143 }
144 APIVERSION_HDA_MULTI_ZONE_SERIES = {
145 "AVR20",
146 "AVR30",
147 "AV40",
148 "AVR21",
149 "AVR31",
150 "AV41",
151 "SDP-55",
152 "SDP-58",
153 }
154 APIVERSION_PA_SERIES = {"PA720", "PA240", "PA410"}
155 APIVERSION_ST_SERIES = {"ST60"}
156
157 APIVERSION_DAB_SERIES = {"AVR450", "AVR750"}
158 APIVERSION_DAB_SERIES.update(
159 "AV860", "AVR850", "AVR550", "AVR390", "RV-6", "RV-9", "MC-10"
160 )
161 APIVERSION_DAB_SERIES.update(APIVERSION_HDA_SERIES)
162
163 APIVERSION_ZONE2_SERIES = set()
164 APIVERSION_ZONE2_SERIES.update(APIVERSION_450_SERIES)
165 APIVERSION_ZONE2_SERIES.update(APIVERSION_860_SERIES)
166 APIVERSION_ZONE2_SERIES.update(APIVERSION_HDA_MULTI_ZONE_SERIES)
167
168 APIVERSION_DOLBY_PL_SERIES = APIVERSION_450_SERIES
169
170 APIVERSION_DOLBY_SURROUND_SERIES = set()
171 APIVERSION_DOLBY_SURROUND_SERIES.update(APIVERSION_860_SERIES)
172 APIVERSION_DOLBY_SURROUND_SERIES.update(APIVERSION_HDA_SERIES)
173
174 APIVERSION_DOLBY_ATMOS_SERIES = set()
175 APIVERSION_DOLBY_ATMOS_SERIES.update(APIVERSION_860_SERIES)
176 APIVERSION_DOLBY_ATMOS_SERIES.update(APIVERSION_HDA_SERIES)
177
178 APIVERSION_DOLBY_VIRT_H_SERIES = APIVERSION_HDA_SERIES
179
180 APIVERSION_DTS_X_SERIES = APIVERSION_DOLBY_SURROUND_SERIES
181
182 APIVERSION_AURO_SERIES = APIVERSION_HDA_PREMIUM_SERIES
183
184 APIVERSION_IMAX_SERIES = set()
185 APIVERSION_IMAX_SERIES.update(APIVERSION_860_SERIES)
186 APIVERSION_IMAX_SERIES.update(APIVERSION_HDA_PREMIUM_SERIES)
187
188 APIVERSION_AMP_DIAGNOSTICS_SERIES = set()
189 APIVERSION_AMP_DIAGNOSTICS_SERIES.update(APIVERSION_SA_SERIES)
190 APIVERSION_AMP_DIAGNOSTICS_SERIES.update(APIVERSION_PA_SERIES)
191
192 APIVERSION_CLASS_G_SERIES = {"PA720", "PA240", "SA20", "SA30", "SA750"}
193
194 APIVERSION_PHONO_SERIES = {"SA30", "SA750"}
195
196 APIVERSION_SIMPLE_IP_SERIES = {"PA720", "PA240", "SA10", "SA20"}
197
198 APIVERSION_APP_SAFETY_SERIES = {"SA30", "SA750"}
199
200
201 class ApiModel(enum.Enum):
202 API450_SERIES = 1
203 API860_SERIES = 2
204 APISA_SERIES = 3
205 APIHDA_SERIES = 4
206 APIPA_SERIES = 5
207 APIST_SERIES = 6
208
209
210 _T = TypeVar("_T", bound="IntOrTypeEnum")
211
212
213 class EnumFlags(enum.IntFlag):
214 ZONE_SUPPORT = enum.auto()
215 SEND_ONLY = enum.auto()
216
217
218 class IntOrTypeEnum(enum.IntEnum):
219 version: set[str] | None
220 flags: EnumFlags
221
222 @classmethod
223 def _missing_(cls, value):
224 if isinstance(value, int):
225 return cls._create_member(value)
226 return None
227
228 @classmethod
229 def _create_member(cls, value):
230 pseudo_member = cls._value2member_map_.get(value, None)
231 if pseudo_member is None:
232 obj = int.__new__(cls, value)
233 obj._name_ = f"CODE_{value}"
234 obj._value_ = value
235 obj.version = None
236 obj.flags = EnumFlags(0)
237 pseudo_member = cls._value2member_map_.setdefault(value, obj)
238 return pseudo_member
239
240 def __new__(cls, value: int, version: set[str] | None = None, flags=EnumFlags(0)):
241 obj = int.__new__(cls, value)
242 obj._value_ = value
243 obj.version = version
244 obj.flags = flags
245 return obj
246
247 @classmethod
248 def from_int(cls: type[_T], value: int) -> _T:
249 return cls(value)
250
251 @classmethod
252 def from_bytes(
253 cls: type[_T],
254 bytes: Iterable[SupportsIndex] | SupportsBytes,
255 byteorder: Literal["little", "big"] = "big",
256 *,
257 signed: bool = False,
258 ) -> _T: # type: ignore[override]
259 return cls.from_int(int.from_bytes(bytes, byteorder=byteorder, signed=signed))
260
261
262 class AnswerCodes(IntOrTypeEnum):
263 STATUS_UPDATE = 0x00
264 ZONE_INVALID = 0x82
265 COMMAND_NOT_RECOGNISED = 0x83
266 PARAMETER_NOT_RECOGNISED = 0x84
267 COMMAND_INVALID_AT_THIS_TIME = 0x85
268 INVALID_DATA_LENGTH = 0x86
269
270
271 class CommandCodes(IntOrTypeEnum):
272 # System Commands
273 POWER = 0x00, None, EnumFlags.ZONE_SUPPORT
274 DISPLAY_BRIGHTNESS = 0x01
275 HEADPHONES = 0x02
276 FMGENRE = 0x03, None, EnumFlags.ZONE_SUPPORT
277 SOFTWARE_VERSION = 0x04
278 RESTORE_FACTORY_DEFAULT = 0x05
279 SAVE_RESTORE_COPY_OF_SETTINGS = 0x06
280 SIMULATE_RC5_IR_COMMAND = 0x08, None, EnumFlags.ZONE_SUPPORT | EnumFlags.SEND_ONLY
281 DISPLAY_INFORMATION_TYPE = 0x09, None, EnumFlags.ZONE_SUPPORT
282 CURRENT_SOURCE = 0x1D, None, EnumFlags.ZONE_SUPPORT # Request
283 HEADPHONES_OVERRIDE = 0x1F, None, EnumFlags.ZONE_SUPPORT
284
285 # Input Commands
286 VIDEO_SELECTION = 0x0A
287 SELECT_ANALOG_DIGITAL = 0x0B
288 VIDEO_INPUT_TYPE = 0x0C # IMAX_ENHANCED on 860 and HDA Series (not AVR5)
289
290 # Output Commands
291 VOLUME = 0x0D, None, EnumFlags.ZONE_SUPPORT # Set/Request
292 MUTE = 0x0E, None, EnumFlags.ZONE_SUPPORT # Request
293 DIRECT_MODE_STATUS = 0x0F # Request
294 DECODE_MODE_STATUS_2CH = 0x10 # Request
295 DECODE_MODE_STATUS_MCH = 0x11 # Request
296 RDS_INFORMATION = 0x12, None, EnumFlags.ZONE_SUPPORT # Request
297 VIDEO_OUTPUT_RESOLUTION = 0x13 # Set/Request
298
299 # Menu Command
300 MENU = 0x14 # Request
301 TUNER_PRESET = 0x15, None, EnumFlags.ZONE_SUPPORT # Set/Request
302 TUNE = 0x16, None, EnumFlags.ZONE_SUPPORT # Set/Request
303 DAB_STATION = 0x18, None, EnumFlags.ZONE_SUPPORT # Set/Request
304 DAB_PROGRAM_TYPE_CATEGORY = 0x19, None, EnumFlags.ZONE_SUPPORT # Set/Request
305 DLS_PDT_INFO = 0x1A, None, EnumFlags.ZONE_SUPPORT # Request
306 PRESET_DETAIL = 0x1B, None, EnumFlags.ZONE_SUPPORT # Request
307 NETWORK_PLAYBACK_STATUS = 0x1C, APIVERSION_HDA_SERIES # Request
308
309 # Network Command
310
311 # Setup
312 TREBLE_EQUALIZATION = 0x35, None, EnumFlags.ZONE_SUPPORT
313 BASS_EQUALIZATION = 0x36, None, EnumFlags.ZONE_SUPPORT
314 ROOM_EQUALIZATION = 0x37, None, EnumFlags.ZONE_SUPPORT
315 DOLBY_VOLUME = 0x38, None, EnumFlags.ZONE_SUPPORT # DOLBY_AUDIO on HDA series
316 DOLBY_LEVELER = 0x39, None, EnumFlags.ZONE_SUPPORT
317 DOLBY_VOLUME_CALIBRATION_OFFSET = 0x3A, None, EnumFlags.ZONE_SUPPORT
318 BALANCE = 0x3B, None, EnumFlags.ZONE_SUPPORT
319
320 DOLBY_PLII_X_MUSIC_DIMENSION = 0x3C
321 DOLBY_PLII_X_MUSIC_CENTRE_WIDTH = 0x3D
322 DOLBY_PLII_X_MUSIC_PANORAMA = 0x3E
323 SUBWOOFER_TRIM = 0x3F, None, EnumFlags.ZONE_SUPPORT
324 LIPSYNC_DELAY = 0x40, None, EnumFlags.ZONE_SUPPORT
325 COMPRESSION = 0x41, None, EnumFlags.ZONE_SUPPORT
326
327 INCOMING_VIDEO_PARAMETERS = 0x42, None
328 INCOMING_AUDIO_FORMAT = 0x43, None
329 INCOMING_AUDIO_SAMPLE_RATE = 0x44
330
331 SUB_STEREO_TRIM = 0x45 # Set/Request
332 VIDEO_BRIGHTNESS = 0x46 # Set/Request
333 VIDEO_CONTRAST = 0x47 # Set/Request
334 VIDEO_COLOUR = 0x48 # Set/Request
335 VIDEO_FILM_MODE = 0x49 # Set/Request
336 VIDEO_EDGE_ENHANCEMENT = 0x4A # Set/Request
337 VIDEO_NOISE_REDUCTION = 0x4C # Set/Request
338 VIDEO_MPEG_NOISE_REDUCTION = 0x4D # Set/Request
339 ZONE_1_OSD_ON_OFF = 0x4E # Set/Request
340 VIDEO_OUTPUT_SWITCHING = 0x4F # Set/Request
341 VIDEO_OUTPUT_FRAME_RATE = 0x50 # Set/Request BLUETOOTH_STATUS on HDA series
342
343 # 2.0 Commands
344 INPUT_NAME = 0x20 # Set/Request
345 FM_SCAN = 0x23
346 DAB_SCAN = 0x24
347 HEARTBEAT = 0x25
348 REBOOT = 0x26
349 SETUP = 0x27, APIVERSION_HDA_SERIES
350 ROOM_EQ_NAMES = 0x34, APIVERSION_HDA_SERIES
351 NOW_PLAYING_INFO = 0x64, APIVERSION_HDA_SERIES, EnumFlags.ZONE_SUPPORT
352 INPUT_CONFIG = 0x28, APIVERSION_HDA_SERIES
353 GENERAL_SETUP = 0x29, APIVERSION_HDA_SERIES
354 SPEAKER_TYPES = 0x2A, APIVERSION_HDA_SERIES
355 SPEAKER_DISTANCES = 0x2B, APIVERSION_HDA_SERIES
356 SPEAKER_LEVELS = 0x2C, APIVERSION_HDA_SERIES
357 VIDEO_INPUTS = 0x2D, APIVERSION_HDA_SERIES
358 HDMI_SETTINGS = 0x2E, APIVERSION_HDA_SERIES
359 ZONE_SETTINGS = 0x2F, APIVERSION_HDA_MULTI_ZONE_SERIES
360 NETWORK_MENU_INFO = 0x30, APIVERSION_HDA_SERIES
361 BLUETOOTH_MENU_INFO = 0x32, APIVERSION_HDA_SERIES
362 ENGINEERING_MENU_INFO = 0x33, APIVERSION_HDA_SERIES
363
364 # Amp Diagnostics
365 DC_OFFSET = 0x51, APIVERSION_AMP_DIAGNOSTICS_SERIES
366 SHORT_CIRCUIT_STATUS = 0x52, APIVERSION_CLASS_G_SERIES
367 TIMEOUT_COUNTER = 0x55, APIVERSION_AMP_DIAGNOSTICS_SERIES
368 LIFTER_TEMPERATURE = (
369 0x56,
370 APIVERSION_CLASS_G_SERIES,
371 ) # Bug in PA720 1.8 firmware - does not return sensor id
372 OUTPUT_TEMPERATURE = (
373 0x57,
374 APIVERSION_AMP_DIAGNOSTICS_SERIES,
375 ) # Bug in PA720 1.8 firmware - does not return sensor id
376 AUTO_SHUTDOWN_CONTROL = 0x58, APIVERSION_AMP_DIAGNOSTICS_SERIES
377
378 # Status/Diagnostics
379 FRIENDLY_NAME = 0x53, APIVERSION_SIMPLE_IP_SERIES
380 IP_ADDRESS = 0x54, APIVERSION_SIMPLE_IP_SERIES
381 PHONO_INPUT_TYPE = 0x59, APIVERSION_PHONO_SERIES
382 INPUT_DETECT = 0x5A, APIVERSION_AMP_DIAGNOSTICS_SERIES
383 PROCESSOR_MODE_INPUT = 0x5B, APIVERSION_SA_SERIES
384 PROCESSOR_MODE_VOLUME = 0x5C, APIVERSION_SA_SERIES
385 SYSTEM_STATUS = 0x5D, APIVERSION_AMP_DIAGNOSTICS_SERIES
386 SYSTEM_MODEL = 0x5E, APIVERSION_AMP_DIAGNOSTICS_SERIES
387 DAC_FILTER = 0x61, APIVERSION_SA_SERIES # Clashes with AMPLIFIER_MODE on PA240
388 MAXIMUM_TURN_ON_VOLUME = 0x65, APIVERSION_APP_SAFETY_SERIES
389 MAXIMUM_VOLUME = 0x66, APIVERSION_APP_SAFETY_SERIES
390 MAXIMUM_STREAMING_VOLUME = 0x67, APIVERSION_APP_SAFETY_SERIES
391
392
393 class SourceCodes(enum.Enum):
394 FOLLOW_ZONE_1 = enum.auto()
395 CD = enum.auto()
396 BD = enum.auto()
397 AV = enum.auto()
398 SAT = enum.auto()
399 PVR = enum.auto()
400 VCR = enum.auto()
401 AUX = enum.auto()
402 DISPLAY = enum.auto()
403 FM = enum.auto()
404 DAB = enum.auto()
405 NET = enum.auto()
406 USB = enum.auto()
407 STB = enum.auto()
408 GAME = enum.auto()
409 PHONO = enum.auto()
410 ARC_ERC = enum.auto()
411 UHD = enum.auto()
412 BT = enum.auto()
413 DIG1 = enum.auto()
414 DIG2 = enum.auto()
415 DIG3 = enum.auto()
416 DIG4 = enum.auto()
417 NET_USB = enum.auto()
418
419 @classmethod
420 def from_bytes(cls, data: bytes, model: ApiModel, zn: int) -> "SourceCodes":
421 try:
422 table = SOURCE_CODES[(model, zn)]
423 except KeyError:
424 raise ValueError(f"Unknown source map for model {model} and zone {zn}")
425 for key, value in table.items():
426 if value == data:
427 return key
428 raise ValueError(
429 "Unknown source code for model {} and zone {} and value {!r}".format(
430 model, zn, data
431 )
432 )
433
434 def to_bytes(self, model: ApiModel, zn: int):
435 try:
436 table = SOURCE_CODES[(model, zn)]
437 except KeyError:
438 raise ValueError(f"Unknown source map for model {model} and zone {zn}")
439 if data := table.get(self):
440 return data
441 raise ValueError(
442 "Unknown byte code for model {} and zone {} and value {}".format(
443 model, zn, self
444 )
445 )
446
447
448 class MenuCodes(IntOrTypeEnum):
449 NONE = 0x00
450 SETUP = 0x02
451 TRIM = 0x03
452 BASS = 0x04
453 TREBLE = 0x05
454 SYNC = 0x06
455 SUB = 0x07
456 TUNER = 0x08
457 NETWORK = 0x09
458 USB = 0x0A
459
460
461 class DecodeMode2CH(IntOrTypeEnum):
462 STEREO = 0x01
463 DOLBY_PLII_IIx_MOVIE = 0x02, APIVERSION_DOLBY_PL_SERIES
464 DOLBY_PLII_IIx_MUSIC = 0x03, APIVERSION_DOLBY_PL_SERIES
465 DOLBY_SURROUND = 0x04, APIVERSION_DOLBY_SURROUND_SERIES
466 DOLBY_PLII_IIx_GAME = 0x05, APIVERSION_DOLBY_PL_SERIES
467 DOLBY_PL = 0x06, APIVERSION_DOLBY_PL_SERIES
468 DTS_NEO_6_CINEMA = 0x07
469 DTS_NEO_6_MUSIC = 0x08
470 MCH_STEREO = 0x09
471
472 DTS_NEURAL_X = 0x0A, APIVERSION_DTS_X_SERIES
473 DTS_VIRTUAL_X = 0x0C, APIVERSION_DTS_X_SERIES
474
475 DOLBY_VIRTUAL_HEIGHT = 0x0D, APIVERSION_DOLBY_VIRT_H_SERIES
476 AURO_NATIVE = 0x0E, APIVERSION_AURO_SERIES
477 AURO_MATIC_3D = 0x0F, APIVERSION_AURO_SERIES
478 AURO_2D = 0x10, APIVERSION_AURO_SERIES
479
480
481 class DecodeModeMCH(IntOrTypeEnum):
482 STEREO_DOWNMIX = 0x01
483 MULTI_CHANNEL = 0x02
484
485 # This is used for DTS_NEURAL_X on 860 series and HDA series
486 DOLBY_D_EX_OR_DTS_ES = 0x03
487
488 DOLBY_PLII_IIx_MOVIE = 0x04, APIVERSION_DOLBY_PL_SERIES
489 DOLBY_PLII_IIx_MUSIC = 0x05, APIVERSION_DOLBY_PL_SERIES
490
491 DOLBY_SURROUND = 0x06, APIVERSION_DOLBY_SURROUND_SERIES
492 DTS_VIRTUAL_X = 0x0C, APIVERSION_DTS_X_SERIES
493
494 DOLBY_VIRTUAL_HEIGHT = 0x0D, APIVERSION_DOLBY_VIRT_H_SERIES
495 AURO_NATIVE = 0x0E, APIVERSION_AURO_SERIES
496 AURO_MATIC_3D = 0x0F, APIVERSION_AURO_SERIES
497 AURO_2D = 0x10, APIVERSION_AURO_SERIES
498
499
500 POWER_WRITE_SUPPORTED = {
501 ApiModel.APISA_SERIES,
502 ApiModel.APIPA_SERIES,
503 ApiModel.APIST_SERIES,
504 }
505
506 MUTE_WRITE_SUPPORTED = POWER_WRITE_SUPPORTED
507
508 SOURCE_WRITE_SUPPORTED = {
509 ApiModel.APISA_SERIES,
510 }
511
512 VOLUME_STEP_SUPPORTED = {
513 ApiModel.APIST_SERIES,
514 }
515
516 DEFAULT_SOURCE_MAPPING = {
517 SourceCodes.FOLLOW_ZONE_1: bytes([0x00]),
518 SourceCodes.CD: bytes([0x01]),
519 SourceCodes.BD: bytes([0x02]),
520 SourceCodes.AV: bytes([0x03]),
521 SourceCodes.SAT: bytes([0x04]),
522 SourceCodes.PVR: bytes([0x05]),
523 SourceCodes.VCR: bytes([0x06]),
524 SourceCodes.AUX: bytes([0x08]),
525 SourceCodes.DISPLAY: bytes([0x09]),
526 SourceCodes.FM: bytes([0x0B]),
527 SourceCodes.DAB: bytes([0x0C]),
528 SourceCodes.NET: bytes([0x0E]),
529 SourceCodes.USB: bytes([0x0F]),
530 SourceCodes.STB: bytes([0x10]),
531 SourceCodes.GAME: bytes([0x11]),
532 SourceCodes.PHONO: bytes([0x12]),
533 SourceCodes.ARC_ERC: bytes([0x13]),
534 }
535
536 HDA_SOURCE_MAPPING = {
537 SourceCodes.FOLLOW_ZONE_1: bytes([0x00]),
538 SourceCodes.CD: bytes([0x01]),
539 SourceCodes.BD: bytes([0x02]),
540 SourceCodes.AV: bytes([0x03]),
541 SourceCodes.SAT: bytes([0x04]),
542 SourceCodes.PVR: bytes([0x05]),
543 SourceCodes.UHD: bytes([0x06]),
544 SourceCodes.AUX: bytes([0x08]),
545 SourceCodes.DISPLAY: bytes([0x09]),
546 SourceCodes.FM: bytes([0x0B]),
547 SourceCodes.DAB: bytes([0x0C]),
548 SourceCodes.NET: bytes([0x0E]),
549 SourceCodes.USB: bytes([0x0F]),
550 SourceCodes.STB: bytes([0x10]),
551 SourceCodes.GAME: bytes([0x11]),
552 SourceCodes.BT: bytes([0x12]),
553 }
554
555 SA_SOURCE_MAPPING = {
556 SourceCodes.PHONO: bytes([0x01]),
557 SourceCodes.AUX: bytes([0x02]),
558 SourceCodes.PVR: bytes([0x03]),
559 SourceCodes.AV: bytes([0x04]),
560 SourceCodes.STB: bytes([0x05]),
561 SourceCodes.CD: bytes([0x06]),
562 SourceCodes.BD: bytes([0x07]),
563 SourceCodes.SAT: bytes([0x08]),
564 SourceCodes.GAME: bytes([0x09]),
565 SourceCodes.NET: bytes([0x0B]),
566 SourceCodes.USB: bytes([0x0B]),
567 SourceCodes.ARC_ERC: bytes([0x0D]),
568 }
569
570 ST_SOURCE_MAPPING = {
571 SourceCodes.DIG1: bytes([0x01]),
572 SourceCodes.DIG2: bytes([0x02]),
573 SourceCodes.DIG3: bytes([0x03]),
574 SourceCodes.DIG4: bytes([0x04]),
575 SourceCodes.NET_USB: bytes([0x05]),
576 }
577
578 SOURCE_CODES = {
579 (ApiModel.API450_SERIES, 1): DEFAULT_SOURCE_MAPPING,
580 (ApiModel.API450_SERIES, 2): DEFAULT_SOURCE_MAPPING,
581 (ApiModel.API860_SERIES, 1): DEFAULT_SOURCE_MAPPING,
582 (ApiModel.API860_SERIES, 2): DEFAULT_SOURCE_MAPPING,
583 (ApiModel.APIHDA_SERIES, 1): HDA_SOURCE_MAPPING,
584 (ApiModel.APIHDA_SERIES, 2): HDA_SOURCE_MAPPING,
585 (ApiModel.APISA_SERIES, 1): SA_SOURCE_MAPPING,
586 (ApiModel.APISA_SERIES, 2): SA_SOURCE_MAPPING,
587 (ApiModel.APIST_SERIES, 1): ST_SOURCE_MAPPING,
588 }
589
590 RC5CODE_DECODE_MODE_MCH: dict[tuple[ApiModel, int], dict[DecodeModeMCH, bytes]] = {
591 (ApiModel.API450_SERIES, 1): {
592 DecodeModeMCH.STEREO_DOWNMIX: bytes([16, 107]),
593 DecodeModeMCH.MULTI_CHANNEL: bytes([16, 106]),
594 DecodeModeMCH.DOLBY_D_EX_OR_DTS_ES: bytes([16, 118]),
595 DecodeModeMCH.DOLBY_PLII_IIx_MOVIE: bytes([16, 103]),
596 DecodeModeMCH.DOLBY_PLII_IIx_MUSIC: bytes([16, 104]),
597 },
598 (ApiModel.API450_SERIES, 2): {},
599 (ApiModel.API860_SERIES, 1): {
600 DecodeModeMCH.STEREO_DOWNMIX: bytes([16, 107]),
601 DecodeModeMCH.MULTI_CHANNEL: bytes([16, 106]),
602 # We map to DTS_NEURAL_X
603 DecodeModeMCH.DOLBY_D_EX_OR_DTS_ES: bytes([16, 113]),
604 DecodeModeMCH.DOLBY_SURROUND: bytes([16, 110]),
605 DecodeModeMCH.DTS_VIRTUAL_X: bytes([16, 115]),
606 },
607 (ApiModel.API860_SERIES, 2): {},
608 (ApiModel.APIHDA_SERIES, 1): {
609 DecodeModeMCH.STEREO_DOWNMIX: bytes([16, 107]),
610 DecodeModeMCH.MULTI_CHANNEL: bytes([16, 106]),
611 # We map to DTS_NEURAL_X
612 DecodeModeMCH.DOLBY_D_EX_OR_DTS_ES: bytes([16, 113]),
613 DecodeModeMCH.DOLBY_SURROUND: bytes([16, 110]),
614 DecodeModeMCH.DOLBY_VIRTUAL_HEIGHT: bytes([16, 115]),
615 DecodeModeMCH.AURO_NATIVE: bytes([16, 103]),
616 DecodeModeMCH.AURO_MATIC_3D: bytes([16, 71]),
617 DecodeModeMCH.AURO_2D: bytes([16, 104]),
618 },
619 (ApiModel.APIHDA_SERIES, 2): {},
620 (ApiModel.APISA_SERIES, 1): {},
621 (ApiModel.APISA_SERIES, 2): {},
622 (ApiModel.APIPA_SERIES, 1): {},
623 (ApiModel.APIPA_SERIES, 2): {},
624 }
625
626 RC5CODE_DECODE_MODE_2CH: dict[tuple[ApiModel, int], dict[DecodeMode2CH, bytes]] = {
627 (ApiModel.API450_SERIES, 1): {
628 DecodeMode2CH.STEREO: bytes([16, 107]),
629 DecodeMode2CH.DOLBY_PLII_IIx_MOVIE: bytes([16, 103]),
630 DecodeMode2CH.DOLBY_PLII_IIx_MUSIC: bytes([16, 104]),
631 DecodeMode2CH.DOLBY_PLII_IIx_GAME: bytes([16, 102]),
632 DecodeMode2CH.DOLBY_PL: bytes([16, 110]),
633 DecodeMode2CH.DTS_NEO_6_CINEMA: bytes([16, 111]),
634 DecodeMode2CH.DTS_NEO_6_MUSIC: bytes([16, 112]),
635 DecodeMode2CH.MCH_STEREO: bytes([16, 69]),
636 },
637 (ApiModel.API450_SERIES, 2): {},
638 (ApiModel.API860_SERIES, 1): {
639 DecodeMode2CH.STEREO: bytes([16, 107]),
640 DecodeMode2CH.DTS_NEURAL_X: bytes([16, 113]),
641 DecodeMode2CH.DTS_VIRTUAL_X: bytes([16, 115]),
642 DecodeMode2CH.DOLBY_PL: bytes([16, 110]),
643 DecodeMode2CH.DTS_NEO_6_CINEMA: bytes([16, 111]),
644 DecodeMode2CH.DTS_NEO_6_MUSIC: bytes([16, 112]),
645 DecodeMode2CH.MCH_STEREO: bytes([16, 69]),
646 },
647 (ApiModel.API860_SERIES, 2): {},
648 (ApiModel.APIHDA_SERIES, 1): {
649 DecodeMode2CH.STEREO: bytes([16, 107]),
650 DecodeMode2CH.DOLBY_SURROUND: bytes([16, 110]),
651 DecodeMode2CH.DTS_NEO_6_CINEMA: bytes([16, 111]),
652 DecodeMode2CH.DTS_NEO_6_MUSIC: bytes([16, 112]),
653 DecodeMode2CH.MCH_STEREO: bytes([16, 69]),
654 DecodeMode2CH.DTS_NEURAL_X: bytes([16, 113]),
655 DecodeMode2CH.DOLBY_VIRTUAL_HEIGHT: bytes([16, 115]),
656 DecodeMode2CH.AURO_NATIVE: bytes([16, 103]),
657 DecodeMode2CH.AURO_MATIC_3D: bytes([16, 71]),
658 DecodeMode2CH.AURO_2D: bytes([16, 104]),
659 },
660 (ApiModel.APIHDA_SERIES, 2): {},
661 (ApiModel.APISA_SERIES, 1): {},
662 (ApiModel.APISA_SERIES, 2): {},
663 (ApiModel.APIPA_SERIES, 1): {},
664 (ApiModel.APIPA_SERIES, 2): {},
665 (ApiModel.APIST_SERIES, 1): {},
666 (ApiModel.APIST_SERIES, 2): {},
667 }
668
669 RC5CODE_SOURCE: dict[tuple[ApiModel, int], dict[SourceCodes, bytes]] = {
670 (ApiModel.API450_SERIES, 1): {
671 SourceCodes.STB: bytes([16, 1]),
672 SourceCodes.AV: bytes([16, 2]),
673 SourceCodes.DAB: bytes([16, 72]),
674 SourceCodes.FM: bytes([16, 54]),
675 SourceCodes.BD: bytes([16, 4]),
676 SourceCodes.GAME: bytes([16, 5]),
677 SourceCodes.VCR: bytes([16, 6]),
678 SourceCodes.CD: bytes([16, 7]),
679 SourceCodes.AUX: bytes([16, 8]),
680 SourceCodes.DISPLAY: bytes([16, 9]),
681 SourceCodes.SAT: bytes([16, 0]),
682 SourceCodes.PVR: bytes([16, 34]),
683 SourceCodes.USB: bytes([16, 18]),
684 SourceCodes.NET: bytes([16, 11]),
685 },
686 (ApiModel.API450_SERIES, 2): {
687 SourceCodes.STB: bytes([23, 8]),
688 SourceCodes.AV: bytes([23, 9]),
689 SourceCodes.DAB: bytes([23, 16]),
690 SourceCodes.FM: bytes([23, 14]),
691 SourceCodes.BD: bytes([23, 7]),
692 SourceCodes.GAME: bytes([23, 11]),
693 SourceCodes.CD: bytes([23, 6]),
694 SourceCodes.AUX: bytes([23, 13]),
695 SourceCodes.PVR: bytes([23, 15]),
696 SourceCodes.USB: bytes([23, 18]),
697 SourceCodes.NET: bytes([23, 19]),
698 SourceCodes.FOLLOW_ZONE_1: bytes([16, 20]),
699 },
700 (ApiModel.API860_SERIES, 1): {
701 SourceCodes.STB: bytes([16, 100]),
702 SourceCodes.AV: bytes([16, 94]),
703 SourceCodes.DAB: bytes([16, 72]),
704 SourceCodes.FM: bytes([16, 28]),
705 SourceCodes.BD: bytes([16, 98]),
706 SourceCodes.GAME: bytes([16, 97]),
707 SourceCodes.VCR: bytes([16, 119]),
708 SourceCodes.CD: bytes([16, 118]),
709 SourceCodes.AUX: bytes([16, 99]),
710 SourceCodes.DISPLAY: bytes([16, 58]),
711 SourceCodes.SAT: bytes([16, 27]),
712 SourceCodes.PVR: bytes([16, 96]),
713 SourceCodes.USB: bytes([16, 93]),
714 SourceCodes.NET: bytes([16, 92]),
715 },
716 (ApiModel.API860_SERIES, 2): {
717 SourceCodes.STB: bytes([23, 8]),
718 SourceCodes.AV: bytes([23, 9]),
719 SourceCodes.DAB: bytes([23, 16]),
720 SourceCodes.FM: bytes([23, 14]),
721 SourceCodes.BD: bytes([23, 7]),
722 SourceCodes.GAME: bytes([23, 11]),
723 SourceCodes.CD: bytes([23, 6]),
724 SourceCodes.AUX: bytes([23, 13]),
725 SourceCodes.PVR: bytes([23, 15]),
726 SourceCodes.USB: bytes([23, 18]),
727 SourceCodes.NET: bytes([23, 19]),
728 SourceCodes.SAT: bytes([23, 20]),
729 SourceCodes.VCR: bytes([23, 21]),
730 SourceCodes.FOLLOW_ZONE_1: bytes([16, 20]),
731 },
732 (ApiModel.APIHDA_SERIES, 1): {
733 SourceCodes.STB: bytes([16, 100]),
734 SourceCodes.AV: bytes([16, 94]),
735 SourceCodes.DAB: bytes([16, 72]),
736 SourceCodes.FM: bytes([16, 28]),
737 SourceCodes.BD: bytes([16, 98]),
738 SourceCodes.GAME: bytes([16, 97]),
739 SourceCodes.UHD: bytes([16, 125]),
740 SourceCodes.CD: bytes([16, 118]),
741 SourceCodes.AUX: bytes([16, 99]),
742 SourceCodes.DISPLAY: bytes([16, 58]),
743 SourceCodes.SAT: bytes([16, 27]),
744 SourceCodes.PVR: bytes([16, 96]),
745 SourceCodes.NET: bytes([16, 92]),
746 SourceCodes.BT: bytes([16, 122]),
747 },
748 (ApiModel.APIHDA_SERIES, 2): {
749 SourceCodes.STB: bytes([23, 8]),
750 SourceCodes.AV: bytes([23, 9]),
751 SourceCodes.DAB: bytes([23, 16]),
752 SourceCodes.FM: bytes([23, 14]),
753 SourceCodes.BD: bytes([23, 7]),
754 SourceCodes.GAME: bytes([23, 11]),
755 SourceCodes.CD: bytes([23, 6]),
756 SourceCodes.AUX: bytes([23, 13]),
757 SourceCodes.PVR: bytes([23, 15]),
758 SourceCodes.USB: bytes([23, 18]),
759 SourceCodes.NET: bytes([23, 19]),
760 SourceCodes.SAT: bytes([23, 20]),
761 SourceCodes.UHD: bytes([23, 23]),
762 SourceCodes.BT: bytes([23, 22]),
763 SourceCodes.FOLLOW_ZONE_1: bytes([16, 20]),
764 },
765 (ApiModel.APISA_SERIES, 1): {
766 SourceCodes.PHONO: bytes([16, 117]),
767 SourceCodes.CD: bytes([16, 118]),
768 SourceCodes.BD: bytes([16, 98]),
769 SourceCodes.SAT: bytes([16, 27]),
770 SourceCodes.PVR: bytes([16, 96]),
771 SourceCodes.AV: bytes([16, 94]),
772 SourceCodes.AUX: bytes([16, 99]),
773 SourceCodes.STB: bytes([16, 100]),
774 SourceCodes.NET: bytes([16, 92]),
775 SourceCodes.USB: bytes([16, 93]),
776 SourceCodes.GAME: bytes([16, 97]),
777 SourceCodes.ARC_ERC: bytes([16, 125]),
778 },
779 (ApiModel.APISA_SERIES, 2): {
780 SourceCodes.PHONO: bytes([16, 117]),
781 SourceCodes.CD: bytes([16, 118]),
782 SourceCodes.BD: bytes([16, 98]),
783 SourceCodes.SAT: bytes([16, 27]),
784 SourceCodes.PVR: bytes([16, 96]),
785 SourceCodes.AV: bytes([16, 94]),
786 SourceCodes.AUX: bytes([16, 99]),
787 SourceCodes.STB: bytes([16, 100]),
788 SourceCodes.NET: bytes([16, 92]),
789 SourceCodes.USB: bytes([16, 93]),
790 SourceCodes.GAME: bytes([16, 97]),
791 SourceCodes.ARC_ERC: bytes([16, 125]),
792 },
793 (ApiModel.APIST_SERIES, 1): {
794 SourceCodes.DIG1: bytes([21, 94]),
795 SourceCodes.DIG2: bytes([21, 98]),
796 SourceCodes.DIG3: bytes([21, 27]),
797 SourceCodes.DIG4: bytes([21, 97]),
798 SourceCodes.USB: bytes([21, 93]),
799 SourceCodes.NET: bytes([21, 92]),
800 },
801 (ApiModel.APIST_SERIES, 2): {},
802 (ApiModel.APIPA_SERIES, 1): {},
803 (ApiModel.APIPA_SERIES, 2): {},
804 }
805
806 RC5CODE_POWER = {
807 (ApiModel.API450_SERIES, 1): {True: bytes([16, 123]), False: bytes([16, 124])},
808 (ApiModel.API450_SERIES, 2): {True: bytes([23, 123]), False: bytes([23, 124])},
809 (ApiModel.API860_SERIES, 1): {True: bytes([16, 123]), False: bytes([16, 124])},
810 (ApiModel.API860_SERIES, 2): {True: bytes([23, 123]), False: bytes([23, 124])},
811 (ApiModel.APIHDA_SERIES, 1): {True: bytes([16, 123]), False: bytes([16, 124])},
812 (ApiModel.APIHDA_SERIES, 2): {True: bytes([23, 123]), False: bytes([23, 124])},
813 (ApiModel.APISA_SERIES, 1): {True: bytes([16, 123]), False: bytes([16, 124])},
814 (ApiModel.APISA_SERIES, 2): {True: bytes([16, 123]), False: bytes([16, 124])},
815 }
816
817 RC5CODE_MUTE = {
818 (ApiModel.API450_SERIES, 1): {
819 True: bytes([16, 119]),
820 False: bytes([16, 120]),
821 },
822 (ApiModel.API450_SERIES, 2): {
823 True: bytes([23, 4]),
824 False: bytes([23, 5]),
825 },
826 (ApiModel.API860_SERIES, 1): {
827 True: bytes([16, 26]),
828 False: bytes([16, 120]),
829 },
830 (ApiModel.API860_SERIES, 2): {
831 True: bytes([23, 4]),
832 False: bytes([23, 5]),
833 },
834 (ApiModel.APIHDA_SERIES, 1): {
835 True: bytes([16, 26]),
836 False: bytes([16, 120]),
837 },
838 (ApiModel.APIHDA_SERIES, 2): {
839 True: bytes([23, 4]),
840 False: bytes([23, 5]),
841 },
842 (ApiModel.APISA_SERIES, 1): {
843 True: bytes([16, 26]),
844 False: bytes([16, 120]),
845 },
846 (ApiModel.APISA_SERIES, 2): {
847 True: bytes([16, 26]),
848 False: bytes([16, 120]),
849 },
850 }
851
852 RC5CODE_VOLUME = {
853 (ApiModel.API450_SERIES, 1): {
854 True: bytes([16, 16]),
855 False: bytes([16, 17]),
856 },
857 (ApiModel.API450_SERIES, 2): {
858 True: bytes([23, 1]),
859 False: bytes([23, 2]),
860 },
861 (ApiModel.API860_SERIES, 1): {
862 True: bytes([16, 16]),
863 False: bytes([16, 17]),
864 },
865 (ApiModel.API860_SERIES, 2): {
866 True: bytes([23, 1]),
867 False: bytes([23, 2]),
868 },
869 (ApiModel.APIHDA_SERIES, 1): {
870 True: bytes([16, 16]),
871 False: bytes([16, 17]),
872 },
873 (ApiModel.APIHDA_SERIES, 2): {
874 True: bytes([23, 1]),
875 False: bytes([23, 2]),
876 },
877 (ApiModel.APISA_SERIES, 1): {
878 True: bytes([16, 16]),
879 False: bytes([16, 17]),
880 },
881 (ApiModel.APISA_SERIES, 2): {
882 True: bytes([16, 16]),
883 False: bytes([16, 17]),
884 },
885 (ApiModel.APIST_SERIES, 1): {
886 True: bytes([21, 86]),
887 False: bytes([21, 85]),
888 },
889 }
890
891
892 class IncomingVideoAspectRatio(IntOrTypeEnum):
893 UNDEFINED = 0x00
894 ASPECT_4_3 = 0x01
895 ASPECT_16_9 = 0x02
896
897
898 class IncomingVideoColorspace(IntOrTypeEnum):
899 NORMAL = 0x00
900 HDR10 = 0x01
901 DOLBY_VISION = 0x02
902 HLG = 0x03
903 HDR10_PLUS = 0x04
904
905
906 class IncomingAudioFormat(IntOrTypeEnum):
907 PCM = 0x00
908 ANALOGUE_DIRECT = 0x01
909 DOLBY_DIGITAL = 0x02
910 DOLBY_DIGITAL_EX = 0x03
911 DOLBY_DIGITAL_SURROUND = 0x04
912 DOLBY_DIGITAL_PLUS = 0x05
913 DOLBY_DIGITAL_TRUE_HD = 0x06
914 DTS = 0x07
915 DTS_96_24 = 0x08
916 DTS_ES_MATRIX = 0x09
917 DTS_ES_DISCRETE = 0x0A
918 DTS_ES_MATRIX_96_24 = 0x0B
919 DTS_ES_DISCRETE_96_24 = 0x0C
920 DTS_HD_MASTER_AUDIO = 0x0D
921 DTS_HD_HIGH_RES_AUDIO = 0x0E
922 DTS_LOW_BIT_RATE = 0x0F
923 DTS_CORE = 0x10
924 PCM_ZERO = 0x13
925 UNSUPPORTED = 0x14
926 UNDETECTED = 0x15
927 DOLBY_ATMOS = 0x16, APIVERSION_DOLBY_ATMOS_SERIES
928 DTS_X = 0x17, APIVERSION_DTS_X_SERIES
929 IMAX_ENHANCED = 0x18, APIVERSION_IMAX_SERIES
930 AURO_3D = 0x19, APIVERSION_AURO_SERIES
931
932
933 class IncomingAudioConfig(IntOrTypeEnum):
934 """List of possible audio configurations."""
935
936 DUAL_MONO = 0x00
937 MONO = 0x01
938 CENTER_ONLY = 0x01
939 STEREO_ONLY = 0x02
940 STEREO_SURR_MONO = 0x03
941 STEREO_SURR_LR = 0x04
942 STEREO_SURR_LR_BACK_MONO = 0x05
943 STEREO_SURR_LR_BACK_LR = 0x06
944 STEREO_SURR_LR_BACK_MATRIX = 0x07
945 STEREO_CENTER = 0x08
946 STEREO_CENTER_SURR_MONO = 0x09
947 STEREO_CENTER_SURR_LR = 0x0A
948 STEREO_CENTER_SURR_LR_BACK_MONO = 0x0B
949 STEREO_CENTER_SURR_LR_BACK_LR = 0x0C
950 STEREO_CENTER_SURR_LR_BACK_MATRIX = 0x0D
951 STEREO_DOWNMIX = 0x0E
952 STEREO_ONLY_LO_RO = 0x0F
953 DUAL_MONO_LFE = 0x10
954 MONO_LFE = 0x11
955 CENTER_LFE = 0x11
956 STEREO_LFE = 0x12
957 STEREO_SURR_MONO_LFE = 0x13
958 STEREO_SURR_LR_LFE = 0x14
959 STEREO_SURR_LR_BACK_MONO_LFE = 0x15
960 STEREO_SURR_LR_BACK_LR_LFE = 0x16
961 STEREO_SURR_LR_BACK_MATRIX_LFE = 0x17
962 STEREO_CENTER_LFE = 0x18
963 STEREO_CENTER_SURR_MONO_LFE = 0x19
964 STEREO_CENTER_SURR_LR_LFE = 0x1A
965 STEREO_CENTER_SURR_LR_BACK_MONO_LFE = 0x1B
966 STEREO_CENTER_SURR_LR_BACK_LR_LFE = 0x1C
967 STEREO_CENTER_SURR_LR_BACK_MATRIX_LFE = 0x1D
968 STEREO_DOWNMIX_LFE = 0x1E
969 STEREO_ONLY_LO_RO_LFE = 0x1F
970 UNKNOWN = 0x20
971 UNDETECTED = 0x21
972 AURO_QUAD = 0x30
973 AURO_5_0 = 0x31
974 AURO_5_1 = 0x32
975 AURO_2_2_2 = 0x33
976 AURO_8_0 = 0x34
977 AURO_9_1 = 0x35
978 AURO_10_1 = 0x36
979 AURO_11_1 = 0x37
980 AURO_13_1 = 0x38
981
982
983 class PresetType(IntOrTypeEnum):
984 """List of possible audio configurations."""
985
986 AM_FREQUENCY = 0x00
987 FM_FREQUENCY = 0x01
988 FM_RDS_NAME = 0x02
989 DAB = 0x03
990
991
992 @attr.s
993 class PresetDetail:
994 index = attr.ib(type=int)
995 type = attr.ib(type=Union[PresetType, int])
996 name = attr.ib(type=str)
997
998 @staticmethod
999 def from_bytes(data: bytes) -> "PresetDetail":
1000 type = PresetType.from_int(data[1])
1001 if type == PresetType.FM_RDS_NAME or type == PresetType.DAB:
1002 name = data[2:].decode("utf8").rstrip()
1003 elif type == PresetType.FM_FREQUENCY:
1004 name = f"{data[2]}.{data[3]:2} MHz"
1005 elif type == PresetType.AM_FREQUENCY:
1006 name = f"{data[2]}{data[3]:2} kHz"
1007 else:
1008 name = str(data[2:])
1009 return PresetDetail(data[0], type, name)
1010
1011
1012 @attr.s
1013 class VideoParameters:
1014 horizontal_resolution = attr.ib(type=int)
1015 vertical_resolution = attr.ib(type=int)
1016 refresh_rate = attr.ib(type=int)
1017 interlaced = attr.ib(type=bool)
1018 aspect_ratio = attr.ib(type=IncomingVideoAspectRatio)
1019 colorspace = attr.ib(type=IncomingVideoColorspace | None, default=None)
1020
1021 @staticmethod
1022 def from_bytes(data: bytes) -> "VideoParameters":
1023 return VideoParameters(
1024 horizontal_resolution=int.from_bytes(data[0:2], "big"),
1025 vertical_resolution=int.from_bytes(data[2:4], "big"),
1026 refresh_rate=data[4],
1027 interlaced=(data[5] == 0x01),
1028 aspect_ratio=IncomingVideoAspectRatio.from_int(data[6]),
1029 # Colorspace is not reported pre-HDA
1030 colorspace=IncomingVideoColorspace.from_int(data[7]) if len(data) >= 8 else None,
1031 )
1032
1033 def to_dict(self) -> dict[str, Any]:
1034 return {
1035 "horizontal_resolution": self.horizontal_resolution,
1036 "vertical_resolution": self.vertical_resolution,
1037 "refresh_rate": self.refresh_rate,
1038 "interlaced": self.interlaced,
1039 "aspect_ratio": self.aspect_ratio,
1040 "colorspace": self.colorspace,
1041 }
1042
1043
1044 @attr.s
1045 class ResponsePacket:
1046 """Represent a response from device."""
1047
1048 zn = attr.ib(type=int)
1049 cc = attr.ib(type=int)
1050 ac = attr.ib(type=int)
1051 data = attr.ib(type=bytes)
1052
1053 def respons_to(self, request: Union["AmxDuetRequest", "CommandPacket"]):
1054 if not isinstance(request, CommandPacket):
1055 return False
1056 return self.zn == request.zn and self.cc == request.cc
1057
1058 @staticmethod
1059 def from_bytes(data: bytes) -> "ResponsePacket":
1060 if len(data) < 6:
1061 raise InvalidPacket(f"Packet to short {data!r}")
1062
1063 if data[4] != len(data) - 6:
1064 raise InvalidPacket(f"Invalid length in data {data!r}")
1065
1066 return ResponsePacket(
1067 data[1],
1068 CommandCodes.from_int(data[2]),
1069 AnswerCodes.from_int(data[3]),
1070 data[5 : 5 + data[4]],
1071 )
1072
1073 def to_bytes(self):
1074 return bytes(
1075 [
1076 *PROTOCOL_STR,
1077 self.zn,
1078 self.cc,
1079 self.ac,
1080 len(self.data),
1081 *self.data,
1082 *PROTOCOL_ETR,
1083 ]
1084 )
1085
1086
1087 @attr.s
1088 class CommandPacket:
1089 """Represent a command sent to device."""
1090
1091 zn = attr.ib(type=int)
1092 cc = attr.ib(type=int)
1093 data = attr.ib(type=bytes)
1094
1095 def to_bytes(self):
1096 return bytes(
1097 [*PROTOCOL_STR, self.zn, self.cc, len(self.data), *self.data, *PROTOCOL_ETR]
1098 )
1099
1100 @staticmethod
1101 def from_bytes(data: bytes) -> "CommandPacket":
1102 if len(data) < 5:
1103 raise InvalidPacket(f"Packet to short {data!r}")
1104
1105 if data[3] != len(data) - 5:
1106 raise InvalidPacket(f"Invalid length in data {data!r}")
1107
1108 return CommandPacket(
1109 data[1], CommandCodes.from_int(data[2]), data[4 : 4 + data[3]]
1110 )
1111
1112
1113 @attr.s
1114 class AmxDuetRequest:
1115 @staticmethod
1116 def from_bytes(data: bytes) -> "AmxDuetRequest":
1117 if not data == b"AMX\r":
1118 raise InvalidPacket(f"Packet is not a amx request {data!r}")
1119 return AmxDuetRequest()
1120
1121 def to_bytes(self):
1122 return b"AMX\r"
1123
1124
1125 @attr.s
1126 class AmxDuetResponse:
1127 values = attr.ib(type=dict)
1128
1129 @property
1130 def device_class(self) -> str | None:
1131 return self.values.get("Device-SDKClass")
1132
1133 @property
1134 def device_make(self) -> str | None:
1135 return self.values.get("Device-Make")
1136
1137 @property
1138 def device_model(self) -> str | None:
1139 return self.values.get("Device-Model")
1140
1141 @property
1142 def device_revision(self) -> str | None:
1143 return self.values.get("Device-Revision")
1144
1145 def respons_to(self, packet: AmxDuetRequest | CommandPacket):
1146 if not isinstance(packet, AmxDuetRequest):
1147 return False
1148 return True
1149
1150 @staticmethod
1151 def from_bytes(data: bytes) -> "AmxDuetResponse":
1152 if not data.startswith(b"AMXB"):
1153 raise InvalidPacket(f"Packet is not a amx response {data!r}")
1154
1155 tags = re.findall(r"<(.+?)=(.+?)>", data[4:].decode("ASCII"))
1156 return AmxDuetResponse(dict(tags))
1157
1158 def to_bytes(self):
1159 res = (
1160 "AMXB"
1161 + "".join([f"<{key}={value}>" for key, value in self.values.items()])
1162 + "\r"
1163 )
1164 return res.encode("ASCII")
1165
1166
1167 async def _read_delimited(reader: asyncio.StreamReader, header_len) -> bytes | None:
1168 try:
1169 start = await reader.readexactly(1)
1170 if start == PROTOCOL_EOF:
1171 _LOGGER.debug("eof")
1172 return None
1173
1174 if start == PROTOCOL_STR:
1175 header = await reader.readexactly(header_len - 1)
1176 data_len = await reader.readexactly(1)
1177 data = await reader.readexactly(int.from_bytes(data_len, "big"))
1178 etr = await reader.readexactly(1)
1179
1180 if etr != PROTOCOL_ETR:
1181 raise InvalidPacket(f"unexpected etr byte {etr!r}")
1182
1183 packet = bytes([*start, *header, *data_len, *data, *etr])
1184 elif start == b"\x01":
1185 """Sometime the AMX header seem to be sent as \x01^AMX"""
1186 header = await reader.readexactly(4)
1187 if header != b"^AMX":
1188 raise InvalidPacket(f"Unexpected AMX header: {header!r}")
1189
1190 data = await reader.readuntil(PROTOCOL_ETR)
1191 packet = bytes([*b"AMX", *data])
1192 elif start == b"A":
1193 header = await reader.readexactly(2)
1194 if header != b"MX":
1195 raise InvalidPacket("Unexpected AMX header")
1196
1197 data = await reader.readuntil(PROTOCOL_ETR)
1198 packet = bytes([*start, *header, *data])
1199 elif start == b"\x00":
1200 raise NullPacket()
1201 else:
1202 raise InvalidPacket(f"unexpected str byte {start!r}")
1203
1204 return packet
1205
1206 except TimeoutError as exception:
1207 raise ConnectionFailed() from exception
1208 except ConnectionError as exception:
1209 raise ConnectionFailed() from exception
1210 except OSError as exception:
1211 raise ConnectionFailed() from exception
1212 except IncompleteReadError as exception:
1213 raise ConnectionFailed() from exception
1214
1215
1216 async def _read_response(
1217 reader: asyncio.StreamReader,
1218 ) -> ResponsePacket | AmxDuetResponse | None:
1219 data = await _read_delimited(reader, 4)
1220 if not data:
1221 return None
1222
1223 if data.startswith(b"AMX"):
1224 return AmxDuetResponse.from_bytes(data)
1225 else:
1226 return ResponsePacket.from_bytes(data)
1227
1228
1229 async def read_response(
1230 reader: asyncio.StreamReader,
1231 ) -> ResponsePacket | AmxDuetResponse | None:
1232 while True:
1233 try:
1234 data = await _read_response(reader)
1235 except InvalidPacket as e:
1236 _LOGGER.warning(str(e))
1237 continue
1238 except NullPacket:
1239 _LOGGER.debug("Ignoring 0x00 start byte sent from some devices")
1240 continue
1241 return data
1242
1243
1244 async def _read_command(
1245 reader: asyncio.StreamReader,
1246 ) -> CommandPacket | AmxDuetRequest | None:
1247 data = await _read_delimited(reader, 3)
1248 if not data:
1249 return None
1250 if data.startswith(b"AMX"):
1251 return AmxDuetRequest.from_bytes(data)
1252 else:
1253 return CommandPacket.from_bytes(data)
1254
1255
1256 async def read_command(
1257 reader: asyncio.StreamReader,
1258 ) -> CommandPacket | AmxDuetRequest | None:
1259 while True:
1260 try:
1261 data = await _read_command(reader)
1262 except InvalidPacket as e:
1263 _LOGGER.warning(str(e))
1264 continue
1265 return data
1266
1267
1268 async def write_packet(
1269 writer: asyncio.StreamWriter,
1270 packet: CommandPacket | ResponsePacket | AmxDuetRequest | AmxDuetResponse,
1271 ) -> None:
1272 try:
1273 data = packet.to_bytes()
1274 writer.write(data)
1275 async with asyncio.timeout(_WRITE_TIMEOUT):
1276 await writer.drain()
1277 except TimeoutError as exception:
1278 raise ConnectionFailed() from exception
1279 except ConnectionError as exception:
1280 raise ConnectionFailed() from exception
1281 except OSError as exception:
1282 raise ConnectionFailed() from exception