Home Automation With Raspberry Pi, Mqtt, And Espruino

Photo of Espruino

Made by Espruino

About the project

Automate your home with Raspberry Pi, MQTT, and Espruino

Project info

Difficulty: Easy

Estimated time: 3 hours

License: Apache License 2.0 (Apache-2.0)

Items used in this project

Hardware components

110991025  ARM Seeed Rasp Pi Zero Barebones Kit 110991025 ARM Seeed Rasp Pi Zero Barebones Kit x 1
SDSDQAF3-008G-I Memory Cards microSD Industrial 8GB SDSDQAF3-008G-I Memory Cards microSD Industrial 8GB x 1

Software apps and online services

Raspbian Lite Raspbian Lite

Story

Setting up your Pi


  • First, you'll need a Raspberry Pi (ideally a Zero W or a Pi 3) with at least an 8gb SD card.

  • Get Raspbian Lite from here: https://www.raspberrypi.org/downloads/raspbian/

  • Follow the instructions for putting Raspbian on an SD card: https://www.raspberrypi.org/documentation/installation/installing-images/README.md

  • Once done, we need to set up 'headless' WiFi on the Pi

  • Unplug the SD card and plug it back in, and some new drives should appear.

  • Open the boot drive, and create a new file called ssh in it. It can be empty, but it's important that the file has noextension like .txt. This will enable the SSH Server so we can connect to the Pi wirelessly when it boots.

  • If your Pi has WiFi which you want to use, create a file in the same drive called wpa_supplicant.conf and put the following text in it, filling in the blanks with your WiFi key and password.

  1. network={
  2. ssid="YourNetworkSSID"
  3. psk="Your Network's Passphrase"
  4. key_mgmt=WPA-PSK
  5. }

  • If you're on Windows, make sure you're using an editor like Notepad++ that allows you to set the line ending style to Unix, not Windows.

  • Eject the SD card in the OS, take it out of your PC and stick it in the Pi. Then plug the Pi into a USB phone charger (using the PWR USB socket if you're on a Pi Zero W).

  • Wait a few minutes until the activity LED stops flashing (sometimes you'll be able to check your router's status page to see if the Pi has connected).

  • Now it's time to install an SSH client. If you're on Linux of Mac OS you already have one, but if you're on Windows you'll want to download and run PuTTY.

  • Now connect via SSH to raspberrypi (or raspberrypi.local) with username pi. You can do this with a menu in PuTTY, or on other platforms just open a command prompt and type ssh pi@raspberrypi. When asked for a password, type raspberry.

Now it's time to make sure the operating system is sized to your SD card.

  • Type sudo raspi-config

  • Use the arrow keys to go to Advanced Options and press Enter, then choose A1 Expand Filesystem. You can also change the password and default hostname (that's currently raspberrypi) here, but I won't cover that.

  • After that, press the right arrow twice to select Finish, then press Enter

  • Press Yes to reboot

  • Now wait a minute, then reconnect with pi at raspberrypi again.

  • Make sure all the package lists are up to date by typing sudo apt-get update

  • Type sudo apt-get install mosquitto mosquitto-clients bluetooth bluez libbluetooth-dev libudev-dev and press enter when prompted to install some packages we'll need - particularly the mosquitto MQTT server

  • Copy and paste this command to install the latest version of node-red and node, and agree when prompted: bash <(curl -sL https://raw.githubusercontent.com/node-red/raspbian-deb-package/master/resources/update-nodejs-and-nodered)

It could take as long as half an hour to complete that step!

  • Now type sudo systemctl start nodered.service to start the node-red service

  • Type cd ~/.node-red && npm install node-red-contrib-ui to install the node-red UI, which will give us a neat dashboard and some graphs. This might take a while!

  • Type sudo systemctl stop nodered.service then sudo systemctl start nodered.service to restart the node-red service with the new UI module we just installed. It may take a minute or two.

  • Type sudo systemctl enable nodered.service to set node-red to start on every boot

  • Now that's done you should be able to go to http://raspberrypi:1880/

  • Drag an inject node from the left on to the page

  • Drag an mqtt node from the output area on to the page

  • Connect the two nodes together by clicking and dragging between the squares on the end of them

  • Double-click on the MQTT node

  • In the menu that appears, type /hello into Topic

  • Under Server choose Add new mqtt-broker and click edit

  • fill in localhost for server, now click Add, then Done to finish the node

  • Now click 'Deploy' in the top right

  • Now type mosquitto_sub -v -h raspberrypi -t "/#" in the SSH window - this will set the Pi listening for all MQTT events (# is a wildcard)

  • If you click the button to the left of the inject block that says timestamp then you should now see a message appearing.

  • In the same way you can create MQTT block to listen for a specific message, and can use mosquitto_pub -h raspberrypi -t "/hello" -m "message text" to send a message to it.

And that's it!

Interfacing with an Espruino WiFi


  1. var WIFI_NAME = "Espruino";
  2. var WIFI_OPTIONS = { password : "helloworld" };
  3. var MQTT_HOST = "raspberrypi";
  4. var PATH = "/mydevice/";
  5. var mqtt;
  6. var wifi;
  7.  
  8. function mqttMessage(pub) {
  9. console.log(
  10. "MQTT=> ",pub.topic,pub.message);
  11. if (pub.topic==PATH+"1/set") {
  12. var v = pub.message!=0;
  13. digitalWrite(B3, !v);
  14. mqtt.publish(PATH+"1/status", v?1:0);
  15. }
  16. if (pub.topic==PATH+"2/set") {
  17. var v = pub.message!=0;
  18. digitalWrite(B4, !v);
  19. mqtt.publish(PATH+"2/status", v?1:0);
  20. }
  21. }
  22.  
  23. function mqttConnect() {
  24. mqtt = require("MQTT").connect({
  25. host: MQTT_HOST,
  26. });
  27. mqtt.on('connected', function() {
  28. console.log("MQTT connected");
  29. // subscribe to wildcard for our name
  30. mqtt.subscribe(PATH+"#");
  31. });
  32. mqtt.on('publish', mqttMessage);
  33. mqtt.on('disconnected', function() {
  34. console.log("MQTT disconnected... reconnecting.");
  35. setTimeout(function() {
  36. mqtt.connect();
  37. }, 1000);
  38. });
  39. }
  40.  
  41. setInterval(function() {
  42. if (!mqtt) return;
  43. mqtt.publish(
  44. PATH+"cputemp",
  45. E.getTemperature());
  46. }, 2*60*1000);
  47.  
  48. setWatch(function() {
  49. if (!mqtt) return;
  50. mqtt.publish(
  51. PATH+"buttonpress",
  52. 1);
  53. }, BTN, {edge:"rising",repeat:true,debounce:50});
  54.  
  55.  
  56. function onInit() {
  57. console.log("Connecting to WiFi");
  58. wifi = require("EspruinoWiFi");
  59. wifi.connect(WIFI_NAME, WIFI_OPTIONS,
  60. function(e) {
  61. if (e) {
  62. console.log("Connection Error: "+e);
  63. return;
  64. }
  65. console.log("WiFi Connected");
  66. wifi.getIP(function(f,ip) {
  67. console.log("IP: ",ip);
  68. mqttConnect();
  69. });
  70. });
  71. }

Interfacing with a SonOff

But for those eager, the code is:

  1. var WIFI_NAME = "Espruino";
  2. var WIFI_OPTIONS = { password : "helloworld" };
  3. var MQTT_HOST = "raspberrypi";
  4. var PATH = "/mydevice/";
  5. var LED = D13;
  6. var RELAY = D12;
  7. var BTN = D0;
  8. var mqtt;
  9. var wifi;
  10.  
  11. function setState(v) {
  12. RELAY.write(v);
  13. LED.write(!v);
  14. mqtt.publish(PATH+"status", v?1:0);
  15. }
  16.  
  17. function mqttMessage(pub) {
  18. console.log("MQTT=> ",pub.topic,pub.message);
  19.  
  20. if (pub.topic == PATH+"set") {
  21. setState(pub.message!=0);
  22. }
  23. if (pub.topic == PATH+"eval") {
  24. try {
  25. mqtt.publish(PATH+"response", eval(pub.message));
  26. } catch(e) {
  27. mqtt.publish(PATH+"exception", e.toString());
  28. }
  29. }
  30. }
  31.  
  32. function mqttConnect() {
  33. mqtt = require("MQTT").connect({
  34. host: MQTT_HOST,
  35. });
  36. mqtt.on('connected', function() {
  37. console.log("MQTT connected");
  38. setTimeout(function() {
  39. mqtt.subscribe(PATH+"#");
  40. }, 1000);
  41. });
  42. mqtt.on('publish', mqttMessage);
  43. }
  44.  
  45.  
  46. function onInit() {
  47. console.log("Connecting WiFi");
  48. setInterval(function() {
  49. if (!mqtt) return;
  50. if (!mqtt.connected) {
  51. console.log("MQTT disconnected... reconnecting.");
  52. mqtt.connect();
  53. }
  54. }, 60*1000);
  55.  
  56. wifi = require("Wifi");
  57. wifi.on('connected',function() {
  58. console.log("Connected to WiFi");
  59. });
  60. wifi.on('disconnected',function() {
  61. console.log("Disconnected from WiFi");
  62. });
  63. wifi.setHostname("MYDEVICE");
  64. wifi.stopAP();
  65. wifi.connect(WIFI_NAME, WIFI_OPTIONS,
  66. function(ap){
  67. console.log("Successful connect.");
  68. });
  69. // wait, and connect MQTT
  70. setTimeout(function() {
  71. console.log("MQTT connecting");
  72. mqttConnect();
  73. }, 10000);
  74. }

Code

Interfacing with a SonOff

Interfacing with an Espruino WiFi

Credits

Photo of Espruino

Espruino

Espruino, Espruino Pico and Puck.js are low-power Microcontrollers that run JavaScript. Espruino is a JavaScript Interpreter for Microcontrollers that is designed to make development quick and easy. The Espruino interpreter is firmware that runs on a variety of different microcontrollers, but we also make Espruino Boards that come with the interpreter pre-installed and are the easiest devices to get started with. However Espruino itself isn't just the interpreter firmware or hardware - there's also the Web IDE, command-line tools, documentation, tutorials, and modules that form a complete solution for embedded software development.

   

Leave your feedback...