So, three things to improve on the last post:
First, I’ve created a github repository which contains the source for our project. It can be found here: https://github.com/bitstobrowser/socketTemp.
To run the code, you can download it either directly to your BeagleBone Black or to your desktop and use a utility, like WinSCP, to transfer it to your BBB. Once on your BBB, navigate to the directory and start the server by executing the following command: node server.js.
Second, let’s quickly review the code to get an understanding of how it works:
- Lines 3-6: Define the set of libraries that we need to use. Importantly, we tell socket.io to listen for any connections on the server’s port.
- Line 8: Here we listen for any HTTP requests on port 8888.
- Lines 10-21: Serve up a client.html file to all browser HTTP requests
- Line 23: Sets a timer to go off every 2500ms or 2.5 seconds. We’ll use this to read and update the attached browsers.
- Lines 25-26: Is the user file which contains the temperature information
- Lines 28-32: This is the function that is called every 2500ms and it reads the contents of the temperature file and then calls another function to send the information out to any clients.
- Lines 34-39: This puts the temperature in a JSON object and then emits (sends) the data to all attached socket connections.
At the client end, it’s even less lines of code:
- Line 6: Creates a socket connection, using the same port as the specified in the browser access.
- Line 7: Defines what we do in case we get a socket message of type ‘temperature’ – we will call the handleTemperature function.
- Lines 9-14: When we receive a ‘temperature’ function, we unpack the JSON object to get the value sent to us. We convert to Fahrenheit for our display. Then finally on line 13, we update the HTML as marked by the “temp” ID with the latest temperature information.
- Lines 18-22: This is our basic HTML display – line 22 will be adjusted whenever we receive a message by the handleTemperature function.
Third, I’ve put a better version of the video up – much better resolution: