Good Stuff Happens in 1:1 Meetings: Why you need them and how to do them well
Hack your home with a Raspberry Pi
1. Hack Your Home
With a Pi
M a d i s o n P H P C o n f e r e n c e 2 0 1 7
K e n M a r k s
2. • IT Programming Instructor at Madison
college
About
Ken Marks
KennethEMarks@gmail.com
@FlibertiGiblets
• Embedded and Medical Device
Software Engineer for 25+ years
• Used to brew my own beer
• Now I roast my own coffee beans
3. Ken Marks - Madison PHP Conference 2017
Goals
To show how easy it is to create a device that reports
sensor data which you can get on the internet
Along the way, you will see that deploying an
application to a Raspberry Pi is just as simple as
deploying to any Linux based LAMP stack
Slides at: http://kennethemarks.us/hackyourhomewithapi
4. Ken Marks - Madison PHP Conference 2017
About this Tutorial
Logging data
Interacting with your Pi
Configuring your Pi
What will you learn?
Creating and installing a Unix Service
Building a Web Service
Building a plotting App
Sending yourself a text message using sendmail (time permitting)
Connecting sensors
5. Ken Marks - Madison PHP Conference 2017
My Motivation for this Tutorial
It starts with a story…
6. Ken Marks - Madison PHP Conference 2017
The Story…
7. “Do I really need to
learn how to solder?”
What did the soldering iron say to the capacitor?
Go flux yourself!
8. Ken Marks - Madison PHP Conference 2017
Soldering Headers to the
Pi and Sensor
9. Ken Marks - Madison PHP Conference 2017
Here is your Pi and Sensor
Mini HDMI adapter
USB OTG cable5V power supply for Pi
Jumper wires
I2C accelerometer
with soldered header
Raspberry Pi Zero W with soldered
header in case with micro SD card
10. Ken Marks - Madison PHP Conference 2017
Interacting with your Pi
11. Ken Marks - Madison PHP Conference 2017
Power up your Pi
Power Supply
Micro USB Power
12. Ken Marks - Madison PHP Conference 2017
SSH into your Pi
Remotely SSH into your Pi using your computer’s terminal program
(Mac/Linux),
or PuTTY (Windows)
Your Pi’s IP address is
labeled on your Pi
Login: pi
Password: pizerow
ssh pi@192.168.10.101
Configure your laptop’s wireless to connect to:
SSID: HYHPI
PSK: hackyourhome!
13. Ken Marks - Madison PHP Conference 2017
Navigate the Filesystem
Checkout the /etc directory
Checkout the /var/www/html directory
See! It’s Raspian (Debian distro of Linux for the Raspberry Pi)
14. Ken Marks - Madison PHP Conference 2017
Configuring your Pi
15. Ken Marks - Madison PHP Conference 2017
Change your Password!
Run raspi-config and change the password on your Pi
sudo raspi-config
16. Ken Marks - Madison PHP Conference 2017
How was your Pi Provisioned?
Download latest Raspbian Lite Image from
https://www.raspberrypi.org/downloads/raspbian/
Burn Image onto SD Card
Unzip the image to a .img file
Using an SD Card Imager (I use Apple Pi Baker for my Mac), burn .img
file to Micro SD card.
17. Ken Marks - Madison PHP Conference 2017
How was your Pi Provisioned?
Insert MicroSD card into
Raspberry Pi Zero W
Login: pi
Boot up Raspberry Pi Zero W
Plug into Pi:
HDMI monitor
USB keyboard
Power supply
Login to Pi:
Password: raspberry
Power Supply
USB Keyboard
HDMI Cable
Mini HDMI
Micro USB OTG
Micro USB Power
Micro SD Card
18. Ken Marks - Madison PHP Conference 2017
How was your Pi Provisioned?
Your Pi has a complete LAMP Stack
19. Ken Marks - Madison PHP Conference 2017
Look! Apache is Running!
On your laptop, bring up a browser and navigate to your Pi’s IP address:
20. Ken Marks - Madison PHP Conference 2017
Connecting Sensors
21. Ken Marks - Madison PHP Conference 2017
Connection Diagram
22. Ken Marks - Madison PHP Conference 2017
Connection Diagram
23. Ken Marks - Madison PHP Conference 2017
Logging Data
24. Ken Marks - Madison PHP Conference 2017
Create a database for storing
accelerometer data
Log into MySQL on the command line and create a user account called
accelerometer that will own a table called accelerometer_data
sudo mysql -u root -p (password is root)
> CREATE USER 'accelerometer'@'localhost' IDENTIFIED BY 'accelerometer';
> GRANT ALL PRIVILEGES ON accelerometer_data.* TO
'accelerometer'@'localhost';
> FLUSH PRIVILEGES;
Exit the MySQL command line tool
The database will be called accelerometer_data, and have a table
called accelerometer_data which will store a time-stamp, and x, y, &
z axis accelerometer data
25. Ken Marks - Madison PHP Conference 2017
Create a database for storing
accelerometer data
In a web browser on your laptop, navigate to your Pi’s adminer web
tool (e.g. 192.168.10.103/adminer) and login as accelerometer
with a password of accelerometer:
26. Ken Marks - Madison PHP Conference 2017
Create a database for storing
accelerometer data
Create the accelerometer database and call it accelerometer_data:
27. Ken Marks - Madison PHP Conference 2017
Create a database for storing
accelerometer data
Download http://flibbertigiblets.com/
files/hackyourhomewithapi/
accelerometer_data.sql to your laptop
In adminer, import the
accelerometer_data.sql file into the newly
created accelerometer_data database:
28. Ken Marks - Madison PHP Conference 2017
Create a database for storing
accelerometer data
The accelerometer_data table should look like this:
29. Ken Marks - Madison PHP Conference 2017
Log the accelerometer data
Install the C++ MySQL Connector on your Pi
This will install the C++ libraries for using MySQL. The header files will
be installed in /usr/include/mysql. Type the following in the SSH
terminal window:
Install the I2C tools in the SSH terminal window:
I’ve created a C program to log 60 seconds of accelerometer data every
100 milliseconds (i.e. 600 rows of data max, deleting the oldest data)
sudo apt-get install default-libmysqlclient-dev libmysqlcppconn-dev
sudo apt-get install -y i2c-tools
30. Ken Marks - Madison PHP Conference 2017
Log the accelerometer data
pi@pizerow:~/accelerometer $ wget http://flibbertigiblets.com/files/
hackyourhomewithapi/log_accelerometer_data.cpp
Using wget (in your terminal window) download http://
flibbertigiblets.com/files/hackyourhomewithapi/
log_accelerometer_data.cpp to your accelerometer folder on your Pi:
On your Pi (in your terminal window), create a folder under your home folder
called accelerometer and change to the accelerometer folder:
pi@pizerow:~ $ mkdir accelerometer
pi@pizerow:~ $ cd accelerometer
pi@pizerow:~/accelerometer $
31. Ken Marks - Madison PHP Conference 2017
Log the accelerometer data
Run the log_accelerometer_data executable program:
g++ -std=c++11 -o log_accelerometer_data log_accelerometer_data.cpp
-lmysqlclient
On your Pi, in a terminal window, in the accelerometer folder, compile
log_accelerometer_data.cpp using the following command:
./log_accelerometer_data
Type ^C to exit from the program
32. Ken Marks - Madison PHP Conference 2017
Creating and Installing
a Unix Service
33. Ken Marks - Madison PHP Conference 2017
Install logging of accelerometer data
as a Unix Service
In order to avoid the pain of having to manually start up the
log_accelerometer_data program every-time we want to use it, we will
create a Unix service that will load the program every-time the system boots,
and unloads it when the system shuts down. This link: http://www.raspberrypi-
spy.co.uk/2015/10/how-to-autorun-a-python-script-on-boot-using-systemd/
explains it well.
34. Ken Marks - Madison PHP Conference 2017
sudo cp accelerometerdatalogging.service /lib/systemd/system
On your Pi, in a terminal window, in the accelerometer folder, copy the
accelerometerdatalogging.service file to the /lib/systemd/system
folder:
Install logging of accelerometer data
as a Unix Service
pi@pizerow:~/accelerometer $ wget http://flibbertigiblets.com/files/
hackyourhomewithapi/accelerometerdatalogging.service
Using wget (in your terminal window) download http://
flibbertigiblets.com/files/hackyourhomewithapi/
accelerometerdatalogging.service to your accelerometer
folder on your Pi:
35. Ken Marks - Madison PHP Conference 2017
Here are the commands to enable, disable, start, and stop the service:
sudo cp log_accelerometer_data /root
Before we can do this, we must copy the log_accelerometer_data
executable program to the /root folder. When we start up our
accelerometerdatalogging service, the program will run from
the /root folder:
Install logging of accelerometer data
as a Unix Service
sudo systemctl enable accelerometerdatalogging.service
sudo systemctl disable accelerometerdatalogging.service
sudo systemctl start accelerometerdatalogging.service
sudo systemctl stop accelerometerdatalogging.service
36. Ken Marks - Madison PHP Conference 2017
Now we can enable and start our logging service.
sudo systemctl enable accelerometerdatalogging.service
First, you must enable the service:
Install logging of accelerometer data
as a Unix Service
sudo systemctl start accelerometerdatalogging.service
Then, you must start the service:
37. Ken Marks - Madison PHP Conference 2017
Let’s Take a Break!
38. Ken Marks - Madison PHP Conference 2017
Building a Web Service
39. Ken Marks - Madison PHP Conference 2017
We want to create a web service that allows a user to get the latest logged
accelerometer data, and the latest accelerometer data entries starting from
a given unique id of an entry
This will be a simple REST service providing two mechanisms for
reading accelerometer data:
Building a Web Service
An HTTP GET (with no query parameters) will get the newest
accelerometer data and the id for the data
An HTTP GET with an id sent as a query parameter will get all
accelerometer data starting with the next id, all the way up to the
newest data. The newest accelerometer data’s id will be returned
40. Ken Marks - Madison PHP Conference 2017
We want to return a JSON payload to the client with the data:
{
"accelerationData": {
"accelerationMeasurements": [
{
"axis": {
"X": "0.078125",
"Y": "-0.15625",
"Z": "-0.996094"
},
"dateTime": "2017-06-14 18:21:33.834"
},
{
"axis": {
"X": "0.081055",
"Y": "-0.117188",
"Z": "-1.00781"
},
"dateTime": "2017-06-14 18:30:04.508"
}
],
"lastMeasurementId": "5893846"
}
}
Building a Web Service
41. Ken Marks - Madison PHP Conference 2017
Building a Web Service
On your Pi, in a terminal window, in the accelerometer folder, unzip the
accelerometerservice.zip file and copy to the accelerometerservice
folder to the /var/www/html folder:
unzip accelerometerservice.zip
sudo cp -r accelerometerservice /var/www/html
pi@pizerow:~/accelerometer $ wget http://flibbertigiblets.com/files/
hackyourhomewithapi/accelerometerservice.zip
Using wget (in your terminal window) download http://
flibbertigiblets.com/files/hackyourhomewithapi/
accelerometerservice.zip to your accelerometer folder on
your Pi:
42. Ken Marks - Madison PHP Conference 2017
Building a Web Service
The service is made up of the following files:
accelerometer_service.php
AccelerometerData.php
AccelerometerDataManager.php
In your browser on your laptop navigate out to
the accelerometer_service.php script:
43. Ken Marks - Madison PHP Conference 2017
Building a Plotting App
44. Ken Marks - Madison PHP Conference 2017
Now, lets create a Client side web page using JavaScript that makes an
AJAX call to the web service to get the latest accelerometer entries every
second. We will use Smoothie Charts (a JavaScript charting library) to chart
the accelerometer data
Building a Plotting App
45. Ken Marks - Madison PHP Conference 2017
unzip accelerometer.zip
sudo cp -r accelerometer /var/www/html
On your Pi, in a terminal window, in the accelerometer folder, unzip the
accelerometer.zip file and copy the accelerometer folder to the /var/
www/html folder:
Building a Plotting App
pi@pizerow:~/accelerometer $ wget http://flibbertigiblets.com/files/
hackyourhomewithapi/accelerometer.zip
Using wget (in your terminal window) download http://
flibbertigiblets.com/files/hackyourhomewithapi/
accelerometer.zip to your accelerometer folder on your Pi:
46. Ken Marks - Madison PHP Conference 2017
Building a Plotting App
The plotting application is made up of the following files:
index.html
smoothie.js
js_get_ip.php
acceleration.js
47. Ken Marks - Madison PHP Conference 2017
Sending a Text Message
using SendMail
48. Ken Marks - Madison PHP Conference 2017
First We Need a State Machine
Dryer Off Dryer Going On
Dryer OnDryer Going Off
< G-Force Oscillation
Tolerance
> G-Force Oscillation
Tolerance
< G-Force Oscillation
Tolerance
duration >
Oscillation Timeout
duration >
Oscillation Timeout
> G-Force Oscillation
Tolerance
Send text
Message
Dryer is off
49. Ken Marks - Madison PHP Conference 2017
Send a Text Message Using SendMail
It’s a good idea to have a separate Gmail account for this
We can use a Gmail account to send a text message to our phone using
SendMail on our Pi
50. Ken Marks - Madison PHP Conference 2017
Send a Text Message Using SendMail
Update and upgrade apt-get in the SSH terminal window:
Install ssmtp, mailutils, and mpack in the SSH terminal window:
sudo apt-get update
sudo apt-get upgrade
sudo apt-get install ssmtp mailutils mpack
Edit the /etc/ssmtp/ssmtp.conf file as sudo using
nano and add these lines to the end of the file:
mailhub=smtp.gmail.com:587
hostname=pizerow
AuthUser=YOU@gmail.com
AuthPass=PASSWORD
useSTARTTLS=YES
51. Ken Marks - Madison PHP Conference 2017
Install State Machine Code
On your Pi, in a terminal window, in the accelerometer folder, unzip the
dryerstatus.zip file:
unzip dryerstatus.zip
pi@pizerow:~/accelerometer $ wget http://flibbertigiblets.com/files/
hackyourhomewithapi/dryerstatus.zip
Using wget (in your terminal window) download http://
flibbertigiblets.com/files/hackyourhomewithapi/
dryerstatus.zip to your accelerometer folder on your Pi:
52. Ken Marks - Madison PHP Conference 2017
Modify the State Machine to Text you a Message
Edit DryerFSM.cpp and
change the phone number to
be your number just before
transitioning to the DryerOff
state in the DryerGoingOff
class:
53. Ken Marks - Madison PHP Conference 2017
Compile and run the State Machine
Run the log_dryer_status
executable program:
g++ -std=c++11 -o log_dryer_status log_dryer_status.cpp
GForceOscillation.cpp DryerFSM.cpp DryerStatusDBManager.cpp
-lmysqlclient -lmysqlcppconn
On your Pi, in a terminal window, in the accelerometer/dryer_status
folder, compile log_dryer_status using the following command:
./log_dryer_status
Type ^C to exit from the program
54. Ken Marks - Madison PHP Conference 2017
sudo cp dryerstatuslogging.service /lib/systemd/system
On your Pi, in a terminal window, in the accelerometer/dryerstatus folder,
copy the dryerstatuslogging.service file to the /lib/systemd/system
folder:
Install Logging of Dryer Status
as a Unix Service
sudo cp log_dryer_status /root
Copy the log_dryer_status executable program to the /root folder. When
we start up our dryerstatuslogging service, the program will run from
the /root folder:
sudo systemctl enable dryerstatuslogging.service
sudo systemctl start dryerstatuslogging.service
Enable and start the service:
55. Ken Marks - Madison PHP Conference 2017
Shutdown Your Pi
sudo shutdown -h now
On your Pi, in a terminal window, enter the following command to shutdown
your Pi:
56. Ken Marks - Madison PHP Conference 2017
Easy as Pi
Thank You!
KennethEMarks@gmail.com
@FlibertiGiblets
Please Leave Feedback at: https://joind.in/talk/d821d
Slides at: http://kennethemarks.us/hackyourhomewithapi
57. Ken Marks - Madison PHP Conference 2017
Appendix
58. Ken Marks - Madison PHP Conference 2017
Tools for Windows
Download PuTTY from http://www.putty.org/
PuTTY (SSH Terminal Window Program)
Download WinSCP from https://winscp.net/eng/download.php
WinSCP (SCP Program)
Download Wget from https://eternallybored.org/misc/wget/
current/wget64.exe
Wget for Windows (wget Program)
59. Ken Marks - Madison PHP Conference 2017
Provisioning your Pi
Download latest Raspbian Lite Image from
https://www.raspberrypi.org/downloads/raspbian/
Burn Image onto SD Card
Unzip the image to a .img file
Using an SD Card Imager (I use Apple Pi Baker for my Mac), burn .img
file to Micro SD card.
60. Ken Marks - Madison PHP Conference 2017
Insert MicroSD card into
Raspberry Pi Zero W
Login: pi
Boot up Raspberry Pi Zero W
Plug into Pi:
HDMI monitor
USB keyboard
Power supply
Login to Pi:
Password: raspberry
Power Supply
USB Keyboard
HDMI Cable
Mini HDMI
Micro USB OTG
Micro USB Power
Micro SD Card
Provisioning your Pi
61. Ken Marks - Madison PHP Conference 2017
Provisioning your Pi
Run raspi-config
Change password: pizerow
sudo raspi-config
Change hostname: pizerow
62. Ken Marks - Madison PHP Conference 2017
Provisioning your Pi
raspi-config
Change Localization Options:
Change Timezone:
US
Central
Change Locale:
Uncheck: en_GB.UTF-8 UTF-8
Check: en_US.UTF-8 UTF-8
Change Wi-fi Country:
US United States
Change Keyboard:
Generic PC-104
(Other)
English (US)
63. Ken Marks - Madison PHP Conference 2017
Provisioning your Pi
raspi-config
Change Interfacing Options:
Change P5 I2C:
Yes
Change P2 SSH:
Yes
Finish Changes and Reboot:
Finish
Save and Reboot
64. Ken Marks - Madison PHP Conference 2017
Provisioning your Pi
Login and get Pi Zero W on WiFi:
Login:
Login: pi
Password: pizerow
network={
ssid=“YOUR SSID”
psk=“YOUR WIRELESS PASSWORD”
proto=RSN
key_mgmt=WPA-PSK
pairwise=CCMP
auth_alg=OPEN
}
Edit /etc/wpa_supplicant/
wpa_supplicant.conf file:
sudo nano /etc/wpa_supplicant/wpa_supplicant.conf
Add the following to the end of the file to get on
the local WiFi (can create multiple entries):
65. Ken Marks - Madison PHP Conference 2017
Provisioning your Pi
Reboot and note IP and MAC address
Reboot:
sudo reboot
Get IP and MAC addresses:
ifconfig
66. Ken Marks - Madison PHP Conference 2017
Provisioning your Pi
Remotely SSH into your Pi
SSH into your Pi from another computer using your
computer’s terminal program or PuTTY (Windows):
ssh pi@192.168.10.103
67. Ken Marks - Madison PHP Conference 2017
Provisioning your Pi
Update Raspbian
Update and upgrade packages on Pi Zero W:
sudo apt-get update
sudo apt-get upgrade
Reboot Pi:
sudo reboot
68. Ken Marks - Madison PHP Conference 2017
Provisioning your Pi
Install LAMP Stack on Pi (Apache)
Install Apache:
sudo apt-get install apache2
Ensure Apache is running:
sudo systemctl status apache2
Bring up a browser on your local computer
and navigate to your Pi's IP address to
see the following web page:
69. Ken Marks - Madison PHP Conference 2017
Provisioning your Pi
Install LAMP Stack on Pi (PHP)
Install PHP 7:
sudo apt-get install php
Verify PHP version:
php -v
70. Ken Marks - Madison PHP Conference 2017
Provisioning your Pi
Install LAMP Stack on Pi (MySQL/MariaDB)
Install MySQL 5.6 (MariaDB 10.1):
sudo apt-get install mysql-server
Set root password to root.
Verify MySQL/MariaDB is running:
sudo systemctl status mysql
Verify MySQL/MariaDB is running:
sudo mysql -u root -p
71. Ken Marks - Madison PHP Conference 2017
Provisioning your Pi
Install LAMP Stack on Pi (PHP/MySQL/Apache)
Install PHP 7.0 connector for MySQL
sudo apt-get install php7.0-mysql
Edit php.ini file to display errors:
In /etc/php/7.0/apache2/php.ini file, set display_errors = On:
sudo nano /etc/php/7.0/apache2/php.ini
72. Ken Marks - Madison PHP Conference 2017
Provisioning your Pi
Test PHP
Create the following index.html page in /var/www/html:
<!DOCTYPE html>
<html>
<head>
<title>Lame Raspberry Pi Zero W Home Page</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u"
crossorigin="anonymous">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css" integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp"
crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></
script>
</head>
<body>
<div class='container'>
<div class='page-header'>
<h1>This is my Less, but Still Lame Raspberry Pi Zero W Home Page</h1>
</div>
<div class='well'>
<h3 class='text-danger'>Wow! If you got here, that means Apache is running. Yay!</h3>
</div>
<div class='well well-sm'>
<h4><a href='test.php' class='text-primary'>Testing PHP</a></h4>
</div>
</div>
</body>
</html>
73. Ken Marks - Madison PHP Conference 2017
Provisioning your Pi
Test PHP
Create the following test.php page in /var/www/html:
<?php
echo "<h1>Testing PHP!</h1><br/>";
date_default_timezone_set('America/Chicago');
echo "<hr>";
echo "<h1>Today is: " . date('l jS of F Y h:i:s A') . "</h1><br/>";
?>
74. Ken Marks - Madison PHP Conference 2017
Provisioning your Pi
Test PHP
Bring up a browser and navigate to your Pi’s IP address to see the
following web page:
75. Ken Marks - Madison PHP Conference 2017
Provisioning your Pi
Install Adminer
On your Pi, download Adminer to your home or Downloads folder:
wget https://github.com/vrana/adminer/releases/download/v4.3.1/
adminer-4.3.1-mysql-en.php
In /var/www/html/ make an adminer folder:
cd /var/www/html
sudo mkdir adminer
Copy the adminer.php file to /var/www/html/adminer/
index.php:
sudo cp ~/Downloads/adminer-4.3.1-mysql-en.php /var/www/html/
adminer/index.php
76. Ken Marks - Madison PHP Conference 2017
Provisioning your Pi
Grant Privileges to DB root account
Grant all privileges to root:
GRANT ALL PRIVILEGES on *.* TO ‘root’@‘localhost’ IDENTIFIED BY ‘root’;
Log into MySQL:
sudo mysql -u root -p
77. Ken Marks - Madison PHP Conference 2017
Provisioning your Pi
Log into Adminer