File: device.py

package info (click to toggle)
python-songpal 0.16.2-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 1,516 kB
  • sloc: python: 2,097; makefile: 7
file content (568 lines) | stat: -rw-r--r-- 21,700 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
"""Module presenting a single supported device."""
import asyncio
import itertools
import logging
from collections import defaultdict
from pprint import pformat as pf
from typing import Any, Dict, List, Optional, Set, Type
from urllib.parse import urlparse

import aiohttp

from songpal.common import SongpalException
from songpal.containers import (
    AvailablePlaybackFunctions,
    Content,
    ContentInfo,
    Input,
    InterfaceInfo,
    PlayInfo,
    Power,
    Scheme,
    Setting,
    SettingsEntry,
    SoftwareUpdateInfo,
    Source,
    Storage,
    SupportedPlaybackFunctions,
    Sysinfo,
    Volume,
    Zone,
)
from songpal.notification import (
    ChangeNotification,
    ConnectChange,
    Notification,
    NotificationCallback,
)
from songpal.service import Service

_LOGGER = logging.getLogger(__name__)


class Device:
    """This is the main entry point for communicating with a device.

    In order to use this you need to obtain the URL for the API first.
    """

    WEBSOCKET_PROTOCOL = "v10.webapi.scalar.sony.com"
    WEBSOCKET_VERSION = 13

    def __init__(self, endpoint, force_protocol=None, debug=0):
        """Initialize Device.

        :param endpoint: the main API endpoint.
        :param force_protocol: can be used to force the protocol (xhrpost/websocket).
        :param debug: debug level. larger than 1 gives even more debug output.
        """
        self.debug = debug
        endpoint = urlparse(endpoint)
        self.endpoint = endpoint.geturl()
        _LOGGER.debug("Endpoint: %s", self.endpoint)

        self.guide_endpoint = endpoint._replace(path="/sony/guide").geturl()
        _LOGGER.debug("Guide endpoint: %s", self.guide_endpoint)

        if force_protocol:
            _LOGGER.warning("Forcing protocol %s", force_protocol)
        self.force_protocol = force_protocol

        self.idgen = itertools.count(start=1)
        self.services = {}  # type: Dict[str, Service]

        self.callbacks: Dict[Type, Set[NotificationCallback]] = defaultdict(set)

    async def __aenter__(self):
        """Asynchronous context manager, initializes the list of available methods."""
        await self.get_supported_methods()

    async def create_post_request(self, method: str, params: Dict = None):
        """Call the given method over POST.

        :param method: Name of the method
        :param params: dict of parameters
        :return: JSON object
        """
        if params is None:
            params = {}
        headers = {"Content-Type": "application/json"}
        payload = {
            "method": method,
            "params": [params],
            "id": next(self.idgen),
            "version": "1.0",
        }

        if self.debug > 1:
            _LOGGER.debug("> POST %s with body: %s", self.guide_endpoint, payload)

        try:
            async with aiohttp.ClientSession(headers=headers) as session:
                res = await session.post(
                    self.guide_endpoint, json=payload, headers=headers
                )
                if self.debug > 1:
                    _LOGGER.debug("Received %s: %s", res.status, res.text)
                if res.status != 200:
                    res_json = await res.json(content_type=None)
                    raise SongpalException(
                        f"Got a non-ok (status {res.status}) response for {method}",
                        error=res_json.get("error"),
                    )

                res_json = await res.json(content_type=None)
        except (aiohttp.InvalidURL, aiohttp.ClientConnectionError) as ex:
            raise SongpalException("Unable to do POST request: %s" % ex) from ex

        if "error" in res_json:
            raise SongpalException(
                "Got an error for %s" % method, error=res_json["error"]
            )

        if self.debug > 1:
            _LOGGER.debug("Got %s: %s", method, pf(res_json))

        return res_json

    async def request_supported_methods(self):
        """Return JSON formatted supported API."""
        return await self.create_post_request("getSupportedApiInfo")

    async def get_supported_methods(self, *, default_latest: bool = False):
        """Get information about supported methods.

        Calling this as the first thing before doing anything else is
        necessary to fill the available services table.
        """
        response = await self.request_supported_methods()

        if "result" in response:
            services = response["result"][0]
            _LOGGER.debug("Got %s services!", len(services))

            for x in services:
                serv = await Service.from_payload(
                    x, self.endpoint, self.idgen, self.debug, self.force_protocol
                )
                if serv is not None:
                    self.services[x["service"]] = serv
                else:
                    _LOGGER.warning("Unable to create service %s", x["service"])

            for service in self.services.values():
                if self.debug > 1:
                    _LOGGER.debug("Service %s", service)
                for api in service.methods:
                    # self.logger.debug("%s > %s" % (service, api))
                    if self.debug > 1:
                        _LOGGER.debug("> %s", api)
                    if api.latest_supported_version is None:
                        _LOGGER.debug(
                            "No supported version specified for %s.%s, using %s",
                            service.name,
                            api.name,
                            api.version,
                        )
                    elif default_latest:
                        api.use_version(api.latest_supported_version)
            return self.services

        return None

    async def get_power(self) -> Power:
        """Get the device state."""
        res = await self.services["system"]["getPowerStatus"]()
        return Power.make(**res)

    async def set_power(self, value: bool):
        """Toggle the device on and off."""
        if value:
            status = "active"
        else:
            status = "off"
        # TODO WoL works when quickboot is not enabled
        return await self.services["system"]["setPowerStatus"](status=status)

    async def get_play_info(self) -> List[PlayInfo]:
        """Return  of the device."""
        info = await self.services["avContent"]["getPlayingContentInfo"]({})
        return [PlayInfo.make(services=self.services, **x) for x in info]

    async def get_power_settings(self) -> List[Setting]:
        """Get power settings."""
        return [
            Setting.make(**x)
            for x in await self.services["system"]["getPowerSettings"]({})
        ]

    async def set_power_settings(self, target: str, value: str) -> bool:
        """Set power settings."""
        params = {"settings": [{"target": target, "value": value}]}
        return await self.services["system"]["setPowerSettings"](params)

    async def get_googlecast_settings(self) -> List[Setting]:
        """Get Googlecast settings."""
        return [
            Setting.make(**x)
            for x in await self.services["system"]["getWuTangInfo"]({})
        ]

    async def set_googlecast_settings(self, target: str, value: str):
        """Set Googlecast settings."""
        params = {"settings": [{"target": target, "value": value}]}
        return await self.services["system"]["setWuTangInfo"](params)

    async def request_settings_tree(self):
        """Get raw settings tree JSON.

        Prefer :func:get_settings: for containerized settings.
        """
        settings = await self.services["system"]["getSettingsTree"](usage="")
        return settings

    async def get_settings(self) -> List[SettingsEntry]:
        """Get a list of available settings.

        See :func:request_settings_tree: for raw settings.
        """
        settings = await self.request_settings_tree()
        return [SettingsEntry.make(**x) for x in settings["settings"]]

    async def get_misc_settings(self) -> List[Setting]:
        """Return miscellaneous settings such as name and timezone."""
        misc = await self.services["system"]["getDeviceMiscSettings"](target="")
        return [Setting.make(**x) for x in misc]

    async def set_misc_settings(self, target: str, value: str):
        """Change miscellaneous settings."""
        params = {"settings": [{"target": target, "value": value}]}
        return await self.services["system"]["setDeviceMiscSettings"](params)

    async def get_interface_information(self) -> InterfaceInfo:
        """Return generic product information."""
        iface = await self.services["system"]["getInterfaceInformation"]()
        return InterfaceInfo.make(**iface)

    async def get_system_info(self) -> Sysinfo:
        """Return system information including mac addresses and current version."""
        return Sysinfo.make(**await self.services["system"]["getSystemInformation"]())

    async def get_sleep_timer_settings(self) -> List[Setting]:
        """Get sleep timer settings."""
        return [
            Setting.make(**x)
            for x in await self.services["system"]["getSleepTimerSettings"]({})
        ]

    async def get_storage_list(self) -> List[Storage]:
        """Return information about connected storage devices."""
        return [
            Storage.make(**x)
            for x in await self.services["system"]["getStorageList"]({})
        ]

    async def get_update_info(self, from_network=True) -> SoftwareUpdateInfo:
        """Get information about updates."""
        if from_network:
            from_network = "true"
        else:
            from_network = "false"
        # from_network = ""
        info = await self.services["system"]["getSWUpdateInfo"](network=from_network)
        return SoftwareUpdateInfo.make(**info)

    async def activate_system_update(self) -> bool:
        """Start a system update if available."""
        return await self.services["system"]["actSWUpdate"]()

    async def get_inputs(self) -> List[Input]:
        """Return list of available outputs."""
        method = self.services["avContent"]["getCurrentExternalTerminalsStatus"]
        if method.supports_version("1.2"):
            method.use_version("1.2")
            res = await method({})
            active_input_uri = (await self.get_available_playback_functions())[0].uri
        else:
            res = await method()
        inputs = []
        for x in res:
            # Hidden inputs (device settings) return with title=""
            if x.get("title") and "meta:zone:output" not in x["meta"]:
                input_ = Input.make(services=self.services, **x)
                if method.supports_version("1.2"):
                    input_.active = input_.uri == active_input_uri
                inputs.append(input_)
        return inputs

    async def get_zones(self) -> List[Zone]:
        """Return list of available zones."""
        method = self.services["avContent"]["getCurrentExternalTerminalsStatus"]
        if method.supports_version("1.2"):
            method.use_version("1.2")
            res = await method({})
        else:
            res = await method()
        zones = [
            Zone.make(services=self.services, **x)
            for x in res
            if "meta:zone:output" in x["meta"]
        ]
        if not zones:
            raise SongpalException("Device has no zones")
        return zones

    async def get_zone(self, name) -> Zone:
        """Get zone by name."""
        zones = await self.get_zones()
        try:
            zone = next(x for x in zones if x.title == name)
            return zone
        except StopIteration:
            raise SongpalException(f"Unable to find zone {name}")

    async def get_setting(self, service: str, method: str, target: str):
        """Get a single setting for service.

        :param service: Service to query.
        :param method: Getter method for the setting, read from ApiMapping.
        :param target: Setting to query.
        :return: JSON response from the device.
        """
        return await self.services[service][method](target=target)

    async def get_bluetooth_settings(self) -> List[Setting]:
        """Get bluetooth settings."""
        bt = await self.services["avContent"]["getBluetoothSettings"]({})
        return [Setting.make(**x) for x in bt]

    async def set_bluetooth_settings(self, target: str, value: str) -> None:
        """Set bluetooth settings."""
        params = {"settings": [{"target": target, "value": value}]}
        return await self.services["avContent"]["setBluetoothSettings"](params)

    async def get_custom_eq(self, target=""):
        """Get custom EQ settings."""
        return await self.services["audio"]["getCustomEqualizerSettings"](
            {"target": target}
        )

    async def set_custom_eq(self, target: str, value: str) -> None:
        """Set custom EQ settings."""
        params = {"settings": [{"target": target, "value": value}]}
        return await self.services["audio"]["setCustomEqualizerSettings"](params)

    async def get_supported_playback_functions(
        self, uri=""
    ) -> List[SupportedPlaybackFunctions]:
        """Return list of inputs and their supported functions."""
        return [
            SupportedPlaybackFunctions.make(**x)
            for x in await self.services["avContent"]["getSupportedPlaybackFunction"](
                uri=uri
            )
        ]

    async def get_playback_settings(self) -> List[Setting]:
        """Get playback settings such as shuffle and repeat."""
        return [
            Setting.make(**x)
            for x in await self.services["avContent"]["getPlaybackModeSettings"]({})
        ]

    async def set_playback_settings(self, target, value) -> None:
        """Set playback settings such a shuffle and repeat."""
        params = {"settings": [{"target": target, "value": value}]}
        return await self.services["avContent"]["setPlaybackModeSettings"](params)

    async def get_schemes(self) -> List[Scheme]:
        """Return supported uri schemes."""
        return [
            Scheme.make(**x)
            for x in await self.services["avContent"]["getSchemeList"]()
        ]

    async def get_source_list(self, scheme: str = "") -> List[Source]:
        """Return available sources for playback."""
        method = self.services["avContent"]["getSourceList"]
        if method.supports_version("1.3"):
            if scheme == "extInput":
                raise SongpalException(
                    "Scheme not supported in version 1.3, use get_inputs() instead"
                )
            method.use_version("1.3")
        res = await method(scheme=scheme)
        return [Source.make(**x) for x in res]

    async def get_content_count(self, source: str):
        """Return file listing for source."""
        params = {"uri": source, "type": None, "target": "all", "view": "flat"}
        return ContentInfo.make(
            **await self.services["avContent"]["getContentCount"](params)
        )

    async def get_contents(self, uri) -> List[Content]:
        """Request content listing recursively for the given URI.

        :param uri: URI for the source.
        :return: List of Content objects.
        """
        contents = [
            Content.make(**x)
            for x in await self.services["avContent"]["getContentList"](uri=uri)
        ]
        contentlist = []

        for content in contents:
            if content.contentKind == "directory" and content.index >= 0:
                # print("got directory %s" % content.uri)
                res = await self.get_contents(content.uri)
                contentlist.extend(res)
            else:
                contentlist.append(content)
                # print("%s%s" % (' ' * depth, content))
        return contentlist

    async def get_volume_information(self) -> List[Volume]:
        """Get the volume information."""
        res = await self.services["audio"]["getVolumeInformation"]({})
        volume_info = [Volume.make(services=self.services, **x) for x in res]
        if len(volume_info) < 1:
            logging.warning("Unable to get volume information")
        elif len(volume_info) > 1:
            logging.debug("The device seems to have more than one volume setting.")
        return volume_info

    async def get_sound_settings(self, target="") -> List[Setting]:
        """Get the current sound settings.

        :param str target: settings target, defaults to all.
        """
        res = await self.services["audio"]["getSoundSettings"]({"target": target})
        return [Setting.make(**x) for x in res]

    async def get_soundfield(self) -> Setting:
        """Get the current sound field settings."""
        res = await self.services["audio"]["getSoundSettings"]({"target": "soundField"})
        return Setting.make(**res[0])

    async def set_soundfield(self, value):
        """Set soundfield."""
        return await self.set_sound_settings("soundField", value)

    async def set_sound_settings(self, target: str, value: str):
        """Change a sound setting."""
        params = {"settings": [{"target": target, "value": value}]}
        return await self.services["audio"]["setSoundSettings"](params)

    async def get_speaker_settings(self, target="") -> List[Setting]:
        """Return speaker settings."""
        speaker_settings = await self.services["audio"]["getSpeakerSettings"](
            {"target": target}
        )
        return [Setting.make(**x) for x in speaker_settings]

    async def set_speaker_settings(self, target: str, value: str):
        """Set speaker settings."""
        params = {"settings": [{"target": target, "value": value}]}
        return await self.services["audio"]["setSpeakerSettings"](params)

    async def get_available_playback_functions(
        self, output=""
    ) -> List[AvailablePlaybackFunctions]:
        """Return available playback functions.

        If no output is given the current is assumed.
        """
        return [
            AvailablePlaybackFunctions.make(**x)
            for x in await self.services["avContent"]["getAvailablePlaybackFunction"](
                output=output
            )
        ]

    def on_notification(self, type_, callback: NotificationCallback) -> None:
        """Register a notification callback.

        The callbacks registered by this method are called when an expected
        notification is received from the device.
        To listen for notifications call :func:listen_notifications:.
        :param type_: Type of the change, e.g., VolumeChange or PowerChange
        :param callback: Callback to call when a notification is received.
        :return:
        """
        self.callbacks[type_].add(callback)

    def clear_notification_callbacks(self):
        """Clear all notification callbacks."""
        self.callbacks.clear()

    async def listen_notifications(
        self, fallback_callback: Optional[NotificationCallback] = None
    ):
        """Listen for notifications from the device forever.

        Use :func:on_notification: to register what notifications to listen to.
        """
        tasks = []

        async def handle_notification(notification: ChangeNotification) -> None:
            fallback_callback_set = (
                {fallback_callback} if fallback_callback is not None else set()
            )

            callbacks = self.callbacks.get(type(notification), fallback_callback_set)
            if not callbacks:
                _LOGGER.debug("No callbacks defined for %s", notification)
                return

            await asyncio.gather(
                *(cb(notification) for cb in callbacks), return_exceptions=True
            )

        tasks = [
            asyncio.ensure_future(serv.listen_all_notifications(handle_notification))
            for serv in self.services.values()
        ]

        try:
            await asyncio.gather(*tasks)
        except Exception as ex:
            # TODO: do a slightly restricted exception handling?
            # Notify about disconnect
            await handle_notification(ConnectChange(connected=False, exception=ex))

    async def stop_listen_notifications(self):
        """Stop listening on notifications."""
        _LOGGER.debug("Stopping listening for notifications..")
        for serv in self.services.values():
            await serv.stop_listen_notifications()

        return True

    async def get_notifications(self) -> List[Notification]:
        """Get available notifications, which can then be subscribed to.

        Call :func:activate: to enable notifications, and :func:listen_notifications:
        to loop forever for notifications.

        :return: List of Notification objects
        """
        notifications = []
        for serv in self.services:
            for notification in self.services[serv].notifications:
                notifications.append(notification)
        return notifications

    async def raw_command(self, service: str, method: str, params: Any):
        """Call an arbitrary method with given parameters.

        This is useful for debugging and trying out commands before
        implementing them properly.
        :param service: Service, use list(self.services) to get a list of availables.
        :param method: Method to call.
        :param params: Parameters as a python object (e.g., dict, list)
        :return: Raw JSON response from the device.
        """
        _LOGGER.info("Calling %s.%s(%s)", service, method, params)
        return await self.services[service][method](params)