If you've followed along with my earlier post, you now have MQTT running on your Raspberry Pi, and an Arduino IoT client that can publish and subscribe to MQTT packets. The next step is developing a real-time web interface that can control your MQTT network.
Why Socket.io and Node.js?
Web browsers typically operate by pulling data from a server when you click on a link. Servers don't usually keep an open connection to the browsers it has serviced, so if some event happens on the server side, the server cannot push that event to your browser, unless you refresh the page.
That's where Socket.io comes in handy. Socket.io maintains an open connection between the server and the browser, which enables the server to push updates to the browser as they happen. This is useful so you can see changes to your IoT network as they happen, and not have to wait for a page refresh.
Step 1: Setup a Web Server on your Raspberry Pi
sudo apt-get install apache2 -y
hostname -I
Now test your web server by using a web browser to navigate to your Raspberry Pi's web address
Step 2: Get Socket.IO, Node.js and the MQTT client
wget http://node-arm.herokuapp.com/node_latest_armhf.deb
sudo dpkg -i node_latest_armhf.deb
sudo apt-get install npm
cd /var/www
sudo npm install mqtt
sudo npm install socket.io
Step 3: Test Your Node.js and MQTT client
create the file
/var/www/mqtt_test.js
node mqtt_test.js
Then change the server URL from
test.mosquitto.org
to your Rpi's IP addressnode mqtt_test.js
Step 4: Get Thomas Reynolds' iOS Style Jquery Checkboxes
cd ~/
wget https://github.com/tdreyno/iphone-style-checkboxes/archive/v1.zip
unzip v1.zip
cd iphone-style-checkboxes-1
sudo cp -pr jquery /var/www
sudo cp -pr images /var/www
sudo cp style.css /var/www
Step 5: Create a Node.js script to link Socket.io to MQTT
create the file
/var/www/pusher.js
node pusher.js &
Step 6: Create your web pagecreate the file
/var/www/iot_demo.html
Step 7: Test your real-time web interface
mosquitto_sub -t "led"
browse to http://your_rpi_ip_address/iot_demo.html
toggle the checkbox, and you should see messages on your MQTT network Now open multiple browsers and try toggling the checkbox