-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdbinterface.js
More file actions
87 lines (76 loc) · 2.22 KB
/
dbinterface.js
File metadata and controls
87 lines (76 loc) · 2.22 KB
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
var mon;
var Device, Measure, Sample;
module.exports = {
initialiseMongo: (mongoose) => {
mon = mongoose;
const {Schema} = mongoose;
mongoose.connect('mongodb://localhost:27017/IoTProject', {
useNewUrlParser: true,
useUnifiedTopology: true
});
//Model for device
Device = mongoose.model('device', {
ID: String,
Friendly: String,
IP: String,
DeviceType: String
});
//Model for data unit
Measure = new Schema({
ID: String,
Measure: Number
});
//Model for data Storage
Sample = mongoose.model('sample', {
Time: { type: Date, default: Date.now },
TotalUsage: Number,
TotalProduction: Number,
BatteryLevel: Number,
Measures: [Measure]
});
},
putDevice: async (json, query) => {
if (json.ID == undefined) {
throw Error("Missing ID");
} else {
var ep = await Device.findOne({ID: json.ID}).exec();
if (ep != null) {
throw Error("ID already exists.");
} else {
const newDevice = new Device({
ID: json.ID,
Friendly: query.Friendly,
IP: query.IP,
DeviceType: query.DeviceType
});
newDevice.save();
}
}
},
putSample: (tu, tp, bl, meas) => {
let t = Date.now();
const newSamp = new Sample({
Time: t,
TotalUsage: tu,
TotalProduction: tp,
BatteryLevel: bl,
Measures: meas
});
newSamp.save();
},
getDevice: async (ID) => {
return await Device.findOne({ID: ID}).exec();
},
getAllDeviceIPs: async() => {
var res = await Device.find({}, 'IP DeviceType ID Friendly');
return res;
},
getLastSample: async() => {
var res = await Sample.find().sort({$natural:-1}).limit(1);
return res;
},
getLastXSamples: async(x) => {
var res = await Sample.find().sort({$natural:-1}).limit(x);
return res;
}
}