-
Notifications
You must be signed in to change notification settings - Fork 15
/
dbus-listener.js
360 lines (318 loc) · 10.6 KB
/
dbus-listener.js
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
const dbus = require('dbus-native')
const _ = require('lodash')
const camelcase = require('camelcase')
module.exports = function (app, messageCallback, address, plugin, pollInterval) {
return new Promise((resolve, reject) => {
const setPluginStatus = app.setPluginStatus
? (msg) => {
app.setPluginStatus(msg)
}
: () => {}
const setPluginError = app.setPluginError
? (msg) => {
app.setPluginError(msg)
}
: () => {}
let msg = `Connecting ${address}`
setPluginStatus(msg)
app.debug(msg)
var bus
if (address) {
bus = dbus.createClient({
busAddress: address,
authMethods: ['ANONYMOUS']
})
} else {
bus = process.env.DBUS_SESSION_BUS_ADDRESS
? dbus.sessionBus()
: dbus.systemBus()
}
if (!bus) {
let msg = 'Could not connect to the D-Bus'
setPluginError(msg)
throw new Error(msg)
}
// Dict that lists the services on D-Bus that we track.
// name owner (:0132 for example) is the key. Properties:
// .name for example: com.victronenergy.battery.ttyO1
// .deviceInstace for example: 0
var services = {}
// get info on all existing D-Bus services at startup
bus.listNames((props, args) => {
args.forEach(name => {
if (name.startsWith('com.victronenergy')) {
bus.getNameOwner(name, (props, args) => {
initService(args, name)
})
}
})
})
function pollDbus () {
_.values(services).forEach(service => {
requestRoot(service)
})
}
function initService (owner, name) {
var service = { name: name }
services[owner] = service
app.debug(`${name} is sender ${owner}`)
bus.invoke(
{
path: '/DeviceInstance',
destination: name,
interface: 'com.victronenergy.BusItem',
member: 'GetValue'
},
function (err, res) {
if (err) {
// There are several dbus services that don't have the /DeviceInstance
// path. They are services that are not interesting for signalk, like
// a process to manage settings on the dbus, the logger to VRM Portal
// and others. All services that send out data for connected devices do
// have the /DeviceInstance path.
if ( services[owner] ) {
app.debug(`warning: error getting device instance for ${name}`)
services[owner].deviceInstance = 99
}
} else {
services[owner].deviceInstance = res[1][0]
}
if ( plugin.options.useDeviceNames !== undefined &&
plugin.options.useDeviceNames ) {
app.debug('requesting custom name for %s', name)
bus.invoke(
{
path: '/CustomName',
destination: name,
interface: 'com.victronenergy.BusItem',
member: 'GetValue'
},
function (err, res) {
if (!err) {
let customName = res[1][0]
app.debug('got custom name %s for %s', customName, name)
services[owner].customName = camelcase(customName)
} else {
services[owner].customName = ''
}
requestRoot(service)
})
} else {
requestRoot(service)
}
}
)
}
function requestRoot (service) {
// app.debug(`getValue / ${service.name}`)
bus.invoke(
{
path: '/',
destination: service.name,
interface: 'com.victronenergy.BusItem',
member: 'GetValue'
},
function (err, res) {
if (err) {
// Some services don't support requesting the root path. They are not
// interesting to signalk, see above in the comments on /DeviceInstance
app.debug(
`warning: error during GetValue on / for ${service.name} ${err}`
)
} else {
var data = {}
res[1][0].forEach(kp => {
data[kp[0]] = kp[1][1][0]
})
service.deviceInstance = data.DeviceInstance
if (!_.isUndefined(data.FluidType)) {
service.fluidType = data.FluidType
}
if (!_.isUndefined(data.TemperatureType)) {
service.temperatureType = data.TemperatureType
}
// app.debug(`${service.name} ${JSON.stringify(data)}`)
let deviceInstance
/*
//FIXME: paths that don't require instance??
if ( _.isUndefined(deviceInstance) ) {
return
}
*/
if ( plugin.options.instanceMappings ) {
const mapping = plugin.options.instanceMappings.find(mapping => {
return service.name.startsWith(mapping.type) && mapping.venusId == service.deviceInstance
})
if ( !_.isUndefined(mapping) ) {
deviceInstance = mapping.signalkId
}
}
if ( deviceInstance === undefined )
{
if ( plugin.options.useDeviceNames !== undefined && plugin.options.useDeviceNames && service.customName !== '' ) {
deviceInstance = service.customName
}
else
deviceInstance = service.deviceInstance
}
var messages = []
_.keys(data).forEach(path => {
messages.push({
path: '/' + path,
senderName: service.name,
value: data[path],
instanceName: deviceInstance,
fluidType: service.fluidType,
temperatureType: service.temperatureType
})
})
messageCallback(messages)
}
}
)
}
function signal_receive (m) {
if (
m.interface === 'com.victronenergy.BusItem'
&& (m.member === 'PropertiesChanged' || m.member === 'ItemsChanged')
) {
properties_changed(m)
} else if (
m.interface == 'org.freedesktop.DBus' &&
m.member == 'NameOwnerChanged'
) {
name_owner_changed(m)
}
}
function name_owner_changed (m) {
name = m.body[0]
old_owner = m.body[1]
new_owner = m.body[2]
app.debug('name owner change: %j', m)
if (name.startsWith('com.victronenergy') && new_owner && new_owner.length > 0 ) {
initService(new_owner, name)
} else {
delete services[old_owner]
}
}
function setValueAndText(data, res) {
data.forEach(entry => {
if (entry[0] == 'Text') {
res.text = entry[1][1][0]
} else if (entry[0] == 'Value') {
res.value = entry[1][1][0]
}
})
return res
}
function properties_changed (m) {
// Message contents:
// { serial: 5192,
// path: '/Dc/0/Power',
// interface: 'com.victronenergy.BusItem',
// member: 'PropertiesChanged',
// signature: 'a{sv}',
// sender: ':1.104',
// type: 4,
// flags: 1,
// body: [ [ [Object], [Object] ] ]}
const sender = m.sender
var service = services[sender]
if (!service || !service.name || typeof service.deviceInstance === 'undefinded' ) {
// See comment above explaining why some services don't have the
// /DeviceInstance path
// app.debug(`warning: unknown service; ${m.sender}`)
return
}
const senderName = service.name
let instanceName
if ( plugin.options.instanceMappings ) {
const mapping = plugin.options.instanceMappings.find(mapping => {
return service.name.startsWith(mapping.type) && mapping.venusId == service.deviceInstance
})
if ( !_.isUndefined(mapping) ) {
instanceName = mapping.signalkId
}
}
if ( instanceName === undefined )
{
if ( plugin.options.useDeviceNames !== undefined && plugin.options.useDeviceNames && service.customName !== '' ) {
instanceName = service.customName
}
else
instanceName = service.deviceInstance
}
let entries
if ( m.member === 'ItemsChanged' ) {
entries = m.body[0]
.map(item => {
return setValueAndText(item[1], { path: item[0] })
})
} else if ( m.member === 'PropertiesChanged' ) {
entries = [ setValueAndText(m.body[0], { path: m.path}) ]
}
entries.forEach(msg => {
msg.instanceName = instanceName
msg.senderName = senderName
})
messageCallback(entries)
}
function setValue (destination, path, value) {
app.debug(`setValue: ${destination} ${path} = ${value}`)
bus.invoke(
{
path: path,
destination: destination,
interface: 'com.victronenergy.BusItem',
member: 'SetValue',
body: [
// top level struct is js array
['n', value] // variant, type is number, value = 1
],
signature: 'v'
},
function (err, res) {
if (err) {
app.error(err)
}
}
)
}
bus.connection.on('connect', () => {
setPluginStatus(`Connected to ${address ? address : 'session bus'}`)
if ( pollInterval > 0 ) {
const pollingTimer = setInterval(pollDbus, pollInterval*1000)
resolve({
setValue,
onStop: () => {
clearInterval(pollingTimer)
}
})
}
})
// if resolved within timeout reject has no effect
setTimeout(() => reject('Timeout waiting for connection'), 10 * 1000)
bus.connection.on('message', signal_receive)
bus.connection.on('error', error => {
setPluginError(error.message)
app.error(error.message)
reject(error)
plugin.onError()
})
bus.connection.on('end', () => {
setPluginError('lost connection to D-Bus')
app.error(`lost connection to D-Bus`)
// here we could (should?) also clear the polling timer. But decided not to do that;
// to be looked at when properly fixing the dbus-connection lost issue.
})
bus.addMatch(
"type='signal',interface='com.victronenergy.BusItem',member='PropertiesChanged'",
d => {}
)
bus.addMatch(
"type='signal',interface='com.victronenergy.BusItem',member='ItemsChanged'",
d => {}
)
bus.addMatch("type='signal',member='NameOwnerChanged'", d => {})
})
}