File: pyamaha.py

package info (click to toggle)
python-aiomusiccast 0.14.8-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, trixie
  • size: 496 kB
  • sloc: python: 2,965; makefile: 152
file content (2228 lines) | stat: -rw-r--r-- 87,795 bytes parent folder | download
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
# taken from github.com/rsc-dev/pyamaha, which is licensed under the MIT License
from __future__ import annotations

import urllib
from asyncio.transports import BaseTransport
from typing import Awaitable, Tuple
from urllib.parse import urlparse
import xml.etree.ElementTree as ET

import aiohttp
from aiomusiccast.exceptions import MusicCastConnectionException, MusicCastConfigurationException, \
    MusicCastParamException
import json
import logging
import queue
from datetime import datetime
from aiohttp import ClientError, ClientTimeout, ClientResponse
import asyncio

BAND = ['common', 'am', 'fm', 'dab']
CD_PLAYBACK = [
    'play',
    'stop',
    'pause',
    'previous',
    'next',
    'fast_reverse_start',
    'fast_reverse_end',
    'fast_forward_start',
    'fast_forward_end',
    'track_select ',
]
DIR = ['next', 'previous']
PLAYBACK = [
    'play',
    'stop',
    'pause',
    'play_pause',
    'previous',
    'next',
    'fast_reverse_start',
    'fast_reverse_end',
    'fast_forward_start',
    'fast_forward_end',
]
PRESET_BAND = ['common', 'separate']
ZONES = ['main', 'zone2', 'zone3', 'zone4']
SERVICE_INFO_TYPE = ['account_list', 'licensing', 'activation_code']
SLEEP = [0, 30, 60, 90, 120]
TUNING = ['up', 'down', 'cancel', 'auto_up', 'auto_down', 'tp_up', 'tp_down', 'direct']
TYPE = ['select', 'play', 'return']
POWER = ['on', 'standby', 'toggle']
LIST_ID = ['main', 'auto_complete', 'search_artist', 'search_track']
LANG = ['en', 'ja', 'fr', 'de', 'es', 'ru', 'it', 'zh']
WIFI = ['none', 'wep', 'wpa2-psk(aes)', 'mixed_mode']
WIFI_DIRECT = ['none', 'wpa2-psk(aes)']
STANDBY = ['off', 'on', 'auto']

RESPONSE_CODE = {
    0: 'Successful request',
    1: 'Initializing',
    2: 'Internal Error',
    3: 'Invalid Request (A method did not exist, a method wasn\'t appropriate etc.)',
    4: 'Invalid Parameter (Out of range, invalid characters etc.)',
    5: 'Guarded (Unable to setup in current status etc.)',
    6: 'Time Out',
    99: 'Firmware Updating',
    100: 'Access Error',
    101: 'Other Errors',
    102: 'Wrong User Name',
    103: 'Wrong Password',
    104: 'Account Expired',
    105: 'Account Disconnected/Gone Off/Shut Down',
    106: 'Account Number Reached to the Limit',
    107: 'Server Maintenance',
    108: 'Invalid Account',
    109: 'License Error',
    110: 'Read Only Mode',
    111: 'Max Stations',
    112: 'Access Denied',
}

_LOGGER = logging.getLogger(__name__)


class MusicCastUdpProtocol(asyncio.DatagramProtocol):
    transport: BaseTransport

    def __init__(self, handle_event) -> None:
        super().__init__()
        self.handle_event = handle_event

    def connection_made(self, transport):
        self.transport = transport

    def datagram_received(self, data, addr):
        message_data = None
        message_str = ""
        try:
            message_str = data.decode()
            message_data = json.loads(message_str)
        except UnicodeDecodeError:
            _LOGGER.error("Received non UTF-8 compliant message: %s", data)
        except ValueError:
            _LOGGER.error("Received invalid message: %s", message_str)
        except Exception:
            _LOGGER.exception("An unexpected error occurred while handling an UDP message.")
        finally:
            asyncio.create_task(self.handle_event(message_data))


class UrlBuilder:
    @classmethod
    def build_query_str(cls, query_params: dict[str, str], **kwargs):
        if not all([param in query_params.keys() for param in kwargs.keys()]):
            raise MusicCastParamException("Unknown parameter while building query string.")
        if not all(param in kwargs for param, req in query_params.items() if req):
            raise MusicCastParamException("Not all required params were provided.")
        return urllib.parse.urlencode({key: val for key, val in kwargs.items() if val is not None})

    @classmethod
    def build_url(cls, url: Tuple, **kwargs):
        return f"{url[0]}?{cls.build_query_str(url[1], **kwargs)}"

    @classmethod
    def build_zone_url(cls, url: Tuple, zone: str, **kwargs):
        base_url = url[0].format(host="{host}", zone=zone)
        return f"{base_url}?{cls.build_query_str(url[1], **kwargs)}"


class AsyncDevice:
    """
    Yamaha async device abstraction class.
    """

    ip: str
    handle_event: Awaitable[[dict], None] | None

    _messages: queue.Queue
    _transport: [BaseTransport, None]

    def __init__(
            self,
            client,
            ip,
            loop,
            handle_event=None,
            upnp_description=None
    ):
        """Ctor.

        Arguments:
            @param client: aiohttp client session.
            @param ip: Yamaha device IP.
        """
        self.ip = ip
        self.client: aiohttp.ClientSession = client
        self.loop = loop
        self.handle_event = handle_event
        self.upnp_description = upnp_description
        self.upnp_avt_ns = None
        self.upnp_avt_ctrl = None

        self._messages = queue.Queue()
        self._headers = {}
        self._transport = None

    # end-of-method __init__

    @property
    def transport(self):
        return self._transport

    async def enable_polling(self):
        # One protocol instance will be created to serve all
        # client requests.
        self._transport, _ = await self.loop.create_datagram_endpoint(
            lambda: MusicCastUdpProtocol(self.handle_event),
            local_addr=('0.0.0.0', 0))

        socket = self._transport.get_extra_info('socket')

        if socket is None:
            self.disable_polling()
            _LOGGER.error("Failed to open UDP connection")
            return

        port = socket.getsockname()[1]

        self._headers.update(
            {"X-AppName": "MusicCast/1.0", "X-AppPort": str(port)}
        )

        await self.request_json(System.get_device_info())

    def disable_polling(self):
        self._headers = {}

        self._transport.close()
        self._transport = None

    async def request(self, *args):
        """Request YamahaExtendedControl API URI.

        Arguments:
            @param args: URI link for GET or tupple (URI, data) for POST.
        """
        try:
            # If it is only a URI, send GET...
            if isinstance(args[0], str):
                return await self.get(args[0])
            else:
                # ...otherwise unpack tuple and send POST
                return await self.post(*(args[0]))
        except ClientError as ce:
            raise MusicCastConnectionException() from ce
        except TimeoutError as te:
            raise MusicCastConnectionException() from te

    # end-of-method request
    @classmethod
    async def build_json(cls, response: ClientResponse):
        """
        A method, which tries to decode the response with errors being ignored.
        @param response: The ClientResponse, which the data should be extrated from
        @return: A dictionary on success
        """
        try:
            text = await response.text()
        except UnicodeDecodeError:
            _LOGGER.warning("Failed to decode response. Trying to decode it with errors being ignored")
            text = await response.text(errors="ignore")
        try:
            return json.loads(text)
        except ValueError:
            _LOGGER.error("Failed to generate JSON from %s", text)
            raise

    async def request_json(self, *args):
        """Request YamahaExtendedControl API URI.

        Arguments:
            @param args: URI link for GET or tupple (URI, data) for POST.
        """
        try:
            # If it is only a URI, send GET...
            if isinstance(args[0], str):
                response = await self.get(args[0])
            else:
                # ...otherwise unpack tuple and send POST
                response = await self.post(*(args[0]))

            return await self.build_json(response)

        except ClientError as ce:
            raise MusicCastConnectionException() from ce
        except TimeoutError as te:
            raise MusicCastConnectionException() from te

    # end-of-method request_json

    async def get(self, uri):
        """Request given URI. Returns response object.

        Arguments:
            @param uri: URI to request
        """
        return await self.client.get(uri.format(host=self.ip), headers=self._headers, timeout=ClientTimeout(total=5))

    # end-of-method get

    async def post(self, uri, data):
        """Send POST request. Returns response object.

        Arguments:
            @param uri: URI to send POST
            @param data: POST data
        """
        return await self.client.post(
            uri.format(host=self.ip), data=json.dumps(data), headers=self._headers
        )

    # end-of-method post

    async def dlna_avt_request(self, action: str, dlna_body_args: dict):
        if not self.upnp_description:
            raise MusicCastConfigurationException("The UPNP description has to be set to perform this action.")

        upnp_port = urlparse(self.upnp_description).port

        if not self.upnp_avt_ctrl or not self.upnp_avt_ns:
            desc = await (await self.client.get(self.upnp_description)).text()
            service_list = desc[desc.find("<serviceList>"):desc.find("</serviceList>") + 14]
            services_xml = ET.fromstring(service_list)
            res = None
            for child in services_xml:
                service_id = child.find("serviceId")
                if service_id.text.find("AVT") != -1:
                    res = child
                    break

            if not res:
                raise MusicCastConfigurationException("Did not find the AVTransport service.")
            self.upnp_avt_ns = res.find("serviceType").text
            self.upnp_avt_ctrl = res.find("controlURL").text

        avt_ctrl_url = f"http://{self.ip}:{upnp_port}{self.upnp_avt_ctrl}"

        dlna_body = "".join(
            [
                f"<{key}>{value}</{key}>" for key, value in dlna_body_args.items()
            ]
        )

        body = (
            '<?xml version="1.0"?>'
            '<s:Envelope s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"'
            ' xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">'
            "<s:Body>"
            f'<u:{action} xmlns:u="{self.upnp_avt_ns}">'
            f"{dlna_body}"
            f"</u:{action}>"
            "</s:Body>"
            "</s:Envelope>"
        )

        headers = {
            'Content-Type': 'text/xml; charset="utf-8"',
            'SOAPACTION': f'"{self.upnp_avt_ns}#{action}"',
            'Accept': '*/*',
            'User-Agent': 'MusicCast/4673 (iOS)',  # Otherwise the main zone switches to server source on play commands
            "Content-Length": str(len(body)),
        }

        return await self.client.request("POST", avt_ctrl_url, headers=headers, data=body)

    pass


# end-of-class Device


class Dist:
    """APIs in regard to Link distribution related setting and getting information."""

    URI = {
        'GET_DISTRIBUTION_INFO': 'http://{host}/YamahaExtendedControl/v1/dist/getDistributionInfo',
        'SET_SERVER_INFO': 'http://{host}/YamahaExtendedControl/v1/dist/setServerInfo',
        'SET_CLIENT_INFO': 'http://{host}/YamahaExtendedControl/v1/dist/setClientInfo',
        'START_DISTRIBUTION': 'http://{host}/YamahaExtendedControl/v1/dist/startDistribution?num={num}',
        'STOP_DISTRIBUTION': 'http://{host}/YamahaExtendedControl/v1/dist/stopDistribution',
        'SET_GROUP_NAME': 'http://{host}/YamahaExtendedControl/v1/dist/setGroupName',
    }

    @staticmethod
    def get_distribution_info():
        """For retrieving a Device information related to Link distribution."""
        return Dist.URI['GET_DISTRIBUTION_INFO']

    # end-of-method get_distribution_info

    @staticmethod
    def set_server_info(group_id, zone=None, type=None, client_list=None):
        """For setting a Link distribution server (Link master).

        Arguments:
            @param group_id: Specify Group ID in 32-digit hex.
                        Specify "" (empty text) here to cancel a Device being the Link
                        distribution server. Group ID will be initialized ("000...")
                        after the cancel operation.
            @param zone: Specifies which target Zone ID to be the Link distribution
                    server. If nothing is specified, current setting is kept. Zone
                    ID to be the Link distribution server is confirmable using
                    system/getFeatures server_zone_list.
                    Values: "main" / "zone2" / "zone3" / "zone4"
            @param type: Specifies a type of adding or removing clients. Not necessary
                    to specify when canceling the Link master status.
                    Values: "add" / "remove"
            @param client_list: Specifies IP addresses of adding/removing clients. Specifiable
                           up to 9 clients
        """
        data = {'group_id': group_id}

        if zone is not None:
            data['zone'] = zone

        if type is not None:
            data['type'] = type

        if client_list is not None:
            data['client_list'] = client_list

        return Dist.URI['SET_SERVER_INFO'], data

    # end-of-method set_server_info

    @staticmethod
    def set_client_info(group_id, zones=None, server_ip_address=None):
        """For setting Link distributed clients. If a Device is already setup as Link distribution server, this
           client setup is denied by that Device: use this API after canceling a Device's Link distribution
           server setup using setServerInfo, then confirming that the target Device's role is changed to other
           values than "server" using getDistributionInfo.

        Arguments:
            @param group_id: Specifies Group ID in 32-digit hex.
                        Specify "" (empty text) here to cancel a Device being a Link
                        distributed client. Group ID will be initialized ("000...") after
                        the cancel operation.
            @param zones: Specifies which target Zone ID to be a Link distributed
                    client. Not necessary to specify when cancelling a client status.
                    Values: "main" / "zone2" / "zone3" / "zone4"
            @param server_ip_address: Specifies the IP Address of the Link distribution server.
        """
        data = {'group_id': group_id}

        if zones is not None:
            data['zone'] = zones

        if server_ip_address is not None:
            data['server_ip_address'] = server_ip_address

        return Dist.URI['SET_CLIENT_INFO'], data

    # end-of-method set_client_info

    @staticmethod
    def start_distribution(num):
        """For initiating Link distribution.
        This is valid to a Device that is setup as Link distribution server.

        Arguments:
            @param num: Specifies Link distribution number on current MusicCast Network.
        """
        return Dist.URI['START_DISTRIBUTION'].format(host='{host}', num=num)

    # end-of-method start_distribution

    @staticmethod
    def stop_distribution():
        """For quitting Link distribution.
        This is valid to a Device that is setup as Link distribution server.
        """
        return Dist.URI['STOP_DISTRIBUTION']

    # end-of-method stop_distribution

    @staticmethod
    def set_group_name(name):
        """For setting up Group Name.
        Note that Group Name is reserved in volatile memory.

        Arguments:
            @param name: Specifies Group Name. Use UTF-8 within 128 bytes. Default name
                    would be used if it's not setup or "" (empty text) is specified.
        """
        data = {'name': name}

        return Dist.URI['SET_GROUP_NAME'], data

    # end-of-method set_group_name

    pass


# end-of-class Dist


class System:
    """System commands."""

    URI = {
        'GET_DEVICE_INFO': 'http://{host}/YamahaExtendedControl/v1/system/getDeviceInfo',
        'GET_FEATURES': 'http://{host}/YamahaExtendedControl/v1/system/getFeatures',
        'GET_NETWORK_STATUS': 'http://{host}/YamahaExtendedControl/v1/system/getNetworkStatus',
        'GET_FUNC_STATUS': 'http://{host}/YamahaExtendedControl/v1/system/getFuncStatus',
        'SET_AUTOPOWER_STANDBY': 'http://{host}/YamahaExtendedControl/v1/system/setAutoPowerStandby?enable={enable}',
        'GET_LOCATION_INFO': 'http://{host}/YamahaExtendedControl/v1/system/getLocationInfo',
        'SEND_IR_CODE': 'http://{host}/YamahaExtendedControl/v1/system/sendIrCode?code={code}',
        'SET_WIRED_LAN': 'http://{host}/YamahaExtendedControl/v1/system/setWiredLan',
        'SET_WIRELESS_LAN': 'http://{host}/YamahaExtendedControl/v1/system/setWirelessLan',
        'SET_WIRELESS_DIRECT': 'http://{host}/YamahaExtendedControl/v1/system/setWirelessDirect',
        'SET_IP_SETTINGS': 'http://{host}/YamahaExtendedControl/v1/system/setIpSettings',
        'SET_NETWORK_NAME': 'http://{host}/YamahaExtendedControl/v1/system/setNetworkName',
        'SET_AIRPLAY_PIN': 'http://{host}/YamahaExtendedControl/v1/system/setAirPlayPin',
        'GET_MAC_ADDRESS_FILTER': 'http://{host}/YamahaExtendedControl/v1/system/getMacAddressFilter',
        'SET_MAC_ADDRESS_FILTER': 'http://{host}/YamahaExtendedControl/v1/system/setMacAddressFilter',
        'GET_NETWORK_STANDBY': 'http://{host}/YamahaExtendedControl/v1/system/getNetworkStandby',
        'SET_NETWORK_STANDBY': 'http://{host}/YamahaExtendedControl/v1/system/setNetworkStandby?standby={standby}',
        'GET_BLUETOOTH_INFO': 'http://{host}/YamahaExtendedControl/v1/system/getBluetoothInfo',
        'SET_BLUETOOTH_STANDBY': 'http://{host}/YamahaExtendedControl/v1/system/setBluetoothStandby?enable={enable}',
        'SET_BLUETOOTH_TX_SETTING':
            'http://{host}/YamahaExtendedControl/v1/system/setBluetoothTxSetting?enable={enable}',
        'GET_BLUETOOTH_DEVICE_LIST': 'http://{host}/YamahaExtendedControl/v1/system/getBluetoothDeviceList',
        'UPDATE_BLUETOOTH_DEVICE_LIST': 'http://{host}/YamahaExtendedControl/v1/system/updateBluetoothDeviceList',
        'CONNECT_BLUETOOTH_DEVICE':
            'http://{host}/YamahaExtendedControl/v1/system/connectBluetoothDevice?address={address}',
        'DISCONNECT_BLUETOOTH_DEVICE': 'http://{host}/YamahaExtendedControl/v1/system/disconnectBluetoothDevice',
        'SET_SPEAKER_A': 'http://{host}/YamahaExtendedControl/v1/system/setSpeakerA?enable={enable}',
        'SET_SPEAKER_B': 'http://{host}/YamahaExtendedControl/v1/system/setSpeakerB?enable={enable}',
        'SET_DIMMER': 'http://{host}/YamahaExtendedControl/v1/system/setDimmer?value={value}',
        'SET_ZONE_B_VOLUME_SYNC': 'http://{host}/YamahaExtendedControl/v1/system/setZoneBVolumeSync?enable={enable}',
        'SET_HDMI_OUT_1': 'http://{host}/YamahaExtendedControl/v1/system/setHdmiOut1?enable={enable}',
        'SET_HDMI_OUT_2': 'http://{host}/YamahaExtendedControl/v1/system/setHdmiOut2?enable={enable}',
        'GET_NAME_TEXT': 'http://{host}/YamahaExtendedControl/v1/system/getNameText?id={id}',
        'SET_NAME_TEXT': 'http://{host}/YamahaExtendedControl/v1/system/setNameText',
        'SET_SPEAKER_PATTERN': 'http://{host}/YamahaExtendedControl/v1/system/setSpeakerPattern?num={num}',
        'SET_PARTYMODE': 'http://{host}/YamahaExtendedControl/v1/system/setPartyMode?enable={enable}',
    }

    @staticmethod
    def get_device_info():
        """For retrieving basic information of a Device."""
        return System.URI['GET_DEVICE_INFO']

    # end-of-method get_device_info

    @staticmethod
    def get_features():
        """For retrieving feature information equipped with a Device."""
        return System.URI['GET_FEATURES']

    # end-of-method get_features

    @staticmethod
    def get_network_status():
        """For retrieving network related setup/information."""
        return System.URI['GET_NETWORK_STATUS']

    # end-of-method get_network_status

    @staticmethod
    def get_func_status():
        """For retrieving setup/information of overall system function.
        Parameters are readable only when corresponding functions are available in "func_list" of /system/getFeatures.
        """
        return System.URI['GET_FUNC_STATUS']

    # end-of-method get_func_status

    @staticmethod
    def set_autopower_standby(enable=True):
        """For setting Auto Power Standby status.
        Actual operations/reactions of enabling Auto Power Standby depend on each Device.

        Arguments:
        @param enable: Specifies Auto Power Standby status.
        """
        return System.URI['SET_AUTOPOWER_STANDBY'].format(
            host='{host}', enable=_bool_to_str(enable)
        )

    # end-of-method set_autopower_standby

    @staticmethod
    def get_location_info():
        """For retrieving Location information."""
        return System.URI['GET_LOCATION_INFO']

    # end-of-method get_location_info

    @staticmethod
    def send_ir_code(code):
        """For sending specific remote IR code.
        A Device is operated same as remote IR code reception. But continuous IR code cannot be used in this command.
        Refer to each Device's IR code list for details..

        Arguments:
        @param code: Specifies IR code in 8-digit hex.
        """
        return System.URI['SEND_IR_CODE'].format(host='{host}', code=code)

    # end-of-method send_ir_code

    @staticmethod
    def set_wired_lan(
            dhcp=None,
            ip_address=None,
            subnet_mask=None,
            default_gateway=None,
            dns_server_1=None,
            dns_server_2=None,
    ):
        """For setting Wired Network. Network connection is switched to wired by using this API. If no
        parameter is specified, current parameter is used. If set parameter is incomplete, it is possible not
        to provide network avalability.

        Arguments:
        @param dhcp: Specifies DHCP setting.
        @param ip_address: Specifies IP Address.
        @param subnet_mask: Specifies Subnet Mask.
        @param default_gateway: Specifies Default Gateway.
        @param dns_server_1: Specifies DNS Server 1.
        @param dns_server_2: Specifies DNS Server 2.
        """
        data = {}

        if dhcp is not None:
            data['dhcp'] = dhcp

        if ip_address is not None:
            data['ip_address'] = ip_address

        if subnet_mask is not None:
            data['subnet_mask'] = subnet_mask

        if default_gateway is not None:
            data['default_gateway'] = default_gateway

        if dns_server_1 is not None:
            data['dns_server_1'] = dns_server_1

        if dns_server_2 is not None:
            data['dns_server_2'] = dns_server_2

        return System.URI['SET_WIRED_LAN'].format(host='{host}'), data

    # end-of-method set_wired_lan

    @staticmethod
    def set_wireless_lan(
            ssid=None,
            wifi_type=None,
            key=None,
            dhcp=None,
            ip_address=None,
            subnet_mask=None,
            default_gateway=None,
            dns_server_1=None,
            dns_server_2=None,
    ):
        """For setting Wireless Network (Wi-Fi). Network connection is switched to wireless (Wi-Fi) by using
        this API. If no parameter is specified, current parameter is used. If set parameter is incomplete, it
        is possible not to provide network avalability.
        """
        data = {}

        if ssid is not None:
            data['ssid'] = ssid

        if wifi_type is not None:
            assert wifi_type in WIFI, 'Invalid TYPE value!'
            data['type'] = wifi_type

        if key is not None:
            data['key'] = key

        if dhcp is not None:
            data['dhcp'] = dhcp

        if ip_address is not None:
            data['ip_address'] = ip_address

        if subnet_mask is not None:
            data['subnet_mask'] = subnet_mask

        if default_gateway is not None:
            data['default_gateway'] = default_gateway

        if dns_server_1 is not None:
            data['dns_server_1'] = dns_server_1

        if dns_server_2 is not None:
            data['dns_server_2'] = dns_server_2

        return System.URI['SET_WIRELESS_LAN'].format(host='{host}'), data

    # end-of-method set_wireless_lan

    @staticmethod
    def set_wireless_direct(wifi_type=None, key=None):
        """For setting Wireless Network (Wireless Direct). Network connection is switched to wireless
        (Wireless Direct) by using this API. If no parameter is specified, current parameter is used. If set
        parameter is incomplete, it is possible not to provide network avalability.
        """
        data = {}

        if wifi_type is not None:
            assert wifi_type in WIFI_DIRECT, 'Invalid TYPE value!'
            data['type'] = wifi_type

        if key is not None:
            data['key'] = key

        return System.URI['SET_WIRELESS_DIRECT'].format(host='{host}'), data

    # end-of-method set_wireless_direct

    @staticmethod
    def set_ip_settings(
            dhcp, ip_address, subnet_mask, default_gateway, dns_server_1, dns_server_2
    ):
        """For setting IP. This API only set IP as maintain same network connection status (Wired/Wireless
        Lan/Wireless Direct/Extend). If no parameter is specified, current parameter is used. If set
        parameter is incomplete, it is possible not to provide network avalability.
        """
        data = {}

        if dhcp is not None:
            data['dhcp'] = dhcp

        if ip_address is not None:
            data['ip_address'] = ip_address

        if subnet_mask is not None:
            data['subnet_mask'] = subnet_mask

        if default_gateway is not None:
            data['default_gateway'] = default_gateway

        if dns_server_1 is not None:
            data['dns_server_1'] = dns_server_1

        if dns_server_2 is not None:
            data['dns_server_2'] = dns_server_2

        return System.URI['SET_WIRED_LAN'].format(host='{host}'), data

    # end-of-method set_ip_settings

    @staticmethod
    def set_network_name(name):
        """For setting Network Name (Friendly Name)"""
        return System.URI['SET_NETWORK_NAME'].format(host='{host}'), {'name': name}

    # end-of-method set_network_name

    @staticmethod
    def set_airplay_pin(pin):
        """For setting AirPlay PIN. This is valid only when "airplay" exists in "func_list" found in
        /system/getFuncStatus.
        """
        return System.URI['SET_AIRPLAY_PIN'].format(host='{host}'), {'pin': pin}

    # end-of-method set_airplay_pin

    @staticmethod
    def get_mac_address_filter():
        """For retrieving setup of MAC Address Filter"""
        return System.URI['GET_MAC_ADDRESS_FILTER']

    # end-of-method get_mac_address_filter

    @staticmethod
    def set_mac_address_filter(filter, *macs):
        """For setting MAC Address Filter"""
        data = {'filter': filter}

        for i, address in enumerate(macs):
            data['address_{}'.format(i + 1)]

            if i >= 9:
                break

        return System.URI['SET_MAC_ADDRESS_FILTER'].format(host='{host}'), data

    # end-of-method set_mac_address_filter

    @staticmethod
    def get_network_standby():
        """For retrieving setup of Network Standby"""
        return System.URI['GET_NETWORK_STANDBY']

    # end-of-method get_network_standby

    @staticmethod
    def set_network_standby(standby):
        """For setting Network Standby"""
        assert standby in STANDBY, 'Invalid STANDBY value!'
        return System.URI['SET_NETWORK_STANDBY'].format(host='{host}', standby=standby)

    # end-of-method set_network_standby

    @staticmethod
    def get_bluetooth_info():
        """For retrieving setup/information of Bluetooth. Parameters are readable only when corresponding
        functions are available in "func_list" of /system/getFuncStatus. "bluetooth_device" parameter is
        contained in "bluetooth_tx_setting".
        """
        return System.URI['GET_BLUETOOTH_INFO']

    # end-of-method get_bluetooth_info

    @staticmethod
    def set_bluetooth_standby(enable=True):
        """For setting Bluetooth Standby"""
        return System.URI['SET_BLUETOOTH_STANDBY'].format(
            host='{host}', enable=_bool_to_str(enable)
        )

    # end-of-method set_bluetooth_standby

    @staticmethod
    def set_bluetooth_tx_setting(enable=True):
        """For setting Bluetooth transmission"""
        return System.URI['SET_BLUETOOTH_TX_SETTING'].format(
            host='{host}', enable=_bool_to_str(enable)
        )

    # end-of-method set_bluetooth_tx_setting

    @staticmethod
    def get_bluetooth_device_list():
        """For retrieving Bluetooth (Sink) device list. This API is available only when "bluetooth_tx_setting"
        is true under /system/getFuncStatus.
        This device list information is in the cach. If update device list information, excute
        /system/updateBluetoothDeviceList.
        """
        return System.URI['GET_BLUETOOTH_DEVICE_LIST']

    # end-of-method get_bluetooth_device_list

    @staticmethod
    def update_bluetooth_device_list():
        """For updating Bluetooth (Sink) device list. This API is available only when "bluetooth_tx_setting"
        is true under /system/getFuncStatus.
        Retrieve update status and list information after finish updating via
        /system/getBluetoothDeviceList.
        """
        return System.URI['UPDATE_BLUETOOTH_DEVICE_LIST']

    # end-of-method update_bluetooth_device_list

    @staticmethod
    def connect_bluetooth_device(address):
        """For connecting Bluetooth (Sink) device. This API is available only when "bluetooth_tx_setting" is
        true under /system/getFuncStatus.
        It is possible to take time to return this API response issued after connection status is fixed.
        """
        return System.URI['CONNECT_BLUETOOTH_DEVICE'].format(
            host='{host}', address=address
        )

    # end-of-method connect_bluetooth_device

    @staticmethod
    def disconnect_bluetooth_device():
        """For disconnecting Bluetooth (Sink) device. This API is available only when "bluetooth_tx_setting"
        is true under /system/getFuncStatus.
        This API response is issued immediately after disconnect request is accepted.
        """
        return System.URI['DISCONNECT_BLUETOOTH_DEVICE']

    # end-of-method disconnect_bluetooth_device

    @staticmethod
    def set_speaker_a(enable=True):
        """For setting Speaker A status"""
        return System.URI['SET_SPEAKER_A'].format(
            host='{host}', enable=_bool_to_str(enable)
        )

    # end-of-method set_speaker_a

    @staticmethod
    def set_speaker_b(enable=True):
        """For setting Speaker A status"""
        return System.URI['SET_SPEAKER_B'].format(
            host='{host}', enable=_bool_to_str(enable)
        )

    # end-of-method set_speaker_b

    @staticmethod
    def set_dimmer(value):
        """For setting FL/LED Dimmer.

        Arguments:
        @param value: Setting Dimmer. Specifies -1 in case of auto setting.
                 Specifies 0 or more than 0 in case of manual setting.
                 Auto setting is available only when -1 is exists in vale range under
                 /system/getFeatures.
                 Value Range: calculated by minimum/maximum/step values gotten
                 via /system/getFeatures
        """
        return System.URI['SET_DIMMER'].format(host='{host}', value=value)

    # end-of-method set_dimmer

    @staticmethod
    def set_zone_b_volume_sync(enable):
        """For setting Zone B volume sync."""
        return System.URI['SET_ZONE_B_VOLUME_SYNC'].format(
            host='{host}', enable=_bool_to_str(enable)
        )

    # end-of-method set_zone_b_volume_sync

    @staticmethod
    def set_hdmi_out_1(enable):
        """set_hdmi_out_1."""
        return System.URI['SET_HDMI_OUT_1'].format(
            host='{host}', enable=_bool_to_str(enable)
        )

    # end-of-method set_hdmi_out_1

    @staticmethod
    def set_hdmi_out_2(enable):
        """set_hdmi_out_1."""
        return System.URI['SET_HDMI_OUT_2'].format(
            host='{host}', enable=_bool_to_str(enable)
        )

    # end-of-method set_hdmi_out_2

    @staticmethod
    def get_name_text(id):
        """For retrieving text information of Zone, Input, Sound program. If they can be renamed, can
        retrieve text information renamed.

        Arguments:
        @param id: Specifies ID. If no ID is specified, retrieve all information of
              Zone, Input, Sound program. Refer to "All ID List" for details (documentation).
        """
        return System.URI['GET_NAME_TEXT'].format(host='{host}', id=id)

    # end-of-method get_name_text

    @staticmethod
    def set_name_text(id, text):
        """For setting text information related to each ID of Zone, Input.

        Arguments:
        @param id: Specifies ID. Input ID can be specified only when
              " rename_enable " is true under /system/getFeatures.
              Sound Program ID can not be specified.
              Note:
              If "main" is specified, Network Name is overwritten with same
              text information to be acceptable both MusicCast CONTROLLER
              (Yamaha) and Spotify App. If Network Name is changed, "main"
              text information is not changed.
        @param text: Specifies text information (UTF-8 within 64 bytes).
                If "" (empty text) is specified, specifies default text information.
        """
        data = {'id': id, 'text': text}
        return System.URI['SET_NAME_TEXT'], data

    # end-of-method set_name_text

    @staticmethod
    def set_partymode(enable=True):
        """For  setting Party  Mode. Available  only  when "party_mode" exists
        in  system func_list  under /system/getFeatures

        Arguments:
        @param enable: boolean
        """
        return System.URI['SET_PARTYMODE'].format(
            host='{host}', enable=_bool_to_str(enable)
        )

    # end-of-method set_partymode

    @staticmethod
    def set_speaker_pattern(num):
        """For setting speaker of device. Available only when "speaker_pattern"
        function exists in system func_list under /system/getFeatures.

        Arguments:
        @param num: int Specifies Speaker pattern number. Values: speaker_pattern
               number from /system/getFeatures
        """
        return System.URI['SET_SPEAKER_PATTERN'].format(host='{host}', num=num)

    # end-of-method set_speaker_pattern

    pass


# end-of-class System


class Zone:
    """Zone commands."""

    URI = {
        'GET_STATUS': 'http://{host}/YamahaExtendedControl/v1/{zone}/getStatus',
        'GET_SOUND_PROGRAM_LIST': 'http://{host}/YamahaExtendedControl/v1/{zone}/getSoundProgramList',
        'SET_POWER': 'http://{host}/YamahaExtendedControl/v1/{zone}/setPower?power={power}',
        'SET_SLEEP': 'http://{host}/YamahaExtendedControl/v1/{zone}/setSleep?sleep={sleep}',
        'SET_VOLUME': 'http://{host}/YamahaExtendedControl/v1/{zone}/setVolume?volume={volume}',
        'SET_MUTE': 'http://{host}/YamahaExtendedControl/v1/{zone}/setMute?enable={enable}',
        'SET_INPUT': 'http://{host}/YamahaExtendedControl/v1/{zone}/setInput?input={input}&mode={mode}',
        'SET_SOUND_PROGRAM': 'http://{host}/YamahaExtendedControl/v1/{zone}/setSoundProgram?program={program}',
        'PREPARE_INPUT_CHANGE': 'http://{host}/YamahaExtendedControl/v1/{zone}/prepareInputChange?input={input}',
        'SET_SURROUND_3D': 'http://{host}/YamahaExtendedControl/v1/{zone}/set3dSurround?enable={enable}',
        'SET_DIRECT': 'http://{host}/YamahaExtendedControl/v1/{zone}/setDirect?enable={enable}',
        'SET_PURE_DIRECT': 'http://{host}/YamahaExtendedControl/v1/{zone}/setPureDirect?enable={enable}',
        'SET_ENHANCER': 'http://{host}/YamahaExtendedControl/v1/{zone}/setEnhancer?enable={enable}',
        'SET_TONE_CONTROL':
            (
                'http://{host}/YamahaExtendedControl/v1/{zone}/setToneControl',
                {'mode': False, 'bass': False, 'treble': False}
            ),
        'SET_EQUALIZER':
            (
                'http://{host}/YamahaExtendedControl/v1/{zone}/setEqualizer',
                {'mode': False, 'low': False, 'mid': False, 'high': False}
            ),
        'SET_BALANCE': 'http://{host}/YamahaExtendedControl/v1/{zone}/setBalance?value={value}',
        'SET_DIALOGUE_LEVEL': 'http://{host}/YamahaExtendedControl/v1/{zone}/setDialogueLevel?value={value}',
        'SET_DIALOGUE_LIFT': 'http://{host}/YamahaExtendedControl/v1/{zone}/setDialogueLift?value={value}',
        'SET_DTS_DIALOGUE_CONTROL': 'http://{host}/YamahaExtendedControl/v1/{zone}/setDtsDialogueControl?num={value}',
        'SET_CLEAR_VOICE': 'http://{host}/YamahaExtendedControl/v1/{zone}/setClearVoice?enable={enable}',
        'SET_SUBWOOFER_VOLUME': 'http://{host}/YamahaExtendedControl/v1/{zone}/setSubwooferVolume?volume={volume}',
        'SET_BASS_EXTENSION': 'http://{host}/YamahaExtendedControl/v1/{zone}/setBassExtension?enable={enable}',
        'SET_EXTRA_BASS': 'http://{host}/YamahaExtendedControl/v1/{zone}/setExtraBass?enable={enable}',
        'GET_SIGNAL_INFO': 'http://{host}/YamahaExtendedControl/v1/{zone}/getSignalInfo',
        'SET_LINK_CONTROL': 'http://{host}/YamahaExtendedControl/v1/{zone}/setLinkControl?control={control}',
        'SET_LINK_AUDIO_DELAY': 'http://{host}/YamahaExtendedControl/v1/{zone}/setLinkAudioDelay?delay={delay}',
        'SET_LINK_AUDIO_QUALITY': 'http://{host}/YamahaExtendedControl/v1/{zone}/setLinkAudioQuality?mode={mode}',
        'SET_ADAPTIVE_DRC': 'http://{host}/YamahaExtendedControl/v1/{zone}/setAdaptiveDrc?enable={enable}',
        'SET_SURR_DECODER_TYPE': 'http://{host}/YamahaExtendedControl/v1/{zone}/setSurroundDecoderType?type={option}',
    }

    @staticmethod
    def get_status(zone):
        """For retrieving basic information of each Zone like power, volume, input and so on.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return Zone.URI['GET_STATUS'].format(host='{host}', zone=zone)

    # end-of-method get_status

    @staticmethod
    def get_sound_program_list(zone):
        """For retrieving a list of Sound Program available in each Zone. It is possible for the list contents to
           be dynamically changed.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return Zone.URI['GET_SOUND_PROGRAM_LIST'].format(host='{host}', zone=zone)

    # end-of-method get_sound_program_list

    @staticmethod
    def set_power(zone, power):
        """For setting power status of each Zone.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param power: Specifies power status.
                     Values: 'on', 'standby', 'toggle'
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        assert power in POWER, 'Invalid POWER value!'
        return Zone.URI['SET_POWER'].format(host='{host}', zone=zone, power=power)

    # end-of-method set_power

    @staticmethod
    def set_sleep(zone, sleep):
        """For setting Sleep Timer for each Zone.
        With Zone B enabled Devices, target Zone is described as Master Power, but Main Zone is used to
        set it up via YXC.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param sleep: Specifies Sleep Time (unit in minutes)
                     Values: 0, 30, 60, 90, 120
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        assert sleep in SLEEP, 'Invalid SLEEP value!'
        return Zone.URI['SET_SLEEP'].format(host='{host}', zone=zone, sleep=sleep)

    # end-of-method set_sleep

    @staticmethod
    def set_volume(zone, volume, step):
        """For setting volume in each Zone. Values of specifying range and steps are different. There are
        some Devices that cannot allow this value to be go up to Device's maximum volume.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param volume: Specifies volume value
                      Value Range: calculated by minimum/maximum/step values gotten via /system/getFeatures.
                      (Available on and after API Version 1.17) 'up', 'down'
            @param step: Specifies volume step value if the volume is 'up' or 'down'. If
                    nothing specified, minimum step value is used implicitly.
                    (Available on and after API Version 1.17)
                    Values: Value range calculated by minimum/maximum/step values gotten via /system/getFeatures.
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        url = Zone.URI['SET_VOLUME'].format(
            host='{host}', zone=zone, volume=volume
        )
        if step:
            url += f"&step={step}"
        return url

    # end-of-method set_volume

    @staticmethod
    def set_mute(zone, enable=True):
        """For setting mute status in each Zone.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param enable: Specifying mute status. Default: True.
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return Zone.URI['SET_MUTE'].format(
            host='{host}', zone=zone, enable=_bool_to_str(enable)
        )

    # end-of-method set_mute

    @staticmethod
    def set_input(zone, input, mode):
        """For selecting each Zone input.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param input: Specifies Input ID.
                     Values: Input IDs gotten via /system/getFeatures
            @param mode: Specifies select mode. If no parameter is specified, actions of input change depend on a
            Device’s specification
            Value: "autoplay_disabled" (Restricts Auto Play of Net/USB related Inputs).
            Available on and after API Version 1.12
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return Zone.URI['SET_INPUT'].format(
            host='{host}', zone=zone, input=input, mode=mode
        )

    # end-of-method set_input

    @staticmethod
    def set_sound_program(zone, program):
        """For selecting Sound Programs.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param program: Specifies Sound Program ID.
                       Values: Sound Program IDs gotten via /system/getFeatures
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return Zone.URI['SET_SOUND_PROGRAM'].format(
            host='{host}', zone=zone, program=program
        )

    # end-of-method set_sound_program

    @staticmethod
    def prepare_input_change(zone, input):
        """Let a Device do necessary process before changing input in a specific zone. This is valid only
        when 'prepare_input_change' exists in 'func_list' found in /system/getFuncStatus.
        MusicCast CONTROLLER executes this API when an input icon is selected in a Room, right
        before sending various APIs (of retrieving list information etc.) regarding selecting input.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param input: Specifies Input ID.
                     Values: Input IDs gotten via /system/getFeatures
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return Zone.URI['PREPARE_INPUT_CHANGE'].format(
            host='{host}', zone=zone, input=input
        )

    # end-of-method prepare_input_change

    @staticmethod
    def set_surround_3d(zone, enable):
        """For setting 3D Surround status.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param enable: Specifies 3D Surround status.
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return Zone.URI['SET_SURROUND_3D'].format(
            host='{host}', zone=zone, enable=_bool_to_str(enable)
        )

    # end-of-method set_surround_3d

    @staticmethod
    def set_direct(zone, enable):
        """For setting Direct status.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param enable: Specifies Direct status.
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return Zone.URI['SET_DIRECT'].format(
            host='{host}', zone=zone, enable=_bool_to_str(enable)
        )

    # end-of-method set_direct

    @staticmethod
    def set_pure_direct(zone, enable):
        """For setting Pure Direct status.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param enable: Specifies Pure Direct status.
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return Zone.URI['SET_PURE_DIRECT'].format(
            host='{host}', zone=zone, enable=_bool_to_str(enable)
        )

    # end-of-method set_pure_direct

    @staticmethod
    def set_enhancer(zone, enable):
        """For setting Enhancer status.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param enable: Specifies Enhancer status.
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return Zone.URI['SET_ENHANCER'].format(
            host='{host}', zone=zone, enable=_bool_to_str(enable)
        )

    # end-of-method set_enhancer

    @staticmethod
    def set_tone_control(zone, mode, bass, treble):
        """For setting Tone Control in each Zone. Values of specifying range and steps are different.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param mode: Specifies Mode setting. If no parameter is specified, current Mode
                    setting is not changed.
                    Regardless of the Mode setting, bass/treble setting can be changed,
                    but valid only when Mode setting is "manual".
            @param bass: Specifies Bass value
                    Values: Value range calculated by minimum/maximum/step values
                    gotten via /system/getFeatures
            @param treble: Specifies Treble value
                      Values: Value range calculated by minimum/maximum/step values
                      gotten via /system/getFeatures
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return UrlBuilder.build_zone_url(Zone.URI["SET_TONE_CONTROL"], zone, mode=mode, bass=bass, treble=treble)

    # end-of-method set_tone_control

    @staticmethod
    def set_equalizer(zone, mode, low, mid, high):
        """For setting Equalizer in each Zone. Values of specifying range and steps are different.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param mode: Specifies Mode setting. If no parameter is specified, current Mode
                    setting is not changed.
                    Regardless of the Mode setting, low/mid/high setting can be
                    changed, but valid only when Mode setting is "manual".
                    Values: Values gotten via /system/getFeatures
            @param low: Specifies Low value
                   Values: Value range calculated by minimum/maximum/step values
                   gotten via /system/getFeatures
            @param mid: Specifies Mid value
                   Values: Value range calculated by minimum/maximum/step values
                   gotten via /system/getFeatures
            @param high: Specifies High value
                    Values: Value range calculated by minimum/maximum/step values
                    gotten via /system/getFeatures
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return UrlBuilder.build_zone_url(Zone.URI["SET_EQUALIZER"], zone, mode=mode, low=low, mid=mid, high=high)

    # end-of-method set_equalizer

    @staticmethod
    def set_balance(zone, value):
        """For setting L/R Balance in each Zone's speaker. Values of specifying range and steps are different.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param value: Specifies L/R Balance value. Negative values are for left side,
                     positive values are for right side balance.
                     Values: Value range calculated by minimum/maximum/step values
                     gotten via /system/getFeatures
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return Zone.URI['SET_BALANCE'].format(host='{host}', zone=zone, value=value)

    # end-of-method set_balance

    @staticmethod
    def set_dialogue_level(zone, value):
        """For setting Dialogue Level in each Zone. Values of specifying range and steps are different.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param value: Specifies Dialogue Level value
                     Values: Value range calculated by minimum/maximum/step values
                     gotten via /system/getFeatures
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return Zone.URI['SET_DIALOGUE_LEVEL'].format(
            host='{host}', zone=zone, value=value
        )

    # end-of-method set_dialogue_level

    @staticmethod
    def set_dialogue_lift(zone, value):
        """For setting Dialogue Lift in each Zone. Values of specifying range and steps are different.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param value: Specifies Dialogue Lift value
                     Values: Value range calculated by minimum/maximum/step values
                     gotten via /system/getFeatures
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return Zone.URI['SET_DIALOGUE_LIFT'].format(
            host='{host}', zone=zone, value=value
        )

    # end-of-method set_dialogue_lift

    @staticmethod
    def set_dts_dialogue_control(zone, value):
        """For setting DTS Dialogue Control in each Zone. Values of specifying range and steps are different.
        Undocumented method.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param value: Specifies DTS Dialogue Control value
                     Values: Value range calculated by minimum/maximum/step values
                     gotten via /system/getFeatures
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return Zone.URI['SET_DTS_DIALOGUE_CONTROL'].format(
            host='{host}', zone=zone, value=value
        )

    # end-of-method set_dts_dialogue_control

    @staticmethod
    def set_clear_voice(zone, enable):
        """For setting Clear Voice in each Zone.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param enable: Specifies Clear Voice setting
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return Zone.URI['SET_CLEAR_VOICE'].format(
            host='{host}', zone=zone, enable=_bool_to_str(enable)
        )

    # end-of-method set_clear_voice

    @staticmethod
    def set_subwoofer_volume(zone, volume):
        """For setting Subwoofer Volume in each Zone.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param volume: Specifies volume value
                      Values: Value range calculated by minimum/maximum/step values
                      gotten via /system/getFeatures
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return Zone.URI['SET_SUBWOOFER_VOLUME'].format(
            host='{host}', zone=zone, volume=volume
        )

    # end-of-method set_subwoofer_volume

    @staticmethod
    def set_bass_extension(zone, enable):
        """For setting Bass Extension in each Zone.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param enable: Specifies Bass Extension setting
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return Zone.URI['SET_BASS_EXTENSION'].format(
            host='{host}', zone=zone, enable=_bool_to_str(enable)
        )

    # end-of-method set_bass_extension

    @staticmethod
    def set_extra_bass(zone, enable):
        """For setting Extra Bass in each Zone.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param enable: Specifies Extra Bass setting
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return Zone.URI['SET_EXTRA_BASS'].format(
            host='{host}', zone=zone, enable=_bool_to_str(enable)
        )

    # end-of-method set_bass_extension

    @staticmethod
    def get_signal_info(zone):
        """For retrieving current playback signal information in each Zone.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return Zone.URI['GET_SIGNAL_INFO'].format(host='{host}', zone=zone)

    # end-of-method get_signal_info

    @staticmethod
    def set_link_control(zone, control):
        """For setting Link Control in each Zone.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param control: Specifies Link Control setting
                       Values: Values gotten via /system/getFeatures
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return Zone.URI['SET_LINK_CONTROL'].format(
            host='{host}', zone=zone, control=control
        )

    # end-of-method set_link_control

    @staticmethod
    def set_link_audio_delay(zone, delay):
        """For setting Link Audio Delay in each Zone. This setting is invalid when Link Control setting is
           "Stability Boost".

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param delay: Specifies Link Audio Delay setting
                     Values: Values gotten via /system/getFeatures
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return Zone.URI['SET_LINK_AUDIO_DELAY'].format(
            host='{host}', zone=zone, delay=delay
        )

    # end-of-method set_link_audio_delay

    @staticmethod
    def set_link_audio_quality(zone, quality):
        """For setting Link Audio Quality in each Zone.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param quality: Specifies Link Audio Quality setting
                    Values: Values gotten via /system/getFeatures
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return Zone.URI['SET_LINK_AUDIO_QUALITY'].format(
            host='{host}', zone=zone, mode=quality
        )

    # end-of-method set_link_audio_delay

    @classmethod
    def set_adaptive_drc(cls, zone, value):
        """For setting Link Audio Quality in each Zone.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param value: Specifies drc enable
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return Zone.URI['SET_ADAPTIVE_DRC'].format(
            host='{host}', zone=zone, enable=_bool_to_str(value)
        )

    @classmethod
    def set_surr_decoder_type(cls, zone, option):
        """For setting Surround decoder type in each Zone.

        Arguments:
            @param zone: Specifies target Zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param option: the surround decoder type to set
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return Zone.URI['SET_SURR_DECODER_TYPE'].format(
            host='{host}', zone=zone, option=option
        )

# end-of-class Zone


class Tuner:
    """APIs in regard to Tuner setting and getting information.
    Target inputs: AM / FM / DAB"""

    URI = {
        'GET_PRESET_INFO': 'http://{host}/YamahaExtendedControl/v1/tuner/getPresetInfo?band={band}',
        'GET_PLAY_INFO': 'http://{host}/YamahaExtendedControl/v1/tuner/getPlayInfo',
        'SET_FREQ': 'http://{host}/YamahaExtendedControl/v1/tuner/setFreq?band={band}&tuning={tuning}&num={num}',
        'RECALL_PRESET': 'http://{host}/YamahaExtendedControl/v1/tuner/recallPreset?zone={zone}&band={band}&num={num}',
        'SWITCH_PRESET': 'http://{host}/YamahaExtendedControl/v1/tuner/switchPreset?dir={dir}',
        'STORE_PRESET': 'http://{host}/YamahaExtendedControl/v1/tuner/storePreset?num={num}',
        'SET_DAB_SERVICE': 'http://{host}/YamahaExtendedControl/v1/tuner/setDabService?dir={dir}',
    }

    @staticmethod
    def get_preset_info(band):
        """For retrieving Tuner preset information.

        Arguments:
            @param band: Specifying a band. Values depend on Preset Type gotten via /system/getFeatures.
                    Values: 'common' (common), 'am', 'fm', 'dab' (separate)
        """
        assert band in BAND, 'Invalid BAND value!'
        return Tuner.URI['GET_PRESET_INFO'].format(host='{host}', band=band)

    # end-of-method get_preset_info

    @staticmethod
    def get_play_info():
        """For retrieving playback information of Tuner."""
        return Tuner.URI['GET_PLAY_INFO']

    # end-of-method get_play_info

    @staticmethod
    def set_freq(band, tuning, num):
        """For setting Tuner frequency.

        Arguments:
            @param band: Specifies Band. Values : 'am', 'fm'
            @param tuning: Specifies a tuning method. Use 'tp_up' and 'tp_down' only when Band is RDS.
                       Values: 'up', 'down', 'cancel', 'auto_up', 'auto_down',
                       'tp_up', 'tp_down', 'direct'
            @param num: Specifies frequency (unit in kHz). Valid only when tuning is 'direct'
        """
        assert band in BAND, 'Invalid BAND value!'
        assert tuning in TUNING, 'Invalid TUNING value!'
        return Tuner.URI['SET_FREQ'].format(
            host='{host}', band=band, tuning=tuning, num=num
        )

    # end-of-method set_freq

    @staticmethod
    def recall_preset(zone, band, num):
        """For recalling a Tuner preset.

        Arguments:
            @param zone: Specifies station recalling zone. This causes input change in specified zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param band: Specifies Band type. Depending on Preset Type gotten via
                    /system/getFeatures, specifying value is different
                    Values: 'common' (band common), 'separate' (each band preset)
            @param num: Specifies Preset number.
                   Value: one in the range gotten via /system/getFeatures
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        assert band in PRESET_BAND, 'Invalid BAND value!'
        return Tuner.URI['RECALL_PRESET'].format(
            host='{host}', zone=zone, band=band, num=num
        )

    # end-of-method recall_preset

    @staticmethod
    def switch_preset(dir):
        """For selecting Tuner preset.
        Call this API after change the target zone's input to Tuner. It is possible to change Band in case of
        preset type is 'common'. In case of preset type is 'separate', need to change the target Band
        before calling this API.
        This API is available on and after API Version 1.17.

        Arguments:
            @param dir: Specifies change direction of preset.
                   Values: 'next', 'previous'
        """
        assert dir in DIR, 'Invalid DIR value!'
        return Tuner.URI['SWITCH_PRESET'].format(host='{host}', dir=dir)

    # end-of-method switch_preset

    @staticmethod
    def store_preset(num):
        """For registering current station to a preset.

        Arguments:
            @param num: Specifying a preset number.
                   Value: one in the range gotten via /system/getFeatures
        """
        return Tuner.URI['STORE_PRESET'].format(host='{host}', num=num)

    # end-of-method store_preset

    @staticmethod
    def set_dab_service(dir):
        """For selecting DAB Service. Available only when DAB is valid to use.

        Arguments:
            @param dir: Specifies change direction of services.
                   Values: 'next', 'previous'
        """
        assert dir in DIR, 'Invalid DIR value!'
        return Tuner.URI['SET_DAB_SERVICE'].format(host='{host}', dir=dir)

    # end-of-method set_dab_service

    pass


# end-of-class Tuner


class NetUSB:
    """APIs in regard to Network/USB related setting and getting information
    Target Inputs: USB / Network related ones (Server / Net Radio / Pandora / Spotify / AirPlay etc.)"""

    URI = {
        'GET_PRESET_INFO': 'http://{host}/YamahaExtendedControl/v1/netusb/getPresetInfo',
        'GET_PLAY_INFO': 'http://{host}/YamahaExtendedControl/v1/netusb/getPlayInfo',
        'SET_PLAYBACK': 'http://{host}/YamahaExtendedControl/v1/netusb/setPlayback?playback={playback}',
        'TOGGLE_REPEAT': 'http://{host}/YamahaExtendedControl/v1/netusb/toggleRepeat',
        'TOGGLE_SHUFFLE': 'http://{host}/YamahaExtendedControl/v1/netusb/toggleShuffle',
        'GET_LIST_INFO': 'http://{host}/YamahaExtendedControl/v1/netusb/getListInfo?input={input}&index={index}&size={size}&lang={lang}&list_id={list_id}',
        'SET_LIST_CONTROL': 'http://{host}/YamahaExtendedControl/v1/netusb/setListControl?list_id={list_id}&type={type}&index={index}&zone={zone}',
        'SET_SEARCH_STRING': 'http://{host}/YamahaExtendedControl/v1/netusb/setSearchString',
        'RECALL_PRESET': 'http://{host}/YamahaExtendedControl/v1/netusb/recallPreset?zone={zone}&num={num}',
        'STORE_PRESET': 'http://{host}/YamahaExtendedControl/v1/netusb/storePreset?num={num}',
        'GET_ACCOUNT_STATUS': 'http://{host}/YamahaExtendedControl/v1/netusb/getAccountStatus',
        'SWITCH_ACCOUNT': 'http://{host}/YamahaExtendedControl/v1/netusb/switchAccount?input={input}&index={index}&timeout={timeout}',
        'GET_SERVICE_INFO': 'http://{host}/YamahaExtendedControl/v1/netusb/getServiceInfo?input={input}&type={type}&timeout={timeout}',
        'SET_REPEAT': 'http://{host}/YamahaExtendedControl/v1/netusb/setRepeat?mode={mode}',
        'SET_SHUFFLE': 'http://{host}/YamahaExtendedControl/v1/netusb/setShuffle?mode={mode}',
    }

    @staticmethod
    def get_preset_info():
        """For retrieving preset information. Presets are common use among Net/USB related input sources."""
        return NetUSB.URI['GET_PRESET_INFO']

    # end-of-method get_preset_info

    @staticmethod
    def get_play_info():
        """For retrieving playback information."""
        return NetUSB.URI['GET_PLAY_INFO']

    # end-of-method get_play_info

    @staticmethod
    def set_playback(playback):
        """For controlling playback status.

        Arguments:
            @param playback: Specifies playback status.
                        Values: 'play', 'stop', 'pause', 'play_pause', 'previous', 'next',
                        'fast_reverse_start', 'fast_reverse_end', 'fast_forward_start',
                        'fast_forward_end'
        """
        assert playback in PLAYBACK, 'Invalid PLAYBACK value!'
        return NetUSB.URI['SET_PLAYBACK'].format(host='{host}', playback=playback)

    # end-of-method set_playback

    @staticmethod
    def toggle_repeat():
        """For toggling repeat setting. No direct / discrete setting commands available."""
        return NetUSB.URI['TOGGLE_REPEAT']

    # end-of-method toggle_repeat

    @staticmethod
    def set_repeat(mode):
        """For setting repeat. Available on after API version 1.19.
        @param mode: Specifies the repeat setting. Value : "off" / "one" / "all"
        """
        return NetUSB.URI['SET_REPEAT'].format(
            host='{host}',
            mode=mode
        )

    @staticmethod
    def set_shuffle(mode):
        """For setting shuffle. Available on after API version 1.19.
        @param mode: Specifies the shuffle setting. Value : "off" / "on" / "songs" / "albums"
        """
        return NetUSB.URI['SET_SHUFFLE'].format(
            host='{host}',
            mode=mode
        )

    @staticmethod
    def toggle_shuffle():
        """For toggling shuffle setting. No direct / discrete setting commands available."""
        return NetUSB.URI['TOGGLE_SHUFFLE']

    # end-of-method toggle_shuffle

    @staticmethod
    def get_list_info(input, index, size, lang, list_id):
        """For retrieving list information. Basically this info is available to all relevant inputs, not limited to
        or independent from current input.

        Arguments:
                @param input: Specifies target Input ID. Controls for setListControl are to work
                         with the input specified here.
                         Values: Input IDs for Net/USB related sources
                @param index: Specifies the reference index (offset from the beginning of the list).
                         Note that this index must be in multiple of 8. If nothing was
                         specified, the reference index previously specified would be used.
                         Values: 0, 8, 16, 24, ..., 64984, 64992
                @param size: Specifies max list size retrieved at a time.
                        Value Range: 1 - 8
                @param lang: Specifies list language. But menu names or text info are not
                        always necessarily pulled in a language specified here. If nothing
                        specified, English ("en") is used implicitly
                        Values: 'en' (English), 'ja' (Japanese), 'fr' (French), 'de'
                        (German), 'es' (Spanish), 'ru' (Russian), 'it' (Italy), 'zh' (Chinese)
                @param list_id: Specifies list ID. If nothing specified, 'main' is chosen implicitly
                           Values: 'main' (common for all Net/USB sources)
                                   'auto_complete' (Pandora)
                                   'search_artist' (Pandora)
                                   'search_track' (Pandora)
        """
        assert lang in LANG, 'Invalid LANG value!'
        return NetUSB.URI['GET_LIST_INFO'].format(
            host='{host}',
            input=input,
            index=index,
            size=size,
            lang=lang,
            list_id=list_id,
        )

    # end-of-method get_list_info

    @staticmethod
    def set_list_control(list_id, type, index, zone):
        """For control a list. Controllable list info is not limited to or independent from current input.

        Arguments:
            @param list_id: Specifies list ID. If nothing specified, 'main' is chosen implicitly
                       Values: 'main' (common for all Net/USB sources)
                               'auto_complete' (Pandora)
                               'search_artist' (Pandora)
                               'search_track' (Pandora)
            @param type: Specifies list transition type. 'select' is to enter and get into one deeper layer than the current
                    layer where the element specified by the index belongs to. 'play' is to start playback current index
                    element, 'return' is to go back one upper layer than current. 'select' and 'play' needs to specify
                    an index at the same time. In case to 'select' an element with its attribute being 'Capable of Search',
                    specify search text using setSearchString in advance. (Or it is possible to specify search text and
                    move layers at the same time by specifying an index in setSearchString).
                    Values: 'select', 'play', 'return'
        """
        assert type in TYPE, 'Invalid TYPE value!'
        assert zone in ZONES, 'Invalid ZONE value!'
        return NetUSB.URI['SET_LIST_CONTROL'].format(
            host='{host}', list_id=list_id, type=type, index=index, zone=zone
        )

    # end-of-method set_list_control

    @staticmethod
    def set_search_string(search_string, list_id=None, index=None):
        """For setting search text.

        Specifies string executing this API before select an element with its attribute being “Capable of Search” or
        retrieve info about searching list(Pandora).

        Arguments:
                @param search_string: Value to search for.
                @param list_id: Specifies list ID. If nothing specified, 'main' is chosen implicitly
                           Values: 'main' (common for all Net/USB sources)
                                   'auto_complete' (Pandora)
                                   'search_artist' (Pandora)
                                   'search_track' (Pandora)
                @param index: Specifies an element position in the list being selected
                         (offset from the beginning of the list). Valid only when the list_id is "main".
                         Specifies index an element with its attribute being "Capable of Search"
                         Controls same as setListControl "select" are to work with the index an element specified.
                         If no index is specified, non-actions of select
                         Values : 0 ~ 64999
        """
        assert isinstance(search_string, str), "search_string has to be a str"
        payload = {'string': search_string}
        if list_id is not None:
            search_list_ids = ['main', 'auto_complete', 'search_artist', 'search_track']
            assert (
                    list_id in search_list_ids
            ), "list_id has to be one of the following " + str(search_list_ids)
            payload['list_id'] = list_id
        if index is not None:
            assert isinstance(index, int), "index has to be an int"
            payload['index'] = index

        return NetUSB.URI['SET_SEARCH_STRING'], payload

    # end-of-method set_search_string

    @staticmethod
    def recall_preset(zone, num):
        """For recalling a content preset.

        Arguments:
            @param zone: Specifies station recalling zone. This causes input change in specified zone.
                    Values: 'main', 'zone2', 'zone3', 'zone4'
            @param num: Specifies Preset number.
                   Value: one in the range gotten via /system/getFeatures
        """
        assert zone in ZONES, 'Invalid ZONE value!'
        return NetUSB.URI['RECALL_PRESET'].format(host='{host}', zone=zone, num=num)

    # end-of-method recall_preset

    @staticmethod
    def store_preset(num):
        """For registering current content to a preset. Presets are common use among Net/USB related
        input sources.

        Arguments:
            @param num: Specifying a preset number.
                   Value: one in the range gotten via /system/getFeatures
        """
        return NetUSB.URI['STORE_PRESET'].format(host='{host}', num=num)

    # end-of-method store_preset

    @staticmethod
    def get_account_status():
        """For retrieving account information registered on Device."""
        return NetUSB.URI['GET_ACCOUNT_STATUS']

    # end-of-method get_account_status

    @staticmethod
    def switch_account(input, index, timeout):
        """For switching account for service corresponding multi account.

        Arguments:
            @param input: Specifies target Input ID.
                     Value: 'pandora'
            @param index: Specifies switch account index.
                     Value : 0 - 7 (Pandora)
            @param timeout: Specifies timeout duration(ms) for this API process. If specifies 0,
                       treat as maximum value.
                       Value: 0 - 60000
        """
        return NetUSB.URI['SWITCH_ACCOUNT'].format(
            host='{host}', input=input, index=index, timeout=timeout
        )

    # end-of-method switch_account

    @staticmethod
    def get_service_info(input, type, timeout):
        """For retrieving information of various Streaming Service. The combination of Input/Type is available
        as follows;

        Account List (account_list) : retrieving list of account registed on Device
        Licensing (licensing) : checking license
        Activation Code (activation_code) : retrieving Activation Code
        * Disable to check Rhapsody license by refering the value of this APIs response_code. a
          Device issues events of netusb - account_updated by condition, retrieve the info excute
          /netusb/getAccountStatus. (Sometimes Deivice not issue events)
        * Before retrieve Activation Code, retrieve Account List and check not to reach Max about
          the num of registration.
        Note: Rhapsody service name will be changed to Napster.

        Arguments:
            @param timeout: Specifies type of retrieving info Value:
"account_list" (Pandora) "licensing" (Napster / Pandora) "activation_code" (Pandora)
            @param type: Specifies type of retrieving info Value:
"account_list" (Pandora) "licensing" (Napster / Pandora) "activation_code" (Pandora)
            @param input: Specifies target Input ID.
                     Value: 'pandora', 'rhapsody', 'napster'
        """
        return NetUSB.URI['GET_SERVICE_INFO'].format(
            host='{host}', input=input, type=type, timeout=timeout
        )

    # end-of-method switch_account

    pass


# end-of-class Network_USB


class CD:
    """APIs in regard to CD setting and getting information."""

    URI = {
        'GET_PLAY_INFO': 'http://{host}/YamahaExtendedControl/v1/cd/getPlayInfo',
        'SET_PLAYBACK': 'http://{host}/YamahaExtendedControl/v1/cd/setPlayback?playback={playback}&num={num}',
        'TOGGLE_TRAY': 'http://{host}/YamahaExtendedControl/v1/cd/toggleTray',
        'TOGGLE_REPEAT': 'http://{host}/YamahaExtendedControl/v1/cd/toggleRepeat',
        'TOGGLE_SHUFFLE': 'http://{host}/YamahaExtendedControl/v1/cd/toggleShuffle',
    }

    @staticmethod
    def get_play_info():
        """For retrieving playback information of CD."""
        return CD.URI['GET_PLAY_INFO']

    # end-of-method get_play_info

    @staticmethod
    def set_playback(playback, num):
        """For controlling playback status.

        Arguments:
        @param playback: Specifies playback status
                    Values: 'play', 'stop', 'pause', 'previous', 'next',
                            'fast_reverse_start', 'fast_reverse_end', 'fast_forward_start',
                            'fast_forward_end', 'track_select'

        @param num: Specifies target track number to playback.
               This parameter is valid only when playback "track_select" is specified.
               Values: 1-512
        """
        assert playback in PLAYBACK, 'Invalid PLAYBACK value!'
        return CD.URI['SET_PLAYBACK'].format(host='{host}', playback=playback, num=num)

    # end-of-method set_playback

    @staticmethod
    def toggle_tray():
        """For toggling CD tray Open/Close setting."""
        return CD.URI['TOGGLE_TRAY']

    # end-of-method toggle_tray

    @staticmethod
    def toggle_repeat():
        """For toggling repeat setting. No direct / discrete setting commands available."""
        return CD.URI['TOGGLE_REPEAT']

    # end-of-method toggle_repeat

    @staticmethod
    def toggle_shuffle():
        """For toggling shuffle setting. No direct / discrete setting commands available."""
        return CD.URI['TOGGLE_SHUFFLE']

    # end-of-method toggle_shuffle

    pass


# end-of-class CD


class Debug:
    """Undocumented Debug commands."""

    URI = {
        'GET_DIAG_INFO': 'http://{host}/YamahaExtendedControl/v1/debug/getDiagInfo',
        'GET_STATUS': 'http://{host}/YamahaExtendedControl/v1/debug/getStatus',
    }

    @staticmethod
    def get_diag_info():
        """None."""
        return Debug.URI['GET_DIAG_INFO']

    # end-of-method get_diag_info

    @staticmethod
    def get_status():
        """None."""
        return Debug.URI['GET_STATUS']

    # end-of-method get_status

    pass


# end-of-class Debug


class Clock:
    """APIs in regarding the clock/alarm setting and getting information."""

    URI = {
        'GET_CLOCK_SETTINGS': 'http://{host}/YamahaExtendedControl/v1/clock/getSettings',
        'SET_AUTO_SYNC': 'http://{host}/YamahaExtendedControl/v1/clock/setAutoSync?enable={enable}',
        'SET_DATE_AND_TIME': 'http://{host}/YamahaExtendedControl/v1/clock/setDateAndTime?date_time={date_time}',
        'SET_CLOCK_FORMAT': 'http://{host}/YamahaExtendedControl/v1/clock/setClockFormat?format={format}',
        'SET_ALARM_SETTINGS': 'http://{host}/YamahaExtendedControl/v1/clock/setAlarmSettings',
    }

    DAYS = [
        "oneday",
        "sunday",
        "monday",
        "tuesday",
        "wednesday",
        "thursday",
        "friday",
        "saturday",
    ]

    @staticmethod
    def get_clock_settings():
        """For retrieving setting related to Clock function."""
        return Clock.URI['GET_CLOCK_SETTINGS']

    @staticmethod
    def set_auto_sync(enable=True):
        """For setting clock time auto sync.

        Available only when "date_and_time" exists in clock - func_list under /system/getFeatures.

        Arguments:
        @param enable: Specifies whether or not clock auto sync is valid

        """
        assert isinstance(enable, bool)
        return Clock.URI['SET_AUTO_SYNC'].format(
            host='{host}', enable=_bool_to_str(enable)
        )

    @staticmethod
    def set_date_and_time(date_time: list[datetime, str]):
        """For setting date and clock time.

        Available only when "date_and_time" exists in clock - func_list under /system/getFeatures.

        Arguments:
        @param date_time: Specifies date and time set on device. Format is "YYMMDDhhmmss".
                     Value : YY : 00 ~ 99 (Year / 2000 ~ 2099)
                     MM : 01 ~ 12 (Month) DD : 01 ~ 31 (Day)
                     hh : 00 ~ 23 (Hour) mm : 00 ~ 59 (Minute) ss : 00 ~ 59 (Second).
                     Alternatively a python datetime object can be used.
        """
        if isinstance(date_time, datetime):
            dat_str = date_time.strftime('%y%m%d%H%M%S')
        else:
            assert isinstance(
                date_time, str
            ), "date_time has to be a str or datetime object."
            dat_str = date_time
        return Clock.URI['SET_DATE_AND_TIME'].format(host='{host}', date_time=dat_str)

    @staticmethod
    def set_clock_format(clock_format: int):
        """For setting format of time display.

        Available only when " clock_format " exists in clock - func_list under /system/getFeatures.

        Arguments:
        @param clock_format: format of time display
                  Values: 12 (12-hour notation) / 24 (24-hour notation)
        """
        assert (
                clock_format == 12 or clock_format == 24
        ), "Only 12 and 24 are possible formats"
        return Clock.URI['SET_CLOCK_FORMAT'].format(
            host='{host}', format=str(clock_format) + 'h'
        )

    @staticmethod
    def set_alarm_settings(
            alarm_on=None,
            volume=None,
            fade_interval=None,
            fade_type=None,
            mode=None,
            repeat=None,
            day=None,
            enable=None,
            alarm_time=None,
            beep=None,
            playback_type=None,
            resume_input=None,
            preset_type=None,
            preset_num=None,
            preset_snooze=None,
    ):
        """For setting alarm function.

        Arguments:
        @param alarm_on: Specifies alarm function status on/off
        @param volume: Specifies alarm volume value
                  Value Range : calculated by minimum/maximum/step value gotten via /system/getFeatures "alarm_volume"
        @param fade_interval: Specifies alarm fade interval (unit in second)
                         Value Range : calculated by minimum/maximum/step
                         value gotten via /system/getFeatures "alarm_fade"
        @param fade_type: Specifies alarm fade type
                     Value : 1 ~ fade_type_max ( value gotten via /system/getFeatures)
        @param mode: Specifies alarm mode
                Value : one gotten via /system/getFeatures "alarm_mode_list"
        @param repeat: Specifies repeat setting. This parameter is valid only when alarm mode "oneday" is specified
        @param day: Specifies target date for alarm setting.
                   This parameter is specified certainly when set detail parameters.
                   Value: "oneday" / "sunday" / "monday" / "tuesday" / "wednesday " / "thursday" / "friday" / "saturday"
        @param enable: 対象日のアラーム設定の有効/無効を指定します。:> WTF?
                    According to google translate: Specify whether to enable/disable the alarm setting for the target day
        @param alarm_time: Specifies alarm start-up time.
                        Format is "hhmm" Values : hh : 00 ~ 23 (Hour) mm : 00 ~ 59 (Minute)
        @param beep: Specifies whether or not beep is valid.
        @param playback_type: Specifies playback type Value : "resume" / "preset"
        @param resume_input: Specifies target Input ID to playback for resume.
                        No playback when "none" is specified.
                        Values: Input IDs gotten via /system/getFeatures "alarm_input_list"
                        This parameter is valid only when playback_type "resume" is specified.
        @param preset_type: Specifies preset type. Values: Type gotten via /system/getFeatures "alarm_preset_list".
                       This parameter is valid only when playback_type "preset" is specified.
        @param preset_num: Specifies preset number. Selectable preset number in each preset type is
                      readable in /system/getFeatures.
                      This parameter is valid only when playback_type "preset" is specified.
        @param preset_snooze: Returns snooze setting. Available only when "snooze" exists in func_list
                         under /system/getFeatures.
                         This parameter is valid only when playback_type "preset" is specified.
        """
        payload = {}
        if alarm_on is not None:
            assert isinstance(alarm_on, bool), "alarm_on has to be a boolean"
            payload['alarm_on'] = alarm_on
        if volume is not None:
            assert isinstance(volume, int), "volume has to be an integer"
            payload['volume'] = volume
        if fade_interval is not None:
            assert isinstance(fade_interval, int), "fade_interval has to be an integer"
            payload['fade_interval'] = fade_interval
        if fade_type is not None:
            assert isinstance(fade_type, int), "fade_type has to be an integer"
            payload['fade_type'] = fade_type
        if mode is not None:
            assert isinstance(mode, str), "mode has to be a str"
            payload['mode'] = mode
        if repeat is not None:
            assert isinstance(repeat, bool), "repeat has to be a bool"
            assert day == 'oneday', "repeat is only valid if day is oneday"
            payload['repeat'] = repeat
        if day is not None:
            assert day in Clock.DAYS, "day has to be one of the following " + str(
                Clock.DAYS
            )
            payload['detail'] = {}
            payload['detail']['day'] = day
            if enable is not None:
                assert isinstance(enable, bool), "enable has to be a bool"
                payload['detail']['enable'] = enable
            if alarm_time is not None:
                assert isinstance(alarm_time, str), "time has to be a str"
                payload['detail']['time'] = alarm_time
            if beep is not None:
                assert isinstance(beep, bool), "beep has to be a bool"
                payload['detail']['beep'] = beep
            if playback_type is not None:
                assert playback_type in [
                    'resume',
                    'preset',
                ], "playback_type has to be resume or preset"
                payload['detail']['playback_type'] = playback_type
                if playback_type == 'resume':
                    payload['detail']['resume'] = dict()
                    if resume_input is not None:
                        assert isinstance(resume_input, str), "resume_input has to be a str"
                        payload['detail']['resume']['input'] = resume_input

                    assert preset_type is None, "preset_type is not compatible with playback_type resume"
                    assert preset_num is None, "preset_num is not compatible with playback_type resume"
                    assert preset_snooze is None, "preset_snooze is not compatible with playback_type resume"
                else:
                    payload['detail']['preset'] = dict()
                    if preset_num is not None:
                        assert isinstance(
                            preset_num, int
                        ), "preset_num has to be an integer"
                        payload['detail']['preset']['num'] = preset_num
                    if preset_type is not None:
                        assert isinstance(preset_type, str), "preset_type has to be a str"
                        payload['detail']['preset']['type'] = preset_type
                    if preset_snooze is not None:
                        assert isinstance(
                            preset_snooze, bool
                        ), "preset_snooze has to be a bool"
                        payload['detail']['preset']['snooze'] = preset_snooze

                    assert resume_input is None, "resume_input is not compatible with playback_type preset"

        return Clock.URI['SET_ALARM_SETTINGS'], payload


# end-of-class Clock


def _bool_to_str(value):
    return str(value).lower()


if __name__ == '__main__':
    pass