-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathanalysis.js
67 lines (54 loc) · 1.97 KB
/
analysis.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
/*
* Analysis Example
* Operate data from devices
*
* Read information from a variable generated by devices,
* run a simple calculation in real-time, and create a new variable with the output.
*
* Instructions
* To run this analysis you need to add a device token to the environment variables,
* To do that, go to your device, then token and copy your token.
* Go the the analysis, then environment variables,
* type device_token on key, and paste your token on value
*/
const { Analysis, Device, Utils } = require("@tago-io/sdk");
// The function startAnalysis will run when you execute your analysis
async function startAnalysis(context) {
// reads the values from the environment and saves it in the variable env_vars
const env_vars = Utils.envToJson(context.environment);
if (!env_vars.device_token) {
return context.log("Missing device_token environment variable");
}
const device = new Device({ token: env_vars.device_token });
// create the filter options to get the data from TagoIO
const filter = {
variable: "water_level",
query: "last_item",
};
const resultArray = await device.getData(filter).catch(() => null);
// Check if the array is not empty
if (!resultArray || !resultArray[0]) {
return context.log("Empty Array");
}
// query:last_item always returns only one value
const value = resultArray[0].value;
const time = resultArray[0].time;
// print to the console at TagoIO
context.log(
`The last record of the water_level is ${value}. It was inserted at ${time}`
);
// Multiplies the water_level value by 2 and inserts it in another variable
const obj_to_save = {
variable: "water_level_double",
value: value * 2,
};
try {
await device.sendData(obj_to_save);
context.log("Successfully Inserted");
} catch (error) {
context.log("Error when inserting:", error);
}
}
Analysis.use(startAnalysis);
// To run analysis on your machine (external)
// Analysis.use(myAnalysis, { token: "YOUR-TOKEN" });