Skip to content

Commit

Permalink
examples: Add asynchronous D-Bus client example
Browse files Browse the repository at this point in the history
Extend the server example with a Sleep method and add a client to
demonstrate an asynchronous D-Bus call with possible timeout handling.
  • Loading branch information
ivanteterevkov committed May 9, 2022
1 parent 16fef22 commit 800df89
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 0 deletions.
10 changes: 10 additions & 0 deletions _examples/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"fmt"
"os"
"time"

"github.com/godbus/dbus/v5"
"github.com/godbus/dbus/v5/introspect"
Expand All @@ -14,6 +15,9 @@ const intro = `
<method name="Foo">
<arg direction="out" type="s"/>
</method>
<method name="Sleep">
<arg direction="in" type="u"/>
</method>
</interface>` + introspect.IntrospectDataString + `</node> `

type foo string
Expand All @@ -23,6 +27,12 @@ func (f foo) Foo() (string, *dbus.Error) {
return string(f), nil
}

func (f foo) Sleep(seconds uint) *dbus.Error {
fmt.Println("Sleeping", seconds, "second(s)")
time.Sleep(time.Duration(seconds) * time.Second)
return nil
}

func main() {
conn, err := dbus.ConnectSessionBus()
if err != nil {
Expand Down
51 changes: 51 additions & 0 deletions _examples/timeout.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
package main

import (
"fmt"
"os"
"time"

"github.com/godbus/dbus/v5"
)

func main() {
conn, err := dbus.ConnectSessionBus()
if err != nil {
fmt.Fprintln(os.Stderr, "Failed to connect to session bus:", err)
os.Exit(1)
}
defer conn.Close()

ch := make(chan *dbus.Call, 10)

obj := conn.Object("com.github.guelfey.Demo", "/com/github/guelfey/Demo")
obj.Go("com.github.guelfey.Demo.Sleep", 0, ch, 5) // 5 seconds

nrAttempts := 3
isResponseReceived := false

for i := 1; i <= nrAttempts && !isResponseReceived; i++ {
fmt.Println("Waiting for response, attempt", i)

select {
case call := <-ch:
if call.Err != nil {
fmt.Fprintln(os.Stderr, "Failed to call Sleep method:", err)
os.Exit(1)
}
isResponseReceived = true
break

// Handle timeout here
case <-time.After(2 * time.Second):
fmt.Println("Timeout")
break
}
}

if isResponseReceived {
fmt.Println("Done!")
} else {
fmt.Fprintln(os.Stderr, "Timeout waiting for Sleep response")
}
}

0 comments on commit 800df89

Please sign in to comment.