-
Notifications
You must be signed in to change notification settings - Fork 0
/
obj.graph.js
80 lines (69 loc) · 2.27 KB
/
obj.graph.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
var GraphWatcher = function () {
var T = this;
var callbacks = [];
var events = {};
T.add = function (key, obj, cb) {
obj.active = false;
obj.state = 2;
obj._state = 2;
obj.timestamp = 0;
obj.value = 0;
if (typeof cb === "function") {
obj.callback = cb;
}
if (typeof obj.ttl === "undefined") {
obj.ttl = 3600;
}
events[key] = obj;
};
var callback = function (e, p) {
callbacks.forEach(function (o) {
if (e === o.E) {
o.C(p);
}
});
};
var _update = function (event, val) {
var now = Date.unix();
if (now - events[event].timestamp >= events[event].ttl) {
events[event].state = 2;
events[event]._state = 2;
events[event].active = false;
console.log("-- event reset: " + event);
}
events[event].value = val;
events[event].timestamp = now;
if (events[event].value <= events[event].low) {
events[event].state = -1;
events[event].active = false;
}
if (events[event].value >= events[event].high) {
events[event].state = 1;
events[event].active = false;
}
if (events[event].value >= events[event].low && events[event].value <= events[event].high) {
events[event].state = 0;
events[event].active = true;
}
if (events[event].state !== events[event]._state) {
if (events[event].active === true) {
console.log("event triggered: " + event);
callback(event, {"name": event, "state": events[event].state, "value": events[event].value});
if (typeof events[event].callback === "function") {
events[event].callback({"name": event, "value": events[event].value});
}
}
events[event]._state = events[event].state;
}
};
T.update = function (event, val) {
if (Array.isArray(event)) {
event.forEach(function (e) {
_update(e, val);
});
return;
}
_update(event, val);
};
return T;
};