plusdeck

Client

Bases: Protocol

A client for the Plus Deck 2C PC Cassette Deck.

Source code in plusdeck/client.py
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
class Client(asyncio.Protocol):
    """A client for the Plus Deck 2C PC Cassette Deck."""

    state: State
    events: AsyncIOEventEmitter
    _loop: asyncio.AbstractEventLoop
    _transport: SerialTransport | None
    _connection_made: asyncio.Future[None]
    _receivers: Set[Receiver]

    def __init__(
        self: Self,
        loop: Optional[asyncio.AbstractEventLoop] = None,
    ):
        _loop = loop if loop else asyncio.get_running_loop()

        self.state: State = State.UNSUBSCRIBED
        self.events: AsyncIOEventEmitter = AsyncIOEventEmitter(_loop)
        self.loop: asyncio.AbstractEventLoop = _loop
        self._connection_made: asyncio.Future[None] = self.loop.create_future()
        self._closed: asyncio.Future[None] = self.loop.create_future()
        self._receivers: Set[Receiver] = set()

    def connection_made(self: Self, transport: asyncio.BaseTransport):
        if not isinstance(transport, SerialTransport):
            self._connection_made.set_exception(
                ConnectionError("Transport is not a SerialTransport")
            )
            return

        self._transport = transport
        self._connection_made.set_result(None)

    @property
    def closed(self: Self) -> asyncio.Future:
        """
        An asyncio.Future that resolves when the connection is closed. This
        may be due either to calling `client.close()` or an Exception.
        """
        return self._closed

    def close(self: Self) -> None:
        """
        Close the connection.
        """
        self._close()

    # Internal method to close the connection, potentially due to an exception.
    def _close(self: Self, exc: Optional[Exception] = None) -> None:
        if self._transport:
            self._transport.close()

        if self.closed.done():
            if exc:
                raise exc
        elif exc:
            self.closed.set_exception(exc)
        else:
            self.closed.set_result(None)

    def _error(self: Self, exc: Exception) -> None:
        receivers = self.receivers()
        if receivers:
            for rcv in receivers:
                rcv.put_nowait((exc, None))
            return

        self._close(exc)

    def send(self, command: Command) -> None:
        """
        Send a command to the Plus Deck 2C PC Cassette Deck.
        """

        if not self._transport:
            raise ConnectionError("Connection has not yet been made.")

        if command == Command.SUBSCRIBE:
            self._on_state(State.SUBSCRIBING)
        elif command == Command.UNSUBSCRIBE:
            self._on_state(State.UNSUBSCRIBING)

        self._transport.write(command.value)

    def play_a(self: Self) -> None:
        """
        Play side A.
        """

        self.send(Command.PLAY_A)

    def play_b(self: Self) -> None:
        """
        Play side B.
        """

        self.send(Command.PLAY_B)

    def fast_forward_a(self: Self) -> None:
        """
        Fast-forward side A.
        """

        self.send(Command.FAST_FORWARD_A)

    def fast_forward_b(self: Self) -> None:
        """
        Fast-forward side B.
        """

        self.send(Command.FAST_FORWARD_B)

    def rewind_a(self: Self) -> None:
        """
        Rewind side A. Equivalent to fast-forwarding side B.
        """

        self.fast_forward_b()

    def rewind_b(self: Self) -> None:
        """
        Rewind side B. Equivalent to fast-forwarding side A.
        """

        self.fast_forward_a()

    def pause(self: Self) -> None:
        """
        Pause if playing, or start playing if paused.
        """

        self.send(Command.PAUSE)

    def stop(self: Self) -> None:
        """
        Stop the tape.
        """

        self.send(Command.STOP)

    def eject(self: Self) -> None:
        """
        Eject the tape.
        """
        self.send(Command.EJECT)

    def data_received(self: Self, data) -> None:
        try:
            for state in State.from_bytes(data):
                self._on_state(state)
        except Exception as exc:
            self._error(exc)

    def _on_state(self: Self, state: State) -> None:
        previous = self.state

        # When turning off, what I've observed is that we always receive
        # exactly one pause event. I'm not entirely sure it's reliable, but
        # until it's disproven I'm treating it as such.
        #
        # If it turns out the single event is unspecified, then the logic may
        # simply be modified to handle any event. If, however, it turns out
        # there are an unspecified number of events, we will need to resort to
        # timeouts.

        if previous == State.UNSUBSCRIBING:
            if not (state == State.PAUSED_A or state == State.PAUSED_B):
                raise SubscriptionError(f"Unexpected state {state} while unsubscribing")
            state = State.UNSUBSCRIBED

        if previous == State.UNSUBSCRIBED and state != State.SUBSCRIBING:
            raise SubscriptionError(f"Unexpected state {state} while unsubscribed")

        self.state = state

        if state != previous:
            if state == State.SUBSCRIBED:
                self.events.emit("subscribed")

            self.events.emit("state", state)

            if state == State.UNSUBSCRIBED:
                self.events.emit("unsubscribed")

            for rcv in list(self._receivers):
                rcv.put_nowait((None, state))

        if state == State.UNSUBSCRIBED:
            for rcv in list(self._receivers):
                rcv.close()

    def on(self: Self, state: State, f: StateHandler) -> Handler:
        """
        Call an event handler on a given state.
        """

        return self.listens_to(state)(f)

    def listens_to(self: Self, state: State) -> Callable[[StateHandler], Handler]:
        """
        Decorate an event handler to be called on a given state.
        """

        want = state

        def decorator(f: StateHandler) -> Handler:
            def handler(state: State) -> None:
                if state == want:
                    f()

            return self.events.add_listener("state", handler)

        return decorator

    def once(self: Self, state: State, f: StateHandler) -> Handler:
        """
        Call an event handler on a given state once.
        """

        return self.listens_once(state)(f)

    def listens_once(self: Self, state: State) -> Callable[[StateHandler], Handler]:
        """
        Decorate an event handler to be called once a given state occurs.
        """

        want = state

        def decorator(f: StateHandler) -> Handler:
            def handler(state: State) -> None:
                if state == want:
                    f()
                    self.events.remove_listener("state", handler)

            return self.events.add_listener("state", handler)

        return decorator

    def wait_for(
        self: Self, state: State, timeout: Optional[float] = None
    ) -> asyncio.Future[None]:
        """
        Wait for a given state to emit. This is a low level method - client.subscribe
        and the Receiver interface will meet most use cases.
        """

        fut = self.loop.create_future()

        @self.listens_once(state)
        def listener() -> None:
            fut.set_result(None)

        return asyncio.ensure_future(asyncio.wait_for(fut, timeout=timeout))

    async def subscribe(self: Self, maxsize: int = 0) -> Receiver:
        """
        Subscribe to state changes.
        """

        rcv = Receiver(client=self, maxsize=maxsize)
        self._receivers.add(rcv)

        if self.state == State.UNSUBSCRIBED:
            # Automatically subscribe
            fut = self.wait_for(State.SUBSCRIBED)
            self.send(Command.SUBSCRIBE)
            await fut
        elif self.state == State.SUBSCRIBING:
            # Wait for in-progress subscription to complete
            await self.wait_for(State.SUBSCRIBED)
        else:
            # Must already be subscribed
            pass

        return rcv

    def receivers(self: Self) -> List[Receiver]:
        """
        Currently active receivers.
        """

        return list(self._receivers)

    async def unsubscribe(self: Self) -> None:
        """
        Unsubscribe from state changes.
        """

        # If already unsubscribing or unsubscribed, we just need to let
        # events take their course
        if self.state in {State.UNSUBSCRIBING, State.UNSUBSCRIBED}:
            return

        # Wait until subscribed in order to avoid whacky state
        if self.state == State.SUBSCRIBING:
            await self.wait_for(State.SUBSCRIBED)

        self.send(Command.UNSUBSCRIBE)

    @asynccontextmanager
    async def session(self):
        """
        Subscribe to events inside an async context manager. Automatically
        unsubscribe when done.
        """

        rcv = await self.subscribe()
        try:
            yield rcv
        finally:
            await self.unsubscribe()

closed property

An asyncio.Future that resolves when the connection is closed. This may be due either to calling client.close() or an Exception.

close()

Close the connection.

Source code in plusdeck/client.py
202
203
204
205
206
def close(self: Self) -> None:
    """
    Close the connection.
    """
    self._close()

eject()

Eject the tape.

Source code in plusdeck/client.py
301
302
303
304
305
def eject(self: Self) -> None:
    """
    Eject the tape.
    """
    self.send(Command.EJECT)

fast_forward_a()

Fast-forward side A.

Source code in plusdeck/client.py
259
260
261
262
263
264
def fast_forward_a(self: Self) -> None:
    """
    Fast-forward side A.
    """

    self.send(Command.FAST_FORWARD_A)

fast_forward_b()

Fast-forward side B.

Source code in plusdeck/client.py
266
267
268
269
270
271
def fast_forward_b(self: Self) -> None:
    """
    Fast-forward side B.
    """

    self.send(Command.FAST_FORWARD_B)

listens_once(state)

Decorate an event handler to be called once a given state occurs.

Source code in plusdeck/client.py
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
def listens_once(self: Self, state: State) -> Callable[[StateHandler], Handler]:
    """
    Decorate an event handler to be called once a given state occurs.
    """

    want = state

    def decorator(f: StateHandler) -> Handler:
        def handler(state: State) -> None:
            if state == want:
                f()
                self.events.remove_listener("state", handler)

        return self.events.add_listener("state", handler)

    return decorator

listens_to(state)

Decorate an event handler to be called on a given state.

Source code in plusdeck/client.py
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
def listens_to(self: Self, state: State) -> Callable[[StateHandler], Handler]:
    """
    Decorate an event handler to be called on a given state.
    """

    want = state

    def decorator(f: StateHandler) -> Handler:
        def handler(state: State) -> None:
            if state == want:
                f()

        return self.events.add_listener("state", handler)

    return decorator

on(state, f)

Call an event handler on a given state.

Source code in plusdeck/client.py
352
353
354
355
356
357
def on(self: Self, state: State, f: StateHandler) -> Handler:
    """
    Call an event handler on a given state.
    """

    return self.listens_to(state)(f)

once(state, f)

Call an event handler on a given state once.

Source code in plusdeck/client.py
375
376
377
378
379
380
def once(self: Self, state: State, f: StateHandler) -> Handler:
    """
    Call an event handler on a given state once.
    """

    return self.listens_once(state)(f)

pause()

Pause if playing, or start playing if paused.

Source code in plusdeck/client.py
287
288
289
290
291
292
def pause(self: Self) -> None:
    """
    Pause if playing, or start playing if paused.
    """

    self.send(Command.PAUSE)

play_a()

Play side A.

Source code in plusdeck/client.py
245
246
247
248
249
250
def play_a(self: Self) -> None:
    """
    Play side A.
    """

    self.send(Command.PLAY_A)

play_b()

Play side B.

Source code in plusdeck/client.py
252
253
254
255
256
257
def play_b(self: Self) -> None:
    """
    Play side B.
    """

    self.send(Command.PLAY_B)

receivers()

Currently active receivers.

Source code in plusdeck/client.py
437
438
439
440
441
442
def receivers(self: Self) -> List[Receiver]:
    """
    Currently active receivers.
    """

    return list(self._receivers)

rewind_a()

Rewind side A. Equivalent to fast-forwarding side B.

Source code in plusdeck/client.py
273
274
275
276
277
278
def rewind_a(self: Self) -> None:
    """
    Rewind side A. Equivalent to fast-forwarding side B.
    """

    self.fast_forward_b()

rewind_b()

Rewind side B. Equivalent to fast-forwarding side A.

Source code in plusdeck/client.py
280
281
282
283
284
285
def rewind_b(self: Self) -> None:
    """
    Rewind side B. Equivalent to fast-forwarding side A.
    """

    self.fast_forward_a()

send(command)

Send a command to the Plus Deck 2C PC Cassette Deck.

Source code in plusdeck/client.py
230
231
232
233
234
235
236
237
238
239
240
241
242
243
def send(self, command: Command) -> None:
    """
    Send a command to the Plus Deck 2C PC Cassette Deck.
    """

    if not self._transport:
        raise ConnectionError("Connection has not yet been made.")

    if command == Command.SUBSCRIBE:
        self._on_state(State.SUBSCRIBING)
    elif command == Command.UNSUBSCRIBE:
        self._on_state(State.UNSUBSCRIBING)

    self._transport.write(command.value)

session() async

Subscribe to events inside an async context manager. Automatically unsubscribe when done.

Source code in plusdeck/client.py
460
461
462
463
464
465
466
467
468
469
470
471
@asynccontextmanager
async def session(self):
    """
    Subscribe to events inside an async context manager. Automatically
    unsubscribe when done.
    """

    rcv = await self.subscribe()
    try:
        yield rcv
    finally:
        await self.unsubscribe()

stop()

Stop the tape.

Source code in plusdeck/client.py
294
295
296
297
298
299
def stop(self: Self) -> None:
    """
    Stop the tape.
    """

    self.send(Command.STOP)

subscribe(maxsize=0) async

Subscribe to state changes.

Source code in plusdeck/client.py
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
async def subscribe(self: Self, maxsize: int = 0) -> Receiver:
    """
    Subscribe to state changes.
    """

    rcv = Receiver(client=self, maxsize=maxsize)
    self._receivers.add(rcv)

    if self.state == State.UNSUBSCRIBED:
        # Automatically subscribe
        fut = self.wait_for(State.SUBSCRIBED)
        self.send(Command.SUBSCRIBE)
        await fut
    elif self.state == State.SUBSCRIBING:
        # Wait for in-progress subscription to complete
        await self.wait_for(State.SUBSCRIBED)
    else:
        # Must already be subscribed
        pass

    return rcv

unsubscribe() async

Unsubscribe from state changes.

Source code in plusdeck/client.py
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
async def unsubscribe(self: Self) -> None:
    """
    Unsubscribe from state changes.
    """

    # If already unsubscribing or unsubscribed, we just need to let
    # events take their course
    if self.state in {State.UNSUBSCRIBING, State.UNSUBSCRIBED}:
        return

    # Wait until subscribed in order to avoid whacky state
    if self.state == State.SUBSCRIBING:
        await self.wait_for(State.SUBSCRIBED)

    self.send(Command.UNSUBSCRIBE)

wait_for(state, timeout=None)

Wait for a given state to emit. This is a low level method - client.subscribe and the Receiver interface will meet most use cases.

Source code in plusdeck/client.py
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
def wait_for(
    self: Self, state: State, timeout: Optional[float] = None
) -> asyncio.Future[None]:
    """
    Wait for a given state to emit. This is a low level method - client.subscribe
    and the Receiver interface will meet most use cases.
    """

    fut = self.loop.create_future()

    @self.listens_once(state)
    def listener() -> None:
        fut.set_result(None)

    return asyncio.ensure_future(asyncio.wait_for(fut, timeout=timeout))

Command

Bases: Enum

A command for the Plus Deck 2C PC Cassette Deck.

Source code in plusdeck/client.py
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
class Command(Enum):
    """A command for the Plus Deck 2C PC Cassette Deck."""

    PLAY_A = b"\x01"
    PLAY_B = b"\x02"
    FAST_FORWARD_A = b"\x03"
    FAST_FORWARD_B = b"\x04"
    PAUSE = b"\x05"
    STOP = b"\x06"
    EJECT = b"\x08"
    SUBSCRIBE = b"\x0b"
    UNSUBSCRIBE = b"\x0c"

    @classmethod
    def from_bytes(cls: Type["Command"], buffer: bytes) -> List["Command"]:
        return [Command(code.to_bytes(length=1, byteorder="little")) for code in buffer]

    @classmethod
    def from_byte(cls: Type["Command"], buffer: bytes) -> "Command":
        if len(buffer) != 1:
            raise ValueError("Can not convert multiple bytes into a single Command")
        return cls.from_bytes(buffer)[0]

    def to_bytes(self: "Command") -> bytes:
        return self.value

Config

Bases: BaseConfig

A config for the Plus Deck 2C PC Cassette Deck.

Source code in plusdeck/config.py
20
21
22
23
24
@config(APP_NAME)
class Config(BaseConfig):
    """A config for the Plus Deck 2C PC Cassette Deck."""

    port: str = field(default_factory=default_port, env_var="PORT")

ConnectionError

Bases: PlusDeckError

A connection error.

Source code in plusdeck/client.py
24
25
26
27
class ConnectionError(PlusDeckError):
    """A connection error."""

    pass

PlusDeckError

Bases: Exception

An error in the Plus Deck 2C PC Cassette Deck client.

Source code in plusdeck/client.py
18
19
20
21
class PlusDeckError(Exception):
    """An error in the Plus Deck 2C PC Cassette Deck client."""

    pass

Receiver

Bases: Queue[Event]

Receive state change events from the Plus Deck 2C PC Cassette Deck.

Source code in plusdeck/client.py
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
class Receiver(asyncio.Queue[Event]):
    """Receive state change events from the Plus Deck 2C PC Cassette Deck."""

    _client: "Client"
    _receiving: bool

    def __init__(self: Self, client: "Client", maxsize=0) -> None:
        super().__init__(maxsize)
        self._client = client
        self._receiving = True

    async def get_state(self: Self, timeout: Optional[float] = None) -> State:
        async with asyncio.timeout(timeout):
            exc, state = await super().get()
            if exc:
                raise exc
            else:
                assert state, "State must be defined"
                return state

    async def expect(self: Self, state: State, timeout: Optional[float] = None) -> None:
        """
        Receive state changes until the expected state.
        """

        current = await self.get_state(timeout)

        while current != state:
            current = await self.get_state(timeout)

    async def __aiter__(self: Self) -> AsyncGenerator[State, None]:
        """Iterate over state change events."""

        while True:
            if not self._receiving:
                break

            state = await self.get_state()

            yield state

            if state == State.UNSUBSCRIBED:
                self._receiving = False

    def close(self: Self) -> None:
        """Close the receiver."""

        self._receiving = False
        try:
            self._client._receivers.remove(self)
        except KeyError:
            pass

__aiter__() async

Iterate over state change events.

Source code in plusdeck/client.py
137
138
139
140
141
142
143
144
145
146
147
148
149
async def __aiter__(self: Self) -> AsyncGenerator[State, None]:
    """Iterate over state change events."""

    while True:
        if not self._receiving:
            break

        state = await self.get_state()

        yield state

        if state == State.UNSUBSCRIBED:
            self._receiving = False

close()

Close the receiver.

Source code in plusdeck/client.py
151
152
153
154
155
156
157
158
def close(self: Self) -> None:
    """Close the receiver."""

    self._receiving = False
    try:
        self._client._receivers.remove(self)
    except KeyError:
        pass

expect(state, timeout=None) async

Receive state changes until the expected state.

Source code in plusdeck/client.py
127
128
129
130
131
132
133
134
135
async def expect(self: Self, state: State, timeout: Optional[float] = None) -> None:
    """
    Receive state changes until the expected state.
    """

    current = await self.get_state(timeout)

    while current != state:
        current = await self.get_state(timeout)

State

Bases: Enum

The state of the Plus Deck 2C PC Cassette Deck.

Source code in plusdeck/client.py
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
class State(Enum):
    """The state of the Plus Deck 2C PC Cassette Deck."""

    PLAYING_A = 10
    PAUSED_A = 12
    PLAYING_B = 20
    SUBSCRIBED = 21
    PAUSED_B = 22
    FAST_FORWARDING_A = 30
    FAST_FORWARDING_B = 40
    STOPPED = 50
    EJECTED = 60
    SUBSCRIBING = -1
    UNSUBSCRIBING = -2
    UNSUBSCRIBED = -3

    @classmethod
    def from_bytes(cls: Type["State"], buffer: bytes) -> List["State"]:
        return [cls(code) for code in buffer]

    @classmethod
    def from_byte(cls: Type["State"], buffer: bytes) -> "State":
        if len(buffer) != 1:
            raise ValueError("Can not convert multiple bytes to a single State")
        return cls.from_bytes(buffer)[0]

    def to_bytes(self: "State") -> bytes:
        if self.value < 0:
            raise ValueError(f"Can not convert {self} to bytes")
        return self.value.to_bytes()

StateError

Bases: PlusDeckError

An error with the Plus Deck 2c PC Cassette Deck's state.

Source code in plusdeck/client.py
30
31
32
33
class StateError(PlusDeckError):
    """An error with the Plus Deck 2c PC Cassette Deck's state."""

    pass

SubscriptionError

Bases: StateError

An error involving subscribing or unsubscribing.

Source code in plusdeck/client.py
36
37
38
39
class SubscriptionError(StateError):
    """An error involving subscribing or unsubscribing."""

    pass

connection(port, loop=None) async

Create a connection to Plus Deck 2C PC Cassette Deck, with an associated async context.

This context will automatically close the connection on exit and wait for the connection to close.

Source code in plusdeck/client.py
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
@asynccontextmanager
async def connection(
    port: str,
    loop: Optional[asyncio.AbstractEventLoop] = None,
) -> AsyncGenerator[Client, None]:
    """
    Create a connection to Plus Deck 2C PC Cassette Deck, with an associated async
    context.

    This context will automatically close the connection on exit and wait for the
    connection to close.
    """

    client = await create_connection(port, loop=loop)

    yield client

    client.close()
    await client.closed

create_connection(port, loop=None) async

Create a connection to the Plus Deck 2C PC Cassette Deck.

Source code in plusdeck/client.py
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
async def create_connection(
    port: str,
    loop: Optional[asyncio.AbstractEventLoop] = None,
) -> Client:
    """
    Create a connection to the Plus Deck 2C PC Cassette Deck.
    """

    _loop = loop if loop else asyncio.get_running_loop()

    _, client = await create_serial_connection(
        _loop,
        lambda: Client(_loop),
        port,
        baudrate=9600,
        bytesize=EIGHTBITS,
        parity=PARITY_NONE,
        stopbits=STOPBITS_ONE,
    )

    await client._connection_made

    return client