Skip to content

Commit

Permalink
body parser & set temperature endpoint/controller method
Browse files Browse the repository at this point in the history
  • Loading branch information
andy-haynes committed Nov 19, 2019
1 parent 677e23a commit ba6fd26
Show file tree
Hide file tree
Showing 3 changed files with 44 additions and 9 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
"@stamp/configure": "^1.0.2",
"@stamp/it": "^1.0.3",
"bluebird": "^3.5.1",
"body-parser": "^1.19.0",
"chip-gpio": "^1.1.3",
"ds18b20": "^0.1.0",
"express": "^4.17.1",
Expand Down
4 changes: 4 additions & 0 deletions src/controller/controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,10 @@ const Controller = stampit.compose(
thermostat: this.thermostat.getLastUpdate(),
};
},
setTargetTemperature(temperature) {
return this.thermostat.initialize()
.then(() => this.thermostat.setTemperature(temperature));
},
shutdown() {
console.warn('Shutting down, better luck next time.');
this.stop();
Expand Down
48 changes: 39 additions & 9 deletions src/server.js
Original file line number Diff line number Diff line change
@@ -1,32 +1,62 @@
const bodyParser = require('body-parser');
const express = require('express');

const app = express();
app.use(bodyParser.json());

function initializeServer({ port }, controller) {
app.get('/alive', (req, res) => {
app.get('/alive', (req, res, next) => {
res.json({ alive: true });
next();
});

app.get('/update', (req, res) => {
app.get('/update', (req, res, next) => {
const lastUpdate = controller.getUpdate();
res.json({ last_update: lastUpdate });
next();
});

app.post('/start', (req, res) => {
app.post('/start', (req, res, next) => {
return controller.start()
.then(() => res.json({ status: 'started' }))
.catch((e) => res.status(500).send(e.message));
.then(() => {
res.json({ status: 'started' });
next();
})
.catch((e) => {
res.status(500).send(e.message);
next(e);
});
});

app.post('/stop', (req, res) => {
app.post('/set_temperature', (req, res, next) => {
const { temperature } = req.body;
return controller.setTargetTemperature(temperature)
.then(() => {
res.json({ status: 'temperature set' });
next();
})
.catch((e) => {
res.status(500).send(e.message);
next(e);
});
});

app.post('/stop', (req, res, next) => {
controller.stop();
res.json({ status: 'paused' });
next();
});

app.post('/shutdown', (req, res) => {
app.post('/shutdown', (req, res, next) => {
return controller.shutdown()
.then(() => res.json({ status: 'shutdown' }))
.catch((e) => res.status(500).json({ error: e.message, stack: e.stack }));
.then(() => {
res.json({ status: 'shutdown' });
next();
})
.catch((e) => {
res.status(500).json({ error: e.message, stack: e.stack });
next(e);
});
});

app.listen(port);
Expand Down

0 comments on commit ba6fd26

Please sign in to comment.