File: client.py

package info (click to toggle)
python-ttls 1.10.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 168 kB
  • sloc: python: 1,043; makefile: 8
file content (578 lines) | stat: -rw-r--r-- 21,928 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
"""
Twinkly Twinkly Little Star
https://github.com/jschlyter/ttls

Copyright (c) 2019 Jakob Schlyter. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
"""

import base64
import logging
import os
import socket
import time
from collections.abc import Callable
from itertools import cycle, islice
from typing import Any

from aiohttp import (
    ClientResponseError,
    ClientSession,
    ClientTimeout,
    ServerDisconnectedError,
)
from aiohttp.web_exceptions import HTTPUnauthorized

from .colours import TwinklyColour, TwinklyColourTuple

_LOGGER = logging.getLogger(__name__)

TwinklyFrame = list[TwinklyColourTuple]
TwinklyResult = dict | None


TWINKLY_MODES = [
    "color",
    "demo",
    "effect",
    "movie",
    "off",
    "playlist",
    "rt",
]
RT_PAYLOAD_MAX_LIGHTS = 300

TWINKLY_MUSIC_DRIVERS_OFFICIAL = {
    "VU Meter": "00000000-0000-0000-0000-000000000001",
    "Beat Hue": "00000000-0000-0000-0000-000000000002",
    "Psychedelica": "00000000-0000-0000-0000-000000000003",
    "Red Vertigo": "00000000-0000-0000-0000-000000000004",
    "Dancing Bands": "00000000-0000-0000-0000-000000000005",
    "Diamond Swirl": "00000000-0000-0000-0000-000000000006",
    "Joyful Stripes": "00000000-0000-0000-0000-000000000007",
    "Angel Fade": "00000000-0000-0000-0000-000000000008",
    "Clockwork": "00000000-0000-0000-0000-000000000009",
    "Sipario": "00000000-0000-0000-0000-00000000000A",
    "Sunset": "00000000-0000-0000-0000-00000000000B",
    "Elevator": "00000000-0000-0000-0000-00000000000C",
}

TWINKLY_MUSIC_DRIVERS_UNOFFICIAL = {
    "VU Meter 2": "00000000-0000-0000-0000-000001000001",
    "Beat Hue 2": "00000000-0000-0000-0000-000001000002",
    "Psychedelica 2": "00000000-0000-0000-0000-000001000003",
    "Sparkle": "00000000-0000-0000-0000-000001000005",
    "Sparkle Hue": "00000000-0000-0000-0000-000001000006",
    "Psycho Sparkle": "00000000-0000-0000-0000-000001000007",
    "Psycho Hue": "00000000-0000-0000-0000-000001000008",
    "Red Line": "00000000-0000-0000-0000-000001000009",
    "Red Vertigo 2": "00000000-0000-0000-0000-000002000004",
    "Dancing Bands 2": "00000000-0000-0000-0000-000002000005",
    "Diamond Swirl 2": "00000000-0000-0000-0000-000002000006",
    "Angel Fade 2": "00000000-0000-0000-0000-000002000008",
    "Clockwork 2": "00000000-0000-0000-0000-000002000009",
    "Sunset 2": "00000000-0000-0000-0000-00000200000B",
}

TWINKLY_MUSIC_DRIVERS = {
    **TWINKLY_MUSIC_DRIVERS_OFFICIAL,
    **TWINKLY_MUSIC_DRIVERS_UNOFFICIAL,
}

TWINKLY_RETURN_CODE = "code"
TWINKLY_RETURN_CODE_OK = 1000

DEFAULT_TIMEOUT = 3


class Twinkly:
    def __init__(
        self,
        host: str,
        session: ClientSession | None = None,
        timeout: int | None = None,
        api_version: int | None = None,
    ):
        self.host = host
        self._timeout = ClientTimeout(total=timeout or DEFAULT_TIMEOUT)
        if session:
            self._session = session
            self._shared_session = True
        else:
            self._session = None
            self._shared_session = False
        self._socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        self._headers: dict[str, str] = {}
        self._rt_port = 7777
        self._expires = None
        self._token = None
        self._details: dict[str, str | int] = {}
        self._default_mode = "movie"
        self._api_version = api_version

    @property
    def base(self) -> str:
        if self._api_version is None:
            raise ValueError("api version isn't set")
        return f"http://{self.host}/xled/v{self._api_version}"

    @property
    def length(self) -> int:
        return int(self._details["number_of_led"])

    def is_rgbw(self) -> bool:
        return self._details["led_profile"] == "RGBW"

    def is_rgb(self) -> bool:
        return self._details["led_profile"] == "RGB"

    @property
    def default_mode(self) -> str:
        return self._default_mode

    @default_mode.setter
    def default_mode(self, mode: str | None = None) -> str:
        if not mode:
            return
        if mode not in TWINKLY_MODES:
            raise ValueError("Invalid mode")
        if mode == "off":
            _LOGGER.warning("Setting default mode to off")
        self._default_mode = mode

    async def close(self) -> None:
        if not self._shared_session:
            await self._get_session().close()
            self._session = None

    async def interview(self, force: bool | None = False) -> None:
        if len(self._details) == 0 or force:
            self._details = await self.get_details()
            mode = await self.get_mode()
            if mode.get("mode") != "off":
                self.default_mode = mode.get("mode")

    def _get_session(self):
        if not self._session:
            self._session = ClientSession()
        return self._session

    async def _info(self) -> Any:
        _LOGGER.debug("INFO")
        try:
            async with self._get_session().get(
                f"http://{self.host}/xled/info",
                timeout=self._timeout,
                raise_for_status=True,
            ) as r:
                _LOGGER.debug("INFO response %d", r.status)
                return await r.json()
        except (ClientResponseError, ServerDisconnectedError) as e:
            raise e

    async def get_api_version(self) -> int:
        if self._api_version is None:
            self._api_version = await self.detect_api_version()
        return self._api_version

    async def detect_api_version(self) -> int:
        try:
            self._api_version = 1
            _ = await self.get_details()
            return 1
        except (ClientResponseError, TwinklyError):
            pass

        try:
            self._api_version = 2
            _ = await self.get_details()
            return 2
        except (ClientResponseError, TwinklyError):
            pass

        self._api_version = None
        return None

    async def _post(self, endpoint: str, require_token: bool = True, **kwargs) -> Any:
        await self.get_api_version()
        if require_token:
            await self.ensure_token()
        _LOGGER.debug("POST endpoint %s", endpoint)
        if "json" in kwargs:
            _LOGGER.debug("POST payload %s", kwargs["json"])
        headers = kwargs.pop("headers", self._headers)
        retry_num = kwargs.pop("retry_num", 0)
        try:
            async with self._get_session().post(
                f"{self.base}/{endpoint}",
                headers=headers,
                timeout=self._timeout,
                raise_for_status=True,
                **kwargs,
            ) as r:
                _LOGGER.debug("POST response %d", r.status)
                return await r.json()
        except ClientResponseError as e:
            if e.status == HTTPUnauthorized.status_code:
                await self._handle_authorized(self._post, endpoint, exception=e, retry_num=retry_num, **kwargs)
            else:
                raise e

    async def _get(self, endpoint: str, require_token: bool = True, **kwargs) -> Any:
        await self.get_api_version()
        if require_token:
            await self.ensure_token()
        _LOGGER.debug("GET endpoint %s", endpoint)
        headers = kwargs.pop("headers", self._headers)
        retry_num = kwargs.pop("retry_num", 0)
        try:
            async with self._get_session().get(
                f"{self.base}/{endpoint}",
                headers=headers,
                timeout=self._timeout,
                raise_for_status=True,
                **kwargs,
            ) as r:
                _LOGGER.debug("GET response %d", r.status)
                return await r.json()
        except ClientResponseError as e:
            if e.status == HTTPUnauthorized.status_code:
                return await self._handle_authorized(
                    self._get,
                    endpoint,
                    exception=e,
                    retry_num=retry_num,
                    **kwargs,
                )
            else:
                raise e

    async def _handle_authorized(self, request_method: Callable, endpoint: str, exception: Exception, **kwargs) -> None:
        max_retries = 1
        retry_num = kwargs.pop("retry_num", 0)

        if retry_num >= max_retries:
            _LOGGER.debug(f"Invalid token for request. Maximum retries of {max_retries} exceeded.")
            raise exception

        retry_num += 1
        _LOGGER.debug(
            "Invalid token for request. " + f"Refreshing token and attempting retry {retry_num} of {max_retries}."
        )
        await self.refresh_token()
        return await request_method(endpoint, headers=self._headers, retry_num=retry_num, **kwargs)

    async def refresh_token(self) -> None:
        await self.login()
        await self.verify_login()
        _LOGGER.debug("Authentication token refreshed")

    async def ensure_token(self) -> str:
        if self._expires is None or self._expires <= time.time():
            _LOGGER.debug("Authentication token expired, will refresh")
            await self.refresh_token()
        else:
            _LOGGER.debug("Authentication token still valid")
        return self._token or ""

    async def login(self) -> None:
        challenge = base64.b64encode(os.urandom(32)).decode()
        payload = {"challenge": challenge}
        async with self._get_session().post(
            f"{self.base}/login",
            json=payload,
            timeout=self._timeout,
            raise_for_status=True,
        ) as r:
            data = await r.json()
        self._token = data["authentication_token"]
        self._headers["X-Auth-Token"] = self._token
        self._expires = time.time() + data["authentication_token_expires_in"]

    async def logout(self) -> None:
        await self._post("logout", json={})
        self._token = None

    async def verify_login(self) -> None:
        await self._post("verify", json={})

    async def get_name(self) -> Any:
        endpoint = "device_name" if await self.get_api_version() == 1 else "device/name"
        return self._valid_response(await self._get(endpoint))

    async def set_name(self, name: str) -> Any:
        endpoint = "device_name" if await self.get_api_version() == 1 else "device/name"
        return await self._post(endpoint, json={"name": name})

    async def reset(self) -> Any:
        return self._valid_response(await self._get("reset"))

    async def get_network_status(self) -> Any:
        endpoint = "network/status" if await self.get_api_version() == 1 else "network/eth/status"
        return self._valid_response(await self._get(endpoint))

    async def get_firmware_version(self) -> Any:
        endpoint = "fw/version" if await self.get_api_version() == 1 else "fw/ct1/version"
        return self._valid_response(await self._get(endpoint))

    async def get_details(self) -> Any:
        return self._valid_response(await self._get("gestalt", require_token=False))

    async def is_on(self) -> bool | None:
        mode = await self.get_mode()
        if mode is None:
            return None
        return mode.get("mode", "off") != "off"

    async def turn_on(self) -> Any:
        return await self.set_mode(self._default_mode)

    async def turn_off(self) -> Any:
        return await self.set_mode("off")

    async def get_brightness(self) -> Any:
        return self._valid_response(await self._get("led/out/brightness"))

    async def set_brightness(self, percent: int) -> Any:
        args = {"value": percent, "type": "A"}
        if await self.get_api_version() >= 2:
            args["mode"] = "enabled"
        return await self._post("led/out/brightness", json=args)

    async def get_mode(self) -> Any:
        endpoint = "led/mode" if await self.get_api_version() == 1 else "application/mode"
        return self._valid_response(await self._get(endpoint))

    async def set_mode(self, mode: str) -> Any:
        endpoint = "led/mode" if await self.get_api_version() == 1 else "application/mode"
        return await self._post(endpoint, json={"mode": mode})

    async def get_mqtt(self) -> Any:
        return self._valid_response(await self._get("mqtt/config"))

    async def set_mqtt(self, data: dict) -> Any:
        return await self._post("mqtt/config", json=data)

    async def send_frame(self, frame: TwinklyFrame) -> None:
        await self.interview()
        if len(frame) != self.length:
            raise ValueError("Invalid frame length")
        token = await self.ensure_token()
        header = bytes([0x01]) + bytes(base64.b64decode(token)) + bytes([self.length])
        payload = []
        for x in frame:
            payload.extend(list(x))
        self._socket.sendto(header + bytes(payload), (self.host, self._rt_port))

    async def send_frame_2(self, frame: TwinklyFrame) -> None:
        await self.interview()
        if len(frame) != self.length:
            raise ValueError("Invalid frame length")
        token = await self.ensure_token()
        frame_segments = [frame[i : i + RT_PAYLOAD_MAX_LIGHTS] for i in range(0, len(frame), RT_PAYLOAD_MAX_LIGHTS)]
        for i in range(0, len(frame_segments)):
            header = bytes([len(frame_segments)]) + bytes(base64.b64decode(token)) + bytes([0, 0]) + bytes([i])
            payload = []
            for x in frame_segments[i]:
                payload.extend(list(x))
            self._socket.sendto(header + bytes(payload), (self.host, self._rt_port))

    async def get_movie_config(self) -> Any:
        if await self.get_api_version() != 1:
            raise NotImplementedError
        return self._valid_response(await self._get("led/movie/config"))

    async def set_movie_config(self, data: dict) -> Any:
        return await self._post("led/movie/config", json=data)

    async def upload_movie(self, movie: bytes) -> Any:
        return await self._post(
            "led/movie/full",
            data=movie,
            headers={"Content-Type": "application/octet-stream"},
        )

    async def set_static_colour(
        self,
        colour: TwinklyColour | TwinklyColourTuple | list[TwinklyColour] | list[TwinklyColourTuple],
    ) -> None:
        if not self._details:
            await self.interview()
        if isinstance(colour, list):
            colour = colour[0]
        if isinstance(colour, tuple):
            colour = TwinklyColour.from_twinkly_tuple(colour)
        if await self.get_api_version() == 1:
            await self._post(
                "led/color",
                json=colour.as_dict(),
            )
            await self.set_mode("color")
        else:
            await self.set_mode("color")
            await self._post(
                "led/color",
                json=colour.as_dict(),
            )

    async def set_cycle_colours(
        self,
        colour: TwinklyColour | TwinklyColourTuple | list[TwinklyColour] | list[TwinklyColourTuple],
    ) -> None:
        if isinstance(colour, TwinklyColour):
            sequence = [colour.as_twinkly_tuple()]
        elif isinstance(colour, tuple):
            sequence = [colour]
        elif isinstance(colour, list):
            sequence = [c.as_twinkly_tuple() for c in colour] if isinstance(colour[0], TwinklyColour) else colour
        else:
            raise TypeError("Unknown colour format")
        frame = list(islice(cycle(sequence), self.length))
        movie = bytes([item for t in frame for item in t])
        await self.upload_movie(movie)
        await self.set_movie_config(
            {
                "frames_number": 1,
                "loop_type": 0,
                "frame_delay": 1000,
                "leds_number": self.length,
            }
        )
        await self.set_mode("movie")

    async def summary(self) -> Any:
        return self._valid_response(await self._get("summary"))

    async def music_on(self) -> Any:
        return await self._post("music/enabled", json={"enabled": 1})

    async def music_off(self) -> Any:
        return await self._post("music/enabled", json={"enabled": 0})

    async def get_music_drivers(self) -> Any:
        """
        This endpoint is not currently used by the Twinkly app, but was discovered through
        trial & error.  It raises a 400 error ('unexpected content-length header') when
        called from aiohttp, but returns JSON when called via requests.
        This endpoint was used to map driver names to IDs and identify the 'unofficial'
        drivers on the device.
        {"code": 1000, "drivers_number": 26, "unique_ids": [<list of ID strings>]}
        """
        # return await self._get("music/drivers")
        raise NotImplementedError

    async def next_music_driver(self) -> Any:
        return await self._post("music/drivers/current", json={"action": "next"})

    async def previous_music_driver(self) -> Any:
        return await self._post("music/drivers/current", json={"action": "prev"})

    async def get_current_music_driver(self) -> Any:
        if await self.get_api_version() != 1:
            raise NotImplementedError
        return self._valid_response(await self._get("music/drivers/current"))

    async def set_current_music_driver(self, driver_name: str) -> Any:
        unique_id = self._music_driver_id(driver_name)
        if not unique_id:
            _LOGGER.error(f"'{driver_name}' is an invalid music driver")
            return
        # An explicit driver cannot be set unless next/previous driver was called first
        current_driver = await self.get_current_music_driver()
        if current_driver["handle"] == -1:
            await self.next_music_driver()
        return await self._post("music/drivers/current", json={"unique_id": unique_id})

    def _music_driver_id(self, driver_name: str) -> Any:
        if driver_name in TWINKLY_MUSIC_DRIVERS_OFFICIAL:
            return TWINKLY_MUSIC_DRIVERS_OFFICIAL[driver_name]
        elif driver_name in TWINKLY_MUSIC_DRIVERS_UNOFFICIAL:
            _LOGGER.warn(f"Music driver '{driver_name}'is defined, but is not officially supported")
            return TWINKLY_MUSIC_DRIVERS_UNOFFICIAL[driver_name]
        else:
            return None

    async def get_saved_movies(self) -> Any:
        return self._valid_response(await self._get("movies"), check_for="movies")

    async def get_current_movie(self) -> Any:
        return self._valid_response(await self._get("movies/current"))

    async def set_current_movie(self, movie_id: int) -> Any:
        return await self._post("movies/current", json={"id": movie_id})

    async def get_current_colour(self) -> Any:
        return self._valid_response(await self._get("led/color"))

    async def get_predefined_effects(self) -> Any:
        """Get the list of predefined effects."""
        if await self.get_api_version() != 1:
            raise NotImplementedError
        return self._valid_response(await self._get("led/effects"))

    async def get_current_predefined_effect(self) -> Any:
        """Get current effect."""
        if await self.get_api_version() != 1:
            raise NotImplementedError
        return self._valid_response(await self._get("led/effects/current"))

    async def set_current_predefined_effect(self, effect_id: int) -> None:
        """Set current effect."""
        await self._post(
            "led/effects/current",
            json={"effect_id": effect_id},
        )

    async def get_playlist(self) -> Any:
        """Get the playlist."""
        endpoint = "playlist" if await self.get_api_version() == 1 else "playlists"
        return self._valid_response(await self._get(endpoint))

    async def get_current_playlist_entry(self) -> Any:
        """Get current playlist."""
        if await self.get_api_version() != 1:
            raise NotImplementedError
        return self._valid_response(await self._get("playlist/current"))

    async def set_current_playlist_entry(self, entry_id: int) -> None:
        """Jump to specific effect in the playlist."""
        await self._post(
            "playlist/current",
            json={"id": entry_id},
        )

    def _valid_response(self, response: dict[Any, Any], check_for: str | None = None) -> dict[Any, Any]:
        """Validate twinkly-responses from the API."""
        result = response.get("result") if response and self._api_version >= 2 else response
        if (
            result
            and result.get(TWINKLY_RETURN_CODE) == TWINKLY_RETURN_CODE_OK
            and (not check_for or check_for in response)
        ):
            _LOGGER.debug("Twinkly response: %s", response)
            return response
        raise TwinklyError(f"Invalid response from Twinkly: {response}")


class TwinklyError(ValueError):
    """Error from the API."""