110 lines
2.8 KiB
JavaScript
110 lines
2.8 KiB
JavaScript
// Global API configuration
|
|
var Api = new Restivus({
|
|
version: 'v1.0',
|
|
useDefaultAuth: true,
|
|
prettyJson: true
|
|
});
|
|
|
|
Api.addRoute('sensorData', {
|
|
authRequired: false
|
|
}, {
|
|
post: function() {
|
|
reactToSensorData(this.bodyParams);
|
|
SensorData.insert({
|
|
temperatureValue: parseFloat(this.bodyParams.temperatureValue),
|
|
humidityValue: parseFloat(this.bodyParams.humidityValue),
|
|
tankLevel0: this.bodyParams.tankLevel0,
|
|
tankLevel1: this.bodyParams.tankLevel1,
|
|
tankLevel2: this.bodyParams.tankLevel2,
|
|
tankLevel3: this.bodyParams.tankLevel3,
|
|
tankLevel4: this.bodyParams.tankLevel4,
|
|
tankFull: this.bodyParams.tankFull,
|
|
owner: this.bodyParams.owner,
|
|
controllerId: this.bodyParams.controllerId,
|
|
created_at: new Date()
|
|
});
|
|
return [];
|
|
}
|
|
});
|
|
|
|
|
|
function reactToSensorData(nextSensorReading) {
|
|
console.log("reacting to sensor");
|
|
var controllerId = nextSensorReading.controllerId;
|
|
var state = stateOrDefault(controllerId).state;
|
|
var shouldStartPumping = (!state.in_valve || state.in_valve === 'closed') && ((parseInt(nextSensorReading.tankFull) === 0) && (state.out_valve === 'closed' || state.out_valve === 'closing'));
|
|
|
|
if (shouldStartPumping) {
|
|
ControllerState.update({
|
|
controller_id: controllerId
|
|
}, {
|
|
'$set': {
|
|
'state.in_valve': 'opening',
|
|
'time': new Date(),
|
|
'set_by': 'server'
|
|
}
|
|
});
|
|
}
|
|
var shouldStopPumping = (state.in_valve === 'open' || state.in_valve === 'opening') && (parseInt(nextSensorReading.tankFull) === 1 || state.out_valve === 'open' || state.out_valve === 'opening');
|
|
|
|
if (shouldStopPumping) {
|
|
ControllerState.update({
|
|
controller_id: controllerId
|
|
}, {
|
|
'$set': {
|
|
'state.in_valve': 'closing',
|
|
'time': new Date(),
|
|
'set_by': 'server'
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
Api.addRoute('state/:id', {
|
|
authRequired: false
|
|
}, {
|
|
post: function() {
|
|
console.log("setting state", this.bodyParams);
|
|
return ControllerState.update({
|
|
controller_id: this.urlParams.id
|
|
}, {
|
|
'$set': {
|
|
'state.out_valve': this.bodyParams.out_valve,
|
|
'state.in_valve': this.bodyParams.in_valve,
|
|
'time': new Date(),
|
|
'set_by': 'client'
|
|
}
|
|
});
|
|
},
|
|
get: function() {
|
|
return stateOrDefault(this.urlParams.id).state;
|
|
}
|
|
});
|
|
|
|
|
|
function stateOrDefault(id) {
|
|
var stateEntry = ControllerState.findOne({
|
|
controller_id: id,
|
|
});
|
|
|
|
if (stateEntry === undefined) {
|
|
stateEntry = ControllerState.insert({
|
|
controller_id: id,
|
|
state: {
|
|
out_valve: 'closed',
|
|
in_valve: 'closed'
|
|
},
|
|
time: new Date(),
|
|
config: {
|
|
draining_period_amount: 40,
|
|
draining_period_unit: 'minutes'
|
|
},
|
|
set_by: 'server'
|
|
});
|
|
};
|
|
var stateEntry = ControllerState.findOne({
|
|
controller_id: id,
|
|
});
|
|
return stateEntry;
|
|
}
|