-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubscribe-location.js
79 lines (71 loc) · 2.23 KB
/
subscribe-location.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
"use strict";
const config = require('./config');
const fetch = require('node-fetch');
const checkStatus = require('./lib/fetch').checkStatus;
const socketio = require('socket.io-client');
const _ = require('underscore');
const apiUrl = config.api.host+config.api.path;
const io = socketio(config.socket.host,{path: config.socket.path});
const deviceId = process.argv[2];
console.log("using api:",apiUrl);
console.log("using socket:",config.socket.host+config.socket.path);
console.log("device:",deviceId);
console.log();
if (!deviceId || deviceId === "undefined") {
console.log("no device id specified!");
process.exit();
}
var sensorMap = {}; //map sensorId to sensor configuration and meta-data
//fetch list of registered devices
fetch(apiUrl+"/devices/"+deviceId)
//check response
.then(response => {
if (response.status >= 400) {
throw Error("could not fetch device information for id "+deviceId+": "+response.status+": "+response.statusText);
}
return response;
})
.then(checkStatus)
//get payload from response
.then(response => response.json())
//read sensor configuration for device
.then(device => {
device.sensors.forEach(sensor => {
sensorMap[sensor.id] = {
name: sensor.name,
unit: sensor.unit
}
});
})
//read device status
.then(()=>{
return fetch(apiUrl+"/devices/"+deviceId+"/status")
.then(checkStatus)
.then(response => response.json())
.then(json => {
console.log("==== device status ====");
console.log(" online:",json.connection);
console.log(" gateway:",json.gateway.name);
console.log(" location:",json.location || "Unknown");
console.log();
})
})
//subscribe to pubsub interface
.then(() => {
io.on("/devices/"+deviceId+"/location",handleDeviceDataEvent)
})
.catch(err=>{
console.log("Error:",err.message);
process.exit()
})
.then(() => {
console.log("press Ctrl-C to quit");
});
//callback function to handle event emitted by the api
function handleDeviceDataEvent (locationEvent) {
if (!locationEvent) {
console.log("-> Unknown");
} else {
console.log("-> ", locationEvent.name, "(", locationEvent.id, ")", " since", new Date(locationEvent.since));
}
}