K O logo
IoT

IoT — going serverless

Author

Kalle

Date Published

This AI-generated image depicts a multi-layered, futuristic architecture model, showcasing interconnected IoT systems, cloud computing, and infrastructure, with Raspberry Pi technology prominently featured.

After bringing the software to the cloud last week, this session is all about the next buzzword: Serverless.

Like the "cloud", "serverless" is also a very vague definition and to make it clear from the start, yes there are running servers to run your serverless code. The term serverless describes more the way the services you develop are written, it's one more step on the abstraction layer. I see two ways to do serverless development, the first is based on SaaS products and basically plug and play of different tools. The second one is referenced as functions running in the cloud, which is more of an architecture decision than a new cloud technology. For larger projects these principles enable you to have a very granular and precise encapsulation of responsibility. For smaller projects serverless development enables you to get running really fast, because you don't have to care about any platform or infrastructure. On the other hand giving away all these decisions also strips away flexibility, so always think carefully about your needs before you set down on one tech-stack.

For this course and our sensor project we will use firebase, a service by google, which also has a generous free plan. After authenticating with your google account you can open the firebase console to manage your projects.

The image shows the Firebase console's welcome screen. It features a "Welcome to Firebase!" message, with options to learn more, view documentation, or get support. Below, there are sections for recent projects, with an option to add a new project or explore a demo project.

When you add a new project to your firebase account you can decide on some privacy and location settings for your service. But to host some functions, at the moment only the us locations are viable.

The image shows a form titled "Add a project" for creating a new project. It includes fields for "Project name" (set to "My awesome project"), "Project ID" (set to "my-awesome-project-id"), "Analytics location" (set to Germany), and "Cloud Firestore location" (set to us-east1). There are checkboxes for sharing Google Analytics data and accepting terms. The "Create project" button is disabled, and there's a "Cancel" button.

With firebase you get an all in one service providing solutions for authentication, database, storage, hosting, functions and even machine learning capabilities. For the sensors project only collects data from the connected sensors so the first migration step from the still file-system based storage solution on heroku is to create a database for your firebase project. To do so select the "Database" section and create a new firestore database (if you aren't sure what you are doing start in locked mode).

To use this database you need the firebase-admin dependency. And you should create a new service account by going to google cloud admin area of your project. The new service account should have the editor role to be able to write data. On the last step create a json key file which will be used to authenticate to the database from the node process. Save the json file to the project folder and add it to a .gitignore file to prevent adding it to a repository.

Before you start working on the actual program you should start by creating the new project on the Raspberry Pi:

1{
2 "name": "firebase-device",
3 "scripts": {
4 "start": "node index.js"
5 },
6 "dependencies": {
7 "node-dht-sensor": "^0.0.34",
8 "onoff": "^3.2.2",
9 "sleep-promise": "^8.0.1",
10 "yargs": "^12.0.5",
11 "firebase-admin": "^6.3.0"
12 }
13}

Unfortunately right now the protocol (gRPC) to transfer data to and from firebase is not directly compatible with Node.js on ARMv6 and has to be built on the device. After running npm install in the project folder run the command

1npm rebuild --build-from-source grpc

The rebuild process takes some time (especially on the Raspberry Pi) so I have prepared a zipped node_modules folder with the installed and rebuild dependencies for node v10.14.1 and v11.1.0

node_modules-node10-grpc-armv6.tar.gz
1curl -o node_modules-node10-grpc-armv6.tar.gz https://github.com/kaoDev/kalleott.de/raw/prebuilt_archives/samples/firebase-device/node_modules-node10-grpc-armv6.tar.gz
2tar -zvxf node_modules-node10-grpc-armv6.tar.gz -C ./
node_modules-node11-grpc-armv6.tar.gz
1curl -o node_modules-node11-grpc-armv6.tar.gz https://github.com/kaoDev/kalleott.de/raw/prebuilt_archives/samples/firebase-device/node_modules-node11-grpc-armv6.tar.gz
2tar -zvxf node_modules-node11-grpc-armv6.tar.gz -C ./

Now that all dependencies are able to run on the device you can start to setup the connection to the "Firestore" database.
1// load the firebase dependency
2const firebase = require("firebase-admin");
3
4// load the certificate data created in
5// https://console.cloud.google.com/iam-admin/serviceaccounts
6// the account needs write access
7const serviceAccount = require("./firebase-key.json");
8
9// initialize firebase app with authentication data
10firebase.initializeApp({
11 credential: firebase.credential.cert(serviceAccount),
12});
13
14// get the reference to the firebase database
15const db = firebase.firestore();
16// set timestampsInSnapshots in the settings
17// (needed to prevent some legacy warnings)
18db.settings({
19 timestampsInSnapshots: true,
20});
Writing data with firestore is pretty straight forward, you just choose a collection to write to and then either add or set the data:
1/**
2 * takes the sensor values for temperature and humidity and the name
3 * of the source sensor
4 *
5 * @param {number} temperature
6 * @param {number} humidity
7 * @param {string} name
8 */
9async function writeData(temperature, humidity, name) {
10 try {
11 await db.collection("sensorData").add({
12 temperature,
13 humidity,
14 name,
15 // let the database create a timestamp
16 date: firebase.firestore.FieldValue.serverTimestamp(),
17 });
18 } catch (e) {
19 console.error("error writing to firestore", e);
20 }
21}

In the firebase console you can now see data added live to your database:

The image shows a Firestore database interface with a collection named "sensorData." Inside this collection, there are multiple documents, one of which is selected (ID: "7kiB8t24rUklmm94gMhr"). The document contains fields: "date" (3 December 2018 at 23:12:05 UTC+1), "humidity" (65), "name" ("Kalle's DHT11"), and "temperature" (22).

Tasks

  • create a firebase app to manage your sensor data
  • extend the program running on the Raspberry Pi to write data to the Firestore
This AI-generated image depicts a futuristic data center with large screens displaying real-time data visualizations and analytics. Rows of workstations with monitors analyze various sensor data and global metrics.

IoT — Data visualization

Learn to visualize IoT data by setting up Firebase and using Recharts to create dynamic charts. This guide covers connecting to Firestore, querying sensor data, and displaying it in a React app with interactive graphs.

Mailing List

If you want to receive updates on new posts, leave your email below.