-
-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathdbus.go
209 lines (173 loc) · 5.67 KB
/
dbus.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
// Copyright (c) 2024 Joshua Rich <[email protected]>
//
// This software is released under the MIT License.
// https://opensource.org/licenses/MIT
//revive:disable:max-public-structs
//go:generate go run golang.org/x/tools/cmd/stringer -type=dbusType -output busType_strings.go
package dbusx
import (
"context"
"errors"
"fmt"
"log/slog"
"os/user"
"github.com/godbus/dbus/v5"
"github.com/joshuar/go-hass-agent/internal/logging"
)
const (
SessionBus dbusType = iota // session
SystemBus // system
PropInterface = "org.freedesktop.DBus.Properties"
PropChangedSignal = PropInterface + ".PropertiesChanged"
loginBasePath = "/org/freedesktop/login1"
loginBaseInterface = "org.freedesktop.login1"
loginManagerInterface = loginBaseInterface + ".Manager"
listSessionsMethod = loginManagerInterface + ".ListSessions"
)
var (
ErrNoBus = errors.New("no D-Bus connection")
ErrNoBusCtx = errors.New("no D-Bus connection in context")
ErrNotPropChanged = errors.New("signal contents do not appear to represent changed properties")
ErrParseInterface = errors.New("could not parse interface name")
ErrParseNewProps = errors.New("could not parse changed properties")
ErrParseOldProps = errors.New("could not parse invalidated properties")
ErrNotValChanged = errors.New("signal contents do not appear to represent a value change")
ErrParseNewVal = errors.New("could not parse new value")
ErrParseOldVal = errors.New("could not parse old value")
ErrNoSessionPath = errors.New("could not determine session path")
ErrInvalidPath = errors.New("invalid D-Bus path")
ErrUnknownBus = errors.New("unknown bus")
)
var DbusTypeMap = map[string]dbusType{
"session": 0,
"system": 1,
}
type dbusType int
// Values represents a property value that changed. It contains the new and old
// values.
type Values[T any] struct {
New T
Old T
}
// Bus represents a particular D-Bus connection to either the system or session
// bus.
type Bus struct {
conn *dbus.Conn
traceLog func(msg string, args ...any)
busType dbusType
}
func (b *Bus) getObject(intr, path string) dbus.BusObject {
return b.conn.Object(intr, dbus.ObjectPath(path))
}
// NewBus creates a D-Bus connection to the requested bus. If a connection
// cannot be established, an error is returned.
//
//nolint:sloglint
func NewBus(ctx context.Context, busType dbusType) (*Bus, error) {
var (
conn *dbus.Conn
err error
)
// Connect to the requested bus.
switch busType {
case SessionBus:
conn, err = dbus.ConnectSessionBus(dbus.WithContext(ctx))
case SystemBus:
conn, err = dbus.ConnectSystemBus(dbus.WithContext(ctx))
default:
return nil, ErrUnknownBus
}
// If the connection fails, we bails.
if err != nil {
return nil, fmt.Errorf("could not connect to bus: %w", err)
}
// Set up our bus object.
bus := &Bus{
conn: conn,
busType: busType,
traceLog: func(msg string, args ...any) {
slog.With(slog.String("subsystem", "dbus"), slog.String("bus", busType.String())).
Log(ctx, logging.LevelTrace, msg, args...)
},
}
// Start a goroutine to close the connection when the context is canceled
// (i.e. agent shutdown).
go func() {
defer conn.Close()
<-ctx.Done()
}()
return bus, nil
}
// GetData fetches data using the given method from D-Bus, as the provided type.
// If there is an error or the result cannot be stored in the given type, it
// will return an non-nil error. To execute a method, see Call. To get the value
// of a property, see GetProp.
func GetData[D any](bus *Bus, path, dest, method string, args ...any) (D, error) {
var (
data D
err error
)
bus.traceLog("Getting data.", slog.String("path", path), slog.String("dest", dest), slog.String("method", method))
obj := bus.getObject(dest, path)
if args != nil {
err = obj.Call(method, 0, args...).Store(&data)
} else {
err = obj.Call(method, 0).Store(&data)
}
if err != nil {
return data, fmt.Errorf("%s: unable to get data %s from %s: %w", bus.busType.String(), method, dest, err)
}
return data, nil
}
func (b *Bus) GetSessionPath() (string, error) {
usr, err := user.Current()
if err != nil {
return "", fmt.Errorf("unable to determine user: %w", err)
}
sessions, err := GetData[[][]any](b, loginBasePath, loginBaseInterface, listSessionsMethod)
if err != nil {
return "", fmt.Errorf("unable to retrieve session path: %w", err)
}
for _, s := range sessions {
if thisUser, ok := s[2].(string); ok && thisUser == usr.Username {
if p, ok := s[4].(dbus.ObjectPath); ok {
return string(p), nil
}
}
}
return "", ErrNoSessionPath
}
// ParseValueChange treats the given signal body as matching a value change of a
// property from an old value to a new value. It will parse the signal body into
// a Value object with old/new values of the given type. If there was a problem
// parsing the signal body, an error will be returned with details of the
// problem.
//
//nolint:mnd
func ParseValueChange[T any](valueChanged []any) (*Values[T], error) {
values := &Values[T]{}
var ok bool
if len(valueChanged) != 2 {
return nil, ErrNotValChanged
}
values.New, ok = valueChanged[0].(T)
if !ok {
return nil, ErrParseNewVal
}
values.Old, ok = valueChanged[1].(T)
if !ok {
return nil, ErrParseOldVal
}
return values, nil
}
// VariantToValue converts a dbus.Variant value into the specified Go type. If
// the value is nil or it cannot be converted, then the return value will be the
// default value of the specified type.
func VariantToValue[S any](variant dbus.Variant) (S, error) {
var value S
err := variant.Store(&value)
if err != nil {
return value, fmt.Errorf("unable to convert D-Bus variant %v to type %T: %w", variant, value, err)
}
return value, nil
}