Gio.DBusConnection¶
class — extends GObject.Object, AsyncInitable, Initable
The GDBusConnection type is used for D-Bus connections to remote
peers such as a message buses.
It is a low-level API that offers a lot of flexibility. For instance,
it lets you establish a connection over any transport that can by represented
as a IOStream.
This class is rarely used directly in D-Bus clients. If you are writing
a D-Bus client, it is often easier to use the bus_own_name,
bus_watch_name or DBusProxy.new_for_bus APIs.
As an exception to the usual GLib rule that a particular object must not
be used by two threads at the same time, GDBusConnections methods may be
called from any thread. This is so that bus_get and
bus_get_sync can safely return the same GDBusConnection when
called from any thread.
Most of the ways to obtain a GDBusConnection automatically initialize it
(i.e. connect to D-Bus): for instance, DBusConnection.new and
bus_get, and the synchronous versions of those methods, give you
an initialized connection. Language bindings for GIO should use
Initable.new or AsyncInitable.new_async, which also
initialize the connection.
If you construct an uninitialized GDBusConnection, such as via
GObject.Object.new, you must initialize it via Initable.init or
AsyncInitable.init_async before using its methods or properties.
Calling methods or accessing properties on a GDBusConnection that has not
completed initialization successfully is considered to be invalid, and leads
to undefined behaviour. In particular, if initialization fails with a
GError, the only valid thing you can do with that GDBusConnection is to
free it with GObject.Object.unref.
An example D-Bus server¶
Here is an example for a D-Bus server: gdbus-example-server.c
An example for exporting a subtree¶
Here is an example for exporting a subtree: gdbus-example-subtree.c
An example for file descriptor passing¶
Here is an example for passing UNIX file descriptors: gdbus-unix-fd-client.c
An example for exporting a GObject¶
Here is an example for exporting a GObject.Object:
gdbus-example-export.c
Constructors¶
new_finish¶
Finishes an operation started with DBusConnection.new.
Parameters:
res— aAsyncResultobtained from theGAsyncReadyCallbackpassed toDBusConnection.new.
new_for_address_finish¶
Finishes an operation started with DBusConnection.new_for_address.
Parameters:
res— aAsyncResultobtained from theGAsyncReadyCallbackpassed toDBusConnection.new
new_for_address_sync¶
@classmethod
def new_for_address_sync(cls, address: str, flags: DBusConnectionFlags | int, observer: DBusAuthObserver | None = ..., cancellable: Cancellable | None = ...) -> DBusConnection
Synchronously connects and sets up a D-Bus client connection for
exchanging D-Bus messages with an endpoint specified by address
which must be in the
D-Bus address format.
This constructor can only be used to initiate client-side
connections - use DBusConnection.new_sync if you need to act
as the server. In particular, flags cannot contain the
DBusConnectionFlags.AUTHENTICATION_SERVER,
DBusConnectionFlags.AUTHENTICATION_ALLOW_ANONYMOUS or
DBusConnectionFlags.AUTHENTICATION_REQUIRE_SAME_USER flags.
This is a synchronous failable constructor. See
DBusConnection.new_for_address for the asynchronous version.
If observer is not None it may be used to control the
authentication process.
Parameters:
address— a D-Bus addressflags— flags describing how to make the connectionobserver— aDBusAuthObserverorNonecancellable— aCancellableorNone
new_sync¶
@classmethod
def new_sync(cls, stream: IOStream, guid: str | None, flags: DBusConnectionFlags | int, observer: DBusAuthObserver | None = ..., cancellable: Cancellable | None = ...) -> DBusConnection
Synchronously sets up a D-Bus connection for exchanging D-Bus messages
with the end represented by stream.
If stream is a SocketConnection, then the corresponding Socket
will be put into non-blocking mode.
The D-Bus connection will interact with stream from a worker thread.
As a result, the caller should not interact with stream after this
method has been called, except by calling GObject.Object.unref on it.
If observer is not None it may be used to control the
authentication process.
This is a synchronous failable constructor. See
DBusConnection.new for the asynchronous version.
Parameters:
stream— aIOStreamguid— the GUID to use if authenticating as a server orNoneflags— flags describing how to make the connectionobserver— aDBusAuthObserverorNonecancellable— aCancellableorNone
Methods¶
add_filter¶
Adds a message filter. Filters are handlers that are run on all incoming and outgoing messages, prior to standard dispatch. Filters are run in the order that they were added. The same handler can be added as a filter more than once, in which case it will be run more than once. Filters added during a filter callback won't be run on the message being processed. Filter functions are allowed to modify and even drop messages.
Note that filters are run in a dedicated message handling thread so
they can't block and, generally, can't do anything but signal a
worker thread. Also note that filters are rarely needed - use API
such as DBusConnection.send_message_with_reply,
DBusConnection.signal_subscribe or DBusConnection.call instead.
If a filter consumes an incoming message the message is not
dispatched anywhere else - not even the standard dispatch machinery
(that API such as DBusConnection.signal_subscribe and
DBusConnection.send_message_with_reply relies on) will see the
message. Similarly, if a filter consumes an outgoing message, the
message will not be sent to the other peer.
If user_data_free_func is non-None, it will be called (in the
thread-default main context of the thread you are calling this
method from) at some point after user_data is no longer
needed. (It is not guaranteed to be called synchronously when the
filter is removed, and may be called after connection has been
destroyed.)
Parameters:
filter_function— a filter function
call¶
def call(self, bus_name: str | None, object_path: str, interface_name: str, method_name: str, parameters: GLib.Variant | None, reply_type: GLib.VariantType | None, flags: DBusCallFlags | int, timeout_msec: int, cancellable: Cancellable | None = ..., callback: Callable[[DBusConnection | None, AsyncResult], None] | None = ...) -> None
Asynchronously invokes the method_name method on the
interface_name D-Bus interface on the remote object at
object_path owned by bus_name.
If connection is closed then the operation will fail with
IOErrorEnum.CLOSED. If cancellable is canceled, the operation will
fail with IOErrorEnum.CANCELLED. If parameters contains a value
not compatible with the D-Bus protocol, the operation fails with
IOErrorEnum.INVALID_ARGUMENT.
If reply_type is non-None then the reply will be checked for having this type and an
error will be raised if it does not match. Said another way, if you give a reply_type
then any non-None return value will be of this type. Unless it’s
G_VARIANT_TYPE_UNIT, the reply_type will be a tuple containing one or more
values.
If the parameters GLib.Variant is floating, it is consumed. This allows
convenient 'inline' use of g_variant_new(), e.g.:
g_dbus_connection_call (connection,
"org.freedesktop.StringThings",
"/org/freedesktop/StringThings",
"org.freedesktop.StringThings",
"TwoStrings",
g_variant_new ("(ss)",
"Thing One",
"Thing Two"),
NULL,
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
(GAsyncReadyCallback) two_strings_done,
NULL);
This is an asynchronous method. When the operation is finished,
callback will be invoked in the thread-default main context
(see GLib.MainContext.push_thread_default)
of the thread you are calling this method from. You can then call
DBusConnection.call_finish to get the result of the operation.
See DBusConnection.call_sync for the synchronous version of this
function.
If callback is None then the D-Bus method call message will be sent with
the DBusMessageFlags.NO_REPLY_EXPECTED flag set.
Parameters:
bus_name— a unique or well-known bus name orNoneifconnectionis not a message bus connectionobject_path— path of remote objectinterface_name— D-Bus interface to invoke method onmethod_name— the name of the method to invokeparameters— aGLib.Varianttuple with parameters for the method orNoneif not passing parametersreply_type— the expected type of the reply (which will be a tuple), orNoneflags— flags from theDBusCallFlagsenumerationtimeout_msec— the timeout in milliseconds, -1 to use the default timeout orG_MAXINTfor no timeoutcancellable— aCancellableorNonecallback— aGAsyncReadyCallbackto call when the request is satisfied orNoneif you don't care about the result of the method invocation
call_finish¶
Finishes an operation started with DBusConnection.call.
Parameters:
res— aAsyncResultobtained from theGAsyncReadyCallbackpassed toDBusConnection.call
call_sync¶
def call_sync(self, bus_name: str | None, object_path: str, interface_name: str, method_name: str, parameters: GLib.Variant | None, reply_type: GLib.VariantType | None, flags: DBusCallFlags | int, timeout_msec: int, cancellable: Cancellable | None = ...) -> GLib.Variant
Synchronously invokes the method_name method on the
interface_name D-Bus interface on the remote object at
object_path owned by bus_name.
If connection is closed then the operation will fail with
IOErrorEnum.CLOSED. If cancellable is canceled, the
operation will fail with IOErrorEnum.CANCELLED. If parameters
contains a value not compatible with the D-Bus protocol, the operation
fails with IOErrorEnum.INVALID_ARGUMENT.
If reply_type is non-None then the reply will be checked for having
this type and an error will be raised if it does not match. Said
another way, if you give a reply_type then any non-None return
value will be of this type.
If the parameters GLib.Variant is floating, it is consumed.
This allows convenient 'inline' use of g_variant_new(), e.g.:
g_dbus_connection_call_sync (connection,
"org.freedesktop.StringThings",
"/org/freedesktop/StringThings",
"org.freedesktop.StringThings",
"TwoStrings",
g_variant_new ("(ss)",
"Thing One",
"Thing Two"),
NULL,
G_DBUS_CALL_FLAGS_NONE,
-1,
NULL,
&error);
The calling thread is blocked until a reply is received. See
DBusConnection.call for the asynchronous version of
this method.
Parameters:
bus_name— a unique or well-known bus name orNoneifconnectionis not a message bus connectionobject_path— path of remote objectinterface_name— D-Bus interface to invoke method onmethod_name— the name of the method to invokeparameters— aGLib.Varianttuple with parameters for the method orNoneif not passing parametersreply_type— the expected type of the reply, orNoneflags— flags from theDBusCallFlagsenumerationtimeout_msec— the timeout in milliseconds, -1 to use the default timeout orG_MAXINTfor no timeoutcancellable— aCancellableorNone
call_with_unix_fd_list¶
def call_with_unix_fd_list(self, bus_name: str | None, object_path: str, interface_name: str, method_name: str, parameters: GLib.Variant | None, reply_type: GLib.VariantType | None, flags: DBusCallFlags | int, timeout_msec: int, fd_list: UnixFDList | None = ..., cancellable: Cancellable | None = ..., callback: Callable[[DBusConnection | None, AsyncResult], None] | None = ...) -> None
Like DBusConnection.call but also takes a UnixFDList object.
The file descriptors normally correspond to G_VARIANT_TYPE_HANDLE
values in the body of the message. For example, if a message contains
two file descriptors, fd_list would have length 2, and
g_variant_new_handle (0) and g_variant_new_handle (1) would appear
somewhere in the body of the message (not necessarily in that order!)
to represent the file descriptors at indexes 0 and 1 respectively.
When designing D-Bus APIs that are intended to be interoperable,
please note that non-GDBus implementations of D-Bus can usually only
access file descriptors if they are referenced in this way by a
value of type G_VARIANT_TYPE_HANDLE in the body of the message.
This method is only available on UNIX.
Parameters:
bus_name— a unique or well-known bus name orNoneifconnectionis not a message bus connectionobject_path— path of remote objectinterface_name— D-Bus interface to invoke method onmethod_name— the name of the method to invokeparameters— aGLib.Varianttuple with parameters for the method orNoneif not passing parametersreply_type— the expected type of the reply, orNoneflags— flags from theDBusCallFlagsenumerationtimeout_msec— the timeout in milliseconds, -1 to use the default timeout orG_MAXINTfor no timeoutfd_list— aUnixFDListorNonecancellable— aCancellableorNonecallback— aGAsyncReadyCallbackto call when the request is satisfied orNoneif you don't * care about the result of the method invocation
call_with_unix_fd_list_finish¶
Finishes an operation started with DBusConnection.call_with_unix_fd_list.
The file descriptors normally correspond to G_VARIANT_TYPE_HANDLE
values in the body of the message. For example,
if GLib.Variant.get_handle returns 5, that is intended to be a reference
to the file descriptor that can be accessed by
g_unix_fd_list_get (*out_fd_list, 5, ...).
When designing D-Bus APIs that are intended to be interoperable,
please note that non-GDBus implementations of D-Bus can usually only
access file descriptors if they are referenced in this way by a
value of type G_VARIANT_TYPE_HANDLE in the body of the message.
Parameters:
res— aAsyncResultobtained from theGAsyncReadyCallbackpassed toDBusConnection.call_with_unix_fd_list
call_with_unix_fd_list_sync¶
def call_with_unix_fd_list_sync(self, bus_name: str | None, object_path: str, interface_name: str, method_name: str, parameters: GLib.Variant | None, reply_type: GLib.VariantType | None, flags: DBusCallFlags | int, timeout_msec: int, fd_list: UnixFDList | None = ..., cancellable: Cancellable | None = ...) -> tuple[GLib.Variant, UnixFDList]
Like DBusConnection.call_sync but also takes and returns UnixFDList objects.
See DBusConnection.call_with_unix_fd_list and
DBusConnection.call_with_unix_fd_list_finish for more details.
This method is only available on UNIX.
Parameters:
bus_name— a unique or well-known bus name orNoneifconnectionis not a message bus connectionobject_path— path of remote objectinterface_name— D-Bus interface to invoke method onmethod_name— the name of the method to invokeparameters— aGLib.Varianttuple with parameters for the method orNoneif not passing parametersreply_type— the expected type of the reply, orNoneflags— flags from theDBusCallFlagsenumerationtimeout_msec— the timeout in milliseconds, -1 to use the default timeout orG_MAXINTfor no timeoutfd_list— aUnixFDListorNonecancellable— aCancellableorNone
close¶
def close(self, cancellable: Cancellable | None = ..., callback: Callable[[DBusConnection | None, AsyncResult], None] | None = ...) -> None
Closes connection. Note that this never causes the process to
exit (this might only happen if the other end of a shared message
bus connection disconnects, see DBusConnection:exit-on-close).
Once the connection is closed, operations such as sending a message
will return with the error IOErrorEnum.CLOSED. Closing a connection
will not automatically flush the connection so queued messages may
be lost. Use DBusConnection.flush if you need such guarantees.
If connection is already closed, this method fails with
IOErrorEnum.CLOSED.
When connection has been closed, the DBusConnection::closed
signal is emitted in the thread-default main context
(see GLib.MainContext.push_thread_default)
of the thread that connection was constructed in.
This is an asynchronous method. When the operation is finished,
callback will be invoked in the thread-default main context
(see GLib.MainContext.push_thread_default)
of the thread you are calling this method from. You can
then call DBusConnection.close_finish to get the result of the
operation. See DBusConnection.close_sync for the synchronous
version.
Parameters:
cancellable— aCancellableorNonecallback— aGAsyncReadyCallbackto call when the request is satisfied orNoneif you don't care about the result
close_finish¶
Finishes an operation started with DBusConnection.close.
Parameters:
res— aAsyncResultobtained from theGAsyncReadyCallbackpassed toDBusConnection.close
close_sync¶
Synchronously closes connection. The calling thread is blocked
until this is done. See DBusConnection.close for the
asynchronous version of this method and more details about what it
does.
Parameters:
cancellable— aCancellableorNone
emit_signal¶
def emit_signal(self, destination_bus_name: str | None, object_path: str, interface_name: str, signal_name: str, parameters: GLib.Variant | None = ...) -> bool
Emits a signal.
If the parameters GVariant is floating, it is consumed.
This can only fail if parameters is not compatible with the D-Bus protocol
(IOErrorEnum.INVALID_ARGUMENT), or if connection has been closed
(IOErrorEnum.CLOSED).
Parameters:
destination_bus_name— the unique bus name for the destination for the signal orNoneto emit to all listenersobject_path— path of remote objectinterface_name— D-Bus interface to emit a signal onsignal_name— the name of the signal to emitparameters— aGLib.Varianttuple with parameters for the signal orNoneif not passing parameters
export_action_group¶
Exports action_group on connection at object_path.
The implemented D-Bus API should be considered private. It is subject to change in the future.
A given object path can only have one action group exported on it.
If this constraint is violated, the export will fail and 0 will be
returned (with error set accordingly).
You can unexport the action group using
DBusConnection.unexport_action_group with the return value of
this function.
The thread default main context is taken at the time of this call. All incoming action activations and state change requests are reported from this context. Any changes on the action group that cause it to emit signals must also come from this same context. Since incoming action activations and state change requests are rather likely to cause changes on the action group, this effectively limits a given action group to being exported from only one main context.
Parameters:
object_path— a D-Bus object pathaction_group— an action group
export_menu_model¶
Exports menu on connection at object_path.
The implemented D-Bus API should be considered private. It is subject to change in the future.
An object path can only have one menu model exported on it. If this
constraint is violated, the export will fail and 0 will be
returned (with error set accordingly).
Exporting menus with sections containing more than
MENU_EXPORTER_MAX_SECTION_SIZE items is not supported and results in
undefined behavior.
You can unexport the menu model using
DBusConnection.unexport_menu_model with the return value of
this function.
Parameters:
object_path— a D-Bus object pathmenu— aMenuModel
flush¶
def flush(self, cancellable: Cancellable | None = ..., callback: Callable[[DBusConnection | None, AsyncResult], None] | None = ...) -> None
Asynchronously flushes connection, that is, writes all queued
outgoing messages to the transport and then flushes the transport
(using OutputStream.flush_async). This is useful in programs
that want to emit a D-Bus signal and then exit immediately. Without
flushing the connection, there is no guarantee that the message has
been sent to the networking buffers in the OS kernel.
This is an asynchronous method. When the operation is finished,
callback will be invoked in the thread-default main context
(see GLib.MainContext.push_thread_default)
of the thread you are calling this method from. You can
then call DBusConnection.flush_finish to get the result of the
operation. See DBusConnection.flush_sync for the synchronous
version.
Parameters:
cancellable— aCancellableorNonecallback— aGAsyncReadyCallbackto call when the request is satisfied orNoneif you don't care about the result
flush_finish¶
Finishes an operation started with DBusConnection.flush.
Parameters:
res— aAsyncResultobtained from theGAsyncReadyCallbackpassed toDBusConnection.flush
flush_sync¶
Synchronously flushes connection. The calling thread is blocked
until this is done. See DBusConnection.flush for the
asynchronous version of this method and more details about what it
does.
Parameters:
cancellable— aCancellableorNone
get_capabilities¶
Gets the capabilities negotiated with the remote peer
get_exit_on_close¶
Gets whether the process is terminated when connection is
closed by the remote peer. See
DBusConnection:exit-on-close for more details.
get_flags¶
Gets the flags used to construct this connection
get_guid¶
The GUID of the peer performing the role of server when
authenticating. See DBusConnection:guid for more details.
get_last_serial¶
Retrieves the last serial number assigned to a DBusMessage on
the current thread. This includes messages sent via both low-level
API such as DBusConnection.send_message as well as
high-level API such as DBusConnection.emit_signal,
DBusConnection.call or DBusProxy.call.
get_peer_credentials¶
Gets the credentials of the authenticated peer. This will always
return None unless connection acted as a server
(e.g. DBusConnectionFlags.AUTHENTICATION_SERVER was passed)
when set up and the client passed credentials as part of the
authentication process.
In a message bus setup, the message bus is always the server and
each application is a client. So this method will always return
None for message bus clients.
get_stream¶
Gets the underlying stream used for IO.
While the DBusConnection is active, it will interact with this
stream from a worker thread, so it is not safe to interact with
the stream directly.
get_unique_name¶
Gets the unique name of connection as assigned by the message
bus. This can also be used to figure out if connection is a
message bus connection.
is_closed¶
Gets whether connection is closed.
register_object¶
def register_object(self, object_path: str, interface_info: DBusInterfaceInfo, vtable: DBusInterfaceVTable | None, user_data: int | None, user_data_free_func: GLib.DestroyNotify) -> int
Registers callbacks for exported objects at object_path with the
D-Bus interface that is described in interface_info.
Calls to functions in vtable (and user_data_free_func) will happen
in the thread-default main context
(see GLib.MainContext.push_thread_default)
of the thread you are calling this method from.
Note that all GLib.Variant values passed to functions in vtable will match
the signature given in interface_info - if a remote caller passes
incorrect values, the org.freedesktop.DBus.Error.InvalidArgs
is returned to the remote caller.
Additionally, if the remote caller attempts to invoke methods or
access properties not mentioned in interface_info the
org.freedesktop.DBus.Error.UnknownMethod resp.
org.freedesktop.DBus.Error.InvalidArgs errors
are returned to the caller.
It is considered a programming error if the
GDBusInterfaceGetPropertyFunc function in vtable returns a
GLib.Variant of incorrect type.
If an existing callback is already registered at object_path and
interface_name, then error is set to IOErrorEnum.EXISTS.
GDBus automatically implements the standard D-Bus interfaces org.freedesktop.DBus.Properties, org.freedesktop.DBus.Introspectable and org.freedesktop.Peer, so you don't have to implement those for the objects you export. You can implement org.freedesktop.DBus.Properties yourself, e.g. to handle getting and setting of properties asynchronously.
Note that the reference count on interface_info will be
incremented by 1 (unless allocated statically, e.g. if the
reference count is -1, see DBusInterfaceInfo.ref) for as long
as the object is exported. Also note that vtable will be copied.
See this [server][classGio.DBusConnection#an-example-d-bus-server]
for an example of how to use this method.
Parameters:
object_path— the object path to register atinterface_info— introspection data for the interfacevtable— aDBusInterfaceVTableto call into orNoneuser_data— data to pass to functions invtableuser_data_free_func— function to call when the object path is unregistered
register_object_with_closures¶
def register_object_with_closures(self, object_path: str, interface_info: DBusInterfaceInfo, method_call_closure: GObject.Closure | None = ..., get_property_closure: GObject.Closure | None = ..., set_property_closure: GObject.Closure | None = ...) -> int
:::warning Deprecated since 2.84 This API is deprecated. :::
Version of DBusConnection.register_object using closures instead of a
DBusInterfaceVTable for easier binding in other languages.
Note that the reference counting semantics of the function wrapped by
method_call_closure are the same as those of
DBusInterfaceMethodCallFunc: ownership of a reference to the
DBusMethodInvocation is transferred to the function.
Parameters:
object_path— The object path to register at.interface_info— Introspection data for the interface.method_call_closure—GObject.Closurefor handling incoming method calls.get_property_closure—GObject.Closurefor getting a property.set_property_closure—GObject.Closurefor setting a property.
register_object_with_closures2¶
def register_object_with_closures2(self, object_path: str, interface_info: DBusInterfaceInfo, method_call_closure: GObject.Closure | None = ..., get_property_closure: GObject.Closure | None = ..., set_property_closure: GObject.Closure | None = ...) -> int
Version of DBusConnection.register_object using closures instead
of a DBusInterfaceVTable for easier binding in other languages.
In contrast to DBusConnection.register_object and
DBusConnection.register_object_with_closures, the reference
counting semantics of the function wrapped by method_call_closure are not
the same as those of DBusInterfaceMethodCallFunc. Ownership of
a reference to the DBusMethodInvocation is not transferred to
the function. Bindings must ensure that they add a reference to the
DBusMethodInvocation before calling any
g_dbus_method_invocation_return_*() methods on it. This should be automatic
as a result of the introspection annotations on those methods.
Parameters:
object_path— The object path to register at.interface_info— Introspection data for the interface.method_call_closure—GObject.Closurefor handling incoming method calls.get_property_closure—GObject.Closurefor getting a property.set_property_closure—GObject.Closurefor setting a property.
register_subtree¶
def register_subtree(self, object_path: str, vtable: DBusSubtreeVTable, flags: DBusSubtreeFlags | int, user_data: int | None, user_data_free_func: GLib.DestroyNotify) -> int
Registers a whole subtree of dynamic objects.
The enumerate and introspection functions in vtable are used to
convey, to remote callers, what nodes exist in the subtree rooted
by object_path.
When handling remote calls into any node in the subtree, first the
enumerate function is used to check if the node exists. If the node exists
or the DBusSubtreeFlags.DISPATCH_TO_UNENUMERATED_NODES flag is set
the introspection function is used to check if the node supports the
requested method. If so, the dispatch function is used to determine
where to dispatch the call. The collected DBusInterfaceVTable and
gpointer will be used to call into the interface vtable for processing¶
the request.
All calls into user-provided code will be invoked in the thread-default
main context (see GLib.MainContext.push_thread_default)
of the thread you are calling this method from.
If an existing subtree is already registered at object_path or
then error is set to IOErrorEnum.EXISTS.
Note that it is valid to register regular objects (using
DBusConnection.register_object) in a subtree registered with
DBusConnection.register_subtree - if so, the subtree handler
is tried as the last resort. One way to think about a subtree
handler is to consider it a fallback handler for object paths not
registered via DBusConnection.register_object or other bindings.
Note that vtable will be copied so you cannot change it after
registration.
See this [server][classGio.DBusConnection#an-example-for-exporting-a-subtree]
for an example of how to use this method.
Parameters:
object_path— the object path to register the subtree atvtable— aDBusSubtreeVTableto enumerate, introspect and dispatch nodes in the subtreeflags— flags used to fine tune the behavior of the subtreeuser_data— data to pass to functions invtableuser_data_free_func— function to call when the subtree is unregistered
remove_filter¶
Removes a filter.
Note that since filters run in a different thread, there is a race
condition where it is possible that the filter will be running even
after calling DBusConnection.remove_filter, so you cannot just
free data that the filter might be using. Instead, you should pass
a GDestroyNotify to DBusConnection.add_filter, which will be
called when it is guaranteed that the data is no longer needed.
Parameters:
filter_id— an identifier obtained fromDBusConnection.add_filter
send_message¶
Asynchronously sends message to the peer represented by connection.
Unless flags contain the
DBusSendMessageFlags.PRESERVE_SERIAL flag, the serial number
will be assigned by connection and set on message via
DBusMessage.set_serial. If out_serial is not None, then the
serial number used will be written to this location prior to
submitting the message to the underlying transport. While it has a volatile
qualifier, this is a historical artifact and the argument passed to it should
not be volatile.
If connection is closed then the operation will fail with
IOErrorEnum.CLOSED. If message is not well-formed,
the operation fails with IOErrorEnum.INVALID_ARGUMENT.
See this [server][classGio.DBusConnection#an-example-d-bus-server]
and [client][classGio.DBusConnection#an-example-for-file-descriptor-passing]
for an example of how to use this low-level API to send and receive
UNIX file descriptors.
Note that message must be unlocked, unless flags contain the
DBusSendMessageFlags.PRESERVE_SERIAL flag.
Parameters:
message— aDBusMessageflags— flags affecting how the message is sent
send_message_with_reply¶
def send_message_with_reply(self, message: DBusMessage, flags: DBusSendMessageFlags | int, timeout_msec: int, cancellable: Cancellable | None = ..., callback: Callable[[DBusConnection | None, AsyncResult], None] | None = ...) -> int
Asynchronously sends message to the peer represented by connection.
Unless flags contain the
DBusSendMessageFlags.PRESERVE_SERIAL flag, the serial number
will be assigned by connection and set on message via
DBusMessage.set_serial. If out_serial is not None, then the
serial number used will be written to this location prior to
submitting the message to the underlying transport. While it has a volatile
qualifier, this is a historical artifact and the argument passed to it should
not be volatile.
If connection is closed then the operation will fail with
IOErrorEnum.CLOSED. If cancellable is canceled, the operation will
fail with IOErrorEnum.CANCELLED. If message is not well-formed,
the operation fails with IOErrorEnum.INVALID_ARGUMENT.
This is an asynchronous method. When the operation is finished, callback
will be invoked in the thread-default main context
(see GLib.MainContext.push_thread_default)
of the thread you are calling this method from. You can then call
DBusConnection.send_message_with_reply_finish to get the result of the operation.
See DBusConnection.send_message_with_reply_sync for the synchronous version.
Note that message must be unlocked, unless flags contain the
DBusSendMessageFlags.PRESERVE_SERIAL flag.
See this [server][classGio.DBusConnection#an-example-d-bus-server]
and [client][classGio.DBusConnection#an-example-for-file-descriptor-passing]
for an example of how to use this low-level API to send and receive
UNIX file descriptors.
Parameters:
message— aDBusMessageflags— flags affecting how the message is senttimeout_msec— the timeout in milliseconds, -1 to use the default timeout orG_MAXINTfor no timeoutcancellable— aCancellableorNonecallback— aGAsyncReadyCallbackto call when the request is satisfied orNoneif you don't care about the result
send_message_with_reply_finish¶
Finishes an operation started with DBusConnection.send_message_with_reply.
Note that error is only set if a local in-process error
occurred. That is to say that the returned DBusMessage object may
be of type DBusMessageType.ERROR. Use
DBusMessage.to_gerror to transcode this to a GLib.Error.
See this [server][classGio.DBusConnection#an-example-d-bus-server]
and [client][classGio.DBusConnection#an-example-for-file-descriptor-passing]
for an example of how to use this low-level API to send and receive
UNIX file descriptors.
Parameters:
res— aAsyncResultobtained from theGAsyncReadyCallbackpassed toDBusConnection.send_message_with_reply
send_message_with_reply_sync¶
def send_message_with_reply_sync(self, message: DBusMessage, flags: DBusSendMessageFlags | int, timeout_msec: int, cancellable: Cancellable | None = ...) -> tuple[DBusMessage, int]
Synchronously sends message to the peer represented by connection
and blocks the calling thread until a reply is received or the
timeout is reached. See DBusConnection.send_message_with_reply
for the asynchronous version of this method.
Unless flags contain the
DBusSendMessageFlags.PRESERVE_SERIAL flag, the serial number
will be assigned by connection and set on message via
DBusMessage.set_serial. If out_serial is not None, then the
serial number used will be written to this location prior to
submitting the message to the underlying transport. While it has a volatile
qualifier, this is a historical artifact and the argument passed to it should
not be volatile.
If connection is closed then the operation will fail with
IOErrorEnum.CLOSED. If cancellable is canceled, the operation will
fail with IOErrorEnum.CANCELLED. If message is not well-formed,
the operation fails with IOErrorEnum.INVALID_ARGUMENT.
Note that error is only set if a local in-process error
occurred. That is to say that the returned DBusMessage object may
be of type DBusMessageType.ERROR. Use
DBusMessage.to_gerror to transcode this to a GLib.Error.
See this [server][classGio.DBusConnection#an-example-d-bus-server]
and [client][classGio.DBusConnection#an-example-for-file-descriptor-passing]
for an example of how to use this low-level API to send and receive
UNIX file descriptors.
Note that message must be unlocked, unless flags contain the
DBusSendMessageFlags.PRESERVE_SERIAL flag.
Parameters:
message— aDBusMessageflags— flags affecting how the message is sent.timeout_msec— the timeout in milliseconds, -1 to use the default timeout orG_MAXINTfor no timeoutcancellable— aCancellableorNone
set_exit_on_close¶
Sets whether the process should be terminated when connection is
closed by the remote peer. See DBusConnection:exit-on-close for
more details.
Note that this function should be used with care. Most modern UNIX
desktops tie the notion of a user session with the session bus, and expect
all of a user's applications to quit when their bus connection goes away.
If you are setting exit_on_close to False for the shared session
bus connection, you should make sure that your application exits
when the user session ends.
Parameters:
exit_on_close— whether the process should be terminated whenconnectionis closed by the remote peer
signal_subscribe¶
def signal_subscribe(self, sender: str | None, interface_name: str | None, member: str | None, object_path: str | None, arg0: str | None, flags: DBusSignalFlags | int, callback: DBusSignalCallback) -> int
Subscribes to signals on connection and invokes callback whenever
the signal is received. Note that callback will be invoked in the
thread-default main context (see GLib.MainContext.push_thread_default)
of the thread you are calling this method from.
If connection is not a message bus connection, sender must be
None.
If sender is a well-known name note that callback is invoked with
the unique name for the owner of sender, not the well-known name
as one would expect. This is because the message bus rewrites the
name. As such, to avoid certain race conditions, users should be
tracking the name owner of the well-known name and use that when
processing the received signal.
If one of DBusSignalFlags.MATCH_ARG0_NAMESPACE or
DBusSignalFlags.MATCH_ARG0_PATH are given, arg0 is
interpreted as part of a namespace or path. The first argument
of a signal is matched against that part as specified by D-Bus.
If user_data_free_func is non-None, it will be called (in the
thread-default main context of the thread you are calling this
method from) at some point after user_data is no longer
needed. (It is not guaranteed to be called synchronously when the
signal is unsubscribed from, and may be called after connection
has been destroyed.)
As callback is potentially invoked in a different thread from where it’s
emitted, it’s possible for this to happen after
DBusConnection.signal_unsubscribe has been called in another thread.
Due to this, user_data should have a strong reference which is freed with
user_data_free_func, rather than pointing to data whose lifecycle is tied
to the signal subscription. For example, if a GObject.Object is used to store the
subscription ID from DBusConnection.signal_subscribe, a strong reference
to that GObject.Object must be passed to user_data, and GObject.Object.unref passed to
user_data_free_func. You are responsible for breaking the resulting
reference count cycle by explicitly unsubscribing from the signal when
dropping the last external reference to the GObject.Object. Alternatively, a weak
reference may be used.
It is guaranteed that if you unsubscribe from a signal using
DBusConnection.signal_unsubscribe from the same thread which made the
corresponding DBusConnection.signal_subscribe call, callback will not
be invoked after DBusConnection.signal_unsubscribe returns.
The returned subscription identifier is an opaque value which is guaranteed to never be zero.
This function can never fail.
Parameters:
sender— sender name to match on (unique or well-known name) orNoneto listen from all sendersinterface_name— D-Bus interface name to match on orNoneto match on all interfacesmember— D-Bus signal name to match on orNoneto match on all signalsobject_path— object path to match on orNoneto match on all object pathsarg0— contents of first string argument to match on orNoneto match on all kinds of argumentsflags—DBusSignalFlagsdescribing how arg0 is used in subscribing to the signalcallback— callback to invoke when there is a signal matching the requested data
signal_unsubscribe¶
Unsubscribes from signals.
Note that there may still be D-Bus traffic to process (relating to this
signal subscription) in the current thread-default GLib.MainContext after this
function has returned. You should continue to iterate the GLib.MainContext
until the GDestroyNotify function passed to
DBusConnection.signal_subscribe is called, in order to avoid memory
leaks through callbacks queued on the GLib.MainContext after it’s stopped being
iterated.
Alternatively, any idle source with a priority lower than GLib.PRIORITY_DEFAULT
that was scheduled after unsubscription, also indicates that all resources
of this subscription are released.
Parameters:
subscription_id— a subscription id obtained fromDBusConnection.signal_subscribe
start_message_processing¶
If connection was created with
DBusConnectionFlags.DELAY_MESSAGE_PROCESSING, this method
starts processing messages. Does nothing on if connection wasn't
created with this flag or if the method has already been called.
unexport_action_group¶
Reverses the effect of a previous call to
DBusConnection.export_action_group.
It is an error to call this function with an ID that wasn’t returned from
DBusConnection.export_action_group or to call it with the same
ID more than once.
Parameters:
export_id— the ID fromDBusConnection.export_action_group
unexport_menu_model¶
Reverses the effect of a previous call to
DBusConnection.export_menu_model.
It is an error to call this function with an ID that wasn't returned
from DBusConnection.export_menu_model or to call it with the
same ID more than once.
Parameters:
export_id— the ID fromDBusConnection.export_menu_model
unregister_object¶
Unregisters an object.
Parameters:
registration_id— a registration id obtained fromDBusConnection.register_object
unregister_subtree¶
Unregisters a subtree.
Parameters:
registration_id— a subtree registration id obtained fromDBusConnection.register_subtree
Static functions¶
new¶
@staticmethod
def new(stream: IOStream, guid: str | None, flags: DBusConnectionFlags | int, observer: DBusAuthObserver | None = ..., cancellable: Cancellable | None = ..., callback: AsyncReadyCallback | None = ...) -> None
Asynchronously sets up a D-Bus connection for exchanging D-Bus messages
with the end represented by stream.
If stream is a SocketConnection, then the corresponding Socket
will be put into non-blocking mode.
The D-Bus connection will interact with stream from a worker thread.
As a result, the caller should not interact with stream after this
method has been called, except by calling GObject.Object.unref on it.
If observer is not None it may be used to control the
authentication process.
When the operation is finished, callback will be invoked. You can
then call DBusConnection.new_finish to get the result of the
operation.
This is an asynchronous failable constructor. See
DBusConnection.new_sync for the synchronous
version.
Parameters:
stream— aIOStreamguid— the GUID to use if authenticating as a server orNoneflags— flags describing how to make the connectionobserver— aDBusAuthObserverorNonecancellable— aCancellableorNonecallback— aGAsyncReadyCallbackto call when the request is satisfied
new_for_address¶
@staticmethod
def new_for_address(address: str, flags: DBusConnectionFlags | int, observer: DBusAuthObserver | None = ..., cancellable: Cancellable | None = ..., callback: AsyncReadyCallback | None = ...) -> None
Asynchronously connects and sets up a D-Bus client connection for
exchanging D-Bus messages with an endpoint specified by address
which must be in the
D-Bus address format.
This constructor can only be used to initiate client-side
connections - use DBusConnection.new if you need to act as the
server. In particular, flags cannot contain the
DBusConnectionFlags.AUTHENTICATION_SERVER,
DBusConnectionFlags.AUTHENTICATION_ALLOW_ANONYMOUS or
DBusConnectionFlags.AUTHENTICATION_REQUIRE_SAME_USER flags.
When the operation is finished, callback will be invoked. You can
then call DBusConnection.new_for_address_finish to get the result of
the operation.
If observer is not None it may be used to control the
authentication process.
This is an asynchronous failable constructor. See
DBusConnection.new_for_address_sync for the synchronous
version.
Parameters:
address— a D-Bus addressflags— flags describing how to make the connectionobserver— aDBusAuthObserverorNonecancellable— aCancellableorNonecallback— aGAsyncReadyCallbackto call when the request is satisfied
Properties¶
address¶
A D-Bus address specifying potential endpoints that can be used when establishing the connection.
authentication_observer¶
A DBusAuthObserver object to assist in the authentication process or None.
capabilities¶
Flags from the DBusCapabilityFlags enumeration
representing connection features negotiated with the other peer.
closed¶
A boolean specifying whether the connection has been closed.
exit_on_close¶
A boolean specifying whether the process will be terminated (by
calling raise(SIGTERM)) if the connection is closed by the
remote peer.
Note that DBusConnection objects returned by bus_get_finish
and bus_get_sync will (usually) have this property set to True.
flags¶
Flags from the DBusConnectionFlags enumeration.
guid¶
The GUID of the peer performing the role of server when authenticating.
If you are constructing a DBusConnection and pass
DBusConnectionFlags.AUTHENTICATION_SERVER in the
DBusConnection:flags property then you must also set this
property to a valid guid.
If you are constructing a DBusConnection and pass
DBusConnectionFlags.AUTHENTICATION_CLIENT in the
DBusConnection:flags property you will be able to read the GUID
of the other peer here after the connection has been successfully
initialized.
Note that the D-Bus specification uses the term ‘UUID’ to refer to this, whereas GLib consistently uses the term ‘GUID’ for historical reasons.
Despite its name, the format of DBusConnection:guid does not follow
RFC 4122 or the Microsoft
GUID format.
stream¶
The underlying IOStream used for I/O.
If this is passed on construction and is a SocketConnection,
then the corresponding Socket will be put into non-blocking mode.
While the DBusConnection is active, it will interact with this
stream from a worker thread, so it is not safe to interact with
the stream directly.
unique_name¶
The unique name as assigned by the message bus or None if the
connection is not open or not a message bus connection.
Signals¶
closed¶
Emitted when the connection is closed.
The cause of this event can be
-
If
DBusConnection.closeis called. In this caseremote_peer_vanishedis set toFalseanderrorisNone. -
If the remote peer closes the connection. In this case
remote_peer_vanishedis set toTrueanderroris set. -
If the remote peer sends invalid or malformed data. In this case
remote_peer_vanishedis set toFalseanderroris set.
Upon receiving this signal, you should give up your reference to
connection. You are guaranteed that this signal is emitted only
once.