-
Notifications
You must be signed in to change notification settings - Fork 22
/
index.js
208 lines (181 loc) 路 5.58 KB
/
index.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
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
const functions = require('firebase-functions');
const admin = require('firebase-admin');
const Geopoint = require('geopoint');
const googleapis = require('googleapis');
admin.initializeApp();
const GeoPointFirestore = admin.firestore.GeoPoint;
const db = admin.firestore();
const DISTANCE_THRESHOLD = 0.05; // 50 meters
const PROJECT_ID = process.env.GCLOUD_PROJECT;
const REGION = 'us-central1';
const REGISTRY = 'asset-tracker-registry';
/**
* Receive a http request with deviceId and updateInterval, then
* call modifyCloudToDeviceConfig method of Cloud IoT Core
* to update the device configuration.
*/
exports.updateDeviceConfig = functions.https.onRequest((req, res) => {
let { deviceId, updateInterval } = req.query;
if (!deviceId) {
res.json({ err: 'Param `deviceId` is required!' });
return;
}
updateInterval = parseInt(updateInterval, 10);
if (!updateInterval) {
res.json({ err: 'Param `updateInterval` is required!' });
return;
}
getCloudIoTClient()
.then(client => {
const device_name = `projects/${PROJECT_ID}/locations/${REGION}/registries/${REGISTRY}/devices/${deviceId}`;
//console.log(device_name);
const newConfig = { update_interval: updateInterval };
const data = new Buffer(JSON.stringify(newConfig), 'utf-8');
const binaryData = data.toString('base64');
client.projects.locations.registries.devices.modifyCloudToDeviceConfig(
{
name: device_name,
resource: {
version_to_update: 0,
data: {
binary_data: binaryData
}
}
},
(err, response) => {
if (!err) {
let deviceRef = db.collection('devices').doc(deviceId);
deviceRef.set(
{
updateInterval
},
{ merge: true }
);
}
res.json({ err, response });
}
);
})
.catch(err => {
res.json({ err });
});
});
/**
* Receive data from pubsub, then
* Maintain last device data on Firestore 'devices' collections then
* Write telemetry raw data to 'devices/location_logs' subcollection
*/
exports.receiveTelemetry = functions.pubsub
.topic('telemetry-topic')
.onPublish((message, context) => {
const attributes = message.attributes;
const payload = message.json;
const deviceId = attributes['deviceId'];
const data = {
deviceId: deviceId,
timestamp: new Date(context.timestamp),
latitude: parseFloat(payload.latlon.lat),
longitude: parseFloat(payload.latlon.lon),
speed: parseFloat(payload.latlon.sp),
deviceTemperature: payload.temp,
deviceFreeRam: payload.free_ram,
deviceTotalRam: payload.total_ram
};
let deviceRef = db.collection('devices').doc(deviceId);
return deviceRef.get().then(doc => {
if (!doc.exists) {
data.state = 'MOVING';
return Promise.all([
updateCurrentDataFirestore(deviceRef, data),
insertLocationLog(deviceRef, data)
]).then(() => {
return updateDeviceDateIndex(deviceRef, data, {});
});
}
let device = doc.data();
let newLocation = new Geopoint(data.latitude, data.longitude);
let lastLocation = new Geopoint(
device.location.latitude,
device.location.longitude
);
let distanceKm = lastLocation.distanceTo(newLocation, true);
if (distanceKm >= DISTANCE_THRESHOLD) {
data.state = 'MOVING';
return Promise.all([
updateCurrentDataFirestore(deviceRef, data),
insertLocationLog(deviceRef, data)
]).then(() => {
return updateDeviceDateIndex(deviceRef, data, device.dateIndex);
});
} else {
data.state = 'STOPPED';
return updateCurrentDataFirestore(deviceRef, data);
}
});
});
const API_SCOPES = ['https://www.googleapis.com/auth/cloud-platform'];
const API_VERSION = 'v1';
const DISCOVERY_API = 'https://cloudiot.googleapis.com/$discovery/rest';
const SERVICE_NAME = 'cloudiot';
const DISCOVERY_URL = `${DISCOVERY_API}?version=${API_VERSION}`;
function getCloudIoTClient() {
return new Promise((resolve, reject) => {
googleapis.auth.getApplicationDefault((err, auth, projectId) => {
if (err) {
reject(err);
return;
}
googleapis.discoverAPI(DISCOVERY_URL, { auth }, (err, service) => {
if (!err) {
resolve(service);
} else {
reject(err);
}
});
});
});
}
/**
* Maintain last status in Firestore
*/
function updateCurrentDataFirestore(deviceRef, data) {
let location = new GeoPointFirestore(data.latitude, data.longitude);
return deviceRef.set(
{
location,
state: data.state,
lastTimestamp: data.timestamp,
speed: data.speed,
deviceTemperature: data.deviceTemperature,
deviceFreeRam: data.deviceFreeRam,
deviceTotalRam: data.deviceTotalRam
},
{ merge: true }
);
}
/**
* Store all the log data in sub collection
*/
function insertLocationLog(deviceRef, data) {
let location = new GeoPointFirestore(data.latitude, data.longitude);
return deviceRef.collection('location_logs').add({
location,
timestamp: data.timestamp,
speed: data.speed
});
}
/**
* Update device date index with all days that have data
*/
function updateDeviceDateIndex(deviceRef, data, dateIndex) {
const key = data.timestamp.toJSON().substring(0, 10);
const count = dateIndex[key];
if (!count) {
dateIndex[key] = 1;
} else {
dateIndex[key] = count + 1;
}
return deviceRef.update({
dateIndex
});
}