Logging your energy consumption over time

For now, we built a smart plug that has more or less the same features as a commercial smart plug: it can control a device, measure the power consumption of this device, and also comes with a nice graphical interface. In this section, we are going to go further, and see how we can easily add functions to our project with some lines of code.

As an example, we are going to see how to log the measurements made by the board into a database on the Pi so that those measurements can be recalled later. As the code for this section is really similar to the previous section, I will only highlight the main changes here.

Start by importing the required module for the database:

var Datastore = require('nedb')
  db = new Datastore();

After that, we define a route to get all the data currently present inside the database:

app.get('/data', function (req, res) {

  db.find({}, function (err, docs) {

    res.json(docs);

  });

});

Inside the measurement loop, we create a new set of data at every iteration and store it in the database:

var data = {
          current: measuredCurrent.toFixed(2),
          power: power.toFixed(2),
          date: new Date()
      };
      db.insert(data, function (err, newDoc) {
          console.log(newDoc);
      });

Let's now try this new piece of software. Again, navigate to the folder where you put the files for this chapter and type the following command:

sudo npm install nedb

This will install the required module for the database. Then, launch the software with the following command:

sudo node meter_log.js

You should see the results from the measurements inside the console just as before, but this time with the confirmation that the document was stored in the database:

Logging your energy consumption over time

Note that I used quite a high refresh rate inside the code for demonstration purposes. Of course, I invite you to modify that in order to avoid filling your database with measurements.

You can also try to read the data that was logged inside the database by going to the following URL:

http://192.168.0.105/data

You should immediately see the results inside the browser:

Logging your energy consumption over time

You can now use this data for your own applications. For example, it can easily be used to calculate the average daily or monthly energy consumption of the device.

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

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