-
Notifications
You must be signed in to change notification settings - Fork 1
/
createDevices.js
72 lines (66 loc) · 2.08 KB
/
createDevices.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
const config = require("config");
const mongoose = require("mongoose");
const DeviceModel = require("./models/device").model;
const SensorModel = require("./models/sensor").model;
const util = require("util");
module.exports.clearDevices = async() => {
try {
await DeviceModel.collection.drop();
await SensorModel.collection.drop();
} catch (e) {
console.log("Devices could not be deleted or no devices exist")
}
}
const preprocessDevice = (device) => {
const sensorTypeMap = device.sensorTypeMap;
const parseSchema = device.parseSchema;
const deviceInfo = device.deviceInfo;
const tmpSensorTypeMap = Object.keys(sensorTypeMap).map((key, index) => {
return {
...sensorTypeMap[key],
bleKey: key,
typeName: sensorTypeMap[key]["type-name"],
};
});
tmpSensorTypeMap.map((sensor) => {
const foundSchema = parseSchema.types.find((elm) => elm.id === sensor.type);
sensor.parseScheme = foundSchema["parse-scheme"].map((elm) => {
return { ...elm, scaleFactor: elm["scale-factor"] };
});
sensor.typeName = foundSchema.type;
delete sensor["type-name"];
delete sensor["type"];
return sensor;
});
return [deviceInfo, tmpSensorTypeMap];
};
const addDeviceToDataBase = async (device, sensorMap) => {
return mongoose
.connect(config.db, { useNewUrlParser: true })
.then(() => {
const mainGeneration = String(device.generation).split(".")[0];
return DeviceModel.findOneAndUpdate({ name: device.name, generation: mainGeneration }, device, {
upsert: true,
new: true,
});
})
.then((deviceDoc) => {
return Promise.all(
sensorMap.map((elm) =>
SensorModel.findOneAndUpdate(
{ name: elm.name, device: deviceDoc._id },
{ ...elm, device: deviceDoc._id },
{
upsert: true,
}
)
)
);
}).catch(err => {
console.log(err)
})
};
module.exports.addDevice = (device) => {
const [deviceInfo, sensorMap] = preprocessDevice(device);
return addDeviceToDataBase(deviceInfo, sensorMap);
};