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