HAP-python 5.1.0__py3-none-any.whl → 5.2.0__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.
pyhap/accessory_driver.py CHANGED
@@ -2,18 +2,19 @@
2
2
 
3
3
  Sending updates to clients
4
4
 
5
- The process of sending value changes to clients happens in two parts - on one hand, the
6
- value change is indicated by a Characteristic and, on the other, that change is sent to a
7
- client. To begin, typically, something in the Accessory's run method will do
5
+ The process of sending value changes to clients happens in two parts - on one hand,
6
+ the value change is indicated by a Characteristic and, on the other, that change is
7
+ sent to a client. To begin, typically, something in the Accessory's run method will do
8
8
  set_value(foo, notify=True) on one of its contained Characteristic. This in turn will
9
9
  create a HAP representation of the change and publish it to the Accessory. This will
10
10
  then add some more information and eventually the value change will reach the
11
11
  AccessoryDriver (all this happens through the publish() interface). The AccessoryDriver
12
12
  will then check if there is a client that subscribed for events from this exact
13
- Characteristic from this exact Accessory (remember, it could be a Bridge with more than
14
- one Accessory in it). If so, a task is created to send the event to the subscribers. This
15
- terminates the call chain and concludes the publishing process from the Characteristic,
16
- the Characteristic does not block waiting for the actual send to happen.
13
+ Characteristic from this exact Accessory (remember, it could be a Bridge with more
14
+ than one Accessory in it). If so, a task is created to send the event to the
15
+ subscribers. This terminates the call chain and concludes the publishing process
16
+ from the Characteristic, the Characteristic does not block waiting for the actual
17
+ send to happen.
17
18
  """
18
19
 
19
20
  import asyncio
@@ -28,13 +29,13 @@ import sys
28
29
  import tempfile
29
30
  import threading
30
31
  import time
31
- from typing import Any, Dict, List, Optional, Tuple
32
+ from typing import Any
32
33
 
33
34
  from zeroconf import ServiceInfo
34
35
  from zeroconf.asyncio import AsyncZeroconf
35
36
 
36
37
  from pyhap import util
37
- from pyhap.accessory import Accessory, get_topic
38
+ from pyhap.accessory import Accessory, Bridge, get_topic
38
39
  from pyhap.characteristic import Characteristic, CharacteristicError
39
40
  from pyhap.const import (
40
41
  HAP_PERMISSION_NOTIFY,
@@ -72,12 +73,23 @@ LEADING_TRAILING_SPACE_DASH = re.compile(r"^[ -]+|[ -]+$")
72
73
  DASH_REGEX = re.compile(r"[-]+")
73
74
  KEYS_TO_EXCLUDE = {HAP_REPR_IID, HAP_REPR_AID}
74
75
 
76
+ # Consecutive failed pair-setup proofs (each is a setup-code guess) before
77
+ # pair-setup is locked out, and for how long.
78
+ MAX_FAILED_PAIRING_ATTEMPTS = 5
79
+ PAIRING_LOCKOUT_SECONDS = 60
75
80
 
76
- def _wrap_char_setter(char, value, client_addr):
81
+ # Prepared writes are short-lived (HomeKit uses ~10 second TTLs); cap both
82
+ # the TTL and the number of pending writes per client so a paired peer cannot
83
+ # grow ``prepared_writes`` without bound.
84
+ MAX_PREPARED_WRITES_PER_CLIENT = 16
85
+ MAX_PREPARED_WRITE_TTL_SECONDS = 30.0
86
+
87
+
88
+ def _wrap_char_setter(char: Any, value: Any, client_addr: Any) -> tuple[int, Any]:
77
89
  """Process an characteristic setter callback trapping and logging all exceptions."""
78
90
  try:
79
91
  response = char.client_update_value(value, client_addr)
80
- except Exception: # pylint: disable=broad-except
92
+ except Exception:
81
93
  logger.exception(
82
94
  "%s: Error while setting characteristic %s to %s",
83
95
  client_addr,
@@ -88,11 +100,11 @@ def _wrap_char_setter(char, value, client_addr):
88
100
  return HAP_SERVER_STATUS.SUCCESS, response
89
101
 
90
102
 
91
- def _wrap_acc_setter(acc, updates_by_service, client_addr):
103
+ def _wrap_acc_setter(acc: Any, updates_by_service: Any, client_addr: Any) -> Any:
92
104
  """Process an accessory setter callback trapping and logging all exceptions."""
93
105
  try:
94
106
  acc.setter_callback(updates_by_service)
95
- except Exception: # pylint: disable=broad-except
107
+ except Exception:
96
108
  logger.exception(
97
109
  "%s: Error while setting characteristics to %s for the %s accessory",
98
110
  updates_by_service,
@@ -103,7 +115,7 @@ def _wrap_acc_setter(acc, updates_by_service, client_addr):
103
115
  return HAP_SERVER_STATUS.SUCCESS
104
116
 
105
117
 
106
- def _wrap_service_setter(service, chars, client_addr):
118
+ def _wrap_service_setter(service: Any, chars: Any, client_addr: Any) -> Any:
107
119
  """Process a service setter callback trapping and logging all exceptions."""
108
120
  # Ideally this would pass the chars as is without converting
109
121
  # them to the display_name, but that would break existing
@@ -111,7 +123,7 @@ def _wrap_service_setter(service, chars, client_addr):
111
123
  service_chars = {char.display_name: value for char, value in chars.items()}
112
124
  try:
113
125
  service.setter_callback(service_chars)
114
- except Exception: # pylint: disable=broad-except
126
+ except Exception:
115
127
  logger.exception(
116
128
  "%s: Error while setting characteristics to %s for the %s service",
117
129
  service_chars,
@@ -125,7 +137,9 @@ def _wrap_service_setter(service, chars, client_addr):
125
137
  class AccessoryMDNSServiceInfo(ServiceInfo):
126
138
  """A mDNS service info representation of an accessory."""
127
139
 
128
- def __init__(self, accessory, state, zeroconf_server=None):
140
+ def __init__(
141
+ self, accessory: Any, state: State, zeroconf_server: Any = None
142
+ ) -> None:
129
143
  self.accessory = accessory
130
144
  self.state: State = state
131
145
 
@@ -147,14 +161,14 @@ class AccessoryMDNSServiceInfo(ServiceInfo):
147
161
  parsed_addresses=self.state.addresses,
148
162
  )
149
163
 
150
- def _valid_name(self):
164
+ def _valid_name(self) -> str:
151
165
  return re.sub(
152
166
  LEADING_TRAILING_SPACE_DASH,
153
167
  "",
154
168
  re.sub(VALID_MDNS_REGEX, " ", self.accessory.display_name),
155
169
  )
156
170
 
157
- def _valid_host_name(self):
171
+ def _valid_host_name(self) -> str:
158
172
  return re.sub(
159
173
  DASH_REGEX,
160
174
  "-",
@@ -164,13 +178,13 @@ class AccessoryMDNSServiceInfo(ServiceInfo):
164
178
  .strip("-"),
165
179
  )
166
180
 
167
- def _setup_hash(self):
181
+ def _setup_hash(self) -> str:
168
182
  setup_hash_material = self.state.setup_id + self.state.mac
169
183
  temp_hash = hashlib.sha512()
170
184
  temp_hash.update(setup_hash_material.encode())
171
185
  return base64.b64encode(temp_hash.digest()[:4]).decode()
172
186
 
173
- def _get_advert_data(self):
187
+ def _get_advert_data(self) -> dict[str, str]:
174
188
  """Generate advertisement data from the accessory."""
175
189
  return {
176
190
  "md": self._valid_name(),
@@ -190,8 +204,7 @@ class AccessoryMDNSServiceInfo(ServiceInfo):
190
204
 
191
205
 
192
206
  class AccessoryDriver:
193
- """
194
- An AccessoryDriver mediates between incoming requests from the HAPServer and
207
+ """An AccessoryDriver mediates between incoming requests from the HAPServer and
195
208
  the Accessory.
196
209
 
197
210
  The driver starts and stops the HAPServer, the mDNS advertisements and responds
@@ -201,28 +214,28 @@ class AccessoryDriver:
201
214
  def __init__(
202
215
  self,
203
216
  *,
204
- address=None,
205
- port=51234,
206
- persist_file="accessory.state",
207
- pincode=None,
208
- encoder=None,
209
- loader=None,
210
- loop=None,
211
- mac=None,
212
- listen_address=None,
213
- advertised_address=None,
214
- interface_choice=None,
215
- async_zeroconf_instance=None,
216
- zeroconf_server=None,
217
- ):
218
- """
219
- Initialize a new AccessoryDriver object.
217
+ address: Any = None,
218
+ port: int = 51234,
219
+ persist_file: str = "accessory.state",
220
+ pincode: Any = None,
221
+ encoder: Any = None,
222
+ loader: Any = None,
223
+ loop: Any = None,
224
+ mac: Any = None,
225
+ listen_address: Any = None,
226
+ advertised_address: Any = None,
227
+ interface_choice: Any = None,
228
+ async_zeroconf_instance: Any = None,
229
+ zeroconf_server: Any = None,
230
+ advertise: bool = True,
231
+ ) -> None:
232
+ """Initialize a new AccessoryDriver object.
220
233
 
221
234
  :param pincode: The pincode that HAP clients must prove they know in order
222
235
  to pair with this `Accessory`. Defaults to None, in which case a random
223
236
  pincode is generated. The pincode has the format "xxx-xx-xxx", where x is
224
237
  a digit.
225
- :type pincode: bytearray
238
+ :type pincode: bytes
226
239
 
227
240
  :param port: The local port on which the accessory will be accessible.
228
241
  In other words, this is the port of the HAPServer.
@@ -257,13 +270,18 @@ class AccessoryDriver:
257
270
  :param interface_choice: The zeroconf interfaces to listen on.
258
271
  :type InterfacesType: [InterfaceChoice.Default, InterfaceChoice.All]
259
272
 
260
- :param async_zeroconf_instance: An AsyncZeroconf instance. When running multiple accessories or
261
- bridges a single zeroconf instance can be shared to avoid the overhead
262
- of processing the same data multiple times.
273
+ :param async_zeroconf_instance: An AsyncZeroconf instance. When running multiple
274
+ accessories or bridges a single zeroconf instance can be shared to avoid
275
+ the overhead of processing the same data multiple times.
263
276
 
264
277
  :param zeroconf_server: The server name that will be used for the zeroconf
265
278
  ServiceInfo.
266
279
  :type zeroconf_server: str
280
+
281
+ :param advertise: Whether to advertise the accessory via mDNS when
282
+ the driver starts. Pass False to run the HAP server without
283
+ mDNS advertising, e.g. for tests or benchmarks.
284
+ :type advertise: bool
267
285
  """
268
286
  if loop is None:
269
287
  if sys.platform == "win32":
@@ -271,11 +289,9 @@ class AccessoryDriver:
271
289
  else:
272
290
  loop = asyncio.new_event_loop()
273
291
 
274
- executor_opts = {"max_workers": None}
275
- if sys.version_info >= (3, 6):
276
- executor_opts["thread_name_prefix"] = "SyncWorker"
277
-
278
- self.executor = ThreadPoolExecutor(**executor_opts)
292
+ self.executor = ThreadPoolExecutor(
293
+ max_workers=None, thread_name_prefix="SyncWorker"
294
+ )
279
295
  loop.set_default_executor(self.executor)
280
296
  self.tid = threading.current_thread()
281
297
  else:
@@ -284,25 +300,30 @@ class AccessoryDriver:
284
300
 
285
301
  self.loop = loop
286
302
 
287
- self.accessory: Optional[Accessory] = None
288
- self.advertiser = async_zeroconf_instance
303
+ self.accessory: Accessory | None = None
304
+ self.advertise = advertise
305
+ self.advertiser: AsyncZeroconf | None = async_zeroconf_instance
289
306
  self.zeroconf_server = zeroconf_server
290
307
  self.interface_choice = interface_choice
291
308
 
292
309
  self.persist_file = os.path.expanduser(persist_file)
293
310
  self.encoder = encoder or AccessoryEncoder()
294
311
  self.topics = {} # topic: set of (address, port) of subscribed clients
295
- # Per-session HAP shared keys, keyed by client (address, port). Needed
296
- # by transports derived from the session, e.g. HomeKit Data Stream.
297
- self.session_shared_keys: Dict[Tuple[str, int], bytes] = {}
298
312
  self.loader = loader or Loader()
299
- self.aio_stop_event = None
313
+ self.aio_stop_event: asyncio.Event | None = None
300
314
  self.stop_event = threading.Event()
301
315
 
302
316
  self.safe_mode = False
303
317
 
304
- self.mdns_service_info = None
305
- self.srp_verifier = None
318
+ self.mdns_service_info: ServiceInfo | None = None
319
+ self._srp_verifier: SrpServer | None = None
320
+
321
+ # Pair-setup rate limiting: each M1 regenerates a 3072-bit SRP
322
+ # verifier and each failed proof is a pincode guess, so excess
323
+ # failures lock pair-setup out for a while (see
324
+ # ``register_failed_pairing_attempt``).
325
+ self._failed_pairing_attempts = 0
326
+ self._pairing_lockout_until = 0.0
306
327
 
307
328
  address = address or util.get_local_address()
308
329
  advertised_address = advertised_address or address
@@ -310,12 +331,16 @@ class AccessoryDriver:
310
331
  address=advertised_address, mac=mac, pincode=pincode, port=port
311
332
  )
312
333
 
313
- listen_address = listen_address or address
314
- network_tuple = (listen_address, self.state.port)
334
+ self._listen_address: str | list[str] = listen_address or address
335
+ network_tuple = (self._listen_address, self.state.port)
315
336
  self.http_server = HAPServer(network_tuple, self)
316
337
  self.prepared_writes = {}
317
338
 
318
- def start(self):
339
+ def listen_address(self) -> str | list[str]:
340
+ """Return the address, or list of addresses, the HAP server listens on."""
341
+ return self._listen_address
342
+
343
+ def start(self) -> None:
319
344
  """Start the event loop and call `start_service`.
320
345
 
321
346
  Pyhap will be stopped gracefully on a KeyBoardInterrupt.
@@ -330,9 +355,11 @@ class AccessoryDriver:
330
355
  and hasattr(asyncio, "SafeChildWatcher")
331
356
  ):
332
357
  logger.debug("Setting child watcher")
333
- watcher = asyncio.SafeChildWatcher() # pylint: disable=deprecated-class
358
+ watcher = asyncio.SafeChildWatcher()
334
359
  watcher.attach_loop(self.loop)
335
- asyncio.set_child_watcher(watcher)
360
+ # Deprecated in 3.12, removed in 3.14; the hasattr guard
361
+ # above keeps this branch unreachable on 3.14+.
362
+ asyncio.set_child_watcher(watcher) # ty: ignore[deprecated]
336
363
  else:
337
364
  logger.debug(
338
365
  "Not setting a child watcher. Set one if "
@@ -348,20 +375,19 @@ class AccessoryDriver:
348
375
  self.loop.close()
349
376
  logger.info("Closed the event loop")
350
377
 
351
- def start_service(self):
378
+ def start_service(self) -> None:
352
379
  """Start the service."""
353
380
  self._validate_start()
354
381
  self.add_job(self.async_start)
355
382
 
356
- def _validate_start(self):
383
+ def _validate_start(self) -> None:
357
384
  """Validate we can start."""
358
385
  if self.accessory is None:
359
386
  raise ValueError(
360
- "You must assign an accessory to the driver, "
361
- "before you can start it."
387
+ "You must assign an accessory to the driver, before you can start it."
362
388
  )
363
389
 
364
- async def async_start(self):
390
+ async def async_start(self) -> None:
365
391
  """Starts the accessory.
366
392
 
367
393
  - Call the accessory's run method.
@@ -374,6 +400,7 @@ class AccessoryDriver:
374
400
  daemon.
375
401
  """
376
402
  self._validate_start()
403
+ assert self.accessory is not None # noqa: S101
377
404
  self.aio_stop_event = asyncio.Event()
378
405
 
379
406
  logger.info(
@@ -394,20 +421,21 @@ class AccessoryDriver:
394
421
  if self.state.set_accessories_hash(self.accessories_hash):
395
422
  self.async_persist()
396
423
 
397
- # Advertise the accessory as a mDNS service.
398
- logger.debug("Starting mDNS.")
399
- self.mdns_service_info = AccessoryMDNSServiceInfo(
400
- self.accessory, self.state, self.zeroconf_server
401
- )
424
+ if self.advertise:
425
+ # Advertise the accessory as a mDNS service.
426
+ logger.debug("Starting mDNS.")
427
+ self.mdns_service_info = AccessoryMDNSServiceInfo(
428
+ self.accessory, self.state, self.zeroconf_server
429
+ )
402
430
 
403
- if not self.advertiser:
404
- zc_args = {}
405
- if self.interface_choice is not None:
406
- zc_args["interfaces"] = self.interface_choice
407
- self.advertiser = AsyncZeroconf(**zc_args)
408
- await self.advertiser.async_register_service(
409
- self.mdns_service_info, cooperating_responders=True
410
- )
431
+ if not self.advertiser:
432
+ zc_args = {}
433
+ if self.interface_choice is not None:
434
+ zc_args["interfaces"] = self.interface_choice
435
+ self.advertiser = AsyncZeroconf(**zc_args)
436
+ await self.advertiser.async_register_service(
437
+ self.mdns_service_info, cooperating_responders=True
438
+ )
411
439
 
412
440
  # Print accessory setup message
413
441
  if not self.state.paired:
@@ -420,17 +448,23 @@ class AccessoryDriver:
420
448
  "AccessoryDriver for %s started successfully", self.accessory.display_name
421
449
  )
422
450
 
423
- def stop(self):
451
+ def stop(self) -> None:
424
452
  """Method to stop pyhap."""
425
453
  self.add_job(self.async_stop)
426
454
 
427
- async def async_stop(self):
455
+ async def async_stop(self) -> None:
428
456
  """Stops the AccessoryDriver and shutdown all remaining tasks."""
429
457
  self.stop_event.set()
458
+ accessory = self.accessory
459
+ assert accessory is not None # noqa: S101
460
+ assert self.aio_stop_event is not None # noqa: S101
430
461
  logger.debug("Stopping HAP server and event sending")
431
- logger.debug("Stopping mDNS advertising for %s", self.accessory.display_name)
432
- await self.advertiser.async_unregister_service(self.mdns_service_info)
433
- await self.advertiser.async_close()
462
+ if self.advertise:
463
+ assert self.advertiser is not None # noqa: S101
464
+ assert self.mdns_service_info is not None # noqa: S101
465
+ logger.debug("Stopping mDNS advertising for %s", accessory.display_name)
466
+ await self.advertiser.async_unregister_service(self.mdns_service_info)
467
+ await self.advertiser.async_close()
434
468
 
435
469
  self.aio_stop_event.set()
436
470
 
@@ -438,15 +472,15 @@ class AccessoryDriver:
438
472
 
439
473
  logger.info(
440
474
  "Stopping accessory %s on address %s, port %s.",
441
- self.accessory.display_name,
475
+ accessory.display_name,
442
476
  self.state.addresses,
443
477
  self.state.port,
444
478
  )
445
479
 
446
- await self.async_add_job(self.accessory.stop)
480
+ await self.async_add_job(accessory.stop)
447
481
 
448
482
  logger.debug(
449
- "AccessoryDriver for %s stopped successfully", self.accessory.display_name
483
+ "AccessoryDriver for %s stopped successfully", accessory.display_name
450
484
  )
451
485
 
452
486
  # Executor=None means a loop wasn't passed in
@@ -457,14 +491,14 @@ class AccessoryDriver:
457
491
 
458
492
  logger.debug("Stop completed")
459
493
 
460
- def add_job(self, target, *args):
494
+ def add_job(self, target: Any, *args: Any) -> None:
461
495
  """Add job to executor pool."""
462
496
  if target is None:
463
497
  raise ValueError("Don't call add_job with None.")
464
498
  self.loop.call_soon_threadsafe(self.async_add_job, target, *args)
465
499
 
466
500
  @util.callback
467
- def async_add_job(self, target, *args):
501
+ def async_add_job(self, target: Any, *args: Any) -> Any:
468
502
  """Add job from within the event loop."""
469
503
  task = None
470
504
 
@@ -479,7 +513,7 @@ class AccessoryDriver:
479
513
 
480
514
  return task
481
515
 
482
- def add_accessory(self, accessory):
516
+ def add_accessory(self, accessory: Accessory) -> None:
483
517
  """Add top level accessory to driver."""
484
518
  self.accessory = accessory
485
519
  if accessory.aid is None:
@@ -489,12 +523,16 @@ class AccessoryDriver:
489
523
  if os.path.exists(self.persist_file):
490
524
  logger.info("Loading Accessory state from `%s`", self.persist_file)
491
525
  self.load()
526
+ # Accessories built before load() have not seen their stored state.
527
+ accessory.restore_accessory_state()
492
528
  else:
493
529
  logger.info("Storing Accessory state in `%s`", self.persist_file)
494
530
  self.persist()
495
531
 
496
532
  @util.callback
497
- def async_subscribe_client_topic(self, client, topic, subscribe=True):
533
+ def async_subscribe_client_topic(
534
+ self, client: Any, topic: str, subscribe: bool = True
535
+ ) -> None:
498
536
  """(Un)Subscribe the given client from the given topic.
499
537
 
500
538
  This method must be run in the event loop.
@@ -505,9 +543,9 @@ class AccessoryDriver:
505
543
  :param topic: The topic to which to subscribe.
506
544
  :type topic: str
507
545
 
508
- :param subscribe: Whether to subscribe or unsubscribe the client. Both subscribing
509
- an already subscribed client and unsubscribing a client that is not subscribed
510
- do nothing.
546
+ :param subscribe: Whether to subscribe or unsubscribe the client. Both
547
+ subscribing an already subscribed client and unsubscribing a client
548
+ that is not subscribed do nothing.
511
549
  :type subscribe: bool
512
550
  """
513
551
  if subscribe:
@@ -525,7 +563,7 @@ class AccessoryDriver:
525
563
  if not subscribed_clients:
526
564
  del self.topics[topic]
527
565
 
528
- def connection_lost(self, client):
566
+ def connection_lost(self, client: Any) -> None:
529
567
  """Called when a connection is lost to a client.
530
568
 
531
569
  This method must be run in the event loop.
@@ -543,9 +581,13 @@ class AccessoryDriver:
543
581
  for topic in client_topics:
544
582
  self.async_subscribe_client_topic(client, topic, subscribe=False)
545
583
  self.prepared_writes.pop(client, None)
546
- self.session_shared_keys.pop(client, None)
547
584
 
548
- def publish(self, data, sender_client_addr=None, immediate=False):
585
+ def publish(
586
+ self,
587
+ data: dict[str, Any],
588
+ sender_client_addr: Any = None,
589
+ immediate: bool = False,
590
+ ) -> None:
549
591
  """Publishes an event to the client.
550
592
 
551
593
  The publishing occurs only if the current client is subscribed to the topic for
@@ -567,11 +609,18 @@ class AccessoryDriver:
567
609
  self.async_send_event, topic, data, sender_client_addr, immediate
568
610
  )
569
611
 
570
- def async_send_event(self, topic, data, sender_client_addr, immediate):
612
+ def async_send_event(
613
+ self,
614
+ topic: str,
615
+ data: dict[str, Any],
616
+ sender_client_addr: Any,
617
+ immediate: bool,
618
+ ) -> None:
571
619
  """Send an event to a client.
572
620
 
573
621
  Must be called in the event loop
574
622
  """
623
+ assert self.aio_stop_event is not None # noqa: S101
575
624
  if self.aio_stop_event.is_set():
576
625
  return
577
626
 
@@ -605,25 +654,29 @@ class AccessoryDriver:
605
654
  for client_addr in unsubs:
606
655
  self.async_subscribe_client_topic(client_addr, topic, False)
607
656
 
608
- def config_changed(self):
657
+ def config_changed(self) -> None:
609
658
  """Notify the driver that the accessory's configuration has changed.
610
659
 
611
660
  Persists the accessory, so that the new configuration is available on
612
- restart. Also, updates the mDNS advertisement, so that iOS clients know they need
613
- to fetch new data.
661
+ restart. Also, updates the mDNS advertisement, so that iOS clients know
662
+ they need to fetch new data.
614
663
  """
615
664
  self.state.increment_config_version()
616
665
  self.persist()
617
666
  self.update_advertisement()
618
667
 
619
- def update_advertisement(self):
668
+ def update_advertisement(self) -> None:
620
669
  """Updates the mDNS service info for the accessory."""
621
670
  self.loop.call_soon_threadsafe(self.async_update_advertisement)
622
671
 
623
672
  @callback
624
- def async_update_advertisement(self):
673
+ def async_update_advertisement(self) -> None:
625
674
  """Updates the mDNS service info for the accessory from the event loop."""
626
675
  logger.debug("Updating mDNS advertisement")
676
+ if not self.advertise:
677
+ logger.debug("Not updating mDNS advertisement: advertising is disabled")
678
+ return
679
+ assert self.advertiser is not None # noqa: S101
627
680
  self.mdns_service_info = AccessoryMDNSServiceInfo(
628
681
  self.accessory, self.state, self.zeroconf_server
629
682
  )
@@ -631,17 +684,24 @@ class AccessoryDriver:
631
684
  self.advertiser.async_update_service(self.mdns_service_info)
632
685
  )
633
686
 
687
+ def accessory_state(self, aid: int) -> dict[str, Any]:
688
+ """Return the persisted state dict of accessory ``aid``.
689
+
690
+ Accessories keep settings here that must survive a restart. Save
691
+ changes with :meth:`async_persist`.
692
+ """
693
+ return self.state.accessory_states.setdefault(aid, {})
694
+
634
695
  @callback
635
- def async_persist(self):
696
+ def async_persist(self) -> None:
636
697
  """Saves the state of the accessory.
637
698
 
638
699
  Must be run in the event loop.
639
700
  """
640
- loop = asyncio.get_event_loop()
641
701
  logger.debug("Scheduling write of accessory state to disk")
642
- util.async_create_background_task(loop.run_in_executor(None, self.persist))
702
+ util.async_create_background_task(self.loop.run_in_executor(None, self.persist))
643
703
 
644
- def persist(self):
704
+ def persist(self) -> None:
645
705
  """Saves the state of the accessory.
646
706
 
647
707
  Must run in executor.
@@ -668,19 +728,19 @@ class AccessoryDriver:
668
728
  if os.path.exists(self.persist_file):
669
729
  os.chmod(self.persist_file, 0o644)
670
730
  os.replace(tmp_filename, self.persist_file)
671
- except Exception: # pylint: disable=broad-except
731
+ except Exception:
672
732
  logger.exception("Failed to persist accessory state")
673
733
  raise
674
734
  finally:
675
735
  if tmp_filename and os.path.exists(tmp_filename):
676
736
  os.remove(tmp_filename)
677
737
 
678
- def load(self):
738
+ def load(self) -> None:
679
739
  """Load the persist file.
680
740
 
681
741
  Must run in executor.
682
742
  """
683
- with open(self.persist_file, "r", encoding="utf8") as file_handle:
743
+ with open(self.persist_file, encoding="utf8") as file_handle:
684
744
  self.encoder.load_into(file_handle, self.state)
685
745
 
686
746
  @callback
@@ -711,6 +771,9 @@ class AccessoryDriver:
711
771
  client_username_bytes,
712
772
  client_permissions,
713
773
  )
774
+ # A successful pairing clears the rate limiter.
775
+ self._failed_pairing_attempts = 0
776
+ self._pairing_lockout_until = 0.0
714
777
  self.state.add_paired_client(
715
778
  client_username_bytes, client_public, client_permissions
716
779
  )
@@ -718,7 +781,32 @@ class AccessoryDriver:
718
781
  return True
719
782
 
720
783
  @callback
721
- def unpair(self, client_uuid):
784
+ def register_failed_pairing_attempt(self) -> None:
785
+ """Register a failed pair-setup attempt.
786
+
787
+ Each failed SRP proof is effectively a setup-code guess and each pair
788
+ setup also regenerates a 3072-bit SRP verifier, so after too many
789
+ consecutive failures pair-setup is locked out for a cooldown period.
790
+
791
+ This method must be run in the event loop.
792
+ """
793
+ self._failed_pairing_attempts += 1
794
+ if self._failed_pairing_attempts >= MAX_FAILED_PAIRING_ATTEMPTS:
795
+ self._pairing_lockout_until = time.monotonic() + PAIRING_LOCKOUT_SECONDS
796
+ self._failed_pairing_attempts = 0
797
+ logger.warning(
798
+ "Pair-setup locked out for %s seconds after %s failed attempts",
799
+ PAIRING_LOCKOUT_SECONDS,
800
+ MAX_FAILED_PAIRING_ATTEMPTS,
801
+ )
802
+
803
+ @property
804
+ def pairing_locked_out(self) -> bool:
805
+ """Whether pair-setup is currently locked out due to failed attempts."""
806
+ return time.monotonic() < self._pairing_lockout_until
807
+
808
+ @callback
809
+ def unpair(self, client_uuid: Any) -> None:
722
810
  """Removes the paired client from the accessory.
723
811
 
724
812
  Persist the new accessory state.
@@ -728,9 +816,15 @@ class AccessoryDriver:
728
816
  """
729
817
  logger.info("Unpairing client %s.", client_uuid)
730
818
  self.state.remove_paired_client(client_uuid)
819
+ if not self.state.paired and self.accessory is not None:
820
+ try:
821
+ self.accessory.reset_accessory_state()
822
+ except Exception:
823
+ # The removed pairing must be saved regardless.
824
+ logger.warning("Failed to reset the accessory state", exc_info=True)
731
825
  self.async_persist()
732
826
 
733
- def finish_pair(self):
827
+ def finish_pair(self) -> None:
734
828
  """Finishing pairing or unpairing.
735
829
 
736
830
  Updates the accessory and updates the mDNS service.
@@ -750,15 +844,21 @@ class AccessoryDriver:
750
844
  if not self.safe_mode:
751
845
  self.update_advertisement()
752
846
 
753
- def setup_srp_verifier(self):
847
+ @property
848
+ def srp_verifier(self) -> SrpServer:
849
+ """Return the SRP verifier (created by setup_srp_verifier)."""
850
+ assert self._srp_verifier is not None # noqa: S101
851
+ return self._srp_verifier
852
+
853
+ def setup_srp_verifier(self) -> None:
754
854
  """Create an SRP verifier for the accessory's info."""
755
855
  # TODO: Move the below hard-coded values somewhere nice.
756
856
  ctx = get_srp_context(3072, hashlib.sha512, 16)
757
857
  verifier = SrpServer(ctx, b"Pair-Setup", self.state.pincode)
758
- self.srp_verifier = verifier
858
+ self._srp_verifier = verifier
759
859
 
760
860
  @property
761
- def accessories_hash(self):
861
+ def accessories_hash(self) -> str:
762
862
  """Hash the get_accessories response to track configuration changes."""
763
863
  # We pass include_value=False to avoid including the value
764
864
  # of the characteristics in the hash. This is because the
@@ -771,7 +871,7 @@ class AccessoryDriver:
771
871
  util.to_sorted_hap_json(self.get_accessories(include_value=False))
772
872
  ).hexdigest()
773
873
 
774
- def get_accessories(self, include_value: bool = True):
874
+ def get_accessories(self, include_value: bool = True) -> dict[str, Any]:
775
875
  """Returns the accessory in HAP format.
776
876
 
777
877
  :return: An example HAP representation is:
@@ -796,6 +896,7 @@ class AccessoryDriver:
796
896
 
797
897
  :rtype: dict
798
898
  """
899
+ assert self.accessory is not None # noqa: S101
799
900
  hap_rep = self.accessory.to_HAP(include_value=include_value)
800
901
  if not isinstance(hap_rep, list):
801
902
  hap_rep = [
@@ -804,7 +905,7 @@ class AccessoryDriver:
804
905
  logger.debug("Get accessories response: %s", hap_rep)
805
906
  return {HAP_REPR_ACCS: hap_rep}
806
907
 
807
- def get_characteristics(self, char_ids):
908
+ def get_characteristics(self, char_ids: Any) -> dict[str, Any]:
808
909
  """Returns values for the required characteristics.
809
910
 
810
911
  :param char_ids: A list of characteristic "paths", e.g. "1.2" is aid 1, iid 2.
@@ -824,6 +925,7 @@ class AccessoryDriver:
824
925
 
825
926
  :rtype: dict
826
927
  """
928
+ assert self.accessory is not None # noqa: S101
827
929
  chars = []
828
930
  for aid_iid in char_ids:
829
931
  aid, iid = (int(i) for i in aid_iid.split("."))
@@ -838,13 +940,23 @@ class AccessoryDriver:
838
940
  char = self.accessory.iid_manager.get_obj(iid)
839
941
  available = self.accessory.available
840
942
  else:
841
- acc = self.accessory.accessories.get(aid)
842
- if acc is None:
843
- continue
844
- available = acc.available
845
- char = acc.iid_manager.get_obj(iid)
846
-
847
- if available:
943
+ # Accessory IIDs other than the standalone one only exist
944
+ # on bridged accessories; anything else is unknown and
945
+ # keeps the per-characteristic failure status.
946
+ bridge = self.accessory
947
+ if isinstance(bridge, Bridge):
948
+ acc = bridge.accessories.get(aid)
949
+ if acc is None:
950
+ continue
951
+ char = acc.iid_manager.get_obj(iid)
952
+ available = acc.available
953
+ else:
954
+ char = None
955
+ available = False
956
+
957
+ # A characteristic IID may resolve to a Service or be unknown;
958
+ # only a Characteristic can report a value.
959
+ if available and isinstance(char, Characteristic):
848
960
  rep[HAP_REPR_VALUE] = char.get_value()
849
961
  rep[HAP_REPR_STATUS] = HAP_SERVER_STATUS.SUCCESS
850
962
  except CharacteristicError:
@@ -853,7 +965,7 @@ class AccessoryDriver:
853
965
  self.accessory.display_name,
854
966
  (aid, iid),
855
967
  )
856
- except Exception: # pylint: disable=broad-except
968
+ except Exception:
857
969
  logger.exception(
858
970
  "%s: Unexpected error getting value for characteristic %s.",
859
971
  self.accessory.display_name,
@@ -864,7 +976,26 @@ class AccessoryDriver:
864
976
  logger.debug("Get chars response: %s", chars)
865
977
  return {HAP_REPR_CHARS: chars}
866
978
 
867
- def set_characteristics(self, chars_query, client_addr):
979
+ def derive_session_key(
980
+ self, client_addr: tuple[str, int] | None, salt: bytes, info: bytes
981
+ ) -> bytes | None:
982
+ """Derive a key from the pair-verify session key of ``client_addr``.
983
+
984
+ For transports set up from the HAP session, e.g. HomeKit Data Stream.
985
+ Never returns the session key itself, see
986
+ :meth:`HAPServerProtocol.derive_key`. Returns ``None`` when the
987
+ connection is unknown or not encrypted.
988
+ """
989
+ if client_addr is None:
990
+ return None
991
+ connection = self.http_server.connections.get(client_addr)
992
+ if connection is None:
993
+ return None
994
+ return connection.derive_key(salt, info)
995
+
996
+ def set_characteristics(
997
+ self, chars_query: dict[str, Any], client_addr: tuple[str, int]
998
+ ) -> dict[str, Any] | None:
868
999
  """Called from ``HAPServerHandler`` when iOS configures the characteristics.
869
1000
 
870
1001
  :param chars_query: A configuration query. For example:
@@ -885,17 +1016,17 @@ class AccessoryDriver:
885
1016
  """
886
1017
  # TODO: Add support for chars that do no support notifications.
887
1018
 
888
- queries: List[Dict[str, Any]] = chars_query[HAP_REPR_CHARS]
1019
+ queries: list[dict[str, Any]] = chars_query[HAP_REPR_CHARS]
889
1020
 
890
1021
  self._notify(queries, client_addr)
891
1022
 
892
- updates_by_accessories_services: Dict[
893
- Accessory, Dict[Service, Dict[Characteristic, Any]]
1023
+ updates_by_accessories_services: dict[
1024
+ Accessory, dict[Service, dict[Characteristic, Any]]
894
1025
  ] = defaultdict(lambda: defaultdict(dict))
895
- results: Dict[int, Dict[int, Dict[str, Any]]] = defaultdict(
1026
+ results: dict[int, dict[int, dict[str, Any]]] = defaultdict(
896
1027
  lambda: defaultdict(dict)
897
1028
  )
898
- char_to_iid: Dict[Characteristic, int] = {}
1029
+ char_to_iid: dict[Characteristic, int] = {}
899
1030
 
900
1031
  expired = False
901
1032
  if HAP_REPR_PID in chars_query:
@@ -904,6 +1035,7 @@ class AccessoryDriver:
904
1035
  expired = expire_time is None or time.time() > expire_time
905
1036
 
906
1037
  primary_accessory = self.accessory
1038
+ assert primary_accessory is not None # noqa: S101
907
1039
  primary_aid = primary_accessory.aid
908
1040
 
909
1041
  for query in queries:
@@ -918,8 +1050,17 @@ class AccessoryDriver:
918
1050
  if aid == primary_aid:
919
1051
  acc = primary_accessory
920
1052
  else:
921
- acc = self.accessory.accessories.get(aid)
1053
+ # Accessory IIDs other than the primary one only exist on
1054
+ # bridged accessories.
1055
+ bridge = self.accessory
1056
+ if not isinstance(bridge, Bridge):
1057
+ continue
1058
+ acc = bridge.accessories.get(aid)
1059
+ if acc is None:
1060
+ continue
922
1061
  char = acc.get_characteristic(aid, iid)
1062
+ if char is None:
1063
+ continue
923
1064
 
924
1065
  set_result = HAP_SERVER_STATUS.INVALID_VALUE_IN_REQUEST
925
1066
  set_result_value = None
@@ -937,11 +1078,13 @@ class AccessoryDriver:
937
1078
  results[aid][iid] = result
938
1079
  char_to_iid[char] = iid
939
1080
  service = char.service
1081
+ assert service is not None # noqa: S101
940
1082
  updates_by_accessories_services[acc][service][char] = value
941
1083
 
942
1084
  # Proccess accessory and service level setter callbacks
943
1085
  for acc, updates_by_service in updates_by_accessories_services.items():
944
1086
  aid = acc.aid
1087
+ assert aid is not None # noqa: S101
945
1088
  aid_results = results[aid]
946
1089
 
947
1090
  # Accessory level setter callbacks
@@ -977,7 +1120,9 @@ class AccessoryDriver:
977
1120
 
978
1121
  return {HAP_REPR_CHARS: characteristics} if nonempty_results_exist else None
979
1122
 
980
- def prepare(self, prepare_query, client_addr):
1123
+ def prepare(
1124
+ self, prepare_query: dict[str, Any], client_addr: tuple[str, int]
1125
+ ) -> dict[str, int]:
981
1126
  """Called from ``HAPServerHandler`` when iOS wants to prepare a write.
982
1127
 
983
1128
  :param prepare_query: A prepare query. For example:
@@ -994,15 +1139,26 @@ class AccessoryDriver:
994
1139
  try:
995
1140
  ttl = prepare_query[HAP_REPR_TTL]
996
1141
  pid = prepare_query[HAP_REPR_PID]
997
- self.prepared_writes.setdefault(client_addr, {})[pid] = time.time() + (
998
- ttl / 1000
999
- )
1000
- except (KeyError, ValueError):
1142
+ now = time.time()
1143
+ pending = self.prepared_writes.setdefault(client_addr, {})
1144
+ # Prune expired entries and cap the number of pending writes so a
1145
+ # paired client cannot grow prepared_writes without bound by
1146
+ # registering endless unique pids with arbitrary TTLs.
1147
+ for stale_pid in [
1148
+ prepared_pid
1149
+ for prepared_pid, expires_at in pending.items()
1150
+ if expires_at <= now
1151
+ ]:
1152
+ del pending[stale_pid]
1153
+ if len(pending) >= MAX_PREPARED_WRITES_PER_CLIENT:
1154
+ del pending[min(pending, key=pending.get)]
1155
+ pending[pid] = now + min(ttl / 1000, MAX_PREPARED_WRITE_TTL_SECONDS)
1156
+ except (KeyError, TypeError, ValueError):
1001
1157
  return {HAP_REPR_STATUS: HAP_SERVER_STATUS.INVALID_VALUE_IN_REQUEST}
1002
1158
 
1003
1159
  return {HAP_REPR_STATUS: HAP_SERVER_STATUS.SUCCESS}
1004
1160
 
1005
- def signal_handler(self, _signal, _frame):
1161
+ def signal_handler(self, _signal: Any, _frame: Any) -> None:
1006
1162
  """Stops the AccessoryDriver for a given signal.
1007
1163
 
1008
1164
  An AccessoryDriver can be registered as a signal handler with this method. For
@@ -1010,8 +1166,8 @@ class AccessoryDriver:
1010
1166
  >>> import signal
1011
1167
  >>> signal.signal(signal.SIGINT, anAccDriver.signal_handler)
1012
1168
 
1013
- Now, when the user hits Ctrl+C, the driver will stop its accessory, the HAP server
1014
- and everything else that needs stopping and will exit gracefully.
1169
+ Now, when the user hits Ctrl+C, the driver will stop its accessory, the
1170
+ HAP server and everything else that needs stopping and will exit gracefully.
1015
1171
  """
1016
1172
  try:
1017
1173
  self.stop()
@@ -1020,7 +1176,7 @@ class AccessoryDriver:
1020
1176
  raise
1021
1177
 
1022
1178
  def _notify(
1023
- self, queries: List[Dict[str, Any]], client_addr: Tuple[str, int]
1179
+ self, queries: list[dict[str, Any]], client_addr: tuple[str, int]
1024
1180
  ) -> None:
1025
1181
  """Notify the driver that the client has subscribed or unsubscribed."""
1026
1182
  for query in queries: