Skip to content

Instantly share code, notes, and snippets.

@monperrus
Created March 16, 2025 10:30
Show Gist options
  • Save monperrus/9d5334a08dd2bea916dea601864b5b43 to your computer and use it in GitHub Desktop.
Save monperrus/9d5334a08dd2bea916dea601864b5b43 to your computer and use it in GitHub Desktop.
a simple python application which expose an example service hello on dbus
#!/usr/bin/env python3
"""
dbus-send --session --dest=com.example.HelloService \
--type=method_call --print-reply \
/com/example/HelloService org.freedesktop.DBus.Introspectable.Introspect
dbus-send --session --dest=com.example.HelloService \
--type=method_call --print-reply \
/com/example/HelloService \
com.example.HelloService.say_hello \
string:"John"
"""
import dbus
import dbus.service
import dbus.mainloop.glib
from gi.repository import GLib
# Define the D-Bus interface name and object path
DBUS_INTERFACE = "com.example.HelloService"
DBUS_PATH = "/com/example/HelloService"
class HelloService(dbus.service.Object):
def __init__(self):
# Initialize the D-Bus main loop
dbus.mainloop.glib.DBusGMainLoop(set_as_default=True)
# Get the session bus
bus = dbus.SessionBus()
# Define the bus name
bus_name = dbus.service.BusName(DBUS_INTERFACE, bus=bus)
# Initialize the D-Bus service object
super().__init__(bus_name, DBUS_PATH)
# Define a D-Bus method that can be called by clients
@dbus.service.method(DBUS_INTERFACE,
in_signature='s', # Input parameter signature (string)
out_signature='s') # Output parameter signature (string)
def say_hello(self, name):
"""
A simple method that takes a name and returns a greeting
"""
return f"Hello, {name}!"
# Define a D-Bus signal that can be emitted
@dbus.service.signal(DBUS_INTERFACE,
signature='s')
def greeting_signal(self, message):
"""
A signal that can be emitted with a message
"""
pass
def main():
# Create an instance of the service
service = HelloService()
# Create the main loop
loop = GLib.MainLoop()
print(f"Service running on D-Bus interface {DBUS_INTERFACE}")
print("Press Ctrl+C to exit")
try:
# Run the main loop
loop.run()
except KeyboardInterrupt:
loop.quit()
print("\nService stopped")
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment