Skip to content

Commit a37d5dd

Browse files
authored
Merge pull request #325 from ivanteterevkov/master
examples: Add asynchronous D-Bus call example
2 parents d17bd42 + 800df89 commit a37d5dd

File tree

2 files changed

+61
-0
lines changed

2 files changed

+61
-0
lines changed

_examples/server.go

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ package main
33
import (
44
"fmt"
55
"os"
6+
"time"
67

78
"github.com/godbus/dbus/v5"
89
"github.com/godbus/dbus/v5/introspect"
@@ -14,6 +15,9 @@ const intro = `
1415
<method name="Foo">
1516
<arg direction="out" type="s"/>
1617
</method>
18+
<method name="Sleep">
19+
<arg direction="in" type="u"/>
20+
</method>
1721
</interface>` + introspect.IntrospectDataString + `</node> `
1822

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

30+
func (f foo) Sleep(seconds uint) *dbus.Error {
31+
fmt.Println("Sleeping", seconds, "second(s)")
32+
time.Sleep(time.Duration(seconds) * time.Second)
33+
return nil
34+
}
35+
2636
func main() {
2737
conn, err := dbus.ConnectSessionBus()
2838
if err != nil {

_examples/timeout.go

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,51 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"os"
6+
"time"
7+
8+
"github.com/godbus/dbus/v5"
9+
)
10+
11+
func main() {
12+
conn, err := dbus.ConnectSessionBus()
13+
if err != nil {
14+
fmt.Fprintln(os.Stderr, "Failed to connect to session bus:", err)
15+
os.Exit(1)
16+
}
17+
defer conn.Close()
18+
19+
ch := make(chan *dbus.Call, 10)
20+
21+
obj := conn.Object("com.github.guelfey.Demo", "/com/github/guelfey/Demo")
22+
obj.Go("com.github.guelfey.Demo.Sleep", 0, ch, 5) // 5 seconds
23+
24+
nrAttempts := 3
25+
isResponseReceived := false
26+
27+
for i := 1; i <= nrAttempts && !isResponseReceived; i++ {
28+
fmt.Println("Waiting for response, attempt", i)
29+
30+
select {
31+
case call := <-ch:
32+
if call.Err != nil {
33+
fmt.Fprintln(os.Stderr, "Failed to call Sleep method:", err)
34+
os.Exit(1)
35+
}
36+
isResponseReceived = true
37+
break
38+
39+
// Handle timeout here
40+
case <-time.After(2 * time.Second):
41+
fmt.Println("Timeout")
42+
break
43+
}
44+
}
45+
46+
if isResponseReceived {
47+
fmt.Println("Done!")
48+
} else {
49+
fmt.Fprintln(os.Stderr, "Timeout waiting for Sleep response")
50+
}
51+
}

0 commit comments

Comments
 (0)