@lifefinder/vsm-mqtt-client-open-source 0.0.46

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/store.js ADDED
@@ -0,0 +1,82 @@
1
+ /*
2
+ The MIT License (MIT)
3
+
4
+ Copyright Sensative AB 2023. All rights reserved.
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
23
+ */
24
+
25
+ // Functions for storage. Optimally this storage would be in a database rather than
26
+ // just reading/writing to the file system. Also a RAM cache would be a nice improvement,
27
+ // BUT consider that it is possible to have multiple instances running which would break
28
+ // consistency if the same device is present in multiple lora network servers (roaming).
29
+
30
+ const fs = require('fs');
31
+
32
+ // If the store is not initialized and requires initialization, do that here
33
+ module.exports.initializeStore = async () => {
34
+ if (!fs.existsSync('storage'))
35
+ fs.mkdirSync('storage');
36
+ }
37
+
38
+ module.exports.fetchObjectFromStore = (deviceid) => {
39
+ let buffer = fs.readFileSync(`storage/${deviceid.toLowerCase()}.json`);
40
+ return JSON.parse(buffer.toString('utf-8'));
41
+ }
42
+
43
+ module.exports.putObjectInStore = (deviceid, obj) => {
44
+ try {
45
+ fs.writeFileSync(`storage/${deviceid.toLowerCase()}.json`, JSON.stringify(obj));
46
+ } catch (e) {
47
+ console.log("Failed to write translation state to storage:", e.message);
48
+ }
49
+ }
50
+
51
+ module.exports.putErrorInStore = (deviceId, e) => {
52
+ let filename = "storage/errors.txt";
53
+ const text = new Date().toISOString() + " " + deviceId.toLowerCase() + " " + e.message + "\n";
54
+ try {
55
+ fs.appendFile(filename, text);
56
+ } catch (e) {}
57
+ }
58
+
59
+ //
60
+ // Return a list of device IDs applicable to the selected integration
61
+ //
62
+ module.exports.readDeviceList = (devicefile) => {
63
+ let devices = [];
64
+ try {
65
+ let buffer = fs.readFileSync(devicefile);
66
+ if (!Buffer.isBuffer(buffer))
67
+ throw new Error("Device list file " + devicefile + " is empty");
68
+ let lines = buffer.toString("utf-8").split('\n');
69
+ for (let i = 0; i < lines.length; ++i) {
70
+ let name = lines[i].trim();
71
+ if (name.startsWith("#") || name.length == 0)
72
+ continue;
73
+ devices.push(name);
74
+ }
75
+ console.log("Device count: " + devices.length);
76
+ } catch (e) {
77
+ console.log("Failed to read device file '" + devicefile + "' : " + e.message);
78
+ }
79
+ return devices;
80
+ }
81
+
82
+ module.exports.getStoreName = () => { return "Local file system object storage" };
package/util.js ADDED
@@ -0,0 +1,35 @@
1
+ // Deep merge function from
2
+ // https://stackoverflow.com/questions/27936772/how-to-deep-merge-instead-of-shallow-merge
3
+ // ... could have included lodash but trying to avoid dependencies
4
+
5
+ const { isDate } = require('util/types');
6
+
7
+
8
+
9
+ const isObject = (item) => {
10
+ return (item && typeof item === 'object' && !Array.isArray(item) && !isDate(item));
11
+ }
12
+
13
+ const mergeDeep = (target, source) => {
14
+ let output = Object.assign({}, target);
15
+ if (isObject(target) && isObject(source)) {
16
+ Object.keys(source).forEach(key => {
17
+ if (isObject(source[key])) {
18
+ if (!(key in target))
19
+ Object.assign(output, { [key]: source[key] });
20
+ else
21
+ output[key] = mergeDeep(target[key], source[key]);
22
+ } else {
23
+ Object.assign(output, { [key]: source[key] });
24
+ }
25
+ });
26
+ }
27
+ return output;
28
+ }
29
+
30
+ const delay = async (ms) => {
31
+ await new Promise(resolve => setTimeout(resolve, ms));
32
+ }
33
+
34
+ module.exports.mergeDeep = mergeDeep;
35
+ module.exports.delay = delay;
@@ -0,0 +1,299 @@
1
+ /*
2
+ The MIT License (MIT)
3
+
4
+ Copyright Sensative AB 2023. All rights reserved.
5
+
6
+ Permission is hereby granted, free of charge, to any person obtaining a copy
7
+ of this software and associated documentation files (the "Software"), to deal
8
+ in the Software without restriction, including without limitation the rights
9
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
10
+ copies of the Software, and to permit persons to whom the Software is
11
+ furnished to do so, subject to the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be included in all
14
+ copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22
+ SOFTWARE.
23
+ */
24
+
25
+ let translator;
26
+ try {
27
+ translator = require('vsm-translator-open-source');
28
+ } catch (e) {
29
+ console.log("Failed to load VSM translator. Did you do yarn install?");
30
+ process.exit(1);
31
+ }
32
+
33
+ const store = process.env.VMC_STORE ? process.env.VMC_STORE : "./store";
34
+ const { initializeStore, fetchObjectFromStore, putObjectInStore, putErrorInStore, readDeviceList, getStoreName } = require(store);
35
+ console.log("Store: " + getStoreName());
36
+
37
+ const { mergeDeep, delay } = require('./util');
38
+ const { processRules} = require('./rules');
39
+
40
+ const isValidDate = (d) => {
41
+ return d instanceof Date && !isNaN(d);
42
+ }
43
+
44
+ const isVsmDevice = (deveui) => {
45
+ if (!deveui.toUpperCase().startsWith("70B3D52C"))
46
+ return false;
47
+ if (!deveui.length == 16)
48
+ return false;
49
+
50
+ // TODO: Filter out deveuis in correct range
51
+ return true;
52
+ }
53
+
54
+ const printUsageAndExit = (hint) => {
55
+ console.log("Usage: node vsm-mqtt-client.js [-v] (-f <device id file> | -a) -i <integration name> -k <loracloud api key> -o <publisher> -d <decorator> -O <publisher>");
56
+ console.log(" " + hint);
57
+ process.exit(1);
58
+ }
59
+
60
+ // Exported for clients to use (intended for downlinks)
61
+ exports.getDevices = async (args) => {
62
+ if (args.f) {
63
+ let devices = await readDeviceList(args.f);
64
+ if (devices.length == 0) {
65
+ console.log("Note: No devices in device file, continuing anyway");
66
+ }
67
+ return devices;
68
+ } else if (!args.w)
69
+ printUsageAndExit();
70
+ }
71
+
72
+ // Exported for clients to use (intended for downlinks)
73
+ exports.getIntegration = async (args) => {
74
+ let integration;
75
+ try {
76
+ const location = process.env.VMC_INTEGRATIONS ? process.env.VMC_INTEGRATIONS : "./integrations";
77
+ integration = require(location + "/" + args.i);
78
+ if (!(integration.api && integration.api.getVersionString && integration.api.checkArgumentsOrExit && integration.api.connectAndSubscribe)) {
79
+ console.log("Integration " + args.i + " lacks a required function");
80
+ process.exit(1);
81
+ }
82
+ } catch (e) {
83
+ console.log(e.message);
84
+ printUsageAndExit();
85
+ }
86
+ return integration;
87
+ }
88
+
89
+ let args_cache = undefined;
90
+ // Exported for clients to use (intended for downlinks)
91
+ exports.getArgs = () => {
92
+ if (args_cache)
93
+ return args_cache;
94
+ args_cache = require('minimist')(process.argv.slice(2));
95
+ return args_cache;
96
+ }
97
+
98
+ // Assigned below in runClient
99
+ let mqtt_client = undefined;
100
+
101
+ // Exported for clients to use (intended for downlinks)
102
+ exports.getMqttClient = () => {
103
+ return mqtt_client;
104
+ }
105
+
106
+ exports.sendDownlink = async (args, deveui, port, buffer) => {
107
+ if (!args || !deveui || !port || !buffer)
108
+ throw { message: "sendDownlink: Required argument missing"};
109
+
110
+ const integration = await this.getIntegration(args);
111
+ // Either below means that initialization did not succeed. Throw!
112
+ if (!integration)
113
+ throw { message: "sendDownlink: Integration not initialized."};
114
+
115
+ if (!this.getMqttClient())
116
+ throw { message: "sendDownlink: MQTT not initialized."};
117
+
118
+ await integration.api.sendDownlink(this.getMqttClient(), args, deveui, port, Buffer.from(buffer, "hex"), false /* confirmed */ );
119
+ }
120
+
121
+ const run = async () => {
122
+ // Command line options handler (simple one)
123
+ const args = this.getArgs();
124
+ if (!args.i)
125
+ printUsageAndExit("-i <Integration name> is required");
126
+ if (!(args.f || args.w))
127
+ printUsageAndExit("-f <device file> or -w is required");
128
+
129
+ args.v && console.log("Selected integration: " + args.i);
130
+ args.v && console.log("Device file: " + args.f);
131
+ args.v && console.log("Selected decorator: " + (args.d ? args.d : "default"));
132
+
133
+ // Initialize and or connect to the storage
134
+ await initializeStore();
135
+
136
+ //
137
+ // Create the list of devices (device ID dependent on each integration), as an array of files
138
+ //
139
+ let devices = await this.getDevices(args);
140
+
141
+ //
142
+ // INTEGRATION
143
+ //
144
+ let integration = await this.getIntegration(args);
145
+ // Allow the integration to check its arguments (e.g. server, credentials, etc)
146
+ console.log("Integration: " + integration.api.getVersionString());
147
+ integration.api.checkArgumentsOrExit(args);
148
+
149
+ //
150
+ // DECORATION
151
+ //
152
+ let decorator;
153
+ try {
154
+ const location = process.env.VMC_DECORATORS ? process.env.VMC_DECORATORS : "./decorators";
155
+ decorator = require(location + "/" + (args.d ? args.d : "default"));
156
+ if (!(decorator.api && decorator.api.decorate && decorator.api.getVersionString)) {
157
+ console.log("Decoration " + args.d + " lacks a required function");
158
+ process.exit(1);
159
+ }
160
+ } catch (e) {
161
+ console.log(e.message);
162
+ printUsageAndExit();
163
+ }
164
+ console.log("Decoration: " + decorator.api.getVersionString());
165
+
166
+ //
167
+ // PUBLISHER
168
+ //
169
+
170
+ let publisher = undefined;
171
+ try {
172
+ const location = process.env.VMC_PUBLISHERS ? process.env.VMC_PUBLISHERS : "./publishers";
173
+ publisher = require(location + "/" + (args.O ? args.O : "console"));
174
+ if (!(publisher.api && publisher.api.getVersionString && publisher.api.checkArgumentsOrExit && publisher.api.publish)) {
175
+ console.log("Publisher " + args.O + " lacks a required function");
176
+ process.exit(1);
177
+ }
178
+ } catch (e) {
179
+ console.log(e.message);
180
+ printUsageAndExit();
181
+ }
182
+ // Allow the integration to check its arguments (e.g. server, credentials, etc)
183
+ console.log("Publisher: " + publisher.api.getVersionString());
184
+ publisher.api.checkArgumentsOrExit(args);
185
+ publisher.api.initialize(args);
186
+
187
+ //
188
+ // SOLVER
189
+ //
190
+
191
+ let solver = undefined;
192
+ try {
193
+ const location = process.env.VMC_SOLVERS ? process.env.VMC_SOLVERS : "./solvers";
194
+ solver = require(location + "/" + (args.z ? args.z : "loracloud"));
195
+ if (!(solver.api && solver.api.getVersionString && solver.api.checkArgumentsOrExit && solver.api.solvePosition && solver.api.loadAlmanac && solver.api.initialize)) {
196
+ console.log("Solver " + args.z + " lacks a required function");
197
+ process.exit(1);
198
+ }
199
+ } catch (e) {
200
+ console.log(e.message);
201
+ printUsageAndExit();
202
+ }
203
+ // Allow the integration to check its arguments (e.g. server, credentials, etc)
204
+ console.log("Positioning Solver: " + solver.api.getVersionString());
205
+ solver.api.checkArgumentsOrExit(args);
206
+ solver.api.initialize(args);
207
+
208
+ // TIME SERIES PROCESSOR
209
+ const seriesProcessor = process.env.VMC_PROCESSOR ? require(process.env.VMC_PROCESSOR) : undefined;
210
+ if (seriesProcessor && seriesProcessor.onTimeSeries && seriesProcessor.getName)
211
+ console.log('Series Processor: ', seriesProcessor.getName());
212
+
213
+ // Function to handle uplinks for a device id on a port with binary data in buffer
214
+ const onUplinkDevicePortBufferDateLatLng = async (client, deviceid, port, buffer, date, lat, lng, maxSize) => {
215
+ if (!(typeof(deviceid) == "string" && isFinite(port) && Buffer.isBuffer(buffer))) {
216
+ console.log(`Integration error: Bad parameter to onUplinkDevicePortBufferDateLatLng:
217
+ typeof(deviceid):${typeof(deviceid)} (expect string), typeof(port)=${typeof(port)} (expect number), Buffer.isBuffer(buffer)=${Buffer.isBuffer(buffer)}`);
218
+ throw new Error("Bad parameter");
219
+ }
220
+
221
+ if ((!isValidDate(date)) || process.env.VMC_DISTRUST_LNS_TIME)
222
+ date = new Date();
223
+
224
+ // If wildcarded, check that we have the correct series of deveuis,
225
+ // unless yggio integration, which does its own check
226
+ if (args.w && (!isVsmDevice(deviceid) && args.i !== 'yggio')) {
227
+ args.v && console.log("Ignoring unrecognized device " + deviceid);
228
+ return;
229
+ }
230
+
231
+ console.log("Uplink: device=" + deviceid + " port="+port + " buffer=" + buffer.toString("hex") + " date="+ date.toISOString() + " lat="+lat + " lng="+lng);
232
+
233
+ // Read previous state for this node
234
+ let previous = {};
235
+ try {
236
+ previous = await fetchObjectFromStore(deviceid);
237
+ // args.v && console.log("previous:", previous);
238
+ } catch (e) {
239
+ args.v && console.log(`Note: No previous data for device ${deviceid}`);
240
+ }
241
+
242
+ // Run translation
243
+ let iotnode = { ...previous,
244
+ encodedData : {
245
+ port : port,
246
+ hexEncoded : buffer.toString('hex'),
247
+ timestamp: date, // TBD if this should be given by the integration instead?
248
+ maxSize: maxSize,
249
+ }
250
+ }
251
+ let result = {}
252
+ try {
253
+ const returned = translator.translate(iotnode);
254
+ result = returned.result;
255
+ let timeseries = returned.timeseries;
256
+ args.v && timeseries && !seriesProcessor && console.log("Ignoring historical timeseries data:", JSON.stringify(timeseries));
257
+ if (Array.isArray(timeseries) && seriesProcessor && seriesProcessor.onTimeSeries) {
258
+ if (args.v) console.log("Invoking series processor " + seriesProcessor.getName() + " with " + timeseries.length + " measurements.");
259
+ await seriesProcessor.onTimeSeries(deviceid, timeseries, iotnode);
260
+ }
261
+ } catch (e) {
262
+ console.log("Failed translation: ", e.message);
263
+ putErrorInStore(deviceid, e);
264
+ }
265
+
266
+ if (!result) {
267
+ // In case we are just filling up with time series data from previous measurements
268
+ console.log("No new results from translator\n");
269
+ return;
270
+ }
271
+
272
+ let next = mergeDeep(iotnode, result);
273
+
274
+ next = await processRules(args, integration, client, solver, deviceid, next, result, date, lat, lng);
275
+
276
+ // Store the next version of the object representation
277
+ await putObjectInStore(deviceid, next, /* diff*/ result);
278
+
279
+ // Publish the data
280
+ publisher.api.publish(args, deviceid, decorator.api.decorate(next, deviceid));
281
+ }
282
+
283
+ const runClient = async () => {
284
+ // Let the integration create connection and add required subscriptions
285
+ try {
286
+ mqtt_client = await integration.api.connectAndSubscribe(args, devices, onUplinkDevicePortBufferDateLatLng);
287
+ } catch (e) {
288
+ console.log("Failed to connect and subscribe: " + e.message);
289
+ process.exit(1);
290
+ }
291
+ while (true) {
292
+ args.v && console.log(new Date().toISOString() + " active");
293
+ await delay(60000);
294
+ }
295
+ }
296
+ await runClient();
297
+ }
298
+
299
+ run();