File: device.py

package info (click to toggle)
python-openhomedevice 2.3.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 300 kB
  • sloc: python: 1,973; xml: 765; makefile: 3
file content (293 lines) | stat: -rw-r--r-- 10,536 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
import json
import asyncio

from async_upnp_client.client_factory import UpnpFactory
from async_upnp_client.aiohttp import AiohttpRequester
# from async_upnp_client.aiohttp import AiohttpNotifyServer

import openhomedevice.didl_lite as didl_lite
import xml.etree.ElementTree as etree


# def on_event(service, service_variables):
#     """Handle a UPnP event."""
#     print(
#         "State variable change for %s, variables: %s",
#         service,
#         ",".join([sv.name for sv in service_variables]),
#     )
#     obj = {
#         "service_id": service.service_id,
#         "service_type": service.service_type,
#         "state_variables": {sv.name: sv.value for sv in service_variables},
#     }
#     print(json.dumps(obj))


class Device(object):
    def __init__(self, location):
        self.location = location

    def setup_services(self):
        self.product_service = self.device.service_id(
            "urn:av-openhome-org:serviceId:Product"
        )
        self.volume_service = self.device.service_id(
            "urn:av-openhome-org:serviceId:Volume"
        )
        self.transport_service = self.device.service_id(
            "urn:av-openhome-org:serviceId:Transport"
        )
        self.playlist_service = self.device.service_id(
            "urn:av-openhome-org:serviceId:Playlist"
        )
        self.info_service = self.device.service_id("urn:av-openhome-org:serviceId:Info")
        self.pins_service = self.device.service_id("urn:av-openhome-org:serviceId:Pins")
        self.radio_service = self.device.service_id(
            "urn:av-openhome-org:serviceId:Radio"
        )
        self.update_service = self.device.service_id("urn:linn-co-uk:serviceId:Update")

    async def init(self):
        requester = AiohttpRequester()
        factory = UpnpFactory(requester)
        self.device = await factory.async_create_device(self.location)
        self.setup_services()

    # async def subscribe(self, service):
    #     service.on_event = on_event
    #     await self.server.event_handler.async_subscribe(service)

    # async def setup_subscriptions(self):
    #     self.server = AiohttpNotifyServer(self.device.requester, 41234)
    #     await self.server.start_server()
    #     print("Listening on: %s", self.server.callback_url)

    #     await self.subscribe(self.product_service)
    #     await self.subscribe(self.volume_service)
    #     await self.subscribe(self.transport_service)
    #     await self.subscribe(self.info_service)

    #     while True:
    #         await asyncio.sleep(120)
    #         await self.server.event_handler.async_resubscribe_all()

    def uuid(self):
        return self.device.udn

    def manufacturer(self):
        return self.device.manufacturer
    
    def model_name(self):
        return self.device.model_name
    
    def friendly_name(self):
        return self.device.friendly_name

    async def name(self):
        action = self.product_service.action("Product")
        return (await action.async_call())["Name"]

    async def room(self):
        action = self.product_service.action("Product")
        return (await action.async_call())["Room"]

    async def set_standby(self, standby_requested):
        await self.product_service.action("SetStandby").async_call(
            Value=standby_requested
        )

    async def is_in_standby(self):
        action = self.product_service.action("Standby")
        return (await action.async_call())["Value"]

    async def transport_state(self):
        if self.transport_service:
            action = self.transport_service.action("TransportState")
            return (await action.async_call()).get("State")

        if (await self.source())["type"] == "Radio":
            action = self.radio_service.action("TransportState")
            return (await action.async_call()).get("Value")

        action = self.playlist_service.action("TransportState")
        return (await action.async_call()).get("Value")

    async def play(self):
        if self.transport_service:
            await self.transport_service.action("Play").async_call()
        else:
            if (await self.source())["type"] == "Radio":
                await self.radio_service.action("Play").async_call()
            else:
                await self.playlist_service.action("Play").async_call()

    async def play_media(self, track_details):
        if self.radio_service and track_details:
            set_channel_action = self.radio_service.action("SetChannel")
            uri = track_details.get("uri", "")
            await set_channel_action.async_call(
                Uri=uri, Metadata=didl_lite.generate_string(track_details)
            )
            await self.radio_service.action("Play").async_call()

    async def stop(self):
        if self.transport_service:
            await self.transport_service.action("Stop").async_call()
        else:
            if (await self.source())["type"] == "Radio":
                await self.radio_service.action("Stop").async_call()
            else:
                await self.playlist_service.action("Stop").async_call()

    async def pause(self):
        if self.transport_service:
            await self.transport_service.action("Pause").async_call()
        else:
            if (await self.source())["type"] == "Radio":
                await self.radio_service.action("Pause").async_call()
            else:
                await self.playlist_service.action("Pause").async_call()

    async def skip(self, offset):
        action = None
        if self.transport_service:
            action = (
                self.transport_service.action("SkipNext")
                if offset > 0
                else self.transport_service.action("SkipPrevious")
            )
        else:
            if (await self.source())["type"] == "Playlist":
                action = (
                    self.playlist_service.action("Next")
                    if offset > 0
                    else self.playlist_service.action("Previous")
                )
        if action:
            for x in range(0, abs(offset)):
                await action.async_call()

    async def source(self):
        index_action = self.product_service.action("SourceIndex")
        source_index = (await index_action.async_call())["Value"]
        source_action = self.product_service.action("Source")
        source_result = await source_action.async_call(Index=source_index)
        return {"type": source_result["Type"], "name": source_result["Name"]}

    @property
    def volume_enabled(self):
        return self.volume_service is not None

    async def volume(self):
        if not self.volume_enabled:
            return None

        action = self.volume_service.action("Volume")
        return (await action.async_call())["Value"]

    async def is_muted(self):
        if not self.volume_enabled:
            return None

        action = self.volume_service.action("Mute")
        result = await action.async_call()
        return result["Value"]

    async def set_volume(self, volume_level):
        if self.volume_enabled:
            action = self.volume_service.action("SetVolume")
            await action.async_call(Value=volume_level)

    async def increase_volume(self):
        if self.volume_enabled:
            await self.volume_service.action("VolumeInc").async_call()

    async def decrease_volume(self):
        if self.volume_enabled:
            await self.volume_service.action("VolumeDec").async_call()

    async def set_mute(self, mute_requested):
        if self.volume_enabled:
            await self.volume_service.action("SetMute").async_call(Value=mute_requested)

    async def set_source(self, index):
        await self.product_service.action("SetSourceIndex").async_call(Value=index)

    async def sources(self):
        action = self.product_service.action("SourceXml")
        result = await action.async_call()
        sources_list_xml = etree.fromstring(result["Value"])

        sources = []
        index = 0
        for source_xml in sources_list_xml:
            visible = source_xml.find("Visible").text == "true"
            if visible:
                sources.append(
                    {
                        "index": index,
                        "name": source_xml.find("Name").text,
                        "type": source_xml.find("Type").text,
                    }
                )
            index = index + 1
        return sources

    async def track_info(self):
        action = self.info_service.action("Track")
        result = await action.async_call()
        return didl_lite.parse(result["Metadata"])

    @property
    def pins_enabled(self):
        return self.device.has_service("urn:av-openhome-org:service:Pins:1")

    async def _get_pin_id_array(self):
        action = self.pins_service.action("GetIdArray")
        result = await action.async_call()
        return json.loads(result["IdArray"])

    async def _pin_metadata(self, ids):
        action = self.pins_service.action("ReadList")
        result = await action.async_call(Ids=json.dumps(ids))
        return json.loads(result["List"])

    async def pins(self):
        if not self.pins_enabled:
            return []

        action = self.pins_service.action("GetDeviceMax")
        max_pins = (await action.async_call())["DeviceMax"]
        pin_id_array = await self._get_pin_id_array()
        pin_metadata = await self._pin_metadata(pin_id_array)

        pins = list()
        for i in range(max_pins):
            if pin_metadata[i].get("id") > 0:
                pin = {
                    "index": i + 1,
                    "title": pin_metadata[i].get("title"),
                    "artworkUri": pin_metadata[i].get("artworkUri"),
                }
                pins.append(pin)
        return pins

    async def invoke_pin(self, pin_id):
        if self.pins_enabled:
            await self.pins_service.action("InvokeIndex").async_call(Index=(pin_id - 1))

    async def software_status(self):
        if self.update_service:
            action = self.update_service.action("GetSoftwareStatus")
            result = await action.async_call()
            return json.loads(result["SoftwareStatus"])

    async def check_latest_firmware(self):
        if self.update_service:
            action = await self.update_service.action("CheckNow").async_call()

    async def update_firmware(self):
        if self.update_service:
            await self.update_service.action("Apply").async_call()