Reader small image

You're reading from  Full Stack Web Development with Raspberry Pi 3

Product typeBook
Published inAug 2017
Reading LevelExpert
PublisherPackt
ISBN-139781788295895
Edition1st Edition
Languages
Right arrow
Author (1)
Soham Kamani
Soham Kamani
author image
Soham Kamani

Soham Kamani is a full-stack developer who has extensive experience in the JavaScript ecosystem. He works as a consultant, developing end-to-end web-based solutions for clients around the world. He is an open source enthusiast and an avid blogger. He has worked on many frameworks and technologies such as React, Angular, Node, Express, Sails, SQLite, Postgres, and MySQL, and he has worked on many projects in the IoT space using Arduino and Raspberry Pi systems.
Read more about Soham Kamani

Right arrow

Deploying our application to Firebase

Everything we did up to this point was restricted to the confines of the Raspberry Pi hardware. Although the Pi is a marvel of engineering in and of itself, it still comes with some limitations due to its small size. While hosting small-scale personal applications should not be much cause for concern, it would not be efficient to host a large-scale application entirely on the Pi.

In addition to this, letting others access your application would be another challenge altogether. How does one ensure that their Pi is always online when people need it? How can we take the load of multiple users without compromising our hardware? How can we ensure that the connectivity from the Pi (which is running in our home) is seamless to someone trying to access it potentially across the world?

The answer to all these questions is that it is nearly impossible...

The Firebase platform

Getting full-scale applications up and running fast and bug-free is surprisingly hard. First, you have to provision your server, then your database, then your UI, and then you've to make sure all components integrate with each other correctly (which is the hardest part). This gets even harder when you want to introduce more advanced functionality, such as authentication, notifications, real-time updates, and encryption.

The Firebase platform solves this pain point by giving us all this out of the box:

  • The Realtime Database is a tool to store and manage an applications persistent data as well as notify us when anything changes.
  • Firebase hosting allows us to move all our frontend static assets to the cloud so that they can be delivered to users across the globe with speed and security.
  • Performance monitoring and analytics give us in-depth information...

Migrating to Firebase

We covered the overall architecture of our application in the second chapter of this book. In order to migrate to Firebase, we need to rethink this architecture and see what we can leverage from the Firebase platform and, more importantly, what we can't.

The User interface

This is probably the easiest to decide. Our user interface takes the form of static files that need to be served to the user.

With Firebase Hosting, we can offload the task of serving static assets and files (arguably the highest load in terms of network traffic) entirely to the cloud.

Moreover, the reliability that a cloud solution provides will lead to faster and more secure retrieval of our static assets.

...

Creating your first Firebase application

To get started with Firebase, you will need to sign up and log in using their website: https://firebase.google.com/.

Go to the Firebase console (by clicking on GO TO CONSOLE), and then click on the Add project button:

You will then be asked some details, after which your new project should be created (and show up in this panel, such as the sensor-project project that is already created)

You can explore your project's console and take a look at the various features and add-ons that Firebase provides:

Installing the Firebase CLI

The Firebase CLI tools help us actually deploy and launch our code. To install the firebase CLI, run the command:

npm install -g firebase-tools

To test...

Migrating the frontend assets

The first part of moving to firebase is migrating our client-side files, which includes all of the HTML, CSS, and client-side JavaScript files we were serving earlier.

Our files are not going to be served on our application server anymore, and we will not be using its APIs anymore. In order to clean things up, we are going to remove the contents of all our API-invoking functions that were there in the client-side script, such as fetchTemperature, fetchHumidity, fetchHumidityHistory, fetchTemperatureHistory, fetchHumidityRange, and fetchTemperatureRange.

The resultant script.js file will look like this:

    const temperatureCanvasCtx = document
       .getElementById('temperature-chart')
       .getContext('2d')

    const temperatureChartConfig = {
      type: 'line',
      data: {
        labels: [],
        datasets...

Adding the Realtime Database

To establish the connection with our Realtime Database, let's create a database and add some dummy data to it first.

Go to the Database tab in the Firebase console, and you should find a database with your application name.

Use the in-app editor to add dummy values for a temperature and humidity key:

Now that we've added the database, let's connect to it from the frontend of our application.

Enabling access to the Firebase Database

Firebase provides us with a lot of security features. By default, an unknown user is not allowed to access data in the database from any frontend application. For our use case, we actually want everyone to have access to the data that we put on our database. To enable this, modify the database.rules.json file to have the following contents :

    {
     "rules": {
        ".read": "auth == null",
        ".write": "auth != null"
      }
    }

Now, everyone can read our data, and anyone who is authorized can write to our database.

Adding listeners to the client-side script

After installing Firebase and initializing the data in the Firebase Realtime Database, append the following code to your public/script.js file:

    /**
     * Initialize a new database with the firebase.database 
constructor */
const database = firebase.database() /** * database.ref returns a reference to a key in the
realtime database. * This reference comes with a listener to read the value
for the first time, and execute some action everytime a
value is received */
const temperatureListener = database.ref('temperature') temperatureListener.on('value', data => { /** * The contents of the listener are pretty much the
same as the listeners in our previous chapters. The only difference being that the value * of the data being read has...

Summary

This chapter started off with an introduction to the Firebase platform and the tools that it offers. It then went on to look at how our each tool that this platform provides would fit into our application's architecture.

After describing a new architecture to accommodate cloud-based APIs, we took a deep dive on migrating some of our code into it. This involved creating our first Firebase application, removing some of our older code, and introducing new code using the Firebase client side API to connect to the platform's cloud-based Realtime Database.

Overall, we completed the connection from client side to the cloud in this chapter. In the next chapter, we will be looking at how to link the other side of our application (sitting on the Raspberry Pi) to Firebase and thus enable our dashboard to show us actual sensor readings from our Pi, anywhere in the world...

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Full Stack Web Development with Raspberry Pi 3
Published in: Aug 2017Publisher: PacktISBN-13: 9781788295895
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Author (1)

author image
Soham Kamani

Soham Kamani is a full-stack developer who has extensive experience in the JavaScript ecosystem. He works as a consultant, developing end-to-end web-based solutions for clients around the world. He is an open source enthusiast and an avid blogger. He has worked on many frameworks and technologies such as React, Angular, Node, Express, Sails, SQLite, Postgres, and MySQL, and he has worked on many projects in the IoT space using Arduino and Raspberry Pi systems.
Read more about Soham Kamani