-
Notifications
You must be signed in to change notification settings - Fork 32
/
index.js
executable file
·369 lines (336 loc) · 10.9 KB
/
index.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
361
362
363
364
365
366
367
368
369
/*
* Copyright 2017 Scott Bender <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const Bacon = require('baconjs')
const _ = require('lodash')
const path = require('path')
const fs = require('fs')
const defaultEngines = 'port, starboard'
const defaultBatteries = '0'
const defaultTanks = 'fuel.0, fuel.1'
const defaultAir = 'outside'
module.exports = function (app) {
var plugin = {}
var unsubscribes = []
var schema
var uiSchema
var calculations
plugin.start = function (props) {
plugin.properties = props
if (!plugin.properties.engine_instances) {
plugin.properties.engine_instances = defaultEngines
}
if (!plugin.properties.battery_instances) {
plugin.properties.battery_instances = defaultBatteries
}
if (!plugin.properties.tank_instances) {
plugin.properties.tank_instances = defaultTanks
}
if (!plugin.properties.air_instances) {
plugin.properties.air_instances = defaultAir
}
if (!plugin.properties.traffic.notificationZones) {
plugin.properties.traffic.notificationZones = []
}
updateOldTrafficConfig()
plugin.engines = plugin.properties.engine_instances
.split(',')
.map(e => e.trim())
plugin.batteries = plugin.properties.battery_instances
.split(',')
.map(e => e.trim())
plugin.tanks = plugin.properties.tank_instances
.split(',')
.map(e => e.trim())
plugin.air = plugin.properties.air_instances.split(',').map(e => e.trim())
calculations = load_calcs(app, plugin, 'calcs')
calculations = [].concat.apply([], calculations)
calculations.forEach(calculation => {
if (calculation.group) {
if (
!props[calculation.group] ||
!props[calculation.group][calculation.optionKey]
) {
return
}
} else if (!props[calculation.optionKey]) {
return
}
var derivedFrom
if (typeof calculation.derivedFrom === 'function') {
derivedFrom = calculation.derivedFrom()
} else derivedFrom = calculation.derivedFrom
var skip_function
if (
(typeof calculation.ttl !== 'undefined' && calculation.ttl > 0) ||
props.default_ttl > 0
) {
// app.debug("using skip")
skip_function = function (before, after) {
var tnow = new Date().getTime()
if (_.isEqual(before, after)) {
// values are equial, but should we emit the delta anyway.
// This protects from a sequence of changes that produce no change from
// generating events, but ensures events are still generated at
// a default rate. On Pi Zero W, the extra cycles reduce power consumption.
if (calculation.nextOutput > tnow) {
// console.log("Rejected dupilate ", calculation.nextOutput - tnow);
return true
}
// console.log("Sent dupilate ", calculation.nextOutput - tnow);
}
var ttl =
typeof calculation.ttl === 'undefined'
? props.default_ttl
: calculation.ttl
// app.debug("ttl: " + ttl, "def: " + props.default_ttl)
calculation.nextOutput = tnow + ttl * 1000
// console.log("New Value ----------------------------- ", before, after);
return false
}
} else {
skip_function = function (before, after) {
return false
}
}
const selfStreams = derivedFrom.map((key, index) => {
let stream
/*
if ( !_.isUndefined(calculation.allContexts) && calculation.allContexts ) {
stream = app.streambundle.getBus(key)
} else {
*/
stream = app.streambundle.getSelfStream(key)
/* } */
if (calculation.defaults && calculation.defaults[index] != undefined) {
stream = stream.merge(Bacon.once(calculation.defaults[index]))
}
return stream
}, app.streambundle)
unsubscribes.push(
Bacon.combineWith(calculation.calculator, selfStreams)
.changes()
.debounceImmediate(calculation.debounceDelay || 20)
.skipDuplicates(skip_function)
.onValue(values => {
if (typeof values !== 'undefined' && values.length > 0) {
if (values[0].context) {
values.forEach(delta => {
app.handleMessage(plugin.id, delta)
})
} else {
let delta = {
context: 'vessels.' + app.selfId,
updates: [
{
values: values
}
]
}
// app.debug("got delta: " + JSON.stringify(delta))
app.handleMessage(plugin.id, delta)
}
}
})
)
})
}
plugin.stop = function () {
unsubscribes.forEach(f => f())
unsubscribes = []
if (calculations) {
calculations.forEach(calc => {
if (calc.stop) {
calc.stop()
}
})
}
}
plugin.id = 'derived-data'
plugin.name = 'Derived Data'
plugin.description = 'Plugin that derives data'
plugin.schema = function () {
updateSchema()
return schema
}
plugin.uiSchema = function () {
updateSchema()
return uiSchema
}
function updateSchema () {
if (!calculations) {
plugin.engines = defaultEngines.split(',').map(e => e.trim())
plugin.batteries = defaultBatteries.split(',').map(e => e.trim())
plugin.tanks = defaultTanks.split(',').map(e => e.trim())
plugin.air = defaultAir.split(',').map(e => e.trim())
calculations = load_calcs(app, plugin, 'calcs')
calculations = [].concat.apply([], calculations)
}
schema = {
title: 'Derived Data',
type: 'object',
properties: {
default_ttl: {
title: 'Default TTL',
type: 'number',
description:
"The plugin won't send out duplicate calculation values for this time period (s) (0=no ttl check)",
default: 0
},
engine_instances: {
title: 'Engines',
type: 'string',
description: 'Comma delimited list of available engines',
default: defaultEngines
},
battery_instances: {
title: 'Batteries',
type: 'string',
description: 'Comma delimited list of available batteries',
default: defaultBatteries
},
tank_instances: {
title: 'Tanks',
type: 'string',
description: 'Comma delimited list of available tanks',
default: defaultTanks
},
air_instances: {
title: 'Air',
type: 'string',
description: 'Comma delimited list of available air areas',
default: defaultAir
}
}
}
uiSchema = {
'ui:order': [
'default_ttl',
'engine_instances',
'battery_instances',
'tank_instances',
'air_instances'
]
}
var groups = {}
calculations.forEach(calc => {
var groupName
if (typeof calc.group !== 'undefined') {
groupName = calc.group
} else {
groupName = 'nogroup'
}
if (!groups[groupName]) {
groups[groupName] = []
}
let title = calc.title
title += ' ['
const derivedFrom =
typeof calc.derivedFrom === 'function'
? calc.derivedFrom()
: calc.derivedFrom
title += derivedFrom
.map(path => `${path}${app.getSelfPath(path) ? '(👍)' : '(-)'}`)
.join(', ')
title += ']'
groups[groupName].push({ ...calc, title })
})
if (groups.nogroup) {
groups.nogroup.forEach(calc => {
uiSchema['ui:order'].push(calc.optionKey)
schema.properties[calc.optionKey] = {
title: calc.title,
type: 'boolean',
default: false
}
if (calc.properties) {
var props =
typeof calc.properties === 'function'
? calc.properties()
: calc.properties
_.extend(schema.properties, props)
}
})
}
_.keys(groups).forEach(groupName => {
if (groupName != 'nogroup') {
uiSchema['ui:order'].push(groupName)
uiSchema[groupName] = {
'ui:order': [],
'ui:field': 'collapsible',
collapse: {
field: 'ObjectField',
wrapClassName: 'panel-group'
}
}
var group = {
title: groupName.charAt(0).toUpperCase() + groupName.slice(1),
type: 'object',
properties: {}
}
groups[groupName].forEach(calc => {
var order = uiSchema[groupName]['ui:order']
order.push(calc.optionKey)
group.properties[calc.optionKey] = {
title: calc.title,
type: 'boolean',
default: false
}
if (calc.properties) {
var props =
typeof calc.properties === 'function'
? calc.properties()
: calc.properties
_.extend(group.properties, props)
_.keys(props).forEach(key => {
order.push(key)
})
}
})
schema.properties[groupName] = group
}
})
// app.debug('schema: ' + JSON.stringify(schema, null, 2))
// app.debug('uiSchema: ' + JSON.stringify(uiSchema, null, 2))
}
function updateOldTrafficConfig () {
if (
!_.isUndefined(plugin.properties.traffic.notificationRange) ||
!_.isUndefined(plugin.properties.traffic.notificationTimeLimit)
) {
plugin.properties.traffic.notificationZones.push({
range: plugin.properties.traffic.notificationRange || 1852,
timeLimit: plugin.properties.traffic.notificationTimeLimit || 600,
level: 'alert',
active: plugin.properties.traffic.sendNotifications
})
delete plugin.properties.traffic.notificationRange
delete plugin.properties.traffic.notificationTimeLimit
app.savePluginOptions(plugin.properties)
}
}
return plugin
}
function load_calcs (app, plugin, dir) {
fpath = path.join(__dirname, dir)
files = fs.readdirSync(fpath)
return files
.map(fname => {
pgn = path.basename(fname, '.js')
return require(path.join(fpath, pgn))(app, plugin)
})
.filter(calc => {
return typeof calc !== 'undefined'
})
}