-
Notifications
You must be signed in to change notification settings - Fork 2
/
filter.coffee
436 lines (371 loc) · 13.9 KB
/
filter.coffee
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
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
module.exports = (env) ->
events = require 'events'
Promise = env.require 'bluebird'
types = env.require('decl-api').types
assert = env.require 'cassert'
M = env.matcher
_ = env.require('lodash')
commons = require('pimatic-plugin-commons')(env)
class AttributeContainer extends events.EventEmitter
constructor: () ->
@values = {}
class FilterPlugin extends env.plugins.Plugin
init: (app, @framework, @config) =>
@debug = @config.debug || false
deviceConfigDef = require("./device-config-schema")
@framework.deviceManager.registerDeviceClass("SimpleMovingAverageFilter", {
configDef: deviceConfigDef.SimpleMovingAverageFilter,
createCallback: (config, lastState) =>
return new SimpleMovingAverageFilter(config, lastState)
})
@framework.deviceManager.registerDeviceClass("SimpleTruncatedMeanFilter", {
configDef: deviceConfigDef.SimpleTruncatedMeanFilter,
createCallback: (config, lastState) =>
return new SimpleTruncatedMeanFilter(config, lastState)
})
@framework.deviceManager.registerDeviceClass("SimpleRateOfChangeFilter", {
configDef: deviceConfigDef.SimpleRateOfChangeFilter,
createCallback: (config, lastState) =>
return new SimpleRateOfChangeFilter(config, lastState)
})
@framework.ruleManager.addActionProvider(new FilterActionProvider @framework, @config)
plugin = new FilterPlugin
class FilterBase extends env.devices.Device
actions:
resetStats:
description: "Resets the stats attribute values"
statsAttributeTemplates:
source:
description: "Source value"
type: types.number
acronym: 'src'
unit: 'source'
min:
description: "Minimum value"
type: types.number
acronym: 'min'
unit: 'source'
max:
description: "Maximum value"
type: types.number
acronym: 'max'
unit: 'source'
mean:
description: "Mean value"
type: types.number
acronym: 'mean'
unit: 'source'
increase:
description: "Increase"
type: types.number
acronym: 'inc'
unit: 'source'
percentChange:
description: "Percentage change"
type: types.number
acronym: 'pc'
unit: '%'
math:
source: (values) -> unless values.length is 0 then values[values.length - 1] else Infinity
min: (values) -> Math.min.apply @, values
max: (values) -> Math.max.apply @, values
mean: (values) ->
# arithmetic mean, also referred to as the average
unless values.length is 0
values.reduce((a, b) -> a + b) / values.length
else
Infinity
increase: (values) =>
result = Infinity
unless values.length is 0
if @_previousValueIncrease?
value = values[values.length - 1]
result = value - @_previousValueIncrease
@_previousValueIncrease = value
else
@_previousValueIncrease = values[values.length - 1]
result = 0.0
return result
percentChange: (values) =>
result = Infinity
unless values.length is 0
if @_previousValuePercentChange?
value = values[values.length - 1]
result = 100 * (value - @_previousValuePercentChange) / @_previousValuePercentChange
@_previousValuePercentChange = value
else
@_previousValuePercentChange = values[values.length - 1]
result = 0.0
return result
constructor: (@config, lastState) ->
@attributes = _.cloneDeep(@attributes)
@statsAttributeValues = new AttributeContainer()
@debug = plugin.debug || false
@base = commons.base @, @config.class
@output = @config.output
@inputValue = 0
@varManager = plugin.framework.variableManager #so you get the variableManager
@_exprChangeListeners = []
@_updateTimerId = null
if @config.timeBasedUpdates
switch @config.updateScale
when 'days' then @_updateTimeout = @config.updateInterval * 86400000
when 'hours' then @_updateTimeout = @config.updateInterval * 3600000
when 'minutes' then @_updateTimeout = @config.updateInterval * 60000
when 'seconds' then @_updateTimeout = @config.updateInterval * 1000
else @_updateTimeout = @config.updateInterval * 1000
else
@_updateTimeout = 0
name = @output.name
@outputAttributeValue = if lastState?[name]? then lastState[name].value else null
@attributes = _.cloneDeep(@attributes)
@attributes[name] = {
description: name
label: (if @output.label? then @output.label else "#{name}")
type: "number"
}
if @output.unit? and @output.unit.length > 0
unless @output.unit is 'auto'
@attributes[name].unit = @output.unit
else
@_deferredUpdate () =>
info = @varManager.parseVariableExpression(@output.expression)
unit = @varManager.inferUnitOfExpression(info.tokens)
unit += '/' + @timeBase if unit? and @timeBase?
@attributes[@output.name].unit = unit
if @output.discrete?
@attributes[name].discrete = @output.discrete
if @output.acronym?
@attributes[name].acronym = @output.acronym
@_createGetter(name, =>
return Promise.resolve @outputAttributeValue
)
# initialize stats attributes
for attributeName in @config.stats
do (attributeName) =>
if _.has @statsAttributeTemplates, attributeName
properties = @statsAttributeTemplates[attributeName]
@attributes[attributeName] =
description: properties.description
type: properties.type
acronym: properties.acronym if properties.acronym?
if properties.unit?
if properties.unit isnt 'source'
@attributes[attributeName].unit = properties.unit
else
@_deferredUpdate () =>
info = @varManager.parseVariableExpression(@output.expression)
sourceUnit = @varManager.inferUnitOfExpression(info.tokens)
@attributes[attributeName].unit = sourceUnit
defaultValue = null # if properties.type is types.number then 0.0 else '-'
@statsAttributeValues.values[attributeName] = lastState?[attributeName]?.value or defaultValue
@statsAttributeValues.on attributeName, ((value) =>
@base.debug "Received update for attribute #{attributeName}: #{value}"
@statsAttributeValues.values[attributeName] = value
@emit attributeName, if value? then value else 0
)
@_createGetter(attributeName, =>
return Promise.resolve @statsAttributeValues.values[attributeName]
)
else
@base.error "Configuration Error. No such attribute: #{attributeName} - skipping."
@resetStatsHandler = (device) =>
if device.id is @.id
@base.debug "Device has changed - resetting stats"
@resetStats()
@_previousValuePercentChange = null
@_previousValueIncrease = null
plugin.framework.once 'deviceChanged', @resetStatsHandler
super()
destroy: () ->
plugin.framework.removeListener 'deviceChanged', @resetStatsHandler
@varManager.cancelNotifyOnChange(cl) for cl in @_exprChangeListeners
clearTimeout @_updateTimerId if @_updateTimerId?
super()
_registerUpdateHandler: (updateHandler) ->
update = () =>
# wait till VariableManager is ready
return @varManager.waitForInit().then( =>
unless @_info?
@_info = @varManager.parseVariableExpression(@output.expression)
if @_updateTimeout is 0
@varManager.notifyOnChange(@_info.tokens, update)
@_exprChangeListeners.push update
unless @_updateTimeout is 0
@_updateTimerId = setTimeout update, @_updateTimeout
switch @_info.datatype
when "numeric" then @varManager.evaluateNumericExpression(@_info.tokens)
when "string" then @varManager.evaluateStringExpression(@_info.tokens)
else
assert false
).then((val) =>
return updateHandler(val)
).catch((error) =>
@base.error "Error on device #{@config.id}:", error.message
)
update()
_setAttribute: (attributeName, value) ->
@outputAttributeValue = value
@emit attributeName, value
_updateStats: (val) ->
@inputValue = val if val?
for own key of @statsAttributeValues.values
v = @statsAttributeValues.values[key]
result = @math[key] if v? then [v, val] else [val]
@statsAttributeValues.emit key, result
_deferredUpdate: (update) ->
if @varManager.inited
update()
else
@varManager.waitForInit().then => update()
_getNumber: (value) ->
if value?
numValue = Number value
unless isNaN numValue
return numValue
else
errorMessage = "Input value is not a number: #{value}"
else
errorMessage = "Input value is null or undefined"
throw new Error errorMessage
resetStats: () ->
for own key of @statsAttributeValues.values
@statsAttributeValues.emit key, null unless key is 'src'
@statsAttributeValues.emit key, @inputValue
Promise.resolve()
class SimpleMovingAverageFilter extends FilterBase
constructor: (@config, lastState) ->
@id = @config.id
@name = @config.name
@size = @config.size
@filterValues = []
@sum = 0.0
@mean = 0.0
@math.mean = () => @mean
super(@config, lastState)
@_registerUpdateHandler((val) =>
val = @_getNumber(val)
@filterValues.push val
@sum = @sum + val
if @filterValues.length > @size
@sum = @sum - @filterValues.shift()
@mean = @sum / @filterValues.length
@_setAttribute @output.name, @mean
@_updateStats val
return @outputAttributeValue
)
destroy: () ->
super()
class SimpleTruncatedMeanFilter extends FilterBase
constructor: (@config, lastState) ->
@id = @config.id
@name = @config.name
@size = @config.size
@filterValues = []
@mean = 0.0
@math.mean = () => @mean
super(@config, lastState)
@_registerUpdateHandler((val) =>
val = @_getNumber(val)
@filterValues.push val
if @filterValues.length > @size
@filterValues.shift()
processedValues = _.clone(@filterValues)
if processedValues.length > 2
processedValues.sort()
processedValues.shift()
processedValues.pop()
@mean = processedValues.reduce(((a, b) => return a + b), 0) / processedValues.length
@_setAttribute @output.name, @mean
@_updateStats val
return @outputAttributeValue
)
destroy: () ->
super()
class SimpleRateOfChangeFilter extends FilterBase
constructor: (@config, lastState) ->
@id = @config.id
@name = @config.name
@size = @config.size
@timeBase = @config.timeBase
@scale = @config.scale
@previousValue = 0.0
@previousTime = 0
@rateOfChange = 0.0
super(@config, lastState)
@_registerUpdateHandler((val) =>
val = @_getNumber(val)
time = new Date()
switch @timeBase
when "second" then time /= 1000
when "minute" then time /= 60000
when "hour" then time /= 3600000
valDifference = val - @previousValue
timeDifference = time - @previousTime
@rateOfChange = valDifference / timeDifference
@base.debug "name: #{@name}"
@base.debug "output attribute: #{@output.name}"
@base.debug "valDifference: #{valDifference}"
@base.debug "timeDifference: #{timeDifference}"
@base.debug "rateOfChange: #{@rateOfChange}"
@base.debug "@previousTime: #{@previousTime}"
unless @previousTime is 0
#we skip the first update because we don't have previous values yet
@_setAttribute @output.name, @rateOfChange
@_updateStats val
@previousTime = time
@previousValue = val
return @outputAttributeValue
)
destroy: () ->
super()
class FilterActionProvider extends env.actions.ActionProvider
constructor: (@framework) ->
parseAction: (input, context) =>
filterDevices = _(@framework.deviceManager.devices).values().filter(
(device) => (
device.hasAction("resetStats")
)
).value()
device = null
action = null
match = null
m = M(input, context).match(['reset '], (m, a) =>
m.matchDevice(filterDevices, (m, d) ->
last = m.match(' stats', {optional: yes})
if last.hadMatch()
# Already had a match with another device?
if device? and device.id isnt d.id
context?.addError(""""#{input.trim()}" is ambiguous.""")
return
device = d
action = a.trim()
match = last.getFullMatch()
)
)
if match?
assert device?
assert action in ['reset']
assert typeof match is "string"
return {
token: match
nextInput: input.substring(match.length)
actionHandler: new FilterActionHandler(device)
}
return null
class FilterActionHandler extends env.actions.ActionHandler
constructor: (@device) ->
setup: ->
@dependOnDevice(@device)
super()
# ### executeAction()
executeAction: (simulate) =>
return (
if simulate
Promise.resolve __("would reset %s", @device.name)
else
@device.resetStats().then( => __("reset %s", @device.name) )
)
# ### hasRestoreAction()
hasRestoreAction: -> false
return plugin