-
Notifications
You must be signed in to change notification settings - Fork 0
/
uavwatcher.js
94 lines (76 loc) · 2.07 KB
/
uavwatcher.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
'use strict';
var _ = require('lodash');
class UAVContainer {
constructor(identifier, value) {
this.identifier = identifier;
this.previousValues = [];
this.currentValue = {value: _.cloneDeep(value), timeFrom: new Date().getTime(), timeTo: null};
this.initialValue = _.cloneDeep(this.currentValue);
this.dirty = true;
}
lastUpdate() {
return this.currentValue.timeFrom;
}
update(val) {
var newValue = _.merge({}, this.currentValue.value, val);
if (_.isEqual(this.currentValue.value, newValue)) {
return;
}
this.currentValue.value = newValue;
this.dirty = true;
}
reset() {
this.update(this.initialValue.value);
}
forceDirty() {
this.dirty = true;
}
done() {
var value = _.cloneDeep(this.currentValue);
value.timeTo = new Date().getTime();
this.previousValues.push(value);
if (this.previousValues.length > 100) {
this.previousValues.shift();
}
this.currentValue.timeFrom = new Date().getTime();
this.currentValue.timeTo = null;
this.dirty = false;
}
}
class UAVWatcher {
constructor() {
this.containers = {};
}
// value is what you get from the payload.data field of an update
push(identifier, value) {
var container = this.containers[identifier];
if (container === undefined) {
container = new UAVContainer(identifier, value);
this.containers[identifier] = container;
} else {
container.update(value);
}
return container;
}
forEachDirty(fn) {
_.forEach(this.containers, function(container) {
if (container.dirty) {
fn(container);
}
});
}
getInitialValue(identifier) {
var container = this.containers[identifier];
return container ? container.initialValue.value : {};
}
get(identifier) {
var container = this.containers[identifier];
return container ? container.currentValue.value : {};
}
reset(identifier) {
var container = this.containers[identifier];
container.reset();
return container ? container.currentValue.value : {};
}
}
module.exports = UAVWatcher;