File: ams.py

package info (click to toggle)
python-bumble 0.0.225-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 9,464 kB
  • sloc: python: 75,258; java: 3,782; javascript: 823; xml: 203; sh: 172; makefile: 8
file content (401 lines) | stat: -rw-r--r-- 13,746 bytes parent folder | download | duplicates (2)
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
# Copyright 2025 Google LLC
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#      https://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

"""
Apple Media Service (AMS).
"""

# -----------------------------------------------------------------------------
# Imports
# -----------------------------------------------------------------------------
from __future__ import annotations

import asyncio
import dataclasses
import enum
import logging
from collections.abc import Iterable

from bumble import utils
from bumble.device import Peer
from bumble.gatt import (
    GATT_AMS_ENTITY_ATTRIBUTE_CHARACTERISTIC,
    GATT_AMS_ENTITY_UPDATE_CHARACTERISTIC,
    GATT_AMS_REMOTE_COMMAND_CHARACTERISTIC,
    GATT_AMS_SERVICE,
    Characteristic,
    TemplateService,
)
from bumble.gatt_client import CharacteristicProxy, ProfileServiceProxy, ServiceProxy

# -----------------------------------------------------------------------------
# Logging
# -----------------------------------------------------------------------------
logger = logging.getLogger(__name__)


# -----------------------------------------------------------------------------
# Protocol
# -----------------------------------------------------------------------------
class RemoteCommandId(utils.OpenIntEnum):
    PLAY = 0
    PAUSE = 1
    TOGGLE_PLAY_PAUSE = 2
    NEXT_TRACK = 3
    PREVIOUS_TRACK = 4
    VOLUME_UP = 5
    VOLUME_DOWN = 6
    ADVANCE_REPEAT_MODE = 7
    ADVANCE_SHUFFLE_MODE = 8
    SKIP_FORWARD = 9
    SKIP_BACKWARD = 10
    LIKE_TRACK = 11
    DISLIKE_TRACK = 12
    BOOKMARK_TRACK = 13


class EntityId(utils.OpenIntEnum):
    PLAYER = 0
    QUEUE = 1
    TRACK = 2


class ActionId(utils.OpenIntEnum):
    POSITIVE = 0
    NEGATIVE = 1


class EntityUpdateFlags(enum.IntFlag):
    TRUNCATED = 1


class PlayerAttributeId(utils.OpenIntEnum):
    NAME = 0
    PLAYBACK_INFO = 1
    VOLUME = 2


class QueueAttributeId(utils.OpenIntEnum):
    INDEX = 0
    COUNT = 1
    SHUFFLE_MODE = 2
    REPEAT_MODE = 3


class ShuffleMode(utils.OpenIntEnum):
    OFF = 0
    ONE = 1
    ALL = 2


class RepeatMode(utils.OpenIntEnum):
    OFF = 0
    ONE = 1
    ALL = 2


class TrackAttributeId(utils.OpenIntEnum):
    ARTIST = 0
    ALBUM = 1
    TITLE = 2
    DURATION = 3


class PlaybackState(utils.OpenIntEnum):
    PAUSED = 0
    PLAYING = 1
    REWINDING = 2
    FAST_FORWARDING = 3


@dataclasses.dataclass
class PlaybackInfo:
    playback_state: PlaybackState = PlaybackState.PAUSED
    playback_rate: float = 1.0
    elapsed_time: float = 0.0


# -----------------------------------------------------------------------------
# GATT Server-side
# -----------------------------------------------------------------------------
class Ams(TemplateService):
    UUID = GATT_AMS_SERVICE

    remote_command_characteristic: Characteristic
    entity_update_characteristic: Characteristic
    entity_attribute_characteristic: Characteristic

    def __init__(self) -> None:
        # TODO not the final implementation
        self.remote_command_characteristic = Characteristic(
            GATT_AMS_REMOTE_COMMAND_CHARACTERISTIC,
            Characteristic.Properties.NOTIFY
            | Characteristic.Properties.WRITE_WITHOUT_RESPONSE,
            Characteristic.Permissions.WRITEABLE,
        )

        # TODO not the final implementation
        self.entity_update_characteristic = Characteristic(
            GATT_AMS_ENTITY_UPDATE_CHARACTERISTIC,
            Characteristic.Properties.NOTIFY | Characteristic.Properties.WRITE,
            Characteristic.Permissions.WRITEABLE,
        )

        # TODO not the final implementation
        self.entity_attribute_characteristic = Characteristic(
            GATT_AMS_ENTITY_ATTRIBUTE_CHARACTERISTIC,
            Characteristic.Properties.READ
            | Characteristic.Properties.WRITE_WITHOUT_RESPONSE,
            Characteristic.Permissions.WRITEABLE | Characteristic.Permissions.READABLE,
        )

        super().__init__(
            [
                self.remote_command_characteristic,
                self.entity_update_characteristic,
                self.entity_attribute_characteristic,
            ]
        )


# -----------------------------------------------------------------------------
# GATT Client-side
# -----------------------------------------------------------------------------
class AmsProxy(ProfileServiceProxy):
    SERVICE_CLASS = Ams

    # NOTE: these don't use adapters, because the format for write and notifications
    # are different.
    remote_command: CharacteristicProxy[bytes]
    entity_update: CharacteristicProxy[bytes]
    entity_attribute: CharacteristicProxy[bytes]

    def __init__(self, service_proxy: ServiceProxy):
        self.remote_command = service_proxy.get_required_characteristic_by_uuid(
            GATT_AMS_REMOTE_COMMAND_CHARACTERISTIC
        )

        self.entity_update = service_proxy.get_required_characteristic_by_uuid(
            GATT_AMS_ENTITY_UPDATE_CHARACTERISTIC
        )

        self.entity_attribute = service_proxy.get_required_characteristic_by_uuid(
            GATT_AMS_ENTITY_ATTRIBUTE_CHARACTERISTIC
        )


class AmsClient(utils.EventEmitter):
    EVENT_SUPPORTED_COMMANDS = "supported_commands"
    EVENT_PLAYER_NAME = "player_name"
    EVENT_PLAYER_PLAYBACK_INFO = "player_playback_info"
    EVENT_PLAYER_VOLUME = "player_volume"
    EVENT_QUEUE_COUNT = "queue_count"
    EVENT_QUEUE_INDEX = "queue_index"
    EVENT_QUEUE_SHUFFLE_MODE = "queue_shuffle_mode"
    EVENT_QUEUE_REPEAT_MODE = "queue_repeat_mode"
    EVENT_TRACK_ARTIST = "track_artist"
    EVENT_TRACK_ALBUM = "track_album"
    EVENT_TRACK_TITLE = "track_title"
    EVENT_TRACK_DURATION = "track_duration"

    supported_commands: set[RemoteCommandId]
    player_name: str = ""
    player_playback_info: PlaybackInfo = PlaybackInfo(PlaybackState.PAUSED, 0.0, 0.0)
    player_volume: float = 1.0
    queue_count: int = 0
    queue_index: int = 0
    queue_shuffle_mode: ShuffleMode = ShuffleMode.OFF
    queue_repeat_mode: RepeatMode = RepeatMode.OFF
    track_artist: str = ""
    track_album: str = ""
    track_title: str = ""
    track_duration: float = 0.0

    def __init__(self, ams_proxy: AmsProxy) -> None:
        super().__init__()
        self._ams_proxy = ams_proxy
        self._started = False
        self._read_attribute_semaphore = asyncio.Semaphore()
        self.supported_commands = set()

    @classmethod
    async def for_peer(cls, peer: Peer) -> AmsClient | None:
        ams_proxy = await peer.discover_service_and_create_proxy(AmsProxy)
        if ams_proxy is None:
            return None
        return cls(ams_proxy)

    async def start(self) -> None:
        logger.debug("subscribing to remote command characteristic")
        await self._ams_proxy.remote_command.subscribe(
            self._on_remote_command_notification
        )

        logger.debug("subscribing to entity update characteristic")
        await self._ams_proxy.entity_update.subscribe(
            lambda data: utils.AsyncRunner.spawn(
                self._on_entity_update_notification(data)
            )
        )

        self._started = True

    async def stop(self) -> None:
        await self._ams_proxy.remote_command.unsubscribe(
            self._on_remote_command_notification
        )
        await self._ams_proxy.entity_update.unsubscribe(
            self._on_entity_update_notification
        )
        self._started = False

    async def observe(
        self,
        entity: EntityId,
        attributes: Iterable[PlayerAttributeId | QueueAttributeId | TrackAttributeId],
    ) -> None:
        await self._ams_proxy.entity_update.write_value(
            bytes([entity] + list(attributes)), with_response=True
        )

    async def command(self, command: RemoteCommandId) -> None:
        await self._ams_proxy.remote_command.write_value(
            bytes([command]), with_response=True
        )

    async def play(self) -> None:
        await self.command(RemoteCommandId.PLAY)

    async def pause(self) -> None:
        await self.command(RemoteCommandId.PAUSE)

    async def toggle_play_pause(self) -> None:
        await self.command(RemoteCommandId.TOGGLE_PLAY_PAUSE)

    async def next_track(self) -> None:
        await self.command(RemoteCommandId.NEXT_TRACK)

    async def previous_track(self) -> None:
        await self.command(RemoteCommandId.PREVIOUS_TRACK)

    async def volume_up(self) -> None:
        await self.command(RemoteCommandId.VOLUME_UP)

    async def volume_down(self) -> None:
        await self.command(RemoteCommandId.VOLUME_DOWN)

    async def advance_repeat_mode(self) -> None:
        await self.command(RemoteCommandId.ADVANCE_REPEAT_MODE)

    async def advance_shuffle_mode(self) -> None:
        await self.command(RemoteCommandId.ADVANCE_SHUFFLE_MODE)

    async def skip_forward(self) -> None:
        await self.command(RemoteCommandId.SKIP_FORWARD)

    async def skip_backward(self) -> None:
        await self.command(RemoteCommandId.SKIP_BACKWARD)

    async def like_track(self) -> None:
        await self.command(RemoteCommandId.LIKE_TRACK)

    async def dislike_track(self) -> None:
        await self.command(RemoteCommandId.DISLIKE_TRACK)

    async def bookmark_track(self) -> None:
        await self.command(RemoteCommandId.BOOKMARK_TRACK)

    def _on_remote_command_notification(self, data: bytes) -> None:
        supported_commands = [RemoteCommandId(command) for command in data]
        logger.debug(
            f"supported commands: {[command.name for command in supported_commands]}"
        )
        for command in supported_commands:
            self.supported_commands.add(command)

        self.emit(self.EVENT_SUPPORTED_COMMANDS)

    async def _on_entity_update_notification(self, data: bytes) -> None:
        entity = EntityId(data[0])
        flags = EntityUpdateFlags(data[2])
        value = data[3:]

        if flags & EntityUpdateFlags.TRUNCATED:
            logger.debug("truncated attribute, fetching full value")

            # Write the entity and attribute we're interested in
            # (protected by a semaphore, so that we only read one attribute at a time)
            async with self._read_attribute_semaphore:
                await self._ams_proxy.entity_attribute.write_value(
                    data[:2], with_response=True
                )
                value = await self._ams_proxy.entity_attribute.read_value()

        if entity == EntityId.PLAYER:
            player_attribute = PlayerAttributeId(data[1])
            if player_attribute == PlayerAttributeId.NAME:
                self.player_name = value.decode()
                self.emit(self.EVENT_PLAYER_NAME)
            elif player_attribute == PlayerAttributeId.PLAYBACK_INFO:
                playback_state_str, playback_rate_str, elapsed_time_str = (
                    value.decode().split(",")
                )
                self.player_playback_info = PlaybackInfo(
                    PlaybackState(int(playback_state_str)),
                    float(playback_rate_str),
                    float(elapsed_time_str),
                )
                self.emit(self.EVENT_PLAYER_PLAYBACK_INFO)
            elif player_attribute == PlayerAttributeId.VOLUME:
                self.player_volume = float(value.decode())
                self.emit(self.EVENT_PLAYER_VOLUME)
            else:
                logger.warning(f"received unknown player attribute {player_attribute}")

        elif entity == EntityId.QUEUE:
            queue_attribute = QueueAttributeId(data[1])
            if queue_attribute == QueueAttributeId.COUNT:
                self.queue_count = int(value)
                self.emit(self.EVENT_QUEUE_COUNT)
            elif queue_attribute == QueueAttributeId.INDEX:
                self.queue_index = int(value)
                self.emit(self.EVENT_QUEUE_INDEX)
            elif queue_attribute == QueueAttributeId.REPEAT_MODE:
                self.queue_repeat_mode = RepeatMode(int(value))
                self.emit(self.EVENT_QUEUE_REPEAT_MODE)
            elif queue_attribute == QueueAttributeId.SHUFFLE_MODE:
                self.queue_shuffle_mode = ShuffleMode(int(value))
                self.emit(self.EVENT_QUEUE_SHUFFLE_MODE)
            else:
                logger.warning(f"received unknown queue attribute {queue_attribute}")

        elif entity == EntityId.TRACK:
            track_attribute = TrackAttributeId(data[1])
            if track_attribute == TrackAttributeId.ARTIST:
                self.track_artist = value.decode()
                self.emit(self.EVENT_TRACK_ARTIST)
            elif track_attribute == TrackAttributeId.ALBUM:
                self.track_album = value.decode()
                self.emit(self.EVENT_TRACK_ALBUM)
            elif track_attribute == TrackAttributeId.TITLE:
                self.track_title = value.decode()
                self.emit(self.EVENT_TRACK_TITLE)
            elif track_attribute == TrackAttributeId.DURATION:
                self.track_duration = float(value.decode())
                self.emit(self.EVENT_TRACK_DURATION)
            else:
                logger.warning(f"received unknown track attribute {track_attribute}")

        else:
            logger.warning(f"received unknown attribute ID {data[1]}")