Modifying our server code to show sensor readings

In Chapter 3, Running a Node Server on the Pi, we developed a node server that had APIs to obtain the temperature and humidity. We did not return real data but used a mock hardcoded response to give the impression of real data. In this section, we will be integrating the code that we discussed in Chapter 4, Extracting Information from the GPIO Pins, and including it in our server code so that every time you make a request to the temperature and humidity APIs, you get real, live data.

Let's take the example of the temperature API:

    app.get('/temperature', function(req, res) {
res.send('24 °C');
});

Now, we add the code for reading from the sensor inside this API:

    app.get('/temperature', function (req, res) {
sensor.read(11, 4, function (err, temperature,
humidity) {
if (err) {
console.error(err);
}
res
.send(temperature.toFixed(1) + '°C');
});
});

We call the sensor.read method every time a user makes a request to /temperature .

Note that we send the response inside the callback of the sensor.read method. This is because we want to wait until the sensor has returned its readings before we send anything back to the user.

We similarly modify the humidity API and get the resulting server.js file:

    const express = require('express');
const
app = express();
const
sensor = require('node-dht-sensor');

app
.get('/temperature', function (req, res) {
sensor.read(11, 4, function (err, temperature,
humidity) {
if (!err) {
res.send(temperature.toFixed(1) + '°C');
}
});
});

app
.get('/humidity', function (req, res) {
sensor.read(11, 4, function (err, temperature,
humidity) {
if (!err) {
res.send(humidity.toFixed(1) + '%');

}
});
});

app
.listen(3000, function(){
console.log('Server listening on port 3000');
});

Overall, our servers, architecture can be described in terms of this diagram:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.117.152.251