Abstracting our sensor library code

We made three assumptions in our previous example:

  • We will always use the DHT11 sensor
  • The sensor will always be attached to pin 4
  • We will always use the node-dht-sensor library

Unfortunately, it isn't wise to assume that these assumptions will always hold true because of the following reasons:

  • We may opt for the more accurate DHT22 sensor
  • Pin 4 may get fried, after which we will have to switch to a different pin
  • The node-dht-sensor library may become deprecated in favor of a more up-to-date library

In any case, as developers, we should make sure that our code remains as flexible as possible. To do this, one possible solution is to make a separate file dedicated to retrieving our sensor readings:

    const sensor = require('node-dht-sensor')
/*
We abstract away the functionality to read sensor
information inside the getSensorReadings function.
This function is also asynchronous. It accepts a callback
function as an argument.
*/
const
getSensorReadings = (callback) => {
sensor.read(11, 4, function (err, temperature,
humidity) {
if (err) {
/*
If there is an error, call the callback function
with the error as its first argument
*/
return callback(err)
}
/*
If everything went well, call the callback with
"null" as the first argument to indicate that there was
no error.
The second and third arguments would be the results
(temperature and humidity respectively)
*/
callback(null, temperature, humidity)
})
}

/*
Finally, export the function so that it can be used by
other parts of our code
*/
module.exports = getSensorReadings

Now that we have separated the sensor read process in a separate module, let's refactor our server code to use it:

    const express = require('express')
const
app = express()
const
getSensorReadings = require('./get-sensor-
readings'
)

app
.get('/temperature', function (req, res) {
getSensorReadings((err, temperature, humidity) => {
if (!err) {
res.send(temperature.toFixed(1) + '°C')
}
})
})

app
.get('/humidity', function (req, res) {
getSensorReadings((err, temperature, humidity) => {
if (!err) {
res.send(humidity.toFixed(1) + '%')
}
})
}

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

Now, we can change the way we get sensor readings and still have our server working fine as long as we follow the callback signature.

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

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