### Go Example Implementation of D-Bus Interface Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/server-interfaces.md An example implementation of the D-Bus Interface in Go, demonstrating how to store and retrieve methods. ```go type MyInterface struct { methods map[string]dbus.Method } func (i *MyInterface) LookupMethod(name string) (dbus.Method, bool) { method, found := i.methods[name] return method, found } ``` -------------------------------- ### Handler Implementation Example Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/server-interfaces.md A sample implementation of the Handler interface, demonstrating how to manage and retrieve ServerObjects based on their paths. ```go type MyHandler struct { objects map[dbus.ObjectPath]dbus.ServerObject } func (h *MyHandler) LookupObject(path dbus.ObjectPath) (dbus.ServerObject, bool) { obj, found := h.objects[path] return obj, found } ``` -------------------------------- ### Go Example Implementation of D-Bus Method Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/server-interfaces.md An example implementation of the D-Bus Method interface in Go, showing how to define a method's behavior and metadata. ```go type MyMethod struct { fn func(...any) ([]any, error) } func (m *MyMethod) Call(args ...any) ([]any, error) { return m.fn(args...) } func (m *MyMethod) NumArguments() int { return 2 // This method takes 2 arguments } func (m *MyMethod) NumReturns() int { return 1 // This method returns 1 value } func (m *MyMethod) ArgumentValue(position int) any { if position == 0 { return int32(0) } return "" } func (m *MyMethod) ReturnValue(position int) any { return "" } ``` -------------------------------- ### Example: Dial with External Authentication Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/connection.md Shows how to establish a D-Bus connection using the external authentication method. ```go conn, err := dbus.Dial(address, dbus.WithAuth(dbus.AuthExternal("user"))) ``` -------------------------------- ### Terminator Interface Example Implementation Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/server-interfaces.md An example of how to implement the Terminator interface. This handler uses a channel to signal cleanup and performs resource release. ```go type MyHandler struct { cleanup chan struct{} } func (h *MyHandler) Terminate() { close(h.cleanup) // Cleanup resources } ``` -------------------------------- ### Example Usage of Properties Map Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/properties.md Demonstrates how to initialize and populate a properties map with service and standard DBus properties. ```go propsMap := prop.Map{ "org.example.Service": { "Status": &prop.Prop{Value: "ready", Writable: false, Emit: prop.EmitFalse}, "Enabled": &prop.Prop{Value: true, Writable: true, Emit: prop.EmitTrue}, "Progress": &prop.Prop{Value: int32(0), Writable: true, Emit: prop.EmitInvalidates}, }, "org.freedesktop.DBus.Properties": { // Standard properties interface }, } ``` -------------------------------- ### ServerObject Implementation Example Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/server-interfaces.md A sample implementation of the ServerObject interface, showing how to manage and retrieve interfaces associated with a D-Bus object. ```go type MyObject struct { interfaces map[string]dbus.Interface } func (o *MyObject) LookupInterface(name string) (dbus.Interface, bool) { iface, found := o.interfaces[name] return iface, found } ``` -------------------------------- ### Example: Dial with Custom Handler Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/connection.md Demonstrates how to establish a D-Bus connection using a custom message handler. ```go conn, err := dbus.Dial(address, dbus.WithHandler(customHandler)) ``` -------------------------------- ### ExportMethodTable Example Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/export.md Demonstrates how to export methods dynamically using a map. This is useful for creating objects with methods that are constructed at runtime. ```go methods := make(map[string]any) methods["GetValue"] = func() (string, *dbus.Error) { return "value", nil } methods["SetValue"] = func(v string) *dbus.Error { fmt.Println("Set to:", v) return nil } conn.ExportMethodTable(methods, "/org/example/Dynamic", "org.example.Interface") ``` -------------------------------- ### Complete DBus Service Example Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/properties.md Demonstrates how to create and export a complete DBus service that manages properties, including setting properties and handling property change callbacks. ```go import ( "github.com/godbus/dbus/v5" "github.com/godbus/dbus/v5/prop" ) type StatusService struct { props *prop.Properties } func (s *StatusService) Start() (*dbus.Error, *dbus.Error) { // Set status property s.props.SetMust("org.example.Service", "Status", "running") return nil, nil } func (s *StatusService) Stop() (*dbus.Error, *dbus.Error) { s.props.SetMust("org.example.Service", "Status", "stopped") return nil, nil } // Handler for property changes func statusCallback(change *prop.Change) *dbus.Error { newStatus := change.Value.(string) fmt.Println("Status changed to:", newStatus) return nil } func main() { conn, _ := dbus.SessionBus() properties, _ := prop.Export(conn, "/org/example/Service", prop.Map{ "org.example.Service": { "Status": { Value: "idle", Writable: false, Emit: prop.EmitTrue, Callback: statusCallback, }, }, }) svc := &StatusService{props: properties} conn.Export(svc, "/org/example/Service", "org.example.Service") // Keep running select {} } ``` -------------------------------- ### Markdown Link Example Source: https://github.com/godbus/dbus/blob/master/_autodocs/DOCUMENTATION_GUIDE.md Demonstrates how internal documentation pages are linked using relative markdown syntax. ```markdown [Call type documentation](call.md) [Complete connection guide](connection.md) ``` -------------------------------- ### Goroutine-Safe Counter Example Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/export.md Provides an example of a goroutine-safe counter using a mutex. Exported objects that maintain state must be goroutine-safe as method invocations occur in separate goroutines. ```go type Counter struct { mu sync.Mutex count int32 } func (c *Counter) Increment() (int32, *dbus.Error) { c.mu.Lock() defer c.mu.Unlock() c.count++ return c.count, nil } ``` -------------------------------- ### Set DBus Message Flags Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/messages.md Example of how to set multiple flags on a DBus message using bitwise OR. ```go msg.Flags = dbus.FlagNoAutoStart | dbus.FlagNoReplyExpected ``` -------------------------------- ### Manage DBus Properties Source: https://github.com/godbus/dbus/blob/master/_autodocs/README.md This example illustrates how to export a DBus object with properties that can be read and written. It defines a property with initial value and specifies its writability and emission behavior. ```go props, _ := prop.Export(conn, "/org/example/Object", prop.Map{ "org.example.Interface": { "Value": { Value: "initial", Writable: true, Emit: prop.EmitTrue, }, }, }) ``` -------------------------------- ### Example Commit Message Source: https://github.com/godbus/dbus/blob/master/CONTRIBUTING.md Follow this format for commit messages to clearly indicate what changed and why. Ensure the subject line is concise and the body explains the reasoning. ```git scripts: add the test-cluster command this uses tmux to setup a test cluster that you can easily kill and start for debugging. Fixes #38 ``` -------------------------------- ### Example SerialGenerator Implementation Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/server-interfaces.md A basic implementation of the SerialGenerator interface using a mutex-protected counter. Suitable for simple use cases where serial reuse is not critical. ```go type MySerialGenerator struct { counter uint32 mu sync.Mutex } func (g *MySerialGenerator) GetSerial() uint32 { g.mu.Lock() defer g.mu.Unlock() g.counter++ return g.counter } func (g *MySerialGenerator) RetireSerial(serial uint32) { // No-op for simple implementation } ``` -------------------------------- ### Get Shared Session Bus Connection in Go Source: https://github.com/godbus/dbus/blob/master/_autodocs/README.md Demonstrates how to obtain a shared session bus connection. Shared connections are cached and should not be closed by the user. ```go conn1, _ := dbus.SessionBus() conn2, _ := dbus.SessionBus() // conn1 and conn2 are the same object // Must not close shared connections ``` -------------------------------- ### Access DBus Message Header Fields Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/messages.md Example of how to retrieve and type-assert values for common header fields from a DBus message. ```go path := msg.Headers[dbus.FieldPath].Value().(dbus.ObjectPath) method := msg.Headers[dbus.FieldMember].Value().(string) sig := msg.Headers[dbus.FieldSignature].Value().(dbus.Signature) ``` -------------------------------- ### Property Change Validation Callback Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/properties.md Example of a Go callback function to validate property changes before they are applied. If the callback returns an error, the property change is rejected. ```go countCallback := func(change *prop.Change) *dbus.Error { count := change.Value.(int32) if count < 0 { return dbus.NewError("org.example.Error.InvalidValue", []any{"Count cannot be negative"}) } return nil // Allow the change } props := prop.Map{ "org.example.Service": { "Count": { Value: int32(0), Writable: true, Emit: prop.EmitTrue, Callback: countCallback, }, }, } ``` -------------------------------- ### Get Property Value or Panic Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/properties.md Retrieves a property value, panicking if the property is not found. This method is useful for accessing known properties during initialization. ```go func (p *Properties) GetMust(iface, property string) any ``` -------------------------------- ### AdvancedObject and AdvancedMethod Go Interfaces Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/server-interfaces.md Implement these Go interfaces to define custom D-Bus method dispatch logic. This setup is useful for advanced features like dynamic method generation and custom routing. ```go type AdvancedObject struct { methodHandlers map[string]AdvancedMethod } type AdvancedMethod struct { fn func(dbus.Sender, ...any) ([]any, error) } func (o *AdvancedObject) LookupInterface(name string) (dbus.Interface, bool) { if name == "org.example.Interface" { return o, true } return nil, false } func (o *AdvancedObject) LookupMethod(name string) (dbus.Method, bool) { method, found := o.methodHandlers[name] return &method, found } ``` -------------------------------- ### BusObject Interface Methods Source: https://github.com/godbus/dbus/blob/master/_autodocs/INDEX.md Provides methods for interacting with remote DBus objects, including calling methods, getting and setting properties, and managing signal subscriptions. ```APIDOC ## BusObject Interface ### Methods - **Call(method, flags, args ...)** - **Purpose**: Synchronous method call. - **Signature**: `(method string, flags Flags, args ...any) *Call` - **CallWithContext(ctx, method, flags, args ...)** - **Purpose**: Synchronous call with context. - **Signature**: `(ctx context.Context, method string, flags Flags, args ...any) *Call` - **Go(method, flags, ch, args ...)** - **Purpose**: Asynchronous call. - **Signature**: `(method string, flags Flags, ch chan *Call, args ...any) *Call` - **GoWithContext(ctx, method, flags, ch, args ...)** - **Purpose**: Asynchronous call with context. - **Signature**: `(ctx context.Context, method string, flags Flags, ch chan *Call, args ...any) *Call` - **GetProperty(name)** - **Purpose**: Get property value. - **Signature**: `(p string) (Variant, error)` - **StoreProperty(name, ptr)** - **Purpose**: Get property into variable. - **Signature**: `(p string, value any) error` - **SetProperty(name, value)** - **Purpose**: Set property value. - **Signature**: `(p string, v any) error` - **Destination()** - **Purpose**: Get target service name. - **Signature**: `() string` - **Path()** - **Purpose**: Get object path. - **Signature**: `() ObjectPath` - **AddMatchSignal(iface, member, opts ...)** - **Purpose**: Subscribe to signals (deprecated). - **Signature**: `(iface, member string, options ...MatchOption) *Call` - **RemoveMatchSignal(iface, member, opts ...)** - **Purpose**: Unsubscribe from signals (deprecated). - **Signature**: `(iface, member string, options ...MatchOption) *Call` ``` -------------------------------- ### Receive All PropertiesChanged Signals Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/signal-matching.md Use WithMatchEavesdrop to receive signals not addressed to the current connection, effectively 'eavesdropping'. This typically requires elevated privileges. This example shows how to receive all PropertiesChanged signals. ```go conn.AddMatchSignal( dbus.WithMatchInterface("org.freedesktop.DBus.Properties"), dbus.WithMatchMember("PropertiesChanged"), dbus.WithMatchEavesdrop(true), ) ``` -------------------------------- ### DBusError Interface Example Implementation Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/server-interfaces.md An example of a custom error type implementing the DBusError interface. It returns a custom D-Bus error name and a message body containing an integer code and a string message. ```go type MyError struct { code int msg string } func (e *MyError) DBusError() (string, []any) { return "org.example.Error.Custom", []any{e.code, e.msg} } ``` -------------------------------- ### Hello Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/connection.md Sends the initial org.freedesktop.DBus.Hello call. This method must be called after authentication but before sending any other messages. Must not be called on shared connections. ```APIDOC ## Hello ### Description Hello sends the initial org.freedesktop.DBus.Hello call. This method must be called after authentication but before sending any other messages. Must not be called on shared connections. ### Returns - `error`: Non-nil if the Hello call fails ``` -------------------------------- ### Working with D-Bus Variants Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/types.md Demonstrates creating D-Bus variants from Go types and retrieving their values. Also shows how to send and receive variants in method calls. ```go // Create variants v1 := dbus.MakeVariant("hello") v2 := dbus.MakeVariant(int32(42)) // Get the value back str := v1.Value().(string) num := v2.Value().(int32) // Send in a method call obj.Call("org.example.Echo", 0, v1, v2) // Receive and store var result dbus.Variant call.Store(&result) fmt.Println(result.Value()) ``` -------------------------------- ### SignatureError Example Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/errors.md SignatureError indicates an invalid D-Bus type signature string. Use dbus.ParseSignature to validate signatures. ```go type SignatureError struct { Sig string Reason string } func (e SignatureError) Error() string ``` ```go sig, err := dbus.ParseSignature("(ii)x") if err != nil { fmt.Println(err) // SignatureError: invalid signature ... } ``` -------------------------------- ### D-Bus Object Paths Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/types.md Demonstrates creating and validating D-Bus object paths, and obtaining a D-Bus object proxy for a given service and path. ```go path := dbus.ObjectPath("/org/freedesktop/DBus/Manager") if !path.IsValid() { log.Fatal("Invalid path") } obj := conn.Object("org.example.Service", path) ``` -------------------------------- ### Get Property Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/properties.md Retrieves the value of a specific property from a D-Bus interface. This method corresponds to the standard `org.freedesktop.DBus.Properties.Get` interface. ```APIDOC ## Get ### Description Get retrieves the value of a property. Implements org.freedesktop.DBus.Properties.Get. ### Method Signature ```go func (p *Properties) Get(iface, property string) (dbus.Variant, *dbus.Error) ``` ### Parameters #### Path Parameters - **iface** (string) - Required - Interface name - **property** (string) - Required - Property name ### Returns - **dbus.Variant**: Property value - ***dbus.Error**: Non-nil if interface or property not found ``` -------------------------------- ### InvalidMessageError Example Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/errors.md InvalidMessageError signifies a malformed D-Bus message or a violation of wire protocol rules. Use dbus.DecodeMessageWithFDs for decoding. ```go type InvalidMessageError string func (e InvalidMessageError) Error() string ``` ```go msg, err := dbus.DecodeMessageWithFDs(reader, fds) if err != nil { if msgErr, ok := err.(dbus.InvalidMessageError); ok { fmt.Println("Invalid message:", msgErr) } } ``` -------------------------------- ### Establish Private Session Bus Connection in Go Source: https://github.com/godbus/dbus/blob/master/_autodocs/README.md Shows how to establish a private session bus connection. Private connections must be explicitly closed using defer conn.Close(). ```go conn, _ := dbus.ConnectSessionBus() defer conn.Close() // Must close ``` -------------------------------- ### InvalidTypeError Example Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/errors.md InvalidTypeError is returned when a Go type cannot be represented in D-Bus. This occurs with types like complex numbers or channels. ```go type InvalidTypeError struct { Type reflect.Type } func (e InvalidTypeError) Error() string ``` ```go call := obj.Call("Method", 0, complex(1, 2)) // Error: InvalidTypeError - complex128 cannot be represented in D-Bus ``` -------------------------------- ### Method and Function Signature Formats Source: https://github.com/godbus/dbus/blob/master/_autodocs/DOCUMENTATION_GUIDE.md Illustrates the standard formats for Go method and function signatures used throughout the documentation. ```go // Method signature format: func (receiver) MethodName(param Type, moreParams ...) (ReturnType, error) // Function signature format: func FunctionName(param Type) (ReturnType, error) ``` -------------------------------- ### Connect with Authentication Methods Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/authentication.md Establish a DBus connection using specified authentication methods. The methods are tried in order until one succeeds. ```go conn, err := dbus.Connect(address, dbus.WithAuth( dbus.AuthExternal("username"), dbus.AuthAnonymous(), )) ``` -------------------------------- ### Connect to D-Bus with Address Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/connection.md Connects to the message bus at the given address, performing authentication and initialization. The returned connection is ready for immediate use. ```go conn, err := dbus.Connect("unix:path=/run/dbus/system_bus_socket") if err != nil { panic(err) } defer conn.Close() ``` -------------------------------- ### Handling Method Call Timeouts with Context Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/errors.md Demonstrates how to implement timeouts for D-Bus method calls using Go's context package. This is the recommended approach as the library does not provide built-in timeouts. ```go ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defuncancel() call := obj.CallWithContext(ctx, "org.example.SlowMethod", 0) if call.Err != nil { if call.Err == context.DeadlineExceeded { fmt.Println("Method call timed out") } else { fmt.Println("Method call failed:", call.Err) } } ``` -------------------------------- ### Get the Context of a D-Bus Connection Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/connection.md Retrieves the context associated with the D-Bus connection. This context is automatically cancelled when the connection is closed. ```go conn.Context() ``` -------------------------------- ### Get Call Context Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/call.md Retrieves the context associated with a D-Bus call. If no context was explicitly provided, it returns the background context. ```go func (c *Call) Context() context.Context ``` -------------------------------- ### Set Authentication Methods Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/connection.md Use WithAuth to specify authentication methods for the auth conversation. If not specified, platform defaults are used. ```go func WithAuth(methods ...Auth) ConnOption ``` -------------------------------- ### Get Property Value Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/properties.md Retrieves the value of a specific property within an interface. Returns a dbus.Variant and a *dbus.Error if the interface or property is not found. ```go func (p *Properties) Get(iface, property string) (dbus.Variant, *dbus.Error) ``` -------------------------------- ### Handle Authentication Failures Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/authentication.md Demonstrates connecting to a D-Bus with explicit authentication and handling potential errors. Use this when default authentication is insufficient or specific credentials are required. ```go conn, err := dbus.Connect(address, dbus.WithAuth( dbus.AuthExternal("username"), )) if err != nil { fmt.Println("Authentication failed:", err) // Could be invalid credentials, missing auth method support, or bus unavailable } ``` -------------------------------- ### Get Bus Object Destination Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/bus-object.md Retrieve the unique or well-known name of the D-Bus service that owns the object. This is useful for identifying the source of an object. ```go func (o *Object) Destination() string ``` ```go dest := obj.Destination() fmt.Println("Object owned by:", dest) ``` -------------------------------- ### Exporting Objects with Path Precedence Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/export.md Demonstrates how to export a general subtree handler and a more specific path handler. The specific path handler takes precedence for calls to that exact path. ```go type Handler struct{} func (h *Handler) Method(msg dbus.Message) (string, *dbus.Error) { path := msg.Headers[dbus.FieldPath].Value().(dbus.ObjectPath) return fmt.Sprintf("Handled at %s", path), nil } h := &Handler{} // Export general handler for entire tree conn.ExportSubtree(h, "/org/example", "org.example.Interface") // This more specific path will be called instead conn.Export(&specificHandler{}, "/org/example/specific", "org.example.Interface") // Calls to /org/example/other/path will use the subtree handler // Calls to /org/example/specific will use the specific handler ``` -------------------------------- ### Troubleshooting Cannot Establish Connection Error Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/authentication.md This error suggests the D-Bus daemon might not be running or the socket path is incorrect. Confirm the bus address and daemon status. ```text Error: ... connection reset by peer ... ``` -------------------------------- ### D-Bus Introspection XML Format Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/introspect.md This is an example of the XML format used for D-Bus introspection. The `introspect.Call` function in Go automatically parses this XML structure. ```xml ``` -------------------------------- ### Checking Message Type Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/messages.md Example of how to check the type of a received D-Bus message and access its headers. This is useful for routing or processing messages based on their intent. ```go if msg.Type == dbus.TypeMethodCall { fmt.Println("Received method call for:", msg.Headers[dbus.FieldMember]) } ``` -------------------------------- ### Connect Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/connection.md Connects to the message bus at the given address, performing authentication and initialization. The returned connection is ready for immediate use. ```APIDOC ## Connect ### Description Connects to the message bus at the given address and performs authentication and initialization (Auth and Hello). The returned connection is ready for immediate use. ### Method ```go func Connect(address string, opts ...ConnOption) (*Conn, error) ``` ### Parameters #### Path Parameters (None) #### Query Parameters (None) #### Request Body (None) ### Parameters - **address** (`string`) - D-Bus address string (e.g., "unix:path=/run/dbus/system_bus_socket") - **opts** (`...ConnOption`) - Variable number of connection configuration options ### Returns - `*Conn`: An authenticated and initialized connection - `error`: Non-nil if connection, authentication, or Hello fails ``` -------------------------------- ### Synchronous vs. Asynchronous D-Bus Calls Source: https://github.com/godbus/dbus/blob/master/_autodocs/README.md Demonstrates the difference between synchronous D-Bus method calls that block until a reply is received and asynchronous calls that return immediately. ```go // Synchronous - blocks until reply result := obj.Call("org.example.Method", 0, args...) // Asynchronous - returns immediately ch := make(chan *dbus.Call, 1) obj.Go("org.example.Method", 0, ch, args...) result := <-ch ``` -------------------------------- ### Get Bus Object Path Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/bus-object.md Retrieve the D-Bus object path for the current object. This path uniquely identifies the object within the D-Bus system. ```go func (o *Object) Path() ObjectPath ``` ```go path := obj.Path() fmt.Println("Object path:", path) ``` -------------------------------- ### Type Conversions in Method Calls Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/types.md Illustrates automatic Go type to D-Bus type conversions during method calls and receiving results using the Store method. ```go // Go types are automatically converted to D-Bus obj.Call("org.example.Method", 0, "string argument", // → STRING int32(42), // → INT32 []string{"a", "b"}, // → ARRAY of STRING map[string]int32{}, ) // Receiving results with Store var s string var nums []int32 var props map[string]dbus.Variant call := obj.Call("org.example.GetProps", 0) call.Store(&s, &nums, &props) ``` -------------------------------- ### DBus Properties Introspection Data Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/properties.md Defines the introspection data structure for the org.freedesktop.DBus.Properties interface, including methods like Get, GetAll, Set, and the PropertiesChanged signal. ```go var IntrospectData = introspect.Interface{ Name: "org.freedesktop.DBus.Properties", Methods: []introspect.Method{ { Name: "Get", Args: []introspect.Arg{ {Name: "interface", Type: "s", Direction: "in"}, {Name: "property", Type: "s", Direction: "in"}, {Name: "value", Type: "v", Direction: "out"}, }, }, // ... GetAll and Set methods }, Signals: []introspect.Signal{ { Name: "PropertiesChanged", Args: []introspect.Arg{ {Name: "interface", Type: "s"}, {Name: "changed_properties", Type: "a{sv}"}, {Name: "invalidates_properties", Type: "as"}, }, }, }, } const IntrospectDataString = `...` // XML format ``` -------------------------------- ### Troubleshooting Connection Refused Error Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/authentication.md This error indicates insufficient permissions to access the D-Bus socket. Verify file permissions on the socket file. ```text Error: ... permission denied ... ``` -------------------------------- ### Exporting and Unexporting Objects Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/export.md Shows how to export a Go object to a specific D-Bus path and interface, and how to unexport it by passing nil. ```go // Export an object conn.Export(obj, "/org/example/Object", "org.example.Interface") // Object is now available for method calls from other D-Bus clients // Unexport an object by passing nil as the value conn.Export(nil, "/org/example/Object", "org.example.Interface") // Object is no longer available ``` -------------------------------- ### Create and Export a DBus Service Source: https://github.com/godbus/dbus/blob/master/_autodocs/README.md This snippet shows how to create a Go struct that can be exported as a DBus service. It includes registering the service with a path and interface, and then requesting a well-known name on the bus. ```go type Service struct{} func (s *Service) Method() (string, *dbus.Error) { return "result", nil } svc := &Service{} conn.Export(svc, "/org/example/Service", "org.example.Interface") // Claim the well-known name conn.BusObject().Call("org.freedesktop.DBus.RequestName", 0, "org.example.Service", uint32(0)) ``` -------------------------------- ### DBus Method Call with Flags Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/call.md Shows how to combine flags like FlagNoAutoStart and FlagNoReplyExpected using bitwise OR to modify method call behavior, such as preventing auto-start or disabling reply waiting. ```go call := obj.Call("org.example.Interface.Method", dbus.FlagNoAutoStart | dbus.FlagNoReplyExpected, args...) ``` -------------------------------- ### Get Shared System Bus Connection Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/connection.md Returns a shared connection to the system bus. The system bus typically requires elevated privileges. This connection must not be closed. ```go bus, err := dbus.SystemBus() if err != nil { panic(err) } ``` -------------------------------- ### EmitType String Method Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/properties.md Provides a human-readable string representation for EmitType constants. ```go func (e EmitType) String() string ``` -------------------------------- ### Explicitly Authenticate an Uninitialized Connection Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/authentication.md Manually authenticate an uninitialized DBus connection by providing a list of authentication methods and then calling Hello to complete initialization. Ensure error handling for each step. ```go conn, err := dbus.Dial(address) if err != nil { panic(err) } // Perform authentication manually methods := []dbus.Auth{ dbus.AuthExternal("username"), dbus.AuthAnonymous(), } err = conn.Auth(methods) if err != nil { panic(err) } // Now perform Hello to complete initialization err = conn.Hello() if err != nil { panic(err) } ``` -------------------------------- ### Get a Remote D-Bus Object Proxy Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/connection.md Creates a proxy for a remote D-Bus object at a specified destination and path. This proxy can be used to invoke methods and access properties on the remote object. ```go obj := conn.Object("org.freedesktop.DBus", "/org/freedesktop/DBus") ``` -------------------------------- ### Create EXTERNAL Authentication Mechanism Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/authentication.md Creates an EXTERNAL authentication mechanism, the default for Unix sockets. Authenticate as the specified user. ```go conn, err := dbus.Dial(address, dbus.WithAuth(dbus.AuthExternal("username"))) ``` -------------------------------- ### Get D-Bus Property Value Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/bus-object.md Retrieves the value of a D-Bus property using its interface and property name. The property name must be in "interface.property" notation. Handles potential errors during retrieval. ```go prop, err := obj.GetProperty("org.example.Interface.Value") if err != nil { log.Fatal(err) } value := prop.Value().(string) ``` -------------------------------- ### Export Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/export.md Registers methods on a value as a D-Bus object. Methods must be exported (start with uppercase), return *Error as the final return value, and have parameters/return values representable in D-Bus. Method calls are invoked in a new goroutine. ```APIDOC ## Export ### Description Registers methods on a value as a D-Bus object. Methods must be exported (start with uppercase), return *Error as the final return value, and have parameters/return values representable in D-Bus. Method calls are invoked in a new goroutine. ### Method `func (conn *Conn) Export(v any, path ObjectPath, iface string) error` ### Parameters #### Path Parameters - **v** (any) - Required - Go value with methods to export - **path** (ObjectPath) - Required - Path at which the object is exported - **iface** (string) - Required - Interface name (e.g., "org.example.Interface") ### Returns - `error`: Non-nil if path is invalid or export fails ### Example ```go type Calculator struct{} func (c *Calculator) Add(a, b int32) (int32, *dbus.Error) { return a + b, nil } func (c *Calculator) Divide(a, b int32) (int32, *dbus.Error) { if b == 0 { return 0, dbus.NewError("org.example.Calculator.DivideByZero", []any{}) } return a / b, nil } calc := &Calculator{} conn.Export(calc, "/org/example/Calculator", "org.example.Calculator") ``` ``` -------------------------------- ### Handle D-Bus Signals Source: https://github.com/godbus/dbus/blob/master/_autodocs/README.md Sets up a channel to receive D-Bus signals and subscribes to specific signal types. Processes incoming signals. ```go import "fmt" import "github.com/godbus/dbus/v5" // Create a signal channel ch := make(chan *dbus.Signal, 32) conn.Signal(ch) // Subscribe to signals conn.AddMatchSignal( dbus.WithMatchInterface("org.freedesktop.DBus.Properties"), dbus.WithMatchMember("PropertiesChanged"), ) // Process signals for sig := range ch { fmt.Println("Signal:", sig.Name, "from", sig.Sender) } ``` -------------------------------- ### GoWithContext Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/bus-object.md Invokes a method asynchronously with context support, allowing for cancellation and timeouts. The call is managed via the provided context and a completion channel. ```APIDOC ## GoWithContext ### Description GoWithContext invokes a method asynchronously with context support. ### Method `GoWithContext` ### Parameters #### Path Parameters - **ctx** (context.Context) - Required - Context for cancellation - **method** (string) - Required - Method name in "interface.member" format - **flags** (Flags) - Required - Message flags - **ch** (chan *Call) - Required - Buffered channel to receive completion - **args** (...any) - Required - Method arguments ### Returns - `*Call`: Call structure for the pending method call ``` -------------------------------- ### Signature Methods Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/types.md Provides methods for interacting with Signature types, including string representation, checking for emptiness, and verifying if it represents a single type. ```go func (s Signature) String() string func (s Signature) Empty() bool func (s Signature) Single() bool ``` -------------------------------- ### WithMatchArg0Namespace Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/signal-matching.md Filters by the first argument as a string namespace. ```APIDOC ## WithMatchArg0Namespace ### Description Filters by the first argument as a string namespace, similar to argpath but for the first argument. ### Method `WithMatchArg0Namespace(arg0Namespace string) MatchOption` ### Parameters #### Path Parameters - **arg0Namespace** (string) - Required - Expected string namespace/prefix ``` -------------------------------- ### Type Conversions for D-Bus Message Bodies Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/messages.md Demonstrates how to populate a message body with various Go types that D-Bus can automatically convert, and how to receive and store these values back into Go variables using dbus.Store. Ensure the order of types in dbus.Store matches the order in msg.Body. ```go // Sending msg.Body = []any{ "string", int32(42), []string{"a", "b"}, map[string]int32{"x": 10}, dbus.MakeVariant(true), } // Receiving var s string var i int32 var sa []string var m map[string]int32 var v dbus.Variant err := dbus.Store(msg.Body, &s, &i, &sa, &m, &v) ``` -------------------------------- ### Create Generic Match Option Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/signal-matching.md Creates a match option with an arbitrary key-value pair. Prefer specific WithMatch* functions for type safety. ```go func WithMatchOption(key, value string) MatchOption ``` -------------------------------- ### Connection Management - Main Entry Points Source: https://github.com/godbus/dbus/blob/master/_autodocs/INDEX.md Provides functions to obtain and establish connections to D-Bus buses, including session, system, and custom addresses, with options for private connections and authentication. ```APIDOC ## Connection Management - Main Entry Points ### Description Functions to get shared or create private connections to D-Bus session and system buses, or to custom addresses. ### Functions - `SessionBus()`: Get shared session bus connection. - `SystemBus()`: Get shared system bus connection. - `ConnectSessionBus(opts ...)`: Create private session bus connection. - `ConnectSystemBus(opts ...)`: Create private system bus connection. - `Connect(address, opts ...)`: Connect to custom address with auth. - `Dial(address, opts ...)`: Connect to custom address (no auth). - `SessionBusPrivate(opts ...)`: Private connection with autolaunch. - `SessionBusPrivateNoAutoStartup(opts ...)`: Private connection without autolaunch. - `SystemBusPrivate(opts ...)`: Unauthenticated system bus connection. - `NewConn(conn, opts ...)`: Wrap an I/O connection. ``` -------------------------------- ### Exporting Methods with Standard Errors Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/export.md Demonstrates how methods returning dbus.Error or standard Go errors are automatically converted to D-Bus errors upon export. ```go type Service struct{} func (s *Service) Method() (*dbus.Error, *dbus.Error) { return dbus.NewError("org.example.Error.Failed", []any{"Error message"}), nil } // Or with ExportAll: func (s *Service) Method2() (string, error) { return "", fmt.Errorf("Something went wrong") // Converted to "org.freedesktop.DBus.Error.Failed" with message body } ``` -------------------------------- ### Use Standard Go Errors with ExportAll Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/errors.md When using `ExportAll`, standard Go errors are automatically converted to D-Bus errors. Simple Go errors become `org.freedesktop.DBus.Error.Failed`. ```go type Service struct{} func (s *Service) Method(input string) (string, error) { if input == "" { // With ExportAll, Go errors are automatically converted return "", errors.New("input cannot be empty") // Becomes "org.freedesktop.DBus.Error.Failed" with message body } return strings.ToUpper(input), nil } conn.ExportAll(&Service{}, "/org/example/Service", "org.example.Interface") ``` -------------------------------- ### SessionBusPrivateNoAutoStartup Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/connection.md Returns a new private connection to the session bus without attempting to autolaunch if the bus is not running. ```APIDOC ## SessionBusPrivateNoAutoStartup ### Description Returns a new private connection to the session bus without attempting to autolaunch if the bus is not running. Fails if no existing session bus is available. ### Method `func` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Returns - `*Conn`: A new authenticated and initialized private session bus connection - `error`: Non-nil if session bus address cannot be determined or connection fails ``` -------------------------------- ### Establish Private System Bus Connection Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/connection.md Connects to the system bus and returns a private connection that must be closed. Options can customize handler, authentication, and interceptor behavior. ```go conn, err := dbus.ConnectSystemBus() if err != nil { panic(err) } defer conn.Close() ``` -------------------------------- ### Handler Functions Source: https://github.com/godbus/dbus/blob/master/_autodocs/INDEX.md Functions for creating default handler instances. ```APIDOC ## NewDefaultHandler ### Description Create default handler. ### Method `NewDefaultHandler()` ``` ```APIDOC ## NewDefaultSignalHandler ### Description Create default signal handler. ### Method `NewDefaultSignalHandler()` ``` -------------------------------- ### Set Connection Context Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/connection.md Use WithContext to set the context for the connection. The connection will be automatically closed when the context is cancelled. ```go func WithContext(ctx context.Context) ConnOption ``` -------------------------------- ### Properties Methods Source: https://github.com/godbus/dbus/blob/master/_autodocs/INDEX.md Methods for interacting with properties on the DBus system. ```APIDOC ## Get ### Description Get the value of a specific property. ### Method Signature `Get(iface, prop)` ### Parameters #### Path Parameters - **iface** (string) - Required - The interface name. - **prop** (string) - Required - The property name. ``` ```APIDOC ## GetAll ### Description Get all properties for a given interface. ### Method Signature `GetAll(iface)` ### Parameters #### Path Parameters - **iface** (string) - Required - The interface name. ``` ```APIDOC ## Set ### Description Set the value of a specific property. ### Method Signature `Set(iface, prop, value)` ### Parameters #### Path Parameters - **iface** (string) - Required - The interface name. - **prop** (string) - Required - The property name. - **value** (interface{}) - Required - The new property value. ``` ```APIDOC ## GetMust ### Description Get a property value, panicking if an error occurs. ### Method Signature `GetMust(iface, prop)` ### Parameters #### Path Parameters - **iface** (string) - Required - The interface name. - **prop** (string) - Required - The property name. ``` ```APIDOC ## SetMust ### Description Set a property value, panicking if an error occurs. ### Method Signature `SetMust(iface, prop, value)` ### Parameters #### Path Parameters - **iface** (string) - Required - The interface name. - **prop** (string) - Required - The property name. - **value** (interface{}) - Required - The new property value. ``` -------------------------------- ### Create a Private D-Bus Connection Source: https://github.com/godbus/dbus/blob/master/_autodocs/README.md Establishes a private connection to the D-Bus session bus. Ensures the connection is closed when done. ```go import "github.com/godbus/dbus/v5" // Or create a private connection conn, err := dbus.ConnectSessionBus() if err != nil { panic(err) } defer conn.Close() ``` -------------------------------- ### Create DBUS_COOKIE_SHA1 Authentication Mechanism Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/authentication.md Creates a DBUS_COOKIE_SHA1 authentication mechanism, primarily used on Windows. Provide the username and home directory path. ```go conn, err := dbus.Dial(address, dbus.WithAuth(dbus.AuthCookieSha1("user", "/home/user"))) ``` -------------------------------- ### Troubleshooting Unknown Authentication Mechanism Error Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/authentication.md This error occurs when the authentication mechanism is not supported. Try an alternative mechanism or check the bus configuration. ```text Error: ... no supported authentication mechanisms ... ``` -------------------------------- ### DBus Response Ordering Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/call.md Demonstrates how to access the ResponseSequence field to determine the relative ordering of method call responses and signals on a DBus connection. ```go call := obj.Call("org.example.Interface.Method", 0) // Get the sequence number of the response seq := call.ResponseSequence // Compare with other responses or signals to determine ordering ``` -------------------------------- ### SignatureOf Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/types.md Generates a D-Bus type signature string from a variadic list of Go values. ```APIDOC ## SignatureOf ### Description SignatureOf returns the D-Bus signature of the given values by examining their Go types. Panics if any value cannot be represented as a D-Bus type. ### Method SignatureOf(vs ...any) Signature ### Parameters #### Parameters - **vs** (`...any`) - Description: Go values to get signatures for ### Returns - **Signature**: The concatenated signatures ### Example ```go sig := dbus.SignatureOf("hello", int32(42), true) // sig.String() == "sib" ``` ``` -------------------------------- ### Export Properties to DBus Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/properties.md Creates and exports a Properties object to a specified DBus path. Use this to manage property values and emit change signals. Requires a DBus connection, object path, and an initial set of properties. ```go import ( "github.com/godbus/dbus/v5" "github.com/godbus/dbus/v5/prop" ) conn, _ := dbus.SessionBus() props := prop.Map{ "org.example.Interface": { "Name": { Value: "Initial Value", Writable: true, Emit: prop.EmitTrue, }, "Count": { Value: int32(0), Writable: true, Emit: prop.EmitTrue, }, }, } properties, err := prop.Export(conn, "/org/example/Object", props) if err != nil { panic(err) } // Now clients can use org.freedesktop.DBus.Properties.Get/Set ``` -------------------------------- ### GetAll Properties in an Interface Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/properties.md Returns all properties within a specified interface. Returns a map of property names to their dbus.Variant values and a *dbus.Error if the interface is not found. ```go func (p *Properties) GetAll(iface string) (map[string]dbus.Variant, *dbus.Error) ``` -------------------------------- ### WithAuth Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/connection.md Sets authentication methods for the auth conversation. If not specified, platform defaults are used. ```APIDOC ## WithAuth ConnOption ### Description Sets authentication methods for the auth conversation. If not specified, platform defaults are used. ### Method ConnOption ### Parameters #### Path Parameters - **methods** (...Auth) - Required - Authentication method instances. Defaults to Platform-specific defaults. ### Request Example ```go conn, err := dbus.Dial(address, dbus.WithAuth(dbus.AuthExternal("user"))) ``` ### Response #### Success Response - **ConnOption**: Configuration function ``` -------------------------------- ### Create and Use BusObject Reference Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/bus-object.md Create a BusObject reference using Conn.Object() to interact with D-Bus services. The validation of the object path and interface occurs when a method is called. ```go bus, _ := dbus.SessionBus() obj := bus.Object("org.freedesktop.DBus", "/org/freedesktop/DBus") // Now invoke methods call := obj.Call("org.freedesktop.DBus.ListNames", 0) ``` -------------------------------- ### Constructing a Low-Level Method Call Message Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/messages.md Manually create a D-Bus message of type MethodCall, setting essential headers like Path, Destination, Member, and Interface. The message body can contain arguments, and the Signature header should be set accordingly. This is useful for advanced scenarios where automatic generation is not desired. ```go msg := &dbus.Message{} msg.Type = dbus.TypeMethodCall msg.Flags = dbus.FlagNoAutoStart msg.Headers = make(map[dbus.HeaderField]dbus.Variant) msg.Headers[dbus.FieldPath] = dbus.MakeVariant(dbus.ObjectPath("/org/example/Object")) msg.Headers[dbus.FieldDestination] = dbus.MakeVariant("org.example.Service") msg.Headers[dbus.FieldMember] = dbus.MakeVariant("DoSomething") msg.Headers[dbus.FieldInterface] = dbus.MakeVariant("org.example.Interface") msg.Body = []any{"arg1", int32(42)} msg.Headers[dbus.FieldSignature] = dbus.MakeVariant(dbus.SignatureOf(msg.Body...)) // Send the message call := conn.Send(msg, make(chan *dbus.Call, 1)) ``` -------------------------------- ### Establish Private Session Bus Connection Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/connection.md Connects to the session bus and returns a private connection that must be closed. Options can customize handler, authentication, and interceptor behavior. ```go conn, err := dbus.ConnectSessionBus() if err != nil { panic(err) } defer conn.Close() ``` -------------------------------- ### Struct Conversion from D-Bus Source: https://github.com/godbus/dbus/blob/master/_autodocs/api-reference/types.md Shows how D-Bus STRUCT types are automatically converted to Go structs. Fields tagged with `dbus:"-"` are ignored. ```go type MyStruct struct { Name string Value int32 Skip string `dbus:"-"` // This field is ignored } // Receiving from D-Bus var result MyStruct call := obj.Call("org.example.GetStruct", 0) call.Store(&result) // D-Bus STRUCT is converted to MyStruct automatically ``` -------------------------------- ### Connection Management - Connection Options Source: https://github.com/godbus/dbus/blob/master/_autodocs/INDEX.md Provides options for configuring D-Bus connections, such as setting custom handlers for messages and signals, defining serial generators, and intercepting messages. ```APIDOC ## Connection Management - Connection Options ### Description Options to customize D-Bus connection behavior, including message handling, signal processing, serial generation, authentication, and message interception. ### Options - `WithHandler(handler)`: Set custom message handler. - `WithSignalHandler(handler)`: Set custom signal handler. - `WithSerialGenerator(gen)`: Set custom serial generator. - `WithAuth(methods ...)`: Set authentication methods. - `WithIncomingInterceptor(fn)`: Inspect incoming messages. - `WithOutgoingInterceptor(fn)`: Inspect outgoing messages. - `WithContext(ctx)`: Set connection context. ```