omnipython-desktop 0.8.1.dev2__py3-none-any.whl → 0.8.1.dev4__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- endpointkit/__init__.py +663 -0
- endpointkit/__init__.pyi +125 -0
- endpointkit/fake.py +138 -0
- endpointkit/fake.pyi +36 -0
- endpointkit/py.typed +0 -0
- hostnet-stubs/__init__.pyi +33 -0
- hostnet.py +141 -0
- icons/__init__.py +167 -0
- icons/__init__.pyi +30 -0
- icons/_material.py +11 -0
- icons/_material.pyi +8 -0
- icons/gfx.py +89 -0
- icons/gfx.pyi +15 -0
- icons/lvgl.py +71 -0
- icons/lvgl.pyi +12 -0
- icons/py.typed +0 -0
- midiports/endpoints.py +205 -0
- midiports/endpoints.pyi +52 -0
- {omnipython_desktop-0.8.1.dev2.dist-info → omnipython_desktop-0.8.1.dev4.dist-info}/METADATA +3 -2
- {omnipython_desktop-0.8.1.dev2.dist-info → omnipython_desktop-0.8.1.dev4.dist-info}/RECORD +26 -6
- {omnipython_desktop-0.8.1.dev2.dist-info → omnipython_desktop-0.8.1.dev4.dist-info}/top_level.txt +6 -0
- ttfio-stubs/__init__.pyi +23 -0
- ttfio.py +122 -0
- usdl2-stubs/__init__.pyi +1 -0
- usdl2.py +12 -0
- {omnipython_desktop-0.8.1.dev2.dist-info → omnipython_desktop-0.8.1.dev4.dist-info}/WHEEL +0 -0
endpointkit/__init__.py
ADDED
|
@@ -0,0 +1,663 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Brad Barnett
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
|
|
5
|
+
"""Choose where audio goes, which MIDI ports are in, which network carries traffic.
|
|
6
|
+
|
|
7
|
+
endpointkit keeps one list of everything a device can connect to, by kind,
|
|
8
|
+
and one choice per kind for the whole device. A script lists and picks::
|
|
9
|
+
|
|
10
|
+
import endpointkit
|
|
11
|
+
|
|
12
|
+
for ep in endpointkit.endpoints("audio.out"):
|
|
13
|
+
print(ep.id, ep.label, ep.state)
|
|
14
|
+
endpointkit.select("audio.out", "a2dp:speaker")
|
|
15
|
+
|
|
16
|
+
and a program that plays, casts or connects hears when the choice moves::
|
|
17
|
+
|
|
18
|
+
def moved(event, kind):
|
|
19
|
+
if event == endpointkit.SELECTION:
|
|
20
|
+
reopen(endpointkit.selected(kind))
|
|
21
|
+
|
|
22
|
+
endpointkit.subscribe("audio.out", moved)
|
|
23
|
+
|
|
24
|
+
The five ideas
|
|
25
|
+
--------------
|
|
26
|
+
A **kind** names a role: ``audio.out``, ``audio.in``, ``midi.in``,
|
|
27
|
+
``midi.out``, ``net``, ``cast.target``, ``camera``, ``gamepad``, ``keys``,
|
|
28
|
+
``pointer``. Each says whether one endpoint is chosen at a time (a camera, a
|
|
29
|
+
cast target, the default network) or many (MIDI inputs merge, audio can fan
|
|
30
|
+
out). `add_kind` adds another without changing anything here.
|
|
31
|
+
|
|
32
|
+
A **provider** is one transport for one kind: I2S, USB audio or Bluetooth
|
|
33
|
+
for ``audio.out``. The library that owns the transport registers it, so this
|
|
34
|
+
package knows no transport by name. A provider says which shared
|
|
35
|
+
**resources** it takes (a radio, the USB port, an I2S bus): two choices that
|
|
36
|
+
take the same resource can't both stand, and `select` says what a choice
|
|
37
|
+
would stop before it stops it.
|
|
38
|
+
|
|
39
|
+
An **endpoint** is what a provider finds: a stable ``id``, a ``label`` a
|
|
40
|
+
person recognises, a ``state`` and what it can do (``caps``). Finding can be
|
|
41
|
+
slow (a Bluetooth scan, cast discovery), so providers report in `poll`, and
|
|
42
|
+
the list fills as it goes.
|
|
43
|
+
|
|
44
|
+
A **selection** is the chosen endpoints of a kind, for the whole device. It
|
|
45
|
+
is saved when a store is set (`set_store`) and comes back after a restart. A
|
|
46
|
+
chosen endpoint that isn't there yet stays chosen and is used when it shows
|
|
47
|
+
up. A program may **pin** a kind for itself while it runs; the pin wins over
|
|
48
|
+
the device's choice until it's lifted.
|
|
49
|
+
|
|
50
|
+
A **subscription** calls you when a kind's endpoints, their states or its
|
|
51
|
+
selection change.
|
|
52
|
+
|
|
53
|
+
Nothing here runs on its own: call `poll` from a timer (appkit's Shell does)
|
|
54
|
+
so slow providers can report. Nothing here draws either: the picker is
|
|
55
|
+
appkit's, and a script uses these calls directly.
|
|
56
|
+
"""
|
|
57
|
+
|
|
58
|
+
import sys
|
|
59
|
+
|
|
60
|
+
try:
|
|
61
|
+
import json
|
|
62
|
+
except ImportError: # a CircuitPython build without json
|
|
63
|
+
json = None
|
|
64
|
+
|
|
65
|
+
try:
|
|
66
|
+
import os
|
|
67
|
+
except ImportError:
|
|
68
|
+
os = None
|
|
69
|
+
|
|
70
|
+
__version__ = "0.0.1"
|
|
71
|
+
|
|
72
|
+
#: One endpoint of the kind is chosen at a time.
|
|
73
|
+
ONE = 1
|
|
74
|
+
#: Any number of endpoints of the kind are chosen at once.
|
|
75
|
+
MANY = 0
|
|
76
|
+
|
|
77
|
+
#: The kinds every device knows, and how many of each can be chosen.
|
|
78
|
+
KINDS = {
|
|
79
|
+
"audio.out": MANY,
|
|
80
|
+
"audio.in": ONE,
|
|
81
|
+
"midi.in": MANY,
|
|
82
|
+
"midi.out": MANY,
|
|
83
|
+
"net": ONE,
|
|
84
|
+
"cast.target": ONE,
|
|
85
|
+
"camera": ONE,
|
|
86
|
+
"gamepad": MANY,
|
|
87
|
+
"keys": MANY,
|
|
88
|
+
"pointer": MANY,
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
AVAILABLE = "available"
|
|
92
|
+
CONNECTED = "connected"
|
|
93
|
+
NEEDS_PAIRING = "needs pairing"
|
|
94
|
+
UNAVAILABLE = "unavailable"
|
|
95
|
+
|
|
96
|
+
#: Subscription events: the list of a kind's endpoints changed.
|
|
97
|
+
ENDPOINTS = "endpoints"
|
|
98
|
+
#: An endpoint's state changed.
|
|
99
|
+
STATE = "state"
|
|
100
|
+
#: The kind's selection, or the pin on it, changed.
|
|
101
|
+
SELECTION = "selection"
|
|
102
|
+
#: A provider failed to start or stop a chosen endpoint; see `Endpoint.error`.
|
|
103
|
+
ERROR = "error"
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def add_kind(name, count=ONE):
|
|
107
|
+
"""Make a new kind known, choosing `ONE` or `MANY` endpoints at a time.
|
|
108
|
+
|
|
109
|
+
Adding a kind that exists with the same count does nothing.
|
|
110
|
+
|
|
111
|
+
Raises:
|
|
112
|
+
ValueError: the kind exists with the other count.
|
|
113
|
+
"""
|
|
114
|
+
if name in KINDS and KINDS[name] != count:
|
|
115
|
+
raise ValueError("kind %r already chooses %s" % (name, "one" if KINDS[name] == ONE else "many"))
|
|
116
|
+
KINDS[name] = count
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class Conflict(Exception):
|
|
120
|
+
"""A choice would stop endpoints that are using the same resources.
|
|
121
|
+
|
|
122
|
+
``stops`` lists those endpoints, and ``resources`` the resources they share
|
|
123
|
+
with the choice. Ask the person, then call `select` again with
|
|
124
|
+
``confirm=True`` to go ahead.
|
|
125
|
+
"""
|
|
126
|
+
|
|
127
|
+
def __init__(self, kind, stops, resources):
|
|
128
|
+
self.kind = kind
|
|
129
|
+
self.stops = stops
|
|
130
|
+
self.resources = resources
|
|
131
|
+
super().__init__(
|
|
132
|
+
"choosing %s stops %s (shares %s)"
|
|
133
|
+
% (kind, ", ".join(ep.label for ep in stops), ", ".join(resources)),
|
|
134
|
+
)
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
class Endpoint:
|
|
138
|
+
"""Something a provider found that the device can connect to.
|
|
139
|
+
|
|
140
|
+
Attributes:
|
|
141
|
+
id (str): stable across restarts, ``"<provider>:<local id>"``.
|
|
142
|
+
label (str): what a person recognises: "Living room speaker".
|
|
143
|
+
kind (str): the kind it belongs to.
|
|
144
|
+
provider (Provider): the provider that found it.
|
|
145
|
+
state (str): `AVAILABLE`, `CONNECTED`, `NEEDS_PAIRING` or `UNAVAILABLE`.
|
|
146
|
+
caps (dict): what it can do, in the kind's own terms (rates,
|
|
147
|
+
channels, a resolution); empty when the provider says nothing.
|
|
148
|
+
resources (tuple): the shared resources it takes when chosen; the
|
|
149
|
+
provider's own unless the endpoint names others.
|
|
150
|
+
error (str or None): why the provider last failed to start or stop it.
|
|
151
|
+
"""
|
|
152
|
+
|
|
153
|
+
def __init__(self, provider, local_id, label, state=AVAILABLE, caps=None, resources=None):
|
|
154
|
+
self.provider = provider
|
|
155
|
+
self.local_id = local_id
|
|
156
|
+
self.id = "%s:%s" % (provider.name, local_id)
|
|
157
|
+
self.kind = provider.kind
|
|
158
|
+
self.label = label
|
|
159
|
+
self.state = state
|
|
160
|
+
self.caps = caps if caps is not None else {}
|
|
161
|
+
self.resources = tuple(resources) if resources is not None else tuple(provider.resources)
|
|
162
|
+
self.error = None
|
|
163
|
+
|
|
164
|
+
def __repr__(self):
|
|
165
|
+
return "<Endpoint %s %r %s>" % (self.id, self.label, self.state)
|
|
166
|
+
|
|
167
|
+
|
|
168
|
+
class Provider:
|
|
169
|
+
"""One transport for one kind. Subclass it in the library that owns the transport.
|
|
170
|
+
|
|
171
|
+
Set ``kind``, ``name`` (unique on the device, the first part of every
|
|
172
|
+
endpoint id) and ``resources``, and write `scan`. A transport whose
|
|
173
|
+
finding is slow writes `poll` too, and one that must do something when
|
|
174
|
+
an endpoint is chosen or let go writes `apply`.
|
|
175
|
+
"""
|
|
176
|
+
|
|
177
|
+
kind = None
|
|
178
|
+
name = None
|
|
179
|
+
resources = ()
|
|
180
|
+
|
|
181
|
+
def __init__(self, kind=None, name=None, resources=None):
|
|
182
|
+
if kind is not None:
|
|
183
|
+
self.kind = kind
|
|
184
|
+
if name is not None:
|
|
185
|
+
self.name = name
|
|
186
|
+
if resources is not None:
|
|
187
|
+
self.resources = tuple(resources)
|
|
188
|
+
if not self.kind or not self.name:
|
|
189
|
+
raise ValueError("a provider needs a kind and a name")
|
|
190
|
+
if ":" in self.name:
|
|
191
|
+
raise ValueError("a provider's name can't hold ':': %r" % self.name)
|
|
192
|
+
|
|
193
|
+
def endpoint(self, local_id, label, state=AVAILABLE, caps=None, resources=None):
|
|
194
|
+
"""An `Endpoint` of this provider, for `scan` and `poll` to return."""
|
|
195
|
+
return Endpoint(self, local_id, label, state, caps, resources)
|
|
196
|
+
|
|
197
|
+
def scan(self):
|
|
198
|
+
"""The endpoints known now, as a list. It must return quickly; start
|
|
199
|
+
anything slow here and report what it finds from `poll`."""
|
|
200
|
+
return []
|
|
201
|
+
|
|
202
|
+
def poll(self):
|
|
203
|
+
"""A new list of endpoints when something changed since the last
|
|
204
|
+
call, or None. Called from the registry's `poll`."""
|
|
205
|
+
return None
|
|
206
|
+
|
|
207
|
+
def apply(self, endpoint, chosen):
|
|
208
|
+
"""Start using *endpoint* when *chosen* is True, stop when False.
|
|
209
|
+
|
|
210
|
+
Raise to refuse; the registry records the message on the endpoint.
|
|
211
|
+
"""
|
|
212
|
+
|
|
213
|
+
def stop(self):
|
|
214
|
+
"""Release whatever the provider holds; called by `Registry.unregister`."""
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
class Registry:
|
|
218
|
+
"""Every provider's endpoints, the device's choices, the pins and the subscribers.
|
|
219
|
+
|
|
220
|
+
Most programs use the module's own registry through the module-level
|
|
221
|
+
functions. Make another for a test, or to keep a second set of choices.
|
|
222
|
+
|
|
223
|
+
Args:
|
|
224
|
+
store (str or None): a JSON file the choices are saved in and loaded
|
|
225
|
+
from. `set_store` sets it later.
|
|
226
|
+
"""
|
|
227
|
+
|
|
228
|
+
def __init__(self, store=None):
|
|
229
|
+
self._providers = []
|
|
230
|
+
self._found = {} # provider name -> list of Endpoint
|
|
231
|
+
self._chosen = {} # kind -> list of ids, the device's choice
|
|
232
|
+
self._pins = {} # kind -> list of (owner, ids), the newest last
|
|
233
|
+
self._applied = {} # kind -> list of ids the providers have started
|
|
234
|
+
self._subs = [] # (kind or None, callback)
|
|
235
|
+
self._store = None
|
|
236
|
+
if store:
|
|
237
|
+
self.set_store(store)
|
|
238
|
+
|
|
239
|
+
# -- providers -------------------------------------------------------------
|
|
240
|
+
|
|
241
|
+
def register(self, provider):
|
|
242
|
+
"""Add *provider*, list what it knows now, and start any choice waiting on it.
|
|
243
|
+
|
|
244
|
+
Raises:
|
|
245
|
+
ValueError: another provider has the same name, or the kind is unknown.
|
|
246
|
+
"""
|
|
247
|
+
if provider.kind not in KINDS:
|
|
248
|
+
raise ValueError("unknown kind %r; add it with add_kind" % provider.kind)
|
|
249
|
+
for p in self._providers:
|
|
250
|
+
if p.name == provider.name:
|
|
251
|
+
raise ValueError("a provider named %r is already registered" % provider.name)
|
|
252
|
+
self._providers.append(provider)
|
|
253
|
+
self._found[provider.name] = []
|
|
254
|
+
self._update(provider, provider.scan())
|
|
255
|
+
return provider
|
|
256
|
+
|
|
257
|
+
def unregister(self, provider):
|
|
258
|
+
"""Remove *provider* and its endpoints, stopping any that were chosen.
|
|
259
|
+
|
|
260
|
+
Their ids stay chosen, so they're used again when the provider returns.
|
|
261
|
+
"""
|
|
262
|
+
if provider not in self._providers:
|
|
263
|
+
return
|
|
264
|
+
self._update(provider, [])
|
|
265
|
+
self._providers.remove(provider)
|
|
266
|
+
del self._found[provider.name]
|
|
267
|
+
try:
|
|
268
|
+
provider.stop()
|
|
269
|
+
except Exception as exc: # noqa: BLE001 - a provider's failure is reported, not raised
|
|
270
|
+
_report("stop", provider.name, exc)
|
|
271
|
+
|
|
272
|
+
def providers(self, kind=None):
|
|
273
|
+
"""The registered providers, of *kind* or of every kind."""
|
|
274
|
+
return [p for p in self._providers if kind is None or p.kind == kind]
|
|
275
|
+
|
|
276
|
+
def poll(self):
|
|
277
|
+
"""Ask each provider for news; returns True when anything changed.
|
|
278
|
+
|
|
279
|
+
Call it from a timer. A provider that raises is reported and skipped.
|
|
280
|
+
"""
|
|
281
|
+
changed = False
|
|
282
|
+
for provider in list(self._providers):
|
|
283
|
+
try:
|
|
284
|
+
found = provider.poll()
|
|
285
|
+
except Exception as exc: # noqa: BLE001
|
|
286
|
+
_report("poll", provider.name, exc)
|
|
287
|
+
continue
|
|
288
|
+
if found is not None:
|
|
289
|
+
changed = self._update(provider, found) or changed
|
|
290
|
+
return changed
|
|
291
|
+
|
|
292
|
+
def refresh(self, kind=None):
|
|
293
|
+
"""Scan again now, every provider of *kind* or of every kind."""
|
|
294
|
+
for provider in self.providers(kind):
|
|
295
|
+
try:
|
|
296
|
+
found = provider.scan()
|
|
297
|
+
except Exception as exc: # noqa: BLE001
|
|
298
|
+
_report("scan", provider.name, exc)
|
|
299
|
+
continue
|
|
300
|
+
self._update(provider, found)
|
|
301
|
+
|
|
302
|
+
# -- endpoints -------------------------------------------------------------
|
|
303
|
+
|
|
304
|
+
def endpoints(self, kind):
|
|
305
|
+
"""The endpoints of *kind* found so far, provider by provider in the
|
|
306
|
+
order they registered."""
|
|
307
|
+
_known(kind)
|
|
308
|
+
out = []
|
|
309
|
+
for provider in self._providers:
|
|
310
|
+
if provider.kind == kind:
|
|
311
|
+
out.extend(self._found[provider.name])
|
|
312
|
+
return out
|
|
313
|
+
|
|
314
|
+
def find(self, endpoint_id):
|
|
315
|
+
"""The `Endpoint` with this id, or None while it isn't found."""
|
|
316
|
+
name = endpoint_id.split(":", 1)[0]
|
|
317
|
+
for ep in self._found.get(name, ()):
|
|
318
|
+
if ep.id == endpoint_id:
|
|
319
|
+
return ep
|
|
320
|
+
return None
|
|
321
|
+
|
|
322
|
+
# -- choices ---------------------------------------------------------------
|
|
323
|
+
|
|
324
|
+
def chosen(self, kind):
|
|
325
|
+
"""The device's choice for *kind* as a list of ids, found or not, ignoring pins."""
|
|
326
|
+
_known(kind)
|
|
327
|
+
return list(self._chosen.get(kind, ()))
|
|
328
|
+
|
|
329
|
+
def pinned(self, kind):
|
|
330
|
+
"""``(owner, ids)`` of the pin in force on *kind*, or None."""
|
|
331
|
+
_known(kind)
|
|
332
|
+
pins = self._pins.get(kind)
|
|
333
|
+
if not pins:
|
|
334
|
+
return None
|
|
335
|
+
owner, ids = pins[-1]
|
|
336
|
+
return owner, list(ids)
|
|
337
|
+
|
|
338
|
+
def selection(self, kind):
|
|
339
|
+
"""The ids in force for *kind*: the newest pin's, or the device's choice."""
|
|
340
|
+
pin = self.pinned(kind)
|
|
341
|
+
return pin[1] if pin else self.chosen(kind)
|
|
342
|
+
|
|
343
|
+
def selected(self, kind):
|
|
344
|
+
"""The chosen endpoints of *kind* that are found, in choice order.
|
|
345
|
+
|
|
346
|
+
For a `ONE` kind this is a list of at most one; take ``[0]`` when it isn't empty.
|
|
347
|
+
"""
|
|
348
|
+
out = []
|
|
349
|
+
for i in self.selection(kind):
|
|
350
|
+
ep = self.find(i)
|
|
351
|
+
if ep is not None:
|
|
352
|
+
out.append(ep)
|
|
353
|
+
return out
|
|
354
|
+
|
|
355
|
+
def conflicts(self, kind, ids):
|
|
356
|
+
"""What choosing *ids* for *kind* would stop: ``(endpoints, resources)``.
|
|
357
|
+
|
|
358
|
+
Only found endpoints count, on both sides.
|
|
359
|
+
"""
|
|
360
|
+
ids = self._ids(kind, ids)
|
|
361
|
+
taking = []
|
|
362
|
+
for i in ids:
|
|
363
|
+
ep = self.find(i)
|
|
364
|
+
if ep is not None:
|
|
365
|
+
taking.extend(r for r in ep.resources if r not in taking)
|
|
366
|
+
stops = []
|
|
367
|
+
shared = []
|
|
368
|
+
replacing = self.selection(kind)
|
|
369
|
+
for other in KINDS:
|
|
370
|
+
for i in self.selection(other):
|
|
371
|
+
if other == kind and (i in ids or i in replacing):
|
|
372
|
+
continue
|
|
373
|
+
ep = self.find(i)
|
|
374
|
+
if ep is None:
|
|
375
|
+
continue
|
|
376
|
+
hit = [r for r in ep.resources if r in taking]
|
|
377
|
+
if hit:
|
|
378
|
+
stops.append(ep)
|
|
379
|
+
shared.extend(r for r in hit if r not in shared)
|
|
380
|
+
# Two endpoints of one choice that need the same resource can't both run.
|
|
381
|
+
seen = []
|
|
382
|
+
for i in ids:
|
|
383
|
+
ep = self.find(i)
|
|
384
|
+
if ep is None:
|
|
385
|
+
continue
|
|
386
|
+
for r in ep.resources:
|
|
387
|
+
if r in seen and ep not in stops:
|
|
388
|
+
stops.append(ep)
|
|
389
|
+
if r not in shared:
|
|
390
|
+
shared.append(r)
|
|
391
|
+
seen.append(r)
|
|
392
|
+
return stops, shared
|
|
393
|
+
|
|
394
|
+
def select(self, kind, ids, confirm=False):
|
|
395
|
+
"""Choose *ids* (one id, a list, or None for nothing) for *kind*, for the whole device.
|
|
396
|
+
|
|
397
|
+
The providers start the new endpoints and stop the old ones, the
|
|
398
|
+
choice is saved, and subscribers hear about it. While a pin is in
|
|
399
|
+
force the choice is saved but the pin's endpoints stay in use.
|
|
400
|
+
|
|
401
|
+
Args:
|
|
402
|
+
confirm (bool): go ahead even when the choice stops other endpoints.
|
|
403
|
+
|
|
404
|
+
Raises:
|
|
405
|
+
Conflict: the choice stops endpoints using the same resources,
|
|
406
|
+
and *confirm* is False. Nothing has changed.
|
|
407
|
+
ValueError: more than one id for a `ONE` kind.
|
|
408
|
+
"""
|
|
409
|
+
ids = self._ids(kind, ids)
|
|
410
|
+
self._make_room(kind, ids, confirm)
|
|
411
|
+
self._chosen[kind] = ids
|
|
412
|
+
self._save()
|
|
413
|
+
self._settle(kind)
|
|
414
|
+
|
|
415
|
+
def pin(self, kind, ids, owner, confirm=False):
|
|
416
|
+
"""Use *ids* for *kind* while *owner* (an app's name) runs, whatever the device's choice.
|
|
417
|
+
|
|
418
|
+
The newest pin on a kind wins. Raises as `select` does.
|
|
419
|
+
"""
|
|
420
|
+
ids = self._ids(kind, ids)
|
|
421
|
+
self._make_room(kind, ids, confirm)
|
|
422
|
+
pins = [p for p in self._pins.get(kind, ()) if p[0] != owner]
|
|
423
|
+
pins.append((owner, ids))
|
|
424
|
+
self._pins[kind] = pins
|
|
425
|
+
self._settle(kind)
|
|
426
|
+
|
|
427
|
+
def unpin(self, owner, kind=None):
|
|
428
|
+
"""Lift *owner*'s pin on *kind*, or all of its pins; the device's choice returns."""
|
|
429
|
+
for k in list(self._pins):
|
|
430
|
+
if kind is not None and k != kind:
|
|
431
|
+
continue
|
|
432
|
+
pins = [p for p in self._pins[k] if p[0] != owner]
|
|
433
|
+
if len(pins) != len(self._pins[k]):
|
|
434
|
+
if pins:
|
|
435
|
+
self._pins[k] = pins
|
|
436
|
+
else:
|
|
437
|
+
del self._pins[k]
|
|
438
|
+
self._settle(k)
|
|
439
|
+
|
|
440
|
+
# -- subscriptions ---------------------------------------------------------
|
|
441
|
+
|
|
442
|
+
def subscribe(self, kind, callback):
|
|
443
|
+
"""Call ``callback(event, kind)`` when *kind* changes, or every kind when None.
|
|
444
|
+
|
|
445
|
+
The event is `ENDPOINTS`, `STATE`, `SELECTION` or `ERROR`. Returns
|
|
446
|
+
*callback*, for `unsubscribe`.
|
|
447
|
+
"""
|
|
448
|
+
if kind is not None:
|
|
449
|
+
_known(kind)
|
|
450
|
+
self._subs.append((kind, callback))
|
|
451
|
+
return callback
|
|
452
|
+
|
|
453
|
+
def unsubscribe(self, callback):
|
|
454
|
+
"""Stop calling *callback*, for every kind it was subscribed to."""
|
|
455
|
+
self._subs = [s for s in self._subs if s[1] is not callback]
|
|
456
|
+
|
|
457
|
+
# -- the store -------------------------------------------------------------
|
|
458
|
+
|
|
459
|
+
def set_store(self, path):
|
|
460
|
+
"""Save choices in *path* (JSON), and load the ones saved there.
|
|
461
|
+
|
|
462
|
+
Loaded choices replace the ones in memory for the kinds they name,
|
|
463
|
+
and providers start them as their endpoints are found.
|
|
464
|
+
"""
|
|
465
|
+
self._store = path
|
|
466
|
+
saved = _load(path)
|
|
467
|
+
for kind, ids in saved.get("selection", {}).items():
|
|
468
|
+
if kind in KINDS and isinstance(ids, list):
|
|
469
|
+
if KINDS[kind] == ONE:
|
|
470
|
+
ids = ids[:1]
|
|
471
|
+
self._chosen[kind] = [str(i) for i in ids]
|
|
472
|
+
self._settle(kind)
|
|
473
|
+
|
|
474
|
+
# -- inside ----------------------------------------------------------------
|
|
475
|
+
|
|
476
|
+
def _ids(self, kind, ids):
|
|
477
|
+
_known(kind)
|
|
478
|
+
if ids is None:
|
|
479
|
+
ids = []
|
|
480
|
+
elif isinstance(ids, str):
|
|
481
|
+
ids = [ids]
|
|
482
|
+
else:
|
|
483
|
+
ids = list(ids)
|
|
484
|
+
if KINDS[kind] == ONE and len(ids) > 1:
|
|
485
|
+
raise ValueError("%s takes one endpoint at a time, not %d" % (kind, len(ids)))
|
|
486
|
+
out = []
|
|
487
|
+
for i in ids:
|
|
488
|
+
if i not in out:
|
|
489
|
+
out.append(i)
|
|
490
|
+
return out
|
|
491
|
+
|
|
492
|
+
def _make_room(self, kind, ids, confirm):
|
|
493
|
+
stops, shared = self.conflicts(kind, ids)
|
|
494
|
+
if not stops:
|
|
495
|
+
return
|
|
496
|
+
if not confirm:
|
|
497
|
+
raise Conflict(kind, stops, shared)
|
|
498
|
+
for ep in stops:
|
|
499
|
+
if ep.id in ids:
|
|
500
|
+
raise ValueError("%s and another choice of %s need %s" % (ep.label, kind, ", ".join(shared)))
|
|
501
|
+
k = ep.kind
|
|
502
|
+
if ep.id in self._chosen.get(k, ()):
|
|
503
|
+
self._chosen[k] = [i for i in self._chosen[k] if i != ep.id]
|
|
504
|
+
if k in self._pins:
|
|
505
|
+
for idx, (owner, pids) in enumerate(self._pins[k]):
|
|
506
|
+
if ep.id in pids:
|
|
507
|
+
self._pins[k][idx] = (owner, [i for i in pids if i != ep.id])
|
|
508
|
+
if k != kind:
|
|
509
|
+
self._settle(k)
|
|
510
|
+
self._save()
|
|
511
|
+
|
|
512
|
+
def _settle(self, kind):
|
|
513
|
+
"""Start and stop endpoints so the providers match the selection, then tell subscribers."""
|
|
514
|
+
want = [i for i in self.selection(kind) if self.find(i) is not None]
|
|
515
|
+
had = self._applied.get(kind, [])
|
|
516
|
+
errors = False
|
|
517
|
+
for i in had:
|
|
518
|
+
if i not in want:
|
|
519
|
+
ep = self.find(i)
|
|
520
|
+
if ep is not None:
|
|
521
|
+
errors = self._apply(ep, False) or errors
|
|
522
|
+
applied = []
|
|
523
|
+
for i in want:
|
|
524
|
+
ep = self.find(i)
|
|
525
|
+
if i in had:
|
|
526
|
+
applied.append(i)
|
|
527
|
+
elif not self._apply(ep, True):
|
|
528
|
+
applied.append(i)
|
|
529
|
+
else:
|
|
530
|
+
errors = True
|
|
531
|
+
self._applied[kind] = applied
|
|
532
|
+
self._notify(SELECTION, kind)
|
|
533
|
+
if errors:
|
|
534
|
+
self._notify(ERROR, kind)
|
|
535
|
+
|
|
536
|
+
def _apply(self, ep, chosen):
|
|
537
|
+
"""Have the provider start or stop *ep*; True when it failed."""
|
|
538
|
+
try:
|
|
539
|
+
ep.provider.apply(ep, chosen)
|
|
540
|
+
except Exception as exc: # noqa: BLE001
|
|
541
|
+
ep.error = str(exc) or exc.__class__.__name__
|
|
542
|
+
return True
|
|
543
|
+
ep.error = None
|
|
544
|
+
return False
|
|
545
|
+
|
|
546
|
+
def _update(self, provider, found):
|
|
547
|
+
"""Take a provider's new list, keeping Endpoint objects for ids it still has."""
|
|
548
|
+
old = self._found.get(provider.name, [])
|
|
549
|
+
olds = {ep.id: ep for ep in old}
|
|
550
|
+
new = []
|
|
551
|
+
list_changed = len(found) != len(old)
|
|
552
|
+
state_changed = False
|
|
553
|
+
for ep in found:
|
|
554
|
+
prev = olds.get(ep.id)
|
|
555
|
+
if prev is None:
|
|
556
|
+
list_changed = True
|
|
557
|
+
new.append(ep)
|
|
558
|
+
continue
|
|
559
|
+
if prev.state != ep.state:
|
|
560
|
+
state_changed = True
|
|
561
|
+
if prev.label != ep.label:
|
|
562
|
+
list_changed = True
|
|
563
|
+
prev.state = ep.state
|
|
564
|
+
prev.label = ep.label
|
|
565
|
+
prev.caps = ep.caps
|
|
566
|
+
prev.resources = ep.resources
|
|
567
|
+
new.append(prev)
|
|
568
|
+
if not list_changed:
|
|
569
|
+
list_changed = [e.id for e in new] != [e.id for e in old]
|
|
570
|
+
# Endpoints that went away are stopped before they're forgotten.
|
|
571
|
+
gone = [ep for ep in old if ep.id not in [e.id for e in new]]
|
|
572
|
+
kind = provider.kind
|
|
573
|
+
for ep in gone:
|
|
574
|
+
if ep.id in self._applied.get(kind, ()):
|
|
575
|
+
self._apply(ep, False)
|
|
576
|
+
self._applied[kind] = [i for i in self._applied[kind] if i != ep.id]
|
|
577
|
+
self._found[provider.name] = new
|
|
578
|
+
if list_changed:
|
|
579
|
+
self._notify(ENDPOINTS, kind)
|
|
580
|
+
if gone or any(e.id in self.selection(kind) for e in new):
|
|
581
|
+
self._settle(kind)
|
|
582
|
+
if state_changed:
|
|
583
|
+
self._notify(STATE, kind)
|
|
584
|
+
return list_changed or state_changed
|
|
585
|
+
|
|
586
|
+
def _notify(self, event, kind):
|
|
587
|
+
for k, callback in list(self._subs):
|
|
588
|
+
if k is None or k == kind:
|
|
589
|
+
try:
|
|
590
|
+
callback(event, kind)
|
|
591
|
+
except Exception as exc: # noqa: BLE001 - one subscriber can't stop the rest
|
|
592
|
+
_report("subscriber", kind, exc)
|
|
593
|
+
|
|
594
|
+
def _save(self):
|
|
595
|
+
if self._store:
|
|
596
|
+
_dump(self._store, {"selection": self._chosen})
|
|
597
|
+
|
|
598
|
+
|
|
599
|
+
def _known(kind):
|
|
600
|
+
if kind not in KINDS:
|
|
601
|
+
raise ValueError("unknown kind %r" % kind)
|
|
602
|
+
|
|
603
|
+
|
|
604
|
+
def _report(what, who, exc):
|
|
605
|
+
if hasattr(sys, "print_exception"):
|
|
606
|
+
sys.print_exception(exc)
|
|
607
|
+
print("endpointkit: %s %s failed: %r" % (who, what, exc))
|
|
608
|
+
|
|
609
|
+
|
|
610
|
+
def _load(path):
|
|
611
|
+
if json is None:
|
|
612
|
+
return {}
|
|
613
|
+
try:
|
|
614
|
+
with open(path) as f:
|
|
615
|
+
data = json.load(f)
|
|
616
|
+
except OSError:
|
|
617
|
+
return {}
|
|
618
|
+
except ValueError:
|
|
619
|
+
print("endpointkit: %s isn't JSON; starting with no saved choices" % path)
|
|
620
|
+
return {}
|
|
621
|
+
return data if isinstance(data, dict) else {}
|
|
622
|
+
|
|
623
|
+
|
|
624
|
+
def _dump(path, data):
|
|
625
|
+
if json is None:
|
|
626
|
+
raise OSError("this build has no json module, so choices can't be saved")
|
|
627
|
+
tmp = path + ".tmp"
|
|
628
|
+
with open(tmp, "w") as f:
|
|
629
|
+
json.dump(data, f)
|
|
630
|
+
replace = getattr(os, "replace", None)
|
|
631
|
+
if replace is not None:
|
|
632
|
+
replace(tmp, path)
|
|
633
|
+
return
|
|
634
|
+
# MicroPython's rename overwrites on littlefs and FAT alike, but not on
|
|
635
|
+
# every host, so clear the old file first when it refuses.
|
|
636
|
+
try:
|
|
637
|
+
os.rename(tmp, path)
|
|
638
|
+
except OSError:
|
|
639
|
+
os.remove(path)
|
|
640
|
+
os.rename(tmp, path)
|
|
641
|
+
|
|
642
|
+
|
|
643
|
+
#: The device's registry, which the functions below use.
|
|
644
|
+
registry = Registry()
|
|
645
|
+
|
|
646
|
+
register = registry.register
|
|
647
|
+
unregister = registry.unregister
|
|
648
|
+
providers = registry.providers
|
|
649
|
+
poll = registry.poll
|
|
650
|
+
refresh = registry.refresh
|
|
651
|
+
endpoints = registry.endpoints
|
|
652
|
+
find = registry.find
|
|
653
|
+
chosen = registry.chosen
|
|
654
|
+
pinned = registry.pinned
|
|
655
|
+
selection = registry.selection
|
|
656
|
+
selected = registry.selected
|
|
657
|
+
conflicts = registry.conflicts
|
|
658
|
+
select = registry.select
|
|
659
|
+
pin = registry.pin
|
|
660
|
+
unpin = registry.unpin
|
|
661
|
+
subscribe = registry.subscribe
|
|
662
|
+
unsubscribe = registry.unsubscribe
|
|
663
|
+
set_store = registry.set_store
|