-
Notifications
You must be signed in to change notification settings - Fork 64
/
Copy pathFieldbusGateway_PumpPLC.agent.nut
339 lines (289 loc) · 10.7 KB
/
FieldbusGateway_PumpPLC.agent.nut
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
// Web Integration Libraries
#require "IBMWatson.class.nut:1.1.0"
#require "InitialState.class.nut:1.0.0"
#require "AutodeskFusionConnect.agent.lib.nut:2.0.0"
// // -------------------------------------------------------
// Message and route names
const TANK_LEVEL_EVENT = "tank_level";
const PUMP_EVENT = "pump";
const TANK_THRESHOLD = "tank_threshold";
const LOCATION = "location";
// Watson Configuration
class Watson {
// Watson Credentials
static API_KEY = "";
static AUTH_TOKEN = "";
static ORG_ID = "";
// Watson Settings
static DEVICE_TYPE = "Fieldbus";
static DEVICE_TYPE_DESCRIPTION = "Fieldbus with PLC";
watson = null;
ready = false;
deviceID = null;
constructor(_deviceID) {
watson = IBMWatson(API_KEY, AUTH_TOKEN, ORG_ID);
deviceID = _deviceID;
configureWatson();
}
function send(msg) {
if (ready) {
local data = { "d": { "data": msg.data },
"ts": watson.formatTimestamp() };
watson.postData(DEVICE_TYPE, deviceID, msg.type, data, function(error, response) {
if (error) server.error("Watson send error: " + error);
else server.log("Watson send successful");
})
}
}
function configureWatson() {
watson.getDeviceType(DEVICE_TYPE, function(err, res) {
switch (err) {
case watson.MISSING_RESOURCE_ERROR:
// dev type doesn't exist yet create it
local typeInfo = {"id" : DEVICE_TYPE, "description" : DEVICE_TYPE_DESCRIPTION};
watson.addDeviceType(typeInfo, function(error, response) {
if (error != null) return reject(error);
server.log("Dev type created");
createDev();
}.bindenv(this));
break;
case null:
// dev type exists, good to use for this device
server.log("Dev type exists");
createDev();
break;
default:
// we encountered an error
server.error(err);
}
}.bindenv(this));
}
function createDev() {
watson.getDevice(DEVICE_TYPE, deviceID, function(err, res) {
switch (err) {
case watson.MISSING_RESOURCE_ERROR:
// dev doesn't exist yet create it
local info = {"deviceId": deviceID, "deviceInfo" : {}, "metadata" : {}};
watson.addDevice(DEVICE_TYPE, info, function(error, response) {
if (error != null) {
server.error(error);
return;
}
server.log("Dev created");
ready = true;
}.bindenv(this));
break;
case null:
// dev exists, update
local info = {"deviceInfo" : {}, "metadata" : {}};
watson.updateDevice(DEVICE_TYPE, deviceID, info, function(error, response) {
if (error != null) {
server.error(error);
return;
}
ready = true;
}.bindenv(this));
break;
default:
// we encountered an error
server.error(err);
}
}.bindenv(this));
}
}
// AutoDesk Fusion Connect Configuration
class FusionConnect {
static HOSTNAME = "";
static HTTPS_PORT = ;
static HTTP_PORT = ;
static MESSAGE_CODE = "in_message";
static POLLING_TIMER = 15;
static MSG_FILTER = 0.7;
fusion = null;
deviceID = null;
_location = null;
_sending = false;
constructor(_deviceID) {
deviceID = _deviceID;
fusion = AutodeskFusionConnect(HOSTNAME, HTTPS_PORT, true);
}
function setHandler(handler) {
fusion.openDirectiveListener(deviceID, POLLING_TIMER, function(resp) {
if ("values" in resp && "tank_threshold" in resp.values) {
handler(resp.values.tank_threshold);
} else {
server.log(http.jsonencode(resp));
}
}.bindenv(this))
}
function send(msg) {
// Filter Tank Level Msgs
if (_sending && msg.type == TANK_LEVEL_EVENT && !overThreshold(msg)) return;
if (HOSTNAME && HTTPS_PORT) {
_sending = true;
local data = {};
data[msg.type] <- msg.data;
server.log(http.jsonencode(data));
fusion.sendMessage(deviceID, MESSAGE_CODE, data, function(err, res) {
if (err) {
server.error("Autodesk send error: " + err);
// foreach (k, v in res) {
// server.log(k + ": " + v)
// }
} else {
// foreach (k, v in res) {
// server.log(k + ": " + v)
// }
server.log("Autodesk send successful");
}
});
imp.wakeup(MSG_FILTER, function() { _sending = false; }.bindenv(this));
}
}
function overThreshold(msg) {
return ("thresh" in msg && msg.data >= msg.data);
}
}
// Initial State Configuration
class InitState {
static ACCESS_KEY = "";
static BUCKET_NAME = "";
is = null;
constructor(deviceID) {
is = InitialState(ACCESS_KEY, deviceID, BUCKET_NAME);
}
function send(msg) {
is.sendEvent(msg.type, msg.data, _respHandler.bindenv(this));
}
function _respHandler(err, res) {
if (err) server.error("Initial state error: " + err);
else server.log("Initial State send successful");
}
}
// Application Code
class App {
// Check for threshold updates from Fusion Connect
static THRESHOLD_TIMER = 60;
static GOOGLE_LOCATION_API_KEY = "";
fc = null;
is = null;
watson = null;
api = null;
devID = null;
tankThreshold = null;
thresholdLoop = null;
constructor() {
devID = imp.configparams.deviceid;
watson = Watson(devID);
fc = FusionConnect(devID);
is = InitState(devID);
openListeners();
fc.setHandler(fusionThresholdHandler.bindenv(this));
}
function openListeners() {
device.on(TANK_LEVEL_EVENT, tankLevelHandler.bindenv(this));
device.on(PUMP_EVENT, pumpEvent.bindenv(this));
device.on(TANK_THRESHOLD, updateThreshold.bindenv(this));
device.on(LOCATION, getLocation.bindenv(this));
}
function fusionThresholdHandler(threshold) {
device.send(TANK_THRESHOLD, threshold);
updateThreshold(threshold, false);
}
function updateThreshold(threshold = null, toFusion = true) {
// Check parameters
if (typeof threshold == "boolean") {
toFusion = threshold;
threshold = null;
}
// Update threshold
if (threshold) tankThreshold = threshold;
// Send to webservices
send({"data" : tankThreshold, "type" : TANK_THRESHOLD}, toFusion);
// Cancel Threshold Loop
if (thresholdLoop) {
imp.cancelwakeup(thresholdLoop);
thresholdLoop = null;
}
// Start Threshold Loop
thresholdLoop = imp.wakeup(THRESHOLD_TIMER, function() {
// Send to everyone except Fusion Connect,
// so we can graph threshold value and tank level
send({"data" : tankThreshold, "type" : TANK_THRESHOLD}, false);
}.bindenv(this))
}
function pumpEvent(state) {
// Send to Webservices
send({"data" : state, "type" : PUMP_EVENT});
}
function tankLevelHandler(level) {
// Send to Webservices
send({"data" : level, "type" : TANK_LEVEL_EVENT, "thresh" : tankThreshold});
}
function send(data, toFusion = true) {
// Log data
server.log(http.jsonencode(data));
// Send to each webservices
if (toFusion) fc.send(data);
watson.send(data);
is.send(data);
}
function getLocation(wifis) {
if (wifis.len() < 2) return callback("Insufficient wifi signals");
local url = "https://www.googleapis.com/geolocation/v1/geolocate?key=" + GOOGLE_LOCATION_API_KEY;
local headers = {
"Content-Type": "application/json"
}
local request = {
"considerIp": false,
"wifiAccessPoints": []
}
// Convert the wifis into a format that google likes
foreach (wifi in wifis) {
local bssid = format("%s:%s:%s:%s:%s:%s", wifi.bssid.slice(0,2),
wifi.bssid.slice(2,4),
wifi.bssid.slice(4,6),
wifi.bssid.slice(6,8),
wifi.bssid.slice(8,10),
wifi.bssid.slice(10,12));
local newwifi = {};
newwifi.macAddress <- bssid.toupper();
newwifi.signalStrength <- wifi.rssi;
newwifi.channel <- wifi.channel;
request.wifiAccessPoints.push(newwifi);
}
// Post the request
http.post(url, headers, http.jsonencode(request)).sendasync(function(res) {
// Parse the response
local body = null;
try {
body = http.jsondecode(res.body);
} catch (e) {
server.error(e);
return;
}
if (res.statuscode == 200 && "location" in body) {
// All looking good
local location = {};
location.latitude <- body.location.lat;
location.longitude <- body.location.lng;
server.log(http.jsonencode(location));
// Send location data here
} else if (res.statuscode == 429) {
// We have been throttled. try again in a second
imp.wakeup(1, function() {
getLocation(wifis);
}.bindenv(this));
} else if ("message" in body) {
// Return Google's error message
server.error(body.message);
} else {
server.error("Error " + res.statuscode);
}
}.bindenv(this));
}
}
// // RUNTIME
// // -------------------------------------------------------
// Initialize & Run the Application
App();