While I was on my internship in Berlin my colleagues complained about the terrific air quality in our office. It was literally so dry you had to have the windows open at all times to kind of make do.

So, naturally, we wanted to do something about it. Of course we couldn’t just go to our boss' boss and complain because we had no evidence. Other than us complaining (my boss' boss was the supervisor of this particular location of the company. Pretty important guy.) And with that in mind I started developing a monitoring solution using a Raspberry Pi and a DHT-11 temperature and humidity sensor.

First, I wanted to write the data collected to an CSV-File, since it was the easiest way of achieving what I wanted. But after a while I realized, that it would be even better to send this data to an API endpoint, which then stores the data in a database.

First getting the data tho. I used python, because it was convenient and already installed on the Pi. Using Adafruits' library for the sensor it was really easy to read the data and store in in a CSV-File.

#!/usr/bin/python3

import Adafruit_DHT
import time
import datetime
import requests
import os
from openpyxl import Workbook

file_path = os.getenv('file_path','dump.xls')
url = os.getenv('url','127.0.0.1:8000/entries')
id = os.getenv('id','default')
pin = int(os.getenv('pin',23))
sleep_time = int(os.getenv('sleep',300))

print(file_path)
print(url)
print(id)
print(pin)
print(sleep_time)

current_row = 2
sensor = Adafruit_DHT.DHT11
wb = Workbook()
ws = wb.active
ws.cell(row=1,column=1,value='Date/Time')
ws.cell(row=1,column=2,value='Humidity')
ws.cell(row=1,column=3,value='Temperature')



while True:
    try:
        humidity, temperature = Adafruit_DHT.read_retry(sensor, pin)
        if humidity is not None and temperature is not None:
            r = requests.post(url,data={'id': id,'time': datetime.datetime.now(), 'temp': temperature, 'hum': humidity})
            ws.cell(row=current_row, column=1,value=datetime.datetime.now())
            ws.cell(row=current_row, column=2,value=humidity)
            ws.cell(row=current_row, column=3,value=temperature)
            current_row += 1
            wb.save(file_path)
            time.sleep(sleep_time)
    except KeyboardInterrupt:
        wb.save(file_path)
        break
    except Exception as e:
        print(str(e))
        wb.save(file_path)

After I decided to build an API for this project I moved to JavaScript and Node.js. I literally chose Node.js because it was the first search result for “build API” (Future Nic: I didn’t know ASP.NET Web APIs were a thing back then ☹️). I also chose MongoDB for my database since I wanted to try something new and I never liked SQL stuffs. I Implemented a POST and a GET route for posting data to the server and getting all the data respectively.

The route for POSTing and GET-ing the data looks like this:

var ObjectID = require("mongodb").ObjectID;

module.exports = function (app, db) {
  app.get("/entries/:id", (req, res) => {
    const id = req.params.id;
    const details = {
      id: "0",
    };
    db.collection("entries")
      .find(details)
      .toArray(function (err, result) {
        if (err) {
          res.send({
            error: "An error has occurred",
          });
        } else {
          res.send(result);
        }
      });
  });
  app.post("/entries", (req, res) => {
    const entry = {
      id: req.body.id,
      time: req.body.time,
      temp: req.body.temp,
      hum: req.body.hum,
    };
    db.collection("entries").insertOne(entry, (err, result) => {
      if (err) {
        res.send({
          error: "An error has occurred",
        });
      } else {
        res.send(result.ops[0]);
      }
    });
  });
};

To be fair: I followed a tutorial on how to build an API, since I had no clue at all lol.

Also the recorded data was kind of not true and/or believable sometimes. I wrote a little .NET console application that parsed all the data and sanity-checked each value because of that. This application is, unfortunately, lost, since I didn’t make a copy of it before I left the company.

You can download my Sensor Handler and the corresponding API on my Github, if you’re interested.