BeagleBone For Dummies (2015)
Part VI
Playing with the BeagleBone
Chapter 15
Running Your Home Automation Web Server
In This Chapter
Understanding the advantages of using the BeagleBone for home automation
Exploring home automation web servers
Writing web pages to control outputs and inputs
Controlling house appliances with the BeagleBone
Improving your web server
The BeagleBone is an outstanding platform for integrating computation with electronics, which allows you to create awe-inspiring projects featuring the best of both worlds. In this chapter, you build your very own home automaton web server — a web page that interacts with the physical world. The objective of this chapter is to help you build a canvas to which you can add more features as you desire.
Exploring What You Can Do
This section explores the possibilities of this project and explains the limitations of creating a web server.
The BeagleBone is quite a powerful tool when it comes to home automation. Because it provides easy access to the web and lots of general purpose input/outputs (GPIOs), you can do several neat things with it. All the projects from the other chapters — and more! — can be controlled remotely through the web server that you build with this chapter. You can control everything from LEDs to your toaster to your air conditioner. Isn’t that exciting?
Limitations exist, however. The main limitation of this project is the fact that accessing your BeagleBone from anywhere in the world (through a hosted website) isn’t as straightforward as you might hope. You’re limited to accessing the BeagleBone through any device — laptop or desktop computer, smartphone, tablet or even another BeagleBone — that’s connected to your router.
If you really want to control your web server from locations outside your workplace or home, you can overcome this limitation through a technique known as router port forwarding. In router port forwarding, a computer — the BeagleBone, in this case — on your network is made accessible by any computer on the Internet. Explaining this technique is beyond the scope of this book, but plenty of tutorials are available on the web. If you port-forward your router and put your website on the Internet, nothing will stop you from using the web server from anywhere in the world.
Examining the Framework
To complete this project, you should know the basics of BoneScript, HTML, and CSS. If you need more information, read Chapters 7 and Chapter 13.
When you’re done with the project in this chapter, your BeagleBone will be hosting a web server, establishing a communication between your device’s web browser and your BeagleBone GPIOs. Your web server is created with some Node.js code, and when you access IP address 192.168.7.2:8888, your web browser requests two files — index.html and stylesheet.css — that are stored on your BeagleBone (see Figure 15-1). Those files are displayed like regular web pages in your web browser so you see a nice graphical user interface (GUI).
Figure 15-1: Diagram of the framework.
192.168.7.2 is the local USB address of your BeagleBone; 8888 is the port that you’ll be using. A port is an application-specific software construct that acts as the endpoint on a computer’s operating system. Theoretically, you can use any number from 0 to 65535 as the port, but some numbers won’t work because they’re reserved — for example, 3000 is reserved for the Cloud9 IDE. You can try whichever port you want, but rest assured that 8888 works just fine.
When you click one of the buttons on your web page, an event triggers and talks with your Node.js code, which has the package socket.io listening for an event to occur. Based on that event message, your Node.js code can either read from or write in your BeagleBone’s pins.
The following sections get into the specifics.
Installing socket.io
Your BeagleBone comes with most Node.js packages that you need, but for this project, you have to install an additional package called socket.io. Type the following commands in a terminal:
sudo npm install update
sudo npm install _g socket.io
The first command updates the list of all available packages to the latest version, and the second one installs socket.io globally. This package allows real-time communication between your web-browser events and your BeagleBone. In other words, as soon as you click a button on your web page, your Node.js code that was listening acts immediately according to the message sent in that event.
You must ensure that your BeagleBone has an Internet connection before you update and install the socket.io package.
Keeping your files organized
We encourage you to use the Cloud9 IDE as often as possible to program your BeagleBone. For this chapter particularly, Cloud9 is perfect for running and debugging projects in Node.js.
Keeping your files organized is a must. Follow these steps to get organized:
1. Create a new folder called controllingOutputs.
This folder is where you’re going to store all the other files.
2. Create the following files in the controllingOutputs folder:
· A JavaScript file named server.js
· An HTML file named index.html
· A CSS file named stylesheet.css
Repurposing your previous HTML and CSS
Chapter 13 explains how to build a website. If you’ve already worked through that chapter, you can start by copying the website files to your new files index.html and stylesheet.css.
We don’t describe the changes that we made in our stylesheet.css file because they’re really minor and not relevant to this chapter. If you’ve read Chapter 13, you should be able to make these changes easily, or customize your web page to look as you prefer. You can also download those files at www.dummies.com/cheatsheet/beaglebone.
Wiring Your Circuit
For the circuit, you need a breadboard, a light-emitting diode (LED), a 220Ω or 470Ω resistor, and two jumper wires. The LED must be connected to pin P9_14 of your BeagleBone. For details on how to wire this circuit, read Chapter 7.
This project isn’t about the LED; it’s about getting the communication between your web server and the BeagleBone running. Normally, lighting up an LED is the first thing you do when employing a new technique. In this case, the new technique is working with the web server. In fact, every electronics enthusiast rejoices whenever they are able to light up an LED with a different technology. But here’s the most important thing: If you can control an LED, you can control any electronic device — such as your toaster, your desktop light, or your air conditioner — through a neat web page that you can access with your smartphone or tablet from the comfort of your sofa. How cool is that?
Writing Your Web Page
You can download all the code used throughout this chapter at www.dummies.com/cheatsheet/beaglebone.
At first, your index.html file will be very similar to the web-page file in Chapter 13. It simply has a few basic tags: <html>, <head>, and <body>. You give a title to your web page and link it to your stylesheet.cssfile. Finally, you insert a wrapper, a logo, a footer, and some <div> tags to organize your content in a centered container. Nothing new here.
<!DOCTYPE html>
<html>
<head>
<title>Home Automation Web Server with BeagleBone</title>
<link rel="stylesheet" href="stylesheet.css" type="text/css" />
</head>
<body>
<div id="wrapper">
<div id="logo"><h1>Home Automation Web Server</h1></div>
<div id="container" class="center">
</div>
<div id="footer"><p>Powered by BeagleBone</p></div>
</div>
</body>
</html>
Creating your GUI
The best thing about this project is that it makes building your own GUI easy. You don’t need a terminal window to input data in or read your data from. Inside the container <div>, type the following code, which displays in your web page the word LED with a heading number two:
<h2>LED</h2>
Below your heading number two, you should have a paragraph tag (<p>) that’s updated when you click the buttons and that also gives you feedback on the LED’s status (on or off):
<p id="outputStatus">Status</p>
In the next snippet of code, you create two buttons that appear on your web page. When you click these buttons, the changeState() function is triggered. This function takes only one parameter: state, which can be 1 or 0.
<div id="buttons"><ul>
<li><a onclick="changeState(1);">ON</a></li>
<li><a onclick="changeState(0);">OFF</a></li>
</ul></div>
Adding JavaScript to your web page
Inserting scripts into your web page makes the page interactive. Any scripts that you want to add to your web page always go inside the <head> tag. Type the following line of code:
<script src = "/socket.io/socket.io.js" ></script>
That snippet of code imports the socket.io library, which is required for establishing a communication between your web page and your server.
Next, you add JavaScript to your web page by adding <script> tags:
<script>
// Your JavaScript code goes here
</script>
Explaining your main JavaScript
All the code in this section goes inside the <script> tags. First, you have to establish communication with your server with the io.connect() function:
// Establishing connection with server
var socket = io.connect();
The changeState(state) function is triggered every time you click a button in the interface. This function takes a state parameter. If state is equal to 1, it emits a changeState event that tells your BeagleBone that it has to turn on the LED. It also updates the paragraph with the ID outputStatus to “Status: ON”.
// Changes the led state
function changeState(state){
if (state==1){
// Emit message changing the state to 1
socket.emit('changeState', '{"state":1}');
// Change led status on web page to ON
document.getElementById("outputStatus").innerHTML = "Status: ON";
}
else if (state==0){
// Emit message changing the state to 0
socket.emit('changeState', '{"state":0}');
// Change led status on web page to OFF
document.getElementById("outputStatus").innerHTML = "Status: OFF";
}
}
The following paragraphs break down the new functions.
The emit() function takes two parameters:
socket.emit(<event name>, <event message>)
· event name is a string with the event name that your server.js file is listening to.
· event name is an object with one value called state, which is 1 or 0.
The getElementById() function searches for an HTML tag with the ID outputStatus and changes the HTML content of that tag to “Status: ON”, as shown in the following snippet of code:
document.getElementById("outputStatus").innerHTML = "Status: ON";
Describing the whole communication process in such detail makes it look as though it will take forever for an LED to turn on or off, but as soon as you start experimenting with this project, you see that this occurrence happens immediately.
Running Your Web Server
This section describes how to create and run a web server. You use some new JavaScript functions and modules for real-time communications. This section is where you see and understand the code you have to run in the Cloud9 IDE to serve your index.html and stylesheet.css files.
Loading modules and initializing a variable
First, you load all the modules required by server.js, such as the following:
· http: This module offers an easy way to interface with the HTTP protocol.
· fs (file system): This module allows you to access your file system.
· path: This module has utilities to handle and transform file paths.
· bonescript: This module makes interactions with your BeagleBone’s GPIOs as easy as possible.
//Loading modules
var http = require('http');
var fs = require('fs');
var path = require('path');
var b = require('bonescript');
Next, you create a new variable called led, which refers to pin P9_14 on your BeagleBone, and initialize that pin as an OUTPUT:
// Create a variable called led, which refers to P9_14
var led = "P9_14";
// Initialize the led as an OUTPUT
b.pinMode(led, b.OUTPUT);
Creating your web server
This part of the code is the trickiest part. The following snippet creates your web server on port 8888. This code is executed only when you access the web page through your web browser. It starts by opening your index.html file; then it checks whether you have a .css file. If it finds one, it styles your web page. If you don’t have your files in the same folder as your server.js file, the web page will be blank, displaying a 404 (page not found) error message.
// Initialize the server on port 8888
var server = http.createServer(function (req, res) {
// requesting files
var file = '.'+((req.url=='/')?'/index.html':req.url);
var fileExtension = path.extname(file);
var contentType = 'text/html';
if(fileExtension == '.css'){
contentType = 'text/css';
}
fs.exists(file, function(exists){
if(exists){
fs.readFile(file, function(error, content){
if(!error){
// Page found, write content
res.writeHead(200,{'content-type':contentType});
res.end(content);
}
})
}
else{
// Page not found
res.writeHead(404);
res.end('Page not found');
}
})
}).listen(8888);
Establishing socket communication
The code in this section is dedicated to establishing the socket communication. First, you have to load socket.io module.
// Loading socket io module
var io = require('socket.io').listen(server);
Sockets are methods for establishing communication between a client program and a server. Normally, a server runs on a specific computer — in this case, the BeagleBone — and features a socket that stays listening. While listening, the server is waiting for a client to make a connection request. A socket is the endpoint of a two-way communication. Simply put, a socket is like your house’s mailbox: It’s the place you go to fetch the data that arrives.
When communication is established, the code waits for an emit with the 'changeState' event name. As soon as that event is triggered, the handleChangeState() function executes.
// When communication is established
io.on('connection', function (socket) {
socket.on('changeState', handleChangeState);
});
The handleChangeState(data) function takes a parameter called data, which contains a string that shows the current state of your LED. Then the code gets the data by using the JSON.parse() method. Next is the digitalWrite() function, which is the code that actually turns your LED on or off.
// Change led state when a button is pressed
function handleChangeState(data) {
var newData = JSON.parse(data);
console.log("LED = " + newData.state);
b.digitalWrite(led, newData.state);
}
If all goes well, a few seconds after you click Run in the Cloud9 IDE, you see a message in the output window saying that the server is running and waiting for a client (your web browser) to make a connection request:
// Displaying a console message for user feedback
server.listen(console.log("Server Running ..."));
Launching your web server
Launching your web server is easy. You simply save all three files. Click Run in the Cloud9 IDE, and you should see a message in your output window that says Server Running....
That’s it! Your web server is up and running, ready to be accessed. Open a tab in your web browser, and type 192.178.7.2:8888. You see a page similar to Figure 15-2.
This code works only if your computer is connected directly to the BeagleBone by USB. If that’s not the case, read the next section to see how to access the BeagleBone through a device connected in your workspace network.
Figure 15-2: Project controlling outputs running on the BeagleBone Black.
Accessing Your BeagleBone with Another Device
With the setup described in the preceding section, you can access your BeagleBone only with devices that are connected directly to your BeagleBone via USB, such as your laptop. The reason is that 192.178.7.2 is the board’s local USB IP address. Perhaps it would be cooler to access the BeagleBone through its Ethernet IP — that is, the address it occupies on your home or office network.
Start by connecting your BeagleBone to your router with an Ethernet cable. In a terminal window — either in the Cloud9 IDE or at a terminal connected via secure shell (SSH) — type the following command:
ifconfig
You should see something similar to Figure 15-3. The ifconfig command displays various information about your Linux computer’s network accessibilities. You see, for example, that usb0 has the address 192.168.7.2, as expected.
What you’re interested in is the Ethernet IP address, which appears immediately after eth0 and is called out in Figure 15-3. That address is the BeagleBone’s IP address in our home network, so it should be a different address for you. Instead of typing 192.168.7.2:8888 in the web browser, you can type your address instead, followed by the port, which is 8888. You can do this on any device — such as a tablet or smartphone — that’s connected to the same router as the BeagleBone, allowing you to access the web page and, ultimately, the BeagleBone’s GPIOs.
Figure 15-3: Entering the ifconfig command.
Dropping Your LED and Controlling an Appliance
We hope you’re happy about seeing that LED light up! We know that it’s just an LED, but socket communication isn’t a very trivial thing, and it’s an extremely useful concept.
Controlling some house appliances may be more exciting than lighting up an LED. You can easily and immediately replace the LED with a new component that allows you to control any device that connects directly to the sockets on the wall.
The easiest route is to get yourself a PowerSwitch Tail II (www.powerswitchtail.com), which provides a safe way of dealing with high-voltage devices (see Figure 15-4).
Photo courtesy of Adafruit Industries
Figure 15-4: PowerSwitch Tail II.
The way this bulky component works is quite straightforward. Rather than connecting a house appliance directly to the wall, you connect it to the PowerSwitch Tail II which plugs into the wall. The PowerSwitch Tail II has three pins that enable it to behave like a simple digital logic device. You connect the device to an output pin of the BeagleBone and GND. Your output pin will send a signal that’s either HIGH or LOW. Whenever the signal is HIGH, there’s a connection to the wall socket; when it’s LOW, the connection is broken, as though the device were unplugged. Table 15-1 shows the pinout according to the code given earlier in the “Running your web server” section, in which P9_14 is the pin that provides the signal.
Table 15-1 Pinout of PowerSwitch Tail II
Pin Number |
Signal Name |
BeagleBone Pins |
1 |
+in (3.3V) |
P9_14 |
2 |
-in |
GND |
3 |
GND |
Not used |
Search for the PowerSwitch Tail II’s instruction sheet for more details on how to wire it up.
There’s another way to have your BeagleBone control a house appliance, but that method is more complicated, requires a bit of extra knowledge and wariness because you’re dealing with alternating current, and involves relay modules. Also, it’s not directly related to the BeagleBone itself. This book doesn’t explain the trick, but plenty of tutorials are available on the Internet.
Adjusting Outputs with PWM
All the projects featured in this book with BoneScript and Python can be modified to work with a custom interface like the one you’ve been building in this chapter. (Read Chapters 7 to 11 for details on BoneScript and Python.) For this project, you need the following supplies:
· A servo motor
· A 1K Ω resistor
· Four jumper wires
Use the circuit diagram in Figure 15-5 as a reference.
Figure 15-5: A servo wired to a BeagleBone Black.
Keeping all your files organized is the key to preventing many annoying bugs and complications. Set up your folder and files as described in these steps:
1. Create a new folder called adjustingPWM.
That folder is where you’re going to store all the other files.
2. In the adjustingPWM folder, create the following files:
· A JavaScript file named server.js
· An HTML file named index.html
· A CSS file named stylesheet.css
This stylesheet.css file is exactly like in the examples earlier in this chapter. Keep in mind that the index.html file also starts from the same place in all examples.
The following code shows the part of the index.html file that should be the same for all the examples in this chapter:
<!DOCTYPE html>
<html>
<head>
<title>Home Automation Web server with BeagleBone</title>
<link rel="stylesheet" href="stylesheet.css" type="text/css" />
<script src = "/socket.io/socket.io.js" ></script>
</head>
<body>
<div id="wrapper">
<div id="logo"><h1>Home Automation Web server</h1></div>
<div id="container" class="center">
</div>
<div id="footer"><p>Powered by BeagleBone</p></div>
</div>
</body>
</html>
<!--All the code up until this point will always be the same.-->
Designing the GUI
This project is quite fun to experiment with! You have a slider that you can drag to adjust the pulse-width modulation (PWM) output. Start by creating a heading 2 that tells what your project is all about:
<h2>Servo Position</h2>
Next, you use the HTML <input> tag:
<input type="range" min="0" max="1" step="0.1" onchange="changePosition(this.value)">
This tag has five attributes:
· type: Displays a range element on your web page
· min: Sets the minimum value for an input (in this case, 0)
· max: Sets the maximum value for an input (in this case, 1)
· step: Sets the interval between values (in this case, 0.1)
· onchange: Executes the changePosition(this.value) function every time you drag the slider
If you start dragging your slider a few steps to the left, and then suddenly stop and release the slider, the last value is sent to your server to update its current servo position.
As soon as you can move a servo, you can adjust the brightness of an LED or the intensity of a buzzer, to name a few examples. This example is just an idea to spark your creativity, displaying how PWM can be controlled through your web server.
Writing your main script
All the following code goes inside <script> tags. First, you have to establish a communication with your server with the io.connect() function:
// Establishing connection with server
var socket = io.connect();
Next, you create a new function called changePosition(value), which takes only one parameter value that refers to the last value read from the slider.
The emit() function triggers a changePosition event that goes with a message telling your server the last position of the slider:
// Changes the servo position
function changePosition(value){
// Emit message changing the servo position to a value from 0 to 1
socket.emit("changePosition", '{"position":"' + value +'"}');
}
Creating your web server
The next bit of code is quite similar to the preceding ones. In fact, parts are exactly the same, so we explain only the newest parts, which are highlighted with bold.
//Loading modules
var http = require('http');
var fs = require('fs');
var path = require('path');
var b = require('bonescript');
// Create a variable called servo, which refers to P9_14
var servo = "P9_14";
// Initialize the server on port 8888
var server = http.createServer(function (req, res) {
// requesting files
var file = '.'+((req.url=='/')?'/index.html':req.url);
var fileExtension = path.extname(file);
var contentType = 'text/html';
if(fileExtension == '.css'){
contentType = 'text/css';
}
fs.exists(file, function(exists){
if(exists){
fs.readFile(file, function(error, content){
if(!error){
// Page found, write content
res.writeHead(200,{'content-type':contentType});
res.end(content);
}
})
}
else{
// Page not found
res.writeHead(404);
res.end('Page not found');
}
})
}).listen(8888);
// Loading socket io module
var io = require('socket.io').listen(server);
// When communication is established
io.on('connection', function (socket) {
socket.on('changePosition', handleChangePosition);
});
// Change servo position according to the slider value
function handleChangePosition(data) {
var newData = JSON.parse(data);
b.analogWrite(servo, newData.position, 60,
console.log("Servo Position = " + newData.position));
}
// Displaying a console message for user feedback
server.listen(console.log("Server Running ..."));
The hardest and most complicated part of this code is the part that deals with running and communicating with the web server itself. Listening to commands from a web browser doesn’t involve any changes. What changes is what you want to do. In this case, you want to control a servo, not set an LED on or off. You start by creating a new variable:
// Create a variable called servo, which refers to P9_14
var servo = "P9_14";
Next, you need to handle what comes through your socket. Specifically, as soon as the web browser establishes a connection, you’re interested in the sliding bar’s current position, which is returned when the changePositionevent is triggered, and you want the handleChangePosition() function to be called.
// When communication is established
io.on('connection', function (socket) {
socket.on('changePosition', handleChangePosition);
});
This function features code that you’re already used to if you’ve completed the “Establishing socket communication” section. The JSON.parse() method extracts the data from the socket communication; then it writes the PWM value into the pin of the servo and prints a message about the servo’s position.
// Change servo position according to the slider value
function handleChangePosition(data) {
var newData = JSON.parse(data);
b.analogWrite(servo, newData.position, 60,
console.log("Servo Position = " + newData.position));
}
Launching the web server to control a PWM output
To launch your web server, you save all three files and click Run in your Cloud9 IDE. When you open your web server, you see a page similar to the one shown in Figure 15-6.
Drag the slider left and right. Enjoy watching your servo move according to your slider bar’s position!
Figure 15-6: Project adjusting PWM running on a BeagleBone Black.
Connecting a temperature sensor
The preceding sections showed how to control outputs through a web server, but it’s also helpful to know how to read and treat inputs. You can create your own weather station that tells you the room temperature, humidity, and brightness level. You can have a passive infrared (PIR) sensor displaying on your web page when someone enters your room. You can even have a wind-speed sensor in your window. There are lots of possibilities.
To add a temperature sensor, you need the following items:
· A breadboard
· Three jumper wires
· A temperature sensor TMP36, which has three pins wired as shown in Figure 15-7
You can use any temperature sensor if you can extract the important details of its datasheet and make the appropriate changes in the code.
The BeagleBone’s Analog-to-Digital Converter (ADC) input pins can only handle input voltages up to 1.8V. If you feed one of them with more than that, things might get nasty. The TMP36 temperature sensor that we suggest you to use surpasses 1.8V only for 266 degrees F (130 degrees C), so it should be safe to wire it directly to the BeagleBone. If you use another sensor, one that surpasses 1.8V at a much lower temperature — or if you’re afraid that the TMP36 will read more than 266 degrees F — you need to use a voltage divider and slightly adapt the code. You can read more about this in Chapter 10.
Figure 15-7: Temperature sensor wired to a BeagleBone Black.
As usual, keeping all your files organized is the key to preventing many annoying bugs and complications, so we suggest that you follow these steps:
1. Create a new folder called readingInputs.
That folder is where you’re going to store all the other files.
2. In the readingInputs folder, create the following files:
· A JavaScript file named server.js
· An HTML file named index.html
· A CSS file named stylesheet.css
The stylesheet.css file is exactly the same as the file discussed earlier in this chapter. The beginning of the index.html page, which affects the design of the web page, is also the same.
Writing your web page
For this project, you don’t really have a GUI. You aren’t prompted to click or change anything. You just look at the page to read information about your sensor. As before, start by displaying on your web page what your project is about:
<h2>Temperature</h2>
Next, add a heading 3 with the ID temperature, which is where you output the current temperature values:
<h3 id="temperature"></h3>
Inside your main <script> tags, you have to establish a communication with your server with the io.connect() function:
var socket = io.connect();
This time, you don’t want to emit data to your server. Instead, you wait for your server to send a new temperature value. When the sensorsUpdate event is triggered, you receive a new input reading that’s extracted with the JSON.parse() method.
Next, you do some math with the voltage that you received to calculate temperature in Celsius and Fahrenheit. Finally, by using the getElementById() function, you update the HTML tag with the temperature ID showing the latest temperature reading.
socket.on('sensorsUpdate', function (data) {
// store new data on reading variable
var reading = JSON.parse(data);
// calculate the temperature according to our voltage
var voltage = reading.temperature * 3.3;
var temperatureC = (voltage-0.5) * 100;
var temperatureF = (temperatureC * 9/5) + 32;
// Displaying temperature in C and F in the web page
document.getElementById("temperature").innerHTML = " " + Math.round(temperatureC)
+ "°C " + Math.round(temperatureF) + "°F";
});
Creating your web server
The following script is quite similar to the preceding ones, so this section explains only the newest snippets of code, which are highlighted with bold:
// Loading modules
var http = require('http');
var fs = require('fs');
var path = require('path');
var b = require('bonescript');
// Create variables
var temperature = 'P9_39';
var s;
// Initialize the server on port 8888
var server = http.createServer(function (req, res) {
// requesting files
var file = '.'+((req.url=='/')?'/index.html':req.url);
var fileExtension = path.extname(file);
var contentType = 'text/html';
if(fileExtension == '.css'){
contentType = 'text/css';
}
fs.exists(file, function(exists){
if(exists){
fs.readFile(file, function(error, content){
if(!error){
// Page found, write content
res.writeHead(200,{'content-type':contentType});
res.end(content);
}
})
}
else{
// Page not found
res.writeHead(404);
res.end('Page not found');
}
})
}).listen(8888);
// Loading socket io module
var io = require('socket.io').listen(server);
// When communication is established
io.on('connection', function (socket) {
s = socket;
// Execute updateSensors function every one second
setInterval(updateSensors, 1000);
});
// Update the new temperature value
function updateSensors(){
temperatureReading = b.analogRead(temperature);
s.emit("sensorsUpdate", '{"temperature":"' + temperatureReading + '"}');
console.log("Updating Sensor");
}
// Displaying a console message for user feedback
server.listen(console.log("Server Running ..."));
The following code creates a new variable called temperature to refer to your pin P9_39. You also need a variable to store your socket object; we call it s.
// Create variables
var temperature = 'P9_39';
var s;
When communication is established, this code is executed. As you see, the setInterval() function executes the updateSensors() function every second for as long as your web server is running.
// When communication is established
io.on('connection', function (socket) {
s = socket;
// Execute updateSensors function every one second
setInterval(updateSensors, 1000);
});
As its name implies, updateSensors() reads the current value of the temperature value and uses the emit() function to send that reading to your web page, which is listening for the sensorsUpdate event to occur.
// Update the new temperature value
function updateSensors(){
temperatureReading = b.analogRead(temperature);
s.emit("sensorsUpdate", '{"temperature":"' + temperatureReading + '"}');
console.log("Updating Sensor");
}
Launching the web server for your temperature monitoring
Simply save all three files and click Run in your Cloud9 IDE. Open your web server. A page similar to the one shown in Figure 15-8 should appear.
Figure 15-8: Project reading inputs running on a BeagleBone Black.
See whether the temperature is correct according to your common sense. We don’t expect you to be able to pinpoint the temperature, but if the temperature reading is off, it’ll be really, really off. You should be able to notice that.
Taking this project further
We don’t think it’s necessary to elaborate on more outputs and sensors that you could connect to the BeagleBone. This chapter explains the three most important things for interacting with the physical world: digital outputs and analog (PWM) outputs and inputs. Whatever ideas you have next are within your reach.
You could incorporate a PIR motion sensor (described in Chapter 8) and create a simple surveillance system for your home. A message could appear on your web page, saying An individual entered your room # seconds ago!, and a buzzer could sound. In the same fashion, you could have a PIR sensor counting the number of people who go in and out of your room, store, or office in a day. That’s interesting data.
The coolest thing about home automation is that you can keep adding new things forever. You could end up with a web page that provides loads of data about what’s going on your house, or you could have the BeagleBone turn on several appliances, such as an air conditioner or a sound system, from anywhere in your house. This chapter is meant to be used as your canvas; from this point, you should be fully capable of throwing some ink into the painting.