27,59 €
Modern web technology and portable computing together have enabled huge advances in the Internet of Things (IoT) space,as well as in areas such as machine learning and big data. The Raspberry Pi is a very popular portable computer for running full stack web applications. This book will empower you to master this rapidly evolving technology to develop complex web applications and interfaces.
This book starts by familiarizing you with the various components that make up the web
development stack and that will integrate into your Raspberry Pi-powered web applications. It also introduces the Raspberry Pi computer and teach you how to get up
and running with a brand new one. Next, this book introduces you to the different kinds of
sensor you’ll use to make your applications; using these skills, you will be able to create
full stack web applications and make them available to users via a web interface. Later,
this book will also teach you how to build interactive web applications using JavaScript
and HTML5 for the visual representation of sensor data. Finally, this book will teach you
how to use a SQLite database to store and retrieve sensor data from multiple Raspberry
Pi computers.
By the end of this book you will be able to create complex full stack web applications
on the Raspberry Pi 3 and will have improved your application’s performance and usability.
Das E-Book können Sie in Legimi-Apps oder einer beliebigen App lesen, die das folgende Format unterstützen:
Seitenzahl: 194
Veröffentlichungsjahr: 2017
BIRMINGHAM - MUMBAI
Copyright © 2017 Packt Publishing
All rights reserved. No part of this book may be reproduced, stored in a retrieval system, or transmitted in any form or by any means, without the prior written permission of the publisher, except in the case of brief quotations embedded in critical articles or reviews.
Every effort has been made in the preparation of this book to ensure the accuracy of the information presented. However, the information contained in this book is sold without warranty, either express or implied. Neither the author, nor Packt Publishing, and its dealers and distributors will be held liable for any damages caused or alleged to be caused directly or indirectly by this book.
Packt Publishing has endeavored to provide trademark information about all of the companies and products mentioned in this book by the appropriate use of capitals. However, Packt Publishing cannot guarantee the accuracy of this information.
First published: August 2017
Production reference: 1020817
ISBN 978-1-78829-589-5
www.packtpub.com
Author
Soham Kamani
Copy Editor
Stuti Srivastava
Reviewers
Avron Bernard Olshewsky
Krishnaraj Varma
Project Coordinator
Virginia Dias
Commissioning Editor
Vijin Boricha
Proofreader
Safis Editing
Acquisition Editor
Meeta Rajani
Indexer
Aishwarya Gangawane
Content Development Editor
Sweeny Dias
Graphics
Kirk D'Penha
Technical Editor
Prashant Chaudhari
Production Coordinator
Aparna Bhagat
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.
Avron Bernard Olshewsky is an entrepreneurial technologist with a background in server-side telecommunication software engineering. Since 2006, he has worked as a founder, advisor, and consultant for technology start-up companies and small businesses. He has over 20 years of commercial software engineering experience, developing and leading innovative software solutions. In addition to advising start-ups on technology viability, architecture, specification, the resources required, funding, and roadmap, he has also been involved with long-established companies such as T-Mobile, Motorola, and IBM in various engineering capacities.
Krishnaraj Varma is a software professional and a tech enthusiast from Kerala, India. Primarily a software architect and a programmer, he started programming in the 90s in DBMS such as dBase and Clipper. After that, he started coding in C and C++ and continues to do so because of his vast interest in these languages. His areas of expertise are Internet of Things, Big Data, real-time streaming pipelines.
Apart from coding and technology, he is interested in nature, movies, and music.
For support files and downloads related to your book, please visit www.PacktPub.com.
Did you know that Packt offers eBook versions of every book published, with PDF and ePub files available? You can upgrade to the eBook version at www.PacktPub.com, and as a print book customer, you are entitled to a discount on the eBook copy. Get in touch with us at [email protected] for more details.
At www.PacktPub.com, you can also read a collection of free technical articles, sign up for a range of free newsletters and receive exclusive discounts and offers on Packt books and eBooks.
https://www.packtpub.com/mapt
Get the most in-demand software skills with Mapt. Mapt gives you full access to all Packt books and video courses, as well as industry-leading tools to help you plan your personal development and advance your career.
Fully searchable across every book published by Packt
Copy and paste, print, and bookmark content
On demand and accessible via a web browser
Thanks for purchasing this Packt book. At Packt, quality is at the heart of our editorial process. To help us improve, please leave us an honest review on this book's Amazon page at https://www.amazon.com/dp/1788295897.
If you'd like to join our team of regular reviewers, you can e-mail us at [email protected]. We award our regular reviewers with free eBooks and videos in exchange for their valuable feedback. Help us be relentless in improving our products!
Preface
What this book covers
What you need for this book
Who this book is for
Conventions
Reader feedback
Customer support
Downloading the example code
Downloading the color images of this book
Errata
Piracy
Questions
Getting Started on the Raspberry Pi
The Internet of Things
A brief look at our application
The sensor interface - perception
The database - persistence
The user interface - presentation
The application server - middleware
Setting up our Raspberry Pi
Remote access
Summary
Getting Up-and-Running with Web Development on the Raspberry Pi
The network
The web development stack
The UI - the user's first encounter
The server - the brains of the application
Client-server communication
Interfacing with external hardware
The database - adding persistence to our data
Integrating the database into our application
The overall architecture
Summary
Running a Node Server on the Pi
Introducing nodes - the server side JavaScript runtime
Installing node on the Pi
Running our first node program
Setting up a version control system
Back to our program
Installing external libraries
Developing the application server
Adding routes to the server
Starting up the server
Keeping the server running in the background
Summary
Extracting Information from the GPIO Pins
The GPIO pins on the Pi
The pin as a standalone component
The Write mode
The Read mode
Fine-tuning our control - using the GPIO command-line tools
The DHT11 sensor
Reading from the sensor
Summary
Retrieving Sensor Readings from the Server
Understanding how our node process takes readings
Modifying our server code to show sensor readings
Optimizing our server
Abstracting our sensor library code
Caching our results
Summary
Creating a Web Page to Display Sensor Data
Extending our application
Serving static files from the Express server
Building the UI's functionality
Adding client-side JavaScript
Fetching sensor readings using XHR
Visually enhancing the UI
Changing the structure of our UI
Adding style to the newly modified structure
Summary
Enhancing Our UI - Using Interactive Charts
Considerations when implementing complex features
Introducing Chart.js
Installing Chart.js
Creating our first chart
Making the server response data-friendly
Modifying the sensor dashboards to consume JSON data
Integrating sensor data into our charts
A code overview
index.js
public/index.html
public/script.js
Summary
SQLite - The Fast and Portable Database
Picking the correct tool for the job
Installation
Creating the temperature and humidity tables
Running CRUD operations
Create
Read
Update
Delete
Aggregations
Advanced aggregations using subqueries
Summary
Integrating SQLite into Our Application
Interfacing SQLite with node
Running queries with node
Making our database module
Adding a new temperature to the database
Fetching the last n readings from a table
Fetching readings between a certain time period
Fetching the average of readings between time periods
Putting the functions together in a module
Integrating the database module into our server application
Upgrading the sensor interface module
Adding an API to get the latest ten readings
Consuming the API on the client side
Adding new features - the ability to view readings from a custom time period
Adding the required APIs
Summary
Making our Application Real Time with Web Sockets
Web sockets
Implementing web sockets in our application
The socket.io library
Client-side installation
Server-side installation
Creating our socket implementation in our application server
Client-side implementation
Summary
Deploying our application to Firebase
The Firebase platform
Migrating to Firebase
The User interface
Database
Server application and sensor interface
Creating your first Firebase application
Installing the Firebase CLI
Logging in to Firebase on the command line
Initializing a new Firebase application
Testing and deploying the application to the cloud
Migrating the frontend assets
Adding Firebase tools
Adding the Realtime Database
Enabling access to the Firebase Database
Adding listeners to the client-side script
Summary
Using Firebase APIs to Update Our Application
Application server versus application process
Securing our application
The application process architecture
Implementing the application process
Summary
Just a few decades back, the average computer was the size of an entire city block and could barely store 5 MB of data. Today, this amount of data is consumed by an average image upload, and the dimensions of the modern computer have reached a stage where we can hold one on the palm of our hands. Alongside the reduction in size, computers have also undergone a tremendous reduction in cost. Raspberry Pi is the flag bearer of portable and affordable computing, barely costing $30 and being small enough to be held in your hand.
The introduction of Raspberry Pi has opened the doors for applications that would not have been feasible otherwise, and that is precisely what you will learn from this book.
In the chapters to follow, you will learn how Raspberry Pi can be utilized to its full potential and act as a sensor interface, a web server, and a database and host all the components of a fully functioning web application. You will also learn how to utilize cloud-based APIs and data storage and combine this with the existing components developed on Raspberry Pi to make an application that can accessed by anyone with an internet connection.
Chapter 1, Getting Started on the Raspberry Pi , takes a brief look at Raspberry Pi, its OS, and how to get started using it
Chapter 2, Getting Up-and-Running with Web Development on the Raspberry Pi, covers a high-level overview of the project that we will build and the different components of its technology stack.
Chapter 3,Running a Node Server on the Pi, helps you get started with Node.js, its installation on the Pi, and how to get up and running with Node.js by running a web server on the Pi.
Chapter 4, Extracting Information from the GPIO Pins, introduces you to the DHT22 sensor and demonstrates how to get information about the temperature and humidity recorded from the sensor.
Chapter 5, Retrieving Sensor Readings from the Server, goes through how to make the sensor readings available to the node server that was made earlier. By the end of this chapter, you will know how to make sensor readings available through a REST API.
Chapter 6,Creating a Web Page to Display Sensor Data, gets you started with your UI development journey by developing a webpage that will make use of the API created in the previous chapter to display the data received from the sensor in a user-friendly webpage.
Chapter 7, Enhancing Our UI - Using Interactive Charts, covers how to make an even richer user interface through the use of charts. This will be achieved through the use of open source chart libraries
Chapter 8,SQLite - The Fast and Portable Database, covers the basic concepts of the SQLite database and teaches you how to install and run it on your Pi.
Chapter 9, Integrating SQLite into Our Application, explains how to upgrade our existing application built in the previous chapters by persisting our data.
Chapter 10,Making Our Application Real Time with Web Sockets, discusses how all this time, the only way for our HTML5 frontend to get data from the server was through polling and making requests at regular intervals. Web sockets allow us to establish a connection only once, after which the server can actually push data to the browser.
Chapter 11, Deploying Our Application to Firebase, reiterates that our entire application is currently hosted on the Raspberry Pi. This works, but is not very scalable. This chapter will go through how to host our UI and database on Google's Firebase cloud architecture.
Chapter 12,Using Firebase APIs to Update Our Application, covers how to update the database by calling Firebase's cloud APIs from Raspberry Pi so that the cloud hosted application can get a continuous feed of the readings on the Pi.
The reader should have some basic knowledge and programming experience (in any programming language). An awareness of the basic concepts regarding HTML and JavaScript would be a plus point, but is not required, and of will be covered in brief in this book. The reader is also expected to have a base level understanding of electronic hardware (how to connect pins and wires).
To execute all the examples given in this book, you will need the following:
A Raspberry Pi board, which will be the device where all the code is executed
Monitor, keyboard, and mouse to interact with the Raspbian OS
Memory card for the Raspberry Pi
Personal computer (optional), although this book is designed such that the entire application can be built and executed on the Pi, having a computer handy can help a lot.
This book is aimed at hobbyist, enthusiasts, and developers eager to develop embedded device-powered web applications. Prior programming experience with JavaScript, HTML5, and Node.js will be beneficial.
In this book, you will find a number of text styles that distinguish between different kinds of information. Here are some examples of these styles and an explanation of their meaning. Code words in text, database table names, folder names, filenames, file extensions, pathnames, dummy URLs, user input, and Twitter handles are shown as follows: "Most of these files have no meaning to us except the INSTRUCTIONS-README.txt file."
A block of code is set as follows:
app.get('/temperature', function(req, res) { res.send('24
°
C'); });
Any command-line input or output is written as follows:
firebase --version
New terms and important words are shown in bold. Words that you see on the screen, for example, in menus or dialog boxes, appear in the text like this: "In the Firebase console, go to the SERVICE ACCOUNTS section of your application settings."
Feedback from our readers is always welcome. Let us know what you think about this book-what you liked or disliked. Reader feedback is important for us as it helps us develop titles that you will really get the most out of. To send us general feedback, simply e-mail [email protected], and mention the book's title in the subject of your message. If there is a topic that you have expertise in and you are interested in either writing or contributing to a book, see our author guide at www.packtpub.com/authors.
Now that you are the proud owner of a Packt book, we have a number of things to help you to get the most from your purchase.
You can download the example code files for this book from your account at http://www.packtpub.com. If you purchased this book elsewhere, you can visit http://www.packtpub.com/supportand register to have the files e-mailed directly to you. You can download the code files by following these steps:
Log in or register to our website using your e-mail address and password.
Hover the mouse pointer on the
SUPPORT
tab at the top.
Click on
Code Downloads & Errata
.
Enter the name of the book in the
Search
box.
Select the book for which you're looking to download the code files.
Choose from the drop-down menu where you purchased this book from.
Click on
Code Download
.
Once the file is downloaded, please make sure that you unzip or extract the folder using the latest version of:
WinRAR / 7-Zip for Windows
Zipeg / iZip / UnRarX for Mac
7-Zip / PeaZip for Linux
The code bundle for the book is also hosted on GitHub at https://github.com/PacktPublishing/Full-Stack-Web-Development-with-Raspberry-Pi-3/. We also have other code bundles from our rich catalog of books and videos available athttps://github.com/PacktPublishing/. Check them out!
We also provide you with a PDF file that has color images of the screenshots/diagrams used in this book. The color images will help you better understand the changes in the output. You can download this file from https://www.packtpub.com/sites/default/files/downloads/FullStackWebDevelopmentwithRaspberryPi3_ColorImages.pdf.
Although we have taken every care to ensure the accuracy of our content, mistakes do happen. If you find a mistake in one of our books-maybe a mistake in the text or the code-we would be grateful if you could report this to us. By doing so, you can save other readers from frustration and help us improve subsequent versions of this book. If you find any errata, please report them by visiting http://www.packtpub.com/submit-errata, selecting your book, clicking on the Errata Submission Form link, and entering the details of your errata. Once your errata are verified, your submission will be accepted and the errata will be uploaded to our website or added to any list of existing errata under the Errata section of that title. To view the previously submitted errata, go to https://www.packtpub.com/books/content/support and enter the name of the book in the search field. The required information will appear under the Errata section.
Piracy of copyrighted material on the Internet is an ongoing problem across all media. At Packt, we take the protection of our copyright and licenses very seriously. If you come across any illegal copies of our works in any form on the Internet, please provide us with the location address or website name immediately so that we can pursue a remedy. Please contact us at [email protected] with a link to the suspected pirated material. We appreciate your help in protecting our authors and our ability to bring you valuable content.
If you have a problem with any aspect of this book, you can contact us at [email protected], and we will do our best to address the problem.
The Raspberry Pi has become hugely popular as a portable computer, and for good reason. When it comes to what you can do with this tiny piece of technology, the sky's the limit. Back in the day, computers used to be the size of entire neighborhood blocks, and only large corporations doing expensive research could afford them. After that, we went on to embrace personal computers, which were still a bit expensive, but, for the most part, could be bought by the common man. This brings us to where we are today, where we can buy a fully functioning Linux computer, which is as big as a credit card, for under $30. It is truly a huge leap in making computers available to anyone and everyone.
The marvel of the Raspberry Pi, however, doesn't end here. Its extreme portability means we can now do things that were not previously possible with traditional desktop computers. The GPIO pins give us easy access to interface with external devices. This allows the Pi to act as a bridge between embedded electronics and sensors and the power that Linux gives us. In essence, we can run any code in our favorite programming language (which can run on Linux) and interface it directly to outside hardware quickly and easily. Once we couple this with the wireless networking capabilities introduced in the Raspberry Pi 3, we gain the ability to make applications that would not have been feasible to make before this device existed.
Web development and portable computing have come a long way. A few years ago, we couldn't dream of making a rich, interactive, and performant application that runs on the browser. Today, not only can we do that, but we can also do it all in the palm of our hands (quite literally). When we think of developing an application that uses databases, application servers, sockets, and cloud APIs, the picture that normally comes to mind is that of many server racks sitting in a huge room. In this book, however, we are going to implement all of that using only the Raspberry Pi.
In this chapter, we will go through the concept of the Internet of Things and discuss how web development on the Raspberry Pi can help us get there. Following this, you will also learn how to set up your Raspberry Pi and access it from our computer.
We will cover the following topics:
The
Internet of Things
(
IoT
)
Our application
Setting up the Raspberry Pi
Remote access
The web has, until today, been a network of computers exchanging data. The limitation of this was that it was a closed loop. People could send and receive data from other people via their computers but rarely much else.
The IoT, in contrast, is a network of devices or sensors that connect the outside world to the internet. Superficially, nothing is different: the internet is still a network of computers. What has changed is that now, these computers are collecting and uploading data from things instead of people. This now allows anyone who is connected to obtain information that is not collected by a human.
The IoT as a concept has been around for a long time, but it is only now that almost anyone can connect a sensor or device to the cloud, and the IoT revolution was hugely enabled by the advent of portable computing, which was led by the Raspberry Pi.
Throughout this book, we are going to go through different components and aspects of web development and embedded systems. These are all going to be held together by our central goal of making an entire web application capable of sensing and displaying the surrounding temperature and humidity.
In order to make a properly functioning system, we have to first build the individual parts. More difficult still is making sure all the parts work well together. Keeping this in mind, let's take a look at the different components of our technology stack and the problems that each of them solves:
