Skip to content
This repository has been archived by the owner on Oct 25, 2018. It is now read-only.

Commit

Permalink
Added REST API route for sensor details
Browse files Browse the repository at this point in the history
  • Loading branch information
cleancoderocker committed Dec 16, 2016
1 parent d6296b7 commit 02a74d2
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 11 deletions.
2 changes: 1 addition & 1 deletion _sensors-project/dummy-sensor/lib/DummySensor.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ module.exports = class DummySensor extends Sensor {
handleStopped() {
return new Promise((resolve, reject) => {
clearInterval(this._intervalHandle);
resolve();
resolve();
});
}
}
3 changes: 3 additions & 0 deletions _sensors-project/sensor-server/lib/APIRouter.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,9 @@ module.exports = class APIRouter extends require("express").Router
this.all("/users", DefaultRouter.xPoweredBy,
parser.json({ "inflate": true, "strict": true }), Users.createStorageDirectory, Users.users);


this.all("/sensors/:sensor", DefaultRouter.xPoweredBy,
parser.json({ "inflate": true, "strict": true }), Sensors.sensor);
this.all("/sensors", DefaultRouter.xPoweredBy,
parser.json({ "inflate": true, "strict": true }), Sensors.sensors);

Expand Down
37 changes: 27 additions & 10 deletions _sensors-project/sensor-server/lib/routes/sensors.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,16 +5,22 @@ const httpError = require("http-errors");
const http = require("http");
const DummySensor = require("dummy-sensor").DummySensor;

let sensors = [];
let sensors = new Map();
for(let i=0; i<10; i++) {
sensors.push(new DummySensor());
let sensor = new DummySensor({
frequency: 2000
});
sensor.onchange = event => sensor.reading = event.reading;
sensors.set(sensor.id, sensor);
}

sensors = sensors.map(sensor =>
({
id: sensor.id
})
)
Array
.from(sensors.entries())
.forEach(entry => entry[1].start());

let sensorsResponse = Array
.from(sensors.keys())
.map(id => ({id: id}));

module.exports = class Sensors
{
Expand All @@ -27,7 +33,7 @@ module.exports = class Sensors
{
"application/json": () =>
{
response.status(200).json({ "sensors": sensors });
response.status(200).json({ "sensors": sensorsResponse });
},
"default": () => { next(new httpError.NotAcceptable()); }
});
Expand All @@ -48,11 +54,22 @@ module.exports = class Sensors

static sensor (request, response, next)
{
let sensor = sensors.get(request.params.sensor);
let sensorResponse = {
id: sensor.id,
reading: sensor.reading
}
switch (request.method)
{

case "GET":

response.format(
{
"application/json": () =>
{
response.status(200).type("application/json").send(sensorResponse);
},
"default": () => { next(new httpError.NotAcceptable()); }
});
break;
case "DELETE":
case "PUT":
Expand Down

0 comments on commit 02a74d2

Please sign in to comment.