-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathSimpleRemoteMonitoringApp.agent.nut
77 lines (60 loc) · 2.62 KB
/
SimpleRemoteMonitoringApp.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
// Simple Remote Monitoring Application Agent Code
// ---------------------------------------------------
// WEBSERVICE LIBRARY
// ---------------------------------------------------
// Libraries must be required before all other code
// Initial State Library
#require "InitialState.class.nut:1.0.0"
// REMOTE MONITORING APPLICATION CODE
// ---------------------------------------------------
// Application code, listen for readings from device,
// when a reading is received send the data to Initial
// State
class Application {
// On Intial State website navigate to "my account"
// page find/create a "Streaming Access Key"
// Paste it into the variable below
static STREAMING_ACCESS_KEY = "";
// Class variables
iState = null;
agentID = null;
constructor() {
// Initialize Initial State
iState = InitialState(STREAMING_ACCESS_KEY);
// The Initial State library will create a bucket
// using the agent ID
agentID = split(http.agenturl(), "/").top();
// Let's log the agent ID here
server.log("Agent ID: " + agentID);
device.on("reading", readingHandler.bindenv(this));
}
function readingHandler(reading) {
// Log the reading from the device. The reading is a
// table, so use JSON encodeing method convert to a string
server.log(http.jsonencode(reading));
// Initial State requires the data in a specific structre
// Build an array with the data from our reading.
local events = [];
events.push({"key" : "temperature", "value" : reading.temperature, "epoch" : reading.time});
events.push({"key" : "humidity", "value" : reading.humidity, "epoch" : reading.time});
events.push({"key" : "accel_x", "value" : reading.accel_x, "epoch" : reading.time});
events.push({"key" : "accel_y", "value" : reading.accel_y, "epoch" : reading.time});
events.push({"key" : "accel_z", "value" : reading.accel_z, "epoch" : reading.time});
// Send reading to Initial State
iState.sendEvents(events, function(err, resp) {
if (err != null) {
// We had trouble sending to Initial State, log the error
server.error("Error sending to Initial State: " + err);
} else {
// A successful send. The response is an empty string, so
// just log a generic send message
server.log("Reading sent to Initial State.");
}
})
}
}
// RUNTIME
// ---------------------------------------------------
server.log("Agent running...");
// Run the Application
Application();