-
Notifications
You must be signed in to change notification settings - Fork 3
/
dbuscommon.go
320 lines (274 loc) · 8.06 KB
/
dbuscommon.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
// Package dbuscommon provides a common dbus server and client base to extend.
package dbuscommon
import (
"github.com/godbus/dbus"
"github.com/godbus/dbus/introspect"
"github.com/godbus/dbus/prop"
"github.com/sqp/godock/libs/cdtype" // Logger type.
"errors"
"fmt"
"reflect"
)
//
//------------------------------------------------------------------[ CLIENT ]--
// NewError creates a dbus error.
//
func NewError(msg string) *dbus.Error {
return dbus.NewError("org.freedesktop.DBus.Error.Failed", []interface{}{msg})
}
// Client is a Dbus client to connect to the internal Dbus server.
//
type Client struct {
dbus.BusObject
srvObj string
testErr func(e error, method string)
}
// GetClient return a connection to the active instance of the internal Dbus
// service if any. Return nil, nil if none found.
// InterfacePath is an optional string to provide if the object use an interface
// path different from SrvObj
//
func GetClient(SrvObj, SrvPath string, InterfacePath ...string) (*Client, error) {
conn, ec := dbus.SessionBus()
if ec != nil {
return nil, ec
}
reply, e := conn.RequestName(SrvObj, dbus.NameFlagDoNotQueue)
if e != nil {
return nil, e
}
conn.ReleaseName(SrvObj)
if reply == dbus.RequestNameReplyPrimaryOwner { // no active instance.
return nil, errors.New("no service found")
}
if len(InterfacePath) == 0 { // Set default interface path = object name.
InterfacePath = []string{SrvObj}
}
// Found active instance, return client.
return &Client{
BusObject: conn.Object(SrvObj, dbus.ObjectPath(SrvPath)),
srvObj: InterfacePath[0],
testErr: func(e error, method string) {},
}, nil
}
// Call calls a method on a Dbus object.
//
func (cl *Client) Call(method string, args ...interface{}) error {
e := cl.BusObject.Call(cl.srvObj+"."+method, 0, args...).Err
cl.testErr(e, method)
return e
}
// Get calls a method on a Dbus object with returned values.
// The list of answers has to be provided before the command arguments.
// The type of each field in answer must be a pointer to a value of the same
// type as expected to be returned by the Dbus method called (its go version).
//
func (cl *Client) Get(method string, answers []interface{}, args ...interface{}) error {
var e error
defer cl.testErr(e, method)
call := cl.BusObject.Call(cl.srvObj+"."+method, 0, args...)
if call.Err != nil {
e = call.Err
return e
}
if len(call.Body) == 0 {
e = errors.New("no data received")
return e
}
if len(call.Body) != len(answers) {
e = fmt.Errorf("size mismatch, need %d found %d", len(call.Body), len(answers))
return e
}
for i := range call.Body {
e = parseShit(call.Body[i], answers[i])
if e != nil {
return e
}
}
return nil
}
func parseShit(src, dest interface{}) error {
switch v := src.(type) {
case string, []byte, []string:
reflect.ValueOf(dest).Elem().Set(reflect.ValueOf(v))
case dbus.Variant:
tmp := v.Value()
if reflect.TypeOf(dest).Elem() != reflect.TypeOf(tmp) {
fmt.Printf("bad type may crash %T to %T\n", v, dest)
}
reflect.ValueOf(dest).Elem().Set(reflect.ValueOf(tmp))
case []dbus.Variant:
tmp := make([]interface{}, len(v))
for i, val := range v {
tmp[i] = val.Value()
}
reflect.ValueOf(dest).Elem().Set(reflect.ValueOf(tmp))
case map[string]dbus.Variant:
_, ok := dest.(*map[string]interface{})
if !ok {
return errors.New("bad dest type, need *map[string]interface{}")
}
tmp := ToMapInterface(v)
reflect.ValueOf(dest).Elem().Set(reflect.ValueOf(tmp))
case []map[string]dbus.Variant:
tmp := make([]map[string]interface{}, len(v))
for i, val := range v {
tmp[i] = ToMapInterface(val)
}
reflect.ValueOf(dest).Elem().Set(reflect.ValueOf(tmp))
default:
return fmt.Errorf("unknown dest type, %T to %T", v, dest)
}
return nil
}
// Go calls a method on a Dbus object without waiting for an answer.
//
func (cl *Client) Go(method string, args ...interface{}) error {
e := cl.BusObject.Go(cl.srvObj+"."+method, dbus.FlagNoReplyExpected, nil, args...).Err
cl.testErr(e, method)
return e
}
// SetTestErr sets a test error function.
//
func (cl *Client) SetTestErr(testErr func(e error, method string)) {
cl.testErr = testErr
}
//
//------------------------------------------------------------------[ SERVER ]--
// Server is a Dbus server with applets service management.
//
type Server struct {
Conn *dbus.Conn // Dbus connection.
Events <-chan *dbus.Signal // Dbus incoming signals channel.
Log cdtype.Logger
srvObj string
srvPath string
}
// NewServer creates a Dbus service.
//
func NewServer(srvObj, srvPath string, log cdtype.Logger) *Server {
conn, c, e := SessionBus()
if log.Err(e, "DBus Connect") {
return nil
}
load := &Server{
Conn: conn,
Events: c,
Log: log,
srvObj: srvObj,
srvPath: srvPath,
}
return load
}
// Find this doc location
// Start will try to start and manage the applets server.
// You must provide the applet arguments used to launch the applet.
// If a server was already active, the applet start request is forwarded and
// no loop will be started, the function just return with the error if any.
//
// Start starts the DBus service with the given object.
// Introspection will be managed and the provided properties exposed.
// Methods will also be auto discovered.
//
func (load *Server) Start(obj interface{}, propsSpec map[string]map[string]*prop.Prop) (bool, error) {
reply, e := load.Conn.RequestName(load.srvObj, dbus.NameFlagDoNotQueue)
if e != nil {
return false, e
}
if reply != dbus.RequestNameReplyPrimaryOwner {
return false, nil
}
// Everything OK, we can register our Dbus methods.
e = load.Conn.Export(obj, dbus.ObjectPath(load.srvPath), load.srvObj)
if load.Log.Err(e, "register service object") {
return false, e
}
introNode := load.Introspect(obj, propsSpec)
e = load.Conn.Export(introspect.NewIntrospectable(introNode), dbus.ObjectPath(load.srvPath), "org.freedesktop.DBus.Introspectable")
if load.Log.Err(e, "register service introspect") {
return false, e
}
return true, nil
}
// Introspect provides introspection data for the DBus service to start.
//
// propsSpec example:
//
// var propsSpec = map[string]map[string]*prop.Prop{
// SrvObj: {
// "Restart": {
// int32(0),
// true,
// prop.EmitTrue,
// func(c *prop.Change) *dbus.Error {
// fmt.Println(c.Name, "changed to", c.Value)
// return nil
// },
// },
// },
// }
//
func (load *Server) Introspect(obj interface{}, propsSpec map[string]map[string]*prop.Prop) *introspect.Node {
var props []introspect.Property
if propsSpec != nil {
tmp := prop.New(load.Conn, dbus.ObjectPath(load.srvPath), propsSpec)
props = tmp.Introspection(load.srvObj)
}
return &introspect.Node{
Name: load.srvPath,
Interfaces: []introspect.Interface{
prop.IntrospectData,
{
Name: load.srvObj,
Methods: introspect.Methods(obj),
Properties: props,
},
},
}
}
//
//------------------------------------------------------------------[ COMMON ]--
// SessionBus creates a Dbus session with a listening chan.
//
func SessionBus() (*dbus.Conn, chan *dbus.Signal, error) {
conn, e := dbus.SessionBus()
if e != nil {
return nil, nil, e
}
c := make(chan *dbus.Signal, 10)
conn.Signal(c)
return conn, c, nil
}
// EavesDrop registers to receive Dbus events for custom parsing.
//
func EavesDrop(match string) (chan *dbus.Message, error) {
conn, e := dbus.SessionBus()
if e != nil {
return nil, e
}
e = conn.BusObject().Call("org.freedesktop.DBus.AddMatch", 0, match).Err
if e != nil {
return nil, e
}
c := make(chan *dbus.Message, 10)
conn.Eavesdrop(c)
return c, nil
}
// ToMapVariant recasts a list of args to map[string]dbus.Variant as requested by the DBus API.
//
func ToMapVariant(input map[string]interface{}) map[string]dbus.Variant {
vars := make(map[string]dbus.Variant)
for k, v := range input {
vars[k] = dbus.MakeVariant(v)
}
return vars
}
// ToMapInterface recasts a map of dbus.Variant to a map of interface.
//
func ToMapInterface(input map[string]dbus.Variant) map[string]interface{} {
out := make(map[string]interface{}, len(input))
for i, v := range input {
out[i] = v.Value()
}
return out
}