dbus-fast 2.45.1__cp311-cp311-macosx_11_0_arm64.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.

Potentially problematic release.


This version of dbus-fast might be problematic. Click here for more details.

Files changed (51) hide show
  1. dbus_fast/__init__.py +82 -0
  2. dbus_fast/__version__.py +10 -0
  3. dbus_fast/_private/__init__.py +1 -0
  4. dbus_fast/_private/_cython_compat.py +14 -0
  5. dbus_fast/_private/address.cpython-311-darwin.so +0 -0
  6. dbus_fast/_private/address.pxd +15 -0
  7. dbus_fast/_private/address.py +117 -0
  8. dbus_fast/_private/constants.py +20 -0
  9. dbus_fast/_private/marshaller.cpython-311-darwin.so +0 -0
  10. dbus_fast/_private/marshaller.pxd +110 -0
  11. dbus_fast/_private/marshaller.py +228 -0
  12. dbus_fast/_private/unmarshaller.cpython-311-darwin.so +0 -0
  13. dbus_fast/_private/unmarshaller.pxd +261 -0
  14. dbus_fast/_private/unmarshaller.py +902 -0
  15. dbus_fast/_private/util.py +176 -0
  16. dbus_fast/aio/__init__.py +5 -0
  17. dbus_fast/aio/message_bus.py +578 -0
  18. dbus_fast/aio/message_reader.cpython-311-darwin.so +0 -0
  19. dbus_fast/aio/message_reader.pxd +13 -0
  20. dbus_fast/aio/message_reader.py +49 -0
  21. dbus_fast/aio/proxy_object.py +207 -0
  22. dbus_fast/auth.py +126 -0
  23. dbus_fast/constants.py +152 -0
  24. dbus_fast/errors.py +84 -0
  25. dbus_fast/glib/__init__.py +3 -0
  26. dbus_fast/glib/message_bus.py +515 -0
  27. dbus_fast/glib/proxy_object.py +319 -0
  28. dbus_fast/introspection.py +683 -0
  29. dbus_fast/message.cpython-311-darwin.so +0 -0
  30. dbus_fast/message.pxd +76 -0
  31. dbus_fast/message.py +387 -0
  32. dbus_fast/message_bus.cpython-311-darwin.so +0 -0
  33. dbus_fast/message_bus.pxd +75 -0
  34. dbus_fast/message_bus.py +1310 -0
  35. dbus_fast/proxy_object.py +358 -0
  36. dbus_fast/py.typed +0 -0
  37. dbus_fast/send_reply.py +61 -0
  38. dbus_fast/service.cpython-311-darwin.so +0 -0
  39. dbus_fast/service.pxd +50 -0
  40. dbus_fast/service.py +686 -0
  41. dbus_fast/signature.cpython-311-darwin.so +0 -0
  42. dbus_fast/signature.pxd +31 -0
  43. dbus_fast/signature.py +481 -0
  44. dbus_fast/unpack.cpython-311-darwin.so +0 -0
  45. dbus_fast/unpack.pxd +13 -0
  46. dbus_fast/unpack.py +24 -0
  47. dbus_fast/validators.py +199 -0
  48. dbus_fast-2.45.1.dist-info/METADATA +263 -0
  49. dbus_fast-2.45.1.dist-info/RECORD +51 -0
  50. dbus_fast-2.45.1.dist-info/WHEEL +6 -0
  51. dbus_fast-2.45.1.dist-info/licenses/LICENSE +22 -0
@@ -0,0 +1,1310 @@
1
+ from __future__ import annotations
2
+
3
+ import inspect
4
+ import logging
5
+ import socket
6
+ import traceback
7
+ import xml.etree.ElementTree as ET
8
+ from functools import partial
9
+ from typing import TYPE_CHECKING, Any, Callable
10
+
11
+ from . import introspection as intr
12
+ from ._private.address import get_bus_address, parse_address
13
+ from ._private.util import replace_fds_with_idx, replace_idx_with_fds
14
+ from .constants import (
15
+ BusType,
16
+ ErrorType,
17
+ MessageFlag,
18
+ MessageType,
19
+ NameFlag,
20
+ ReleaseNameReply,
21
+ RequestNameReply,
22
+ )
23
+ from .errors import DBusError, InvalidAddressError
24
+ from .message import Message
25
+ from .proxy_object import BaseProxyObject
26
+ from .send_reply import SendReply
27
+ from .service import HandlerType, ServiceInterface, _Method, _Property
28
+ from .signature import Variant
29
+ from .validators import assert_bus_name_valid, assert_object_path_valid
30
+
31
+ MESSAGE_TYPE_CALL = MessageType.METHOD_CALL
32
+ MESSAGE_TYPE_SIGNAL = MessageType.SIGNAL
33
+ NO_REPLY_EXPECTED_VALUE = MessageFlag.NO_REPLY_EXPECTED.value
34
+ NO_REPLY_EXPECTED = MessageFlag.NO_REPLY_EXPECTED
35
+ NONE = MessageFlag.NONE
36
+ _LOGGER = logging.getLogger(__name__)
37
+
38
+
39
+ _Message = Message
40
+
41
+
42
+ def _expects_reply(msg: _Message) -> bool:
43
+ """Whether a message expects a reply."""
44
+ if msg.flags is NO_REPLY_EXPECTED:
45
+ return False
46
+ if msg.flags is NONE:
47
+ return True
48
+ # Slow check for NO_REPLY_EXPECTED
49
+ flag_value = msg.flags.value
50
+ return not (flag_value & NO_REPLY_EXPECTED_VALUE)
51
+
52
+
53
+ def _block_unexpected_reply(reply: _Message) -> None:
54
+ """Block a reply if it's not expected.
55
+
56
+ Previously we silently ignored replies that were not expected, but this
57
+ lead to implementation errors that were hard to debug. Now we log a
58
+ debug message instead.
59
+ """
60
+ _LOGGER.debug(
61
+ "Blocked attempt to send a reply from handler "
62
+ "that received a message with flag "
63
+ "MessageFlag.NO_REPLY_EXPECTED: %s",
64
+ reply,
65
+ )
66
+
67
+
68
+ BLOCK_UNEXPECTED_REPLY = _block_unexpected_reply
69
+
70
+
71
+ class BaseMessageBus:
72
+ """An abstract class to manage a connection to a DBus message bus.
73
+
74
+ The message bus class is the entry point into all the features of the
75
+ library. It sets up a connection to the DBus daemon and exposes an
76
+ interface to send and receive messages and expose services.
77
+
78
+ This class is not meant to be used directly by users. For more information,
79
+ see the documentation for the implementation of the message bus you plan to
80
+ use.
81
+
82
+ :param bus_type: The type of bus to connect to. Affects the search path for
83
+ the bus address.
84
+ :type bus_type: :class:`BusType <dbus_fast.BusType>`
85
+ :param bus_address: A specific bus address to connect to. Should not be
86
+ used under normal circumstances.
87
+ :type bus_address: str
88
+ :param ProxyObject: The proxy object implementation for this message bus.
89
+ Must be passed in by an implementation that supports the high-level client.
90
+ :type ProxyObject: Type[:class:`BaseProxyObject
91
+ <dbus_fast.proxy_object.BaseProxyObject>`]
92
+
93
+ :ivar unique_name: The unique name of the message bus connection. It will
94
+ be :class:`None` until the message bus connects.
95
+ :vartype unique_name: str
96
+ :ivar connected: True if this message bus is expected to be able to send
97
+ and receive messages.
98
+ :vartype connected: bool
99
+ """
100
+
101
+ __slots__ = (
102
+ "_ProxyObject",
103
+ "_bus_address",
104
+ "_disconnected",
105
+ "_fd",
106
+ "_high_level_client_initialized",
107
+ "_machine_id",
108
+ "_match_rules",
109
+ "_method_return_handlers",
110
+ "_name_owner_match_rule",
111
+ "_name_owners",
112
+ "_negotiate_unix_fd",
113
+ "_path_exports",
114
+ "_serial",
115
+ "_sock",
116
+ "_stream",
117
+ "_user_disconnect",
118
+ "_user_message_handlers",
119
+ "unique_name",
120
+ )
121
+
122
+ def __init__(
123
+ self,
124
+ bus_address: str | None = None,
125
+ bus_type: BusType = BusType.SESSION,
126
+ ProxyObject: type[BaseProxyObject] | None = None,
127
+ negotiate_unix_fd: bool = False,
128
+ ) -> None:
129
+ self.unique_name: str | None = None
130
+ self._disconnected = False
131
+ self._negotiate_unix_fd = negotiate_unix_fd
132
+
133
+ # True if the user disconnected himself, so don't throw errors out of
134
+ # the main loop.
135
+ self._user_disconnect = False
136
+
137
+ self._method_return_handlers: dict[
138
+ int, Callable[[Message | None, Exception | None], None]
139
+ ] = {}
140
+ self._serial = 0
141
+ self._user_message_handlers: list[
142
+ Callable[[Message], Message | bool | None]
143
+ ] = []
144
+ # the key is the name and the value is the unique name of the owner.
145
+ # This cache is kept up to date by the NameOwnerChanged signal and is
146
+ # used to route messages to the correct proxy object. (used for the
147
+ # high level client only)
148
+ self._name_owners: dict[str, str] = {}
149
+ # used for the high level service
150
+ self._path_exports: dict[str, dict[str, ServiceInterface]] = {}
151
+ self._bus_address = (
152
+ parse_address(bus_address)
153
+ if bus_address
154
+ else parse_address(get_bus_address(bus_type))
155
+ )
156
+ # the bus implementations need this rule for the high level client to
157
+ # work correctly.
158
+ self._name_owner_match_rule = "sender='org.freedesktop.DBus',interface='org.freedesktop.DBus',path='/org/freedesktop/DBus',member='NameOwnerChanged'"
159
+ # _match_rules: the keys are match rules and the values are ref counts
160
+ # (used for the high level client only)
161
+ self._match_rules: dict[str, int] = {}
162
+ self._high_level_client_initialized = False
163
+ self._ProxyObject = ProxyObject
164
+
165
+ # machine id is lazy loaded
166
+ self._machine_id: int | None = None
167
+ self._sock: socket.socket | None = None
168
+ self._fd: int | None = None
169
+ self._stream: Any | None = None
170
+
171
+ self._setup_socket()
172
+
173
+ @property
174
+ def connected(self) -> bool:
175
+ if self.unique_name is None or self._disconnected or self._user_disconnect:
176
+ return False
177
+ return True
178
+
179
+ def export(self, path: str, interface: ServiceInterface) -> None:
180
+ """Export the service interface on this message bus to make it available
181
+ to other clients.
182
+
183
+ :param path: The object path to export this interface on.
184
+ :type path: str
185
+ :param interface: The service interface to export.
186
+ :type interface: :class:`ServiceInterface
187
+ <dbus_fast.service.ServiceInterface>`
188
+
189
+ :raises:
190
+ - :class:`InvalidObjectPathError <dbus_fast.InvalidObjectPathError>` - If the given object path is not valid.
191
+ - :class:`ValueError` - If an interface with this name is already exported on the message bus at this path
192
+ """
193
+ assert_object_path_valid(path)
194
+ if not isinstance(interface, ServiceInterface):
195
+ raise TypeError("interface must be a ServiceInterface")
196
+
197
+ if path not in self._path_exports:
198
+ self._path_exports[path] = {}
199
+ elif interface.name in self._path_exports[path]:
200
+ raise ValueError(
201
+ f'An interface with this name is already exported on this bus at path "{path}": "{interface.name}"'
202
+ )
203
+
204
+ self._path_exports[path][interface.name] = interface
205
+ ServiceInterface._add_bus(interface, self, self._make_method_handler)
206
+ self._emit_interface_added(path, interface)
207
+
208
+ def unexport(
209
+ self, path: str, interface: ServiceInterface | str | None = None
210
+ ) -> None:
211
+ """Unexport the path or service interface to make it no longer
212
+ available to clients.
213
+
214
+ :param path: The object path to unexport.
215
+ :type path: str
216
+ :param interface: The interface instance or the name of the interface
217
+ to unexport. If ``None``, unexport every interface on the path.
218
+ :type interface: :class:`ServiceInterface
219
+ <dbus_fast.service.ServiceInterface>` or str or None
220
+
221
+ :raises:
222
+ - :class:`InvalidObjectPathError <dbus_fast.InvalidObjectPathError>` - If the given object path is not valid.
223
+ """
224
+ assert_object_path_valid(path)
225
+ interface_name: str | None
226
+ if interface is None:
227
+ interface_name = None
228
+ elif type(interface) is str:
229
+ interface_name = interface
230
+ elif isinstance(interface, ServiceInterface):
231
+ interface_name = interface.name
232
+ else:
233
+ raise TypeError(
234
+ f"interface must be a ServiceInterface or interface name not {type(interface)}"
235
+ )
236
+
237
+ if (interfaces := self._path_exports.get(path)) is None:
238
+ return
239
+ removed_interface_names: list[str] = []
240
+
241
+ if interface_name is not None:
242
+ if (removed_interface := interfaces.pop(interface_name, None)) is None:
243
+ return
244
+ removed_interface_names.append(interface_name)
245
+ if not interfaces:
246
+ del self._path_exports[path]
247
+ ServiceInterface._remove_bus(removed_interface, self)
248
+ else:
249
+ del self._path_exports[path]
250
+ for removed_interface in interfaces.values():
251
+ removed_interface_names.append(removed_interface.name)
252
+ ServiceInterface._remove_bus(removed_interface, self)
253
+
254
+ self._emit_interface_removed(path, removed_interface_names)
255
+
256
+ def introspect(
257
+ self,
258
+ bus_name: str,
259
+ path: str,
260
+ callback: Callable[[intr.Node | None, Exception | None], None],
261
+ check_callback_type: bool = True,
262
+ validate_property_names: bool = True,
263
+ ) -> None:
264
+ """Get introspection data for the node at the given path from the given
265
+ bus name.
266
+
267
+ Calls the standard ``org.freedesktop.DBus.Introspectable.Introspect``
268
+ on the bus for the path.
269
+
270
+ :param bus_name: The name to introspect.
271
+ :type bus_name: str
272
+ :param path: The path to introspect.
273
+ :type path: str
274
+ :param callback: A callback that will be called with the introspection
275
+ data as a :class:`Node <dbus_fast.introspection.Node>`.
276
+ :type callback: :class:`Callable`
277
+ :param check_callback_type: Whether to check callback type or not.
278
+ :type check_callback_type: bool
279
+ :param validate_property_names: Whether to validate property names or not.
280
+ :type validate_property_names: bool
281
+
282
+ :raises:
283
+ - :class:`InvalidObjectPathError <dbus_fast.InvalidObjectPathError>` - If the given object path is not valid.
284
+ - :class:`InvalidBusNameError <dbus_fast.InvalidBusNameError>` - If the given bus name is not valid.
285
+ """
286
+ if check_callback_type:
287
+ BaseMessageBus._check_callback_type(callback)
288
+
289
+ def reply_notify(reply: Message | None, err: Exception | None) -> None:
290
+ try:
291
+ BaseMessageBus._check_method_return(reply, err, "s")
292
+ result = intr.Node.parse(
293
+ reply.body[0], # type: ignore[union-attr]
294
+ validate_property_names=validate_property_names,
295
+ )
296
+ except Exception as e:
297
+ callback(None, e)
298
+ return
299
+
300
+ callback(result, None)
301
+
302
+ self._call(
303
+ Message(
304
+ destination=bus_name,
305
+ path=path,
306
+ interface="org.freedesktop.DBus.Introspectable",
307
+ member="Introspect",
308
+ ),
309
+ reply_notify,
310
+ )
311
+
312
+ def _emit_interface_added(self, path: str, interface: ServiceInterface) -> None:
313
+ """Emit the ``org.freedesktop.DBus.ObjectManager.InterfacesAdded`` signal.
314
+
315
+ This signal is intended to be used to alert clients when
316
+ a new interface has been added.
317
+
318
+ :param path: Path of exported object.
319
+ :type path: str
320
+ :param interface: Exported service interface.
321
+ :type interface: :class:`ServiceInterface
322
+ <dbus_fast.service.ServiceInterface>`
323
+ """
324
+ if self._disconnected:
325
+ return
326
+
327
+ def get_properties_callback(
328
+ interface: ServiceInterface,
329
+ result: Any,
330
+ user_data: Any,
331
+ e: Exception | None,
332
+ ) -> None:
333
+ if e is not None:
334
+ try:
335
+ raise e
336
+ except Exception:
337
+ _LOGGER.error(
338
+ "An exception ocurred when emitting ObjectManager.InterfacesAdded for %s. "
339
+ "Some properties will not be included in the signal.",
340
+ interface.name,
341
+ exc_info=True,
342
+ )
343
+
344
+ body = {interface.name: result}
345
+
346
+ self.send(
347
+ Message.new_signal(
348
+ path=path,
349
+ interface="org.freedesktop.DBus.ObjectManager",
350
+ member="InterfacesAdded",
351
+ signature="oa{sa{sv}}",
352
+ body=[path, body],
353
+ )
354
+ )
355
+
356
+ ServiceInterface._get_all_property_values(interface, get_properties_callback)
357
+
358
+ def _emit_interface_removed(self, path: str, removed_interfaces: list[str]) -> None:
359
+ """Emit the ``org.freedesktop.DBus.ObjectManager.InterfacesRemoved` signal.
360
+
361
+ This signal is intended to be used to alert clients when
362
+ a interface has been removed.
363
+
364
+ :param path: Path of removed (unexported) object.
365
+ :type path: str
366
+ :param removed_interfaces: List of unexported service interfaces.
367
+ :type removed_interfaces: list[str]
368
+ """
369
+ if self._disconnected:
370
+ return
371
+
372
+ self.send(
373
+ Message.new_signal(
374
+ path=path,
375
+ interface="org.freedesktop.DBus.ObjectManager",
376
+ member="InterfacesRemoved",
377
+ signature="oas",
378
+ body=[path, removed_interfaces],
379
+ )
380
+ )
381
+
382
+ def request_name(
383
+ self,
384
+ name: str,
385
+ flags: NameFlag = NameFlag.NONE,
386
+ callback: None
387
+ | (Callable[[RequestNameReply | None, Exception | None], None]) = None,
388
+ check_callback_type: bool = True,
389
+ ) -> None:
390
+ """Request that this message bus owns the given name.
391
+
392
+ :param name: The name to request.
393
+ :type name: str
394
+ :param flags: Name flags that affect the behavior of the name request.
395
+ :type flags: :class:`NameFlag <dbus_fast.NameFlag>`
396
+ :param callback: A callback that will be called with the reply of the
397
+ request as a :class:`RequestNameReply <dbus_fast.RequestNameReply>`.
398
+ :type callback: :class:`Callable`
399
+
400
+ :raises:
401
+ - :class:`InvalidBusNameError <dbus_fast.InvalidBusNameError>` - If the given bus name is not valid.
402
+ """
403
+ assert_bus_name_valid(name)
404
+
405
+ if callback is not None and check_callback_type:
406
+ BaseMessageBus._check_callback_type(callback)
407
+
408
+ if type(flags) is not NameFlag:
409
+ flags = NameFlag(flags)
410
+
411
+ message = Message(
412
+ destination="org.freedesktop.DBus",
413
+ path="/org/freedesktop/DBus",
414
+ interface="org.freedesktop.DBus",
415
+ member="RequestName",
416
+ signature="su",
417
+ body=[name, flags],
418
+ )
419
+
420
+ if callback is None:
421
+ self._call(message, None)
422
+ return
423
+
424
+ def reply_notify(reply: Message | None, err: Exception | None) -> None:
425
+ try:
426
+ BaseMessageBus._check_method_return(reply, err, "u")
427
+ result = RequestNameReply(reply.body[0]) # type: ignore[union-attr]
428
+ except Exception as e:
429
+ callback(None, e)
430
+ return
431
+
432
+ callback(result, None)
433
+
434
+ self._call(message, reply_notify)
435
+
436
+ def release_name(
437
+ self,
438
+ name: str,
439
+ callback: None
440
+ | (Callable[[ReleaseNameReply | None, Exception | None], None]) = None,
441
+ check_callback_type: bool = True,
442
+ ) -> None:
443
+ """Request that this message bus release the given name.
444
+
445
+ :param name: The name to release.
446
+ :type name: str
447
+ :param callback: A callback that will be called with the reply of the
448
+ release request as a :class:`ReleaseNameReply
449
+ <dbus_fast.ReleaseNameReply>`.
450
+ :type callback: :class:`Callable`
451
+
452
+ :raises:
453
+ - :class:`InvalidBusNameError <dbus_fast.InvalidBusNameError>` - If the given bus name is not valid.
454
+ """
455
+ assert_bus_name_valid(name)
456
+
457
+ if callback is not None and check_callback_type:
458
+ BaseMessageBus._check_callback_type(callback)
459
+
460
+ message = Message(
461
+ destination="org.freedesktop.DBus",
462
+ path="/org/freedesktop/DBus",
463
+ interface="org.freedesktop.DBus",
464
+ member="ReleaseName",
465
+ signature="s",
466
+ body=[name],
467
+ )
468
+
469
+ if callback is None:
470
+ self._call(message, None)
471
+ return
472
+
473
+ def reply_notify(reply: Message | None, err: Exception | None) -> None:
474
+ try:
475
+ BaseMessageBus._check_method_return(reply, err, "u")
476
+ result = ReleaseNameReply(reply.body[0]) # type: ignore[union-attr]
477
+ except Exception as e:
478
+ callback(None, e)
479
+ return
480
+
481
+ callback(result, None)
482
+
483
+ self._call(message, reply_notify)
484
+
485
+ def get_proxy_object(
486
+ self, bus_name: str, path: str, introspection: intr.Node | str | ET.Element
487
+ ) -> BaseProxyObject:
488
+ """Get a proxy object for the path exported on the bus that owns the
489
+ name. The object is expected to export the interfaces and nodes
490
+ specified in the introspection data.
491
+
492
+ This is the entry point into the high-level client.
493
+
494
+ :param bus_name: The name on the bus to get the proxy object for.
495
+ :type bus_name: str
496
+ :param path: The path on the client for the proxy object.
497
+ :type path: str
498
+ :param introspection: XML introspection data used to build the
499
+ interfaces on the proxy object.
500
+ :type introspection: :class:`Node <dbus_fast.introspection.Node>` or str or :class:`ElementTree`
501
+
502
+ :returns: A proxy object for the given path on the given name.
503
+ :rtype: :class:`BaseProxyObject <dbus_fast.proxy_object.BaseProxyObject>`
504
+
505
+ :raises:
506
+ - :class:`InvalidBusNameError <dbus_fast.InvalidBusNameError>` - If the given bus name is not valid.
507
+ - :class:`InvalidObjectPathError <dbus_fast.InvalidObjectPathError>` - If the given object path is not valid.
508
+ - :class:`InvalidIntrospectionError <dbus_fast.InvalidIntrospectionError>` - If the introspection data for the node is not valid.
509
+ """
510
+ if self._ProxyObject is None:
511
+ raise Exception(
512
+ "the message bus implementation did not provide a proxy object class"
513
+ )
514
+
515
+ self._init_high_level_client()
516
+
517
+ return self._ProxyObject(bus_name, path, introspection, self)
518
+
519
+ def disconnect(self) -> None:
520
+ """Disconnect the message bus by closing the underlying connection asynchronously.
521
+
522
+ All pending and future calls will error with a connection error.
523
+ """
524
+ self._user_disconnect = True
525
+ if self._sock:
526
+ try:
527
+ self._sock.shutdown(socket.SHUT_RDWR)
528
+ except Exception:
529
+ _LOGGER.warning("could not shut down socket", exc_info=True)
530
+
531
+ def next_serial(self) -> int:
532
+ """Get the next serial for this bus. This can be used as the ``serial``
533
+ attribute of a :class:`Message <dbus_fast.Message>` to manually handle
534
+ the serial of messages.
535
+
536
+ :returns: The next serial for the bus.
537
+ :rtype: int
538
+ """
539
+ self._serial += 1
540
+ return self._serial
541
+
542
+ def add_message_handler(
543
+ self, handler: Callable[[Message], Message | bool | None]
544
+ ) -> None:
545
+ """Add a custom message handler for incoming messages.
546
+
547
+ The handler should be a callable that takes a :class:`Message
548
+ <dbus_fast.Message>`. If the message is a method call, you may return
549
+ another Message as a reply and it will be marked as handled. You may
550
+ also return ``True`` to mark the message as handled without sending a
551
+ reply.
552
+
553
+ :param handler: A handler that will be run for every message the bus
554
+ connection received.
555
+ :type handler: :class:`Callable` or None
556
+ """
557
+ error_text = "a message handler must be callable with a single parameter"
558
+ if not callable(handler):
559
+ raise TypeError(error_text)
560
+
561
+ handler_signature = inspect.signature(handler)
562
+ if len(handler_signature.parameters) != 1:
563
+ raise TypeError(error_text)
564
+
565
+ self._user_message_handlers.append(handler)
566
+
567
+ def remove_message_handler(
568
+ self, handler: Callable[[Message], Message | bool | None]
569
+ ) -> None:
570
+ """Remove a message handler that was previously added by
571
+ :func:`add_message_handler()
572
+ <dbus_fast.message_bus.BaseMessageBus.add_message_handler>`.
573
+
574
+ :param handler: A message handler.
575
+ :type handler: :class:`Callable`
576
+ """
577
+ for i, h in enumerate(self._user_message_handlers):
578
+ if h == handler:
579
+ del self._user_message_handlers[i]
580
+ return
581
+
582
+ def send(self, msg: Message) -> None:
583
+ """Asynchronously send a message on the message bus.
584
+
585
+ :param msg: The message to send.
586
+ :type msg: :class:`Message <dbus_fast.Message>`
587
+ """
588
+ raise NotImplementedError(
589
+ 'the "send" method must be implemented in the inheriting class'
590
+ )
591
+
592
+ def _finalize(self, err: Exception | None) -> None:
593
+ """should be called after the socket disconnects with the disconnection
594
+ error to clean up resources and put the bus in a disconnected state"""
595
+ if self._disconnected:
596
+ return
597
+
598
+ self._disconnected = True
599
+
600
+ for handler in self._method_return_handlers.values():
601
+ try:
602
+ handler(None, err)
603
+ except Exception:
604
+ _LOGGER.warning(
605
+ "a message handler threw an exception on shutdown", exc_info=True
606
+ )
607
+
608
+ self._method_return_handlers.clear()
609
+
610
+ for path in list(self._path_exports):
611
+ self.unexport(path)
612
+
613
+ self._user_message_handlers.clear()
614
+
615
+ def _interface_signal_notify(
616
+ self,
617
+ interface: ServiceInterface,
618
+ interface_name: str,
619
+ member: str,
620
+ signature: str,
621
+ body: list[Any],
622
+ unix_fds: list[int] = [],
623
+ ) -> None:
624
+ path: str | None = None
625
+ for p, ifaces in self._path_exports.items():
626
+ for i in ifaces.values():
627
+ if i is interface:
628
+ path = p
629
+
630
+ if path is None:
631
+ raise Exception(
632
+ "Could not find interface on bus (this is a bug in dbus-fast)"
633
+ )
634
+
635
+ self.send(
636
+ Message.new_signal(
637
+ path=path,
638
+ interface=interface_name,
639
+ member=member,
640
+ signature=signature,
641
+ body=body,
642
+ unix_fds=unix_fds,
643
+ )
644
+ )
645
+
646
+ def _introspect_export_path(self, path: str) -> intr.Node:
647
+ assert_object_path_valid(path)
648
+
649
+ if (interfaces := self._path_exports.get(path)) is not None:
650
+ node = intr.Node.default(path)
651
+ for interface in interfaces.values():
652
+ node.interfaces.append(interface.introspect())
653
+ else:
654
+ node = intr.Node(path)
655
+
656
+ children = set()
657
+
658
+ for export_path in self._path_exports:
659
+ if not export_path.startswith(path):
660
+ continue
661
+
662
+ child_path = export_path.split(path, maxsplit=1)[1]
663
+ if path != "/" and child_path and child_path[0] != "/":
664
+ continue
665
+
666
+ child_path = child_path.lstrip("/")
667
+ child_name = child_path.split("/", maxsplit=1)[0]
668
+
669
+ children.add(child_name)
670
+
671
+ node.nodes = [intr.Node(name) for name in children if name]
672
+
673
+ return node
674
+
675
+ def _setup_socket(self) -> None:
676
+ err = None
677
+
678
+ for transport, options in self._bus_address:
679
+ filename: bytes | str | None = None
680
+ ip_addr = ""
681
+ ip_port = 0
682
+
683
+ if transport == "unix":
684
+ self._sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
685
+ self._stream = self._sock.makefile("rwb")
686
+ self._fd = self._sock.fileno()
687
+
688
+ if "path" in options:
689
+ filename = options["path"]
690
+ elif "abstract" in options:
691
+ filename = b"\0" + options["abstract"].encode()
692
+ else:
693
+ raise InvalidAddressError(
694
+ "got unix transport with unknown path specifier"
695
+ )
696
+
697
+ try:
698
+ self._sock.connect(filename)
699
+ self._sock.setblocking(False)
700
+ break
701
+ except Exception as e:
702
+ err = e
703
+
704
+ elif transport == "tcp":
705
+ self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
706
+ self._stream = self._sock.makefile("rwb")
707
+ self._fd = self._sock.fileno()
708
+
709
+ if "host" in options:
710
+ ip_addr = options["host"]
711
+ if "port" in options:
712
+ ip_port = int(options["port"])
713
+
714
+ try:
715
+ self._sock.connect((ip_addr, ip_port))
716
+ self._sock.setblocking(False)
717
+ break
718
+ except Exception as e:
719
+ err = e
720
+
721
+ else:
722
+ raise InvalidAddressError(f"got unknown address transport: {transport}")
723
+
724
+ if err:
725
+ raise err
726
+
727
+ def _reply_notify(
728
+ self,
729
+ msg: Message,
730
+ callback: Callable[[Message | None, Exception | None], None],
731
+ reply: Message | None,
732
+ err: Exception | None,
733
+ ) -> None:
734
+ """Callback on reply."""
735
+ if reply and msg.destination and reply.sender:
736
+ self._name_owners[msg.destination] = reply.sender
737
+ callback(reply, err)
738
+
739
+ def _call(
740
+ self,
741
+ msg: Message,
742
+ callback: Callable[[Message | None, Exception | None], None] | None,
743
+ ) -> None:
744
+ if not msg.serial:
745
+ msg.serial = self.next_serial()
746
+
747
+ # Make sure the return reply handler is installed
748
+ # before sending the message to avoid a race condition
749
+ # where the reply is lost in case the backend can
750
+ # send it right away.
751
+ if (reply_expected := _expects_reply(msg)) and callback is not None:
752
+ self._method_return_handlers[msg.serial] = partial(
753
+ self._reply_notify, msg, callback
754
+ )
755
+
756
+ self.send(msg)
757
+
758
+ if not reply_expected and callback is not None:
759
+ callback(None, None)
760
+
761
+ @staticmethod
762
+ def _check_callback_type(callback: Callable) -> None:
763
+ """Raise a TypeError if the user gives an invalid callback as a parameter"""
764
+
765
+ text = "a callback must be callable with two parameters"
766
+
767
+ if not callable(callback):
768
+ raise TypeError(text)
769
+
770
+ fn_signature = inspect.signature(callback)
771
+ if len(fn_signature.parameters) != 2:
772
+ raise TypeError(text)
773
+
774
+ @staticmethod
775
+ def _check_method_return(
776
+ msg: Message | None, err: Exception | None, signature: str
777
+ ) -> None:
778
+ if err:
779
+ raise err
780
+ if msg is None:
781
+ raise DBusError(
782
+ ErrorType.INTERNAL_ERROR, "invalid message type for method call", msg
783
+ )
784
+ if msg.message_type == MessageType.METHOD_RETURN and msg.signature == signature:
785
+ return
786
+ if msg.message_type == MessageType.ERROR:
787
+ raise DBusError._from_message(msg)
788
+ raise DBusError(
789
+ ErrorType.INTERNAL_ERROR, "invalid message type for method call", msg
790
+ )
791
+
792
+ def _process_message(self, msg: _Message) -> None:
793
+ """Process a message received from the message bus."""
794
+ handled = False
795
+ for user_handler in self._user_message_handlers:
796
+ try:
797
+ if result := user_handler(msg):
798
+ if type(result) is Message:
799
+ self.send(result)
800
+ handled = True
801
+ break
802
+ except DBusError as e:
803
+ if msg.message_type is MESSAGE_TYPE_CALL:
804
+ self.send(e._as_message(msg))
805
+ handled = True
806
+ break
807
+ _LOGGER.exception("A message handler raised an exception: %s", e)
808
+ except Exception as e:
809
+ _LOGGER.exception("A message handler raised an exception: %s", e)
810
+ if msg.message_type is MESSAGE_TYPE_CALL:
811
+ self.send(
812
+ Message.new_error(
813
+ msg,
814
+ ErrorType.INTERNAL_ERROR,
815
+ f"An internal error occurred: {e}.\n{traceback.format_exc()}",
816
+ )
817
+ )
818
+ handled = True
819
+ break
820
+
821
+ if msg.message_type is MESSAGE_TYPE_SIGNAL:
822
+ if (
823
+ msg.member == "NameOwnerChanged"
824
+ and msg.sender == "org.freedesktop.DBus"
825
+ and msg.path == "/org/freedesktop/DBus"
826
+ and msg.interface == "org.freedesktop.DBus"
827
+ ):
828
+ name = msg.body[0]
829
+ if new_owner := msg.body[2]:
830
+ self._name_owners[name] = new_owner
831
+ elif name in self._name_owners:
832
+ del self._name_owners[name]
833
+ return
834
+
835
+ if msg.message_type is MESSAGE_TYPE_CALL:
836
+ if not handled:
837
+ handler = self._find_message_handler(msg)
838
+ if not _expects_reply(msg):
839
+ if handler:
840
+ handler(msg, BLOCK_UNEXPECTED_REPLY) # type: ignore[arg-type]
841
+ else:
842
+ _LOGGER.error(
843
+ '"%s.%s" with signature "%s" could not be found',
844
+ msg.interface,
845
+ msg.member,
846
+ msg.signature,
847
+ )
848
+ return
849
+
850
+ send_reply = SendReply(self, msg)
851
+ with send_reply:
852
+ if handler:
853
+ handler(msg, send_reply)
854
+ else:
855
+ send_reply(
856
+ Message.new_error(
857
+ msg,
858
+ ErrorType.UNKNOWN_METHOD,
859
+ f"{msg.interface}.{msg.member} with signature "
860
+ f'"{msg.signature}" could not be found',
861
+ )
862
+ )
863
+ return
864
+
865
+ # An ERROR or a METHOD_RETURN
866
+ return_handler = self._method_return_handlers.get(msg.reply_serial)
867
+ if return_handler is not None:
868
+ if not handled:
869
+ return_handler(msg, None)
870
+ del self._method_return_handlers[msg.reply_serial]
871
+
872
+ def _callback_method_handler(
873
+ self,
874
+ interface: ServiceInterface,
875
+ method: _Method,
876
+ msg: Message,
877
+ send_reply: SendReply,
878
+ ) -> None:
879
+ """This is the callback that will be called when a method call is."""
880
+ args = ServiceInterface._c_msg_body_to_args(msg) if msg.unix_fds else msg.body
881
+ result = method.fn(interface, *args)
882
+ if send_reply is BLOCK_UNEXPECTED_REPLY or _expects_reply(msg) is False:
883
+ return
884
+ body_fds = ServiceInterface._c_fn_result_to_body(
885
+ result,
886
+ method.out_signature_tree,
887
+ self._negotiate_unix_fd,
888
+ )
889
+ send_reply(
890
+ Message(
891
+ message_type=MessageType.METHOD_RETURN,
892
+ reply_serial=msg.serial,
893
+ destination=msg.sender,
894
+ signature=method.out_signature,
895
+ body=body_fds[0],
896
+ unix_fds=body_fds[1],
897
+ )
898
+ )
899
+
900
+ def _make_method_handler(
901
+ self, interface: ServiceInterface, method: _Method
902
+ ) -> HandlerType:
903
+ return partial(self._callback_method_handler, interface, method)
904
+
905
+ def _find_message_handler(self, msg: _Message) -> HandlerType | None:
906
+ """Find the message handler for for METHOD_CALL messages."""
907
+ if TYPE_CHECKING:
908
+ assert msg.member is not None
909
+ assert msg.path is not None
910
+
911
+ if msg.interface is not None and "org.freedesktop.DBus." in msg.interface:
912
+ if (
913
+ msg.interface == "org.freedesktop.DBus.Introspectable"
914
+ and msg.member == "Introspect"
915
+ and msg.signature == ""
916
+ ):
917
+ return self._default_introspect_handler
918
+
919
+ if msg.interface == "org.freedesktop.DBus.Properties":
920
+ return self._default_properties_handler
921
+
922
+ if msg.interface == "org.freedesktop.DBus.Peer":
923
+ if msg.member == "Ping" and msg.signature == "":
924
+ return self._default_ping_handler
925
+ if msg.member == "GetMachineId" and msg.signature == "":
926
+ return self._default_get_machine_id_handler
927
+
928
+ if (
929
+ msg.interface == "org.freedesktop.DBus.ObjectManager"
930
+ and msg.member == "GetManagedObjects"
931
+ ):
932
+ return self._default_get_managed_objects_handler
933
+
934
+ if (interfaces := self._path_exports.get(msg.path)) is None:
935
+ return None
936
+
937
+ if msg.interface is None:
938
+ return self._find_any_message_handler_matching_signature(interfaces, msg)
939
+
940
+ if (interface := interfaces.get(msg.interface)) is not None and (
941
+ handler := ServiceInterface._get_enabled_handler_by_name_signature(
942
+ interface, self, msg.member, msg.signature
943
+ )
944
+ ) is not None:
945
+ return handler
946
+
947
+ return None
948
+
949
+ def _find_any_message_handler_matching_signature(
950
+ self, interfaces: dict[str, ServiceInterface], msg: _Message
951
+ ) -> HandlerType | None:
952
+ # No interface, so we need to search all interfaces for the method
953
+ # with a matching signature
954
+ for interface in interfaces.values():
955
+ if (
956
+ handler := ServiceInterface._get_enabled_handler_by_name_signature(
957
+ interface, self, msg.member, msg.signature
958
+ )
959
+ ) is not None:
960
+ return handler
961
+ return None
962
+
963
+ def _default_introspect_handler(self, msg: Message, send_reply: SendReply) -> None:
964
+ if TYPE_CHECKING:
965
+ assert msg.path is not None
966
+ introspection = self._introspect_export_path(msg.path).tostring()
967
+ send_reply(Message.new_method_return(msg, "s", [introspection]))
968
+
969
+ def _default_ping_handler(self, msg: Message, send_reply: SendReply) -> None:
970
+ send_reply(Message.new_method_return(msg))
971
+
972
+ def _send_machine_id_reply(self, msg: Message, send_reply: SendReply) -> None:
973
+ send_reply(Message.new_method_return(msg, "s", [self._machine_id]))
974
+
975
+ def _default_get_machine_id_handler(
976
+ self, msg: Message, send_reply: SendReply
977
+ ) -> None:
978
+ if self._machine_id:
979
+ self._send_machine_id_reply(msg, send_reply)
980
+ return
981
+
982
+ def reply_handler(reply: Message | None, err: Exception | None) -> None:
983
+ if err or reply is None:
984
+ # the bus has been disconnected, cannot send a reply
985
+ return
986
+
987
+ if reply.message_type == MessageType.METHOD_RETURN:
988
+ self._machine_id = reply.body[0]
989
+ self._send_machine_id_reply(msg, send_reply)
990
+ elif (
991
+ reply.message_type == MessageType.ERROR and reply.error_name is not None
992
+ ):
993
+ send_reply(Message.new_error(msg, reply.error_name, str(reply.body)))
994
+ else:
995
+ send_reply(
996
+ Message.new_error(msg, ErrorType.FAILED, "could not get machine_id")
997
+ )
998
+
999
+ self._call(
1000
+ Message(
1001
+ destination="org.freedesktop.DBus",
1002
+ path="/org/freedesktop/DBus",
1003
+ interface="org.freedesktop.DBus.Peer",
1004
+ member="GetMachineId",
1005
+ ),
1006
+ reply_handler,
1007
+ )
1008
+
1009
+ def _default_get_managed_objects_handler(
1010
+ self, msg: Message, send_reply: SendReply
1011
+ ) -> None:
1012
+ result_signature = "a{oa{sa{sv}}}"
1013
+ error_handled = False
1014
+
1015
+ def is_result_complete() -> bool:
1016
+ if not result:
1017
+ return True
1018
+ for n, interfaces in result.items():
1019
+ for value in interfaces.values():
1020
+ if value is None:
1021
+ return False
1022
+
1023
+ return True
1024
+
1025
+ if TYPE_CHECKING:
1026
+ assert msg.path is not None
1027
+
1028
+ nodes = [
1029
+ node
1030
+ for node in self._path_exports
1031
+ if msg.path == "/" or node.startswith(msg.path + "/")
1032
+ ]
1033
+
1034
+ # first build up the result object to know when it's complete
1035
+ result: dict[str, dict[str, Any]] = {
1036
+ node: dict.fromkeys(self._path_exports[node]) for node in nodes
1037
+ }
1038
+
1039
+ if is_result_complete():
1040
+ send_reply(Message.new_method_return(msg, result_signature, [result]))
1041
+ return
1042
+
1043
+ def get_all_properties_callback(
1044
+ interface: ServiceInterface, values: Any, node: str, err: Exception | None
1045
+ ) -> None:
1046
+ nonlocal error_handled
1047
+ if err is not None:
1048
+ if not error_handled:
1049
+ error_handled = True
1050
+ send_reply.send_error(err)
1051
+ return
1052
+
1053
+ result[node][interface.name] = values
1054
+
1055
+ if is_result_complete():
1056
+ send_reply(Message.new_method_return(msg, result_signature, [result]))
1057
+
1058
+ for node in nodes:
1059
+ for interface in self._path_exports[node].values():
1060
+ ServiceInterface._get_all_property_values(
1061
+ interface, get_all_properties_callback, node
1062
+ )
1063
+
1064
+ def _default_properties_handler(self, msg: Message, send_reply: SendReply) -> None:
1065
+ methods = {"Get": "ss", "Set": "ssv", "GetAll": "s"}
1066
+ if msg.member not in methods or methods[msg.member] != msg.signature:
1067
+ raise DBusError(
1068
+ ErrorType.UNKNOWN_METHOD,
1069
+ f'properties interface doesn\'t have method "{msg.member}" with signature "{msg.signature}"',
1070
+ )
1071
+
1072
+ interface_name = msg.body[0]
1073
+ if interface_name == "":
1074
+ raise DBusError(
1075
+ ErrorType.NOT_SUPPORTED,
1076
+ "getting and setting properties with an empty interface string is not supported yet",
1077
+ )
1078
+
1079
+ if msg.path not in self._path_exports:
1080
+ raise DBusError(
1081
+ ErrorType.UNKNOWN_OBJECT, f'no interfaces at path: "{msg.path}"'
1082
+ )
1083
+
1084
+ if (interface := self._path_exports[msg.path].get(interface_name)) is None:
1085
+ if interface_name in [
1086
+ "org.freedesktop.DBus.Properties",
1087
+ "org.freedesktop.DBus.Introspectable",
1088
+ "org.freedesktop.DBus.Peer",
1089
+ "org.freedesktop.DBus.ObjectManager",
1090
+ ]:
1091
+ # the standard interfaces do not have properties
1092
+ if msg.member == "Get" or msg.member == "Set":
1093
+ prop_name = msg.body[1]
1094
+ raise DBusError(
1095
+ ErrorType.UNKNOWN_PROPERTY,
1096
+ f'interface "{interface_name}" does not have property "{prop_name}"',
1097
+ )
1098
+ if msg.member == "GetAll":
1099
+ send_reply(Message.new_method_return(msg, "a{sv}", [{}]))
1100
+ return
1101
+ assert False
1102
+ raise DBusError(
1103
+ ErrorType.UNKNOWN_INTERFACE,
1104
+ f'could not find an interface "{interface_name}" at path: "{msg.path}"',
1105
+ )
1106
+
1107
+ properties = ServiceInterface._get_properties(interface)
1108
+
1109
+ if msg.member == "Get" or msg.member == "Set":
1110
+ prop_name = msg.body[1]
1111
+ match = [
1112
+ prop
1113
+ for prop in properties
1114
+ if prop.name == prop_name and not prop.disabled
1115
+ ]
1116
+ if not match:
1117
+ raise DBusError(
1118
+ ErrorType.UNKNOWN_PROPERTY,
1119
+ f'interface "{interface_name}" does not have property "{prop_name}"',
1120
+ )
1121
+
1122
+ prop = match[0]
1123
+ if msg.member == "Get":
1124
+ if not prop.access.readable():
1125
+ raise DBusError(
1126
+ ErrorType.UNKNOWN_PROPERTY,
1127
+ "the property does not have read access",
1128
+ )
1129
+
1130
+ def get_property_callback(
1131
+ interface: ServiceInterface,
1132
+ prop: _Property,
1133
+ prop_value: Any,
1134
+ err: Exception | None,
1135
+ ) -> None:
1136
+ try:
1137
+ if err is not None:
1138
+ send_reply.send_error(err)
1139
+ return
1140
+
1141
+ body, unix_fds = replace_fds_with_idx(
1142
+ prop.signature, [prop_value]
1143
+ )
1144
+
1145
+ send_reply(
1146
+ Message.new_method_return(
1147
+ msg,
1148
+ "v",
1149
+ [Variant(prop.signature, body[0])],
1150
+ unix_fds=unix_fds,
1151
+ )
1152
+ )
1153
+ except Exception as e:
1154
+ send_reply.send_error(e)
1155
+
1156
+ ServiceInterface._get_property_value(
1157
+ interface, prop, get_property_callback
1158
+ )
1159
+
1160
+ elif msg.member == "Set":
1161
+ if not prop.access.writable():
1162
+ raise DBusError(
1163
+ ErrorType.PROPERTY_READ_ONLY, "the property is readonly"
1164
+ )
1165
+ value = msg.body[2]
1166
+ if value.signature != prop.signature:
1167
+ raise DBusError(
1168
+ ErrorType.INVALID_SIGNATURE,
1169
+ f'wrong signature for property. expected "{prop.signature}"',
1170
+ )
1171
+ assert prop.prop_setter
1172
+
1173
+ def set_property_callback(
1174
+ interface: ServiceInterface, prop: _Property, err: Exception | None
1175
+ ) -> None:
1176
+ if err is not None:
1177
+ send_reply.send_error(err)
1178
+ return
1179
+ send_reply(Message.new_method_return(msg))
1180
+
1181
+ body = replace_idx_with_fds(
1182
+ value.signature, [value.value], msg.unix_fds
1183
+ )
1184
+ ServiceInterface._set_property_value(
1185
+ interface, prop, body[0], set_property_callback
1186
+ )
1187
+
1188
+ elif msg.member == "GetAll":
1189
+
1190
+ def get_all_properties_callback(
1191
+ interface: ServiceInterface,
1192
+ values: Any,
1193
+ user_data: Any,
1194
+ err: Exception | None,
1195
+ ) -> None:
1196
+ if err is not None:
1197
+ send_reply.send_error(err)
1198
+ return
1199
+ body, unix_fds = replace_fds_with_idx("a{sv}", [values])
1200
+ send_reply(
1201
+ Message.new_method_return(msg, "a{sv}", body, unix_fds=unix_fds)
1202
+ )
1203
+
1204
+ ServiceInterface._get_all_property_values(
1205
+ interface, get_all_properties_callback
1206
+ )
1207
+
1208
+ else:
1209
+ assert False
1210
+
1211
+ def _init_high_level_client(self) -> None:
1212
+ """The high level client is initialized when the first proxy object is
1213
+ gotten. Currently just sets up the match rules for the name owner cache
1214
+ so signals can be routed to the right objects."""
1215
+ if self._high_level_client_initialized:
1216
+ return
1217
+ self._high_level_client_initialized = True
1218
+
1219
+ def add_match_notify(msg: Message | None, err: Exception | None) -> None:
1220
+ if err:
1221
+ _LOGGER.error(
1222
+ f'add match request failed. match="{self._name_owner_match_rule}", {err}'
1223
+ )
1224
+ elif msg is not None and msg.message_type == MessageType.ERROR:
1225
+ _LOGGER.error(
1226
+ f'add match request failed. match="{self._name_owner_match_rule}", {msg.body[0]}'
1227
+ )
1228
+
1229
+ self._call(
1230
+ Message(
1231
+ destination="org.freedesktop.DBus",
1232
+ interface="org.freedesktop.DBus",
1233
+ path="/org/freedesktop/DBus",
1234
+ member="AddMatch",
1235
+ signature="s",
1236
+ body=[self._name_owner_match_rule],
1237
+ ),
1238
+ add_match_notify,
1239
+ )
1240
+
1241
+ def _add_match_rule(self, match_rule: str) -> None:
1242
+ """Add a match rule. Match rules added by this function are refcounted
1243
+ and must be removed by _remove_match_rule(). This is for use in the
1244
+ high level client only."""
1245
+ if match_rule == self._name_owner_match_rule:
1246
+ return
1247
+
1248
+ if match_rule in self._match_rules:
1249
+ self._match_rules[match_rule] += 1
1250
+ return
1251
+
1252
+ self._match_rules[match_rule] = 1
1253
+
1254
+ def add_match_notify(msg: Message | None, err: Exception | None) -> None:
1255
+ if err:
1256
+ _LOGGER.error(f'add match request failed. match="{match_rule}", {err}')
1257
+ elif msg is not None and msg.message_type == MessageType.ERROR:
1258
+ _LOGGER.error(
1259
+ f'add match request failed. match="{match_rule}", {msg.body[0]}'
1260
+ )
1261
+
1262
+ self._call(
1263
+ Message(
1264
+ destination="org.freedesktop.DBus",
1265
+ interface="org.freedesktop.DBus",
1266
+ path="/org/freedesktop/DBus",
1267
+ member="AddMatch",
1268
+ signature="s",
1269
+ body=[match_rule],
1270
+ ),
1271
+ add_match_notify,
1272
+ )
1273
+
1274
+ def _remove_match_rule(self, match_rule: str) -> None:
1275
+ """Remove a match rule added with _add_match_rule(). This is for use in
1276
+ the high level client only."""
1277
+ if match_rule == self._name_owner_match_rule:
1278
+ return
1279
+
1280
+ if match_rule in self._match_rules:
1281
+ self._match_rules[match_rule] -= 1
1282
+ if self._match_rules[match_rule] > 0:
1283
+ return
1284
+
1285
+ del self._match_rules[match_rule]
1286
+
1287
+ def remove_match_notify(msg: Message | None, err: Exception | None) -> None:
1288
+ if self._disconnected:
1289
+ return
1290
+
1291
+ if err:
1292
+ _LOGGER.error(
1293
+ f'remove match request failed. match="{match_rule}", {err}'
1294
+ )
1295
+ elif msg is not None and msg.message_type == MessageType.ERROR:
1296
+ _LOGGER.error(
1297
+ f'remove match request failed. match="{match_rule}", {msg.body[0]}'
1298
+ )
1299
+
1300
+ self._call(
1301
+ Message(
1302
+ destination="org.freedesktop.DBus",
1303
+ interface="org.freedesktop.DBus",
1304
+ path="/org/freedesktop/DBus",
1305
+ member="RemoveMatch",
1306
+ signature="s",
1307
+ body=[match_rule],
1308
+ ),
1309
+ remove_match_notify,
1310
+ )