This is my first post on home automation. As a 'Hello World' project, switching on/off a bulb is a common use case. This post is not an exception. But to spice it up, we'll use MQTT (MQ Telemetry Transport) - a machine-to-machine (M2M)/Internet of Things (IOT) connectivity protocol and an android app (IoT MQTT Dashboard). Bulb is merely a symbolic representation of an electrical device. We can practically control any device (Internet of Things) over internet.

Disclaimer: If you don't have required knowledge and training to handle electric main lines, DO NOT try this on your own. Take professional help from an electrician. It might cause life-threatening electrical injuries. Thus exercise caution.

What is MQTT?

MQTT is a machine-to-machine (M2M)/"Internet of Things" connectivity protocol. It was designed as an extremely lightweight publish/subscribe messaging transport. It is useful for connections with remote locations where a small code footprint is required and/or network bandwidth is at a premium. For example, it has been used in sensors communicating to a broker via satellite link, over occasional dial-up connections with healthcare providers, and in a range of home automation and small device scenarios. It is also ideal for mobile applications because of its small size, low power usage, minimised data packets, and efficient distribution of information to one or many receivers (more...)

Tools,Technologies and Components used in this article

  1. MicroPython
  2. WebREPL
  3. MQTT
  4. CloudMQTT - A globally distributed MQTT broker
  5. IoT MQTT Dashboard - Android App
  6. Components:
    • ESP8266 ESP-12E
    • Breadboard
    • 3.3v & 5v Breadboard Power Supply
    • Breadboard Jumper Wires
    • 10k Resistors - 3
    • Push Button Switch - 1
    • 1uF Capacitor - 1
    • 5v Relay Module - 1
    • Electric bulb & holder - 1
    • Main lines & wires

What is Relay?

A relay is an electrically operated switch. Many relays use an electromagnet to mechanically operate a switch, but other operating principles are also used, such as solid-state relays. Relays are used where it is necessary to control a circuit by a separate low-power signal, or where several circuits must be controlled by one signal. (more...)

1. Prerequisite

For better understanding, I would recomend you to go through following posts.

  1. How to flash MicroPython firmware onto an ESP8266 ESP-12E chip using esptool?
  2. How to setup WebREPL to connect to Python prompt (REPL) of ESP8266 over WIFI network?
  3. Example: Remotely switch on/off and control brightness of an LED using MicroPython WebREPL
  4. Configure STA_IF interface of ESP8266 (MycroPython firmware) to connect with WIFI network automatically on boot

2. Sign up for Cute Cat CloudMQTT plan

There are many MQTT brokers available as cloud service. Even, you can install any MQTT broker (e.g. Mosquitto) in your local machine and use the same too.

  1. Open CloudMQTT website and sign up for Cute Cat plan.
    sign up for CloudMQTT Cute Cat plan
  2. Login and open Control Panel. Click "Create" button.
    CloudMQTT Control Panel
  3. Create a new CloudMQTT instance.
    Create a new CloudMQTT instance
  4. Click the "Details" button of newly created CloudMQTT instance (e.g. "MyHome").
    Details - CloudMQTT instance
  5. Later, we?ll use following details from CloudMQTT console to connect to the CloudMQTT broker from clients (ESP8266 device and IoT MQTT Dashboard android app) to publish and consume messages.
    CloudMQTT console

3. Install and configure IoT MQTT Dashboard android app

There are many MQTT client applications available in Google Play Store. Feel free to explore any one that suits your requirements. For this post, I am using IoT MQTT Dashboard.

  1. Open Google Play Store and install IoT MQTT Dashboard Android App.
    Google Play Store - IoT MQTT Dashboard
  2. Open the application and click the Plus Sign (+) button to create a connection.
  3. Enter all the details of CloudMQTT instance (e.g. "MyHome") and click "Create" button.
    IoT MQTT Dashboard - create a connection
  4. That connection will appear in the dashboard. Open that connection.
    IoT MQTT Dashboard - connections
  5. Open publish tab and click Plus Sign (+).
    IoT MQTT Dashboard - publish tab - click Plus Sign to add component
  6. Choose "Switch" component.
    IoT MQTT Dashboard - Switch component
  7. Fill up all the fields and click the "Create" button.
    IoT MQTT Dashboard - add Switch component
  8. Switch button will appear in the Publish tab.
    IoT MQTT Dashboard - Publish tab
  9. Now, if we switch the button on or off, '1' or '0' will be published to the topic (e.g. room/light) respectively. If any MQTT client is subscribed to the same topic, it?ll receive the value '1' or '0' accordingly. We can check the connectivity, by switching on/off the button few times and verify the value in Websocket UI of CloudMQTT Console.
    IoT MQTT Dashboard - CloudMQTT Console - Websocket UI

Demo:

4. Build the Circuit

Connect all the components as shown in the diagram below.

CAUTION: DO NOT touch any open wire or part of the circuit while main power is on. There is risk of electric shock.

Circuit Diagram
Circuit Diagram

Circuit Design
Circuit Design

5. Configure ESP8266 as MQTT client

  1. Connect to WebREPL of ESP8266 using Chrome or Firefox browser.
  2. Press Ctrl & E to enable paste mode. Paste following code and Ctrl & D to finish.
    from umqtt.simple import MQTTClient
    from machine import Pin
    import machine
    import ubinascii
    
    # Setup a GPIO Pin for output
    bulbPin = Pin(12, Pin.OUT)
    
    # Modify below section as required
    CONFIG = {
         # Configuration details of the MQTT broker
         "MQTT_BROKER": "m10.cloudmqtt.com",
         "USER": "dnwbhwcf",
         "PASSWORD": "W02aPkUfpG2S",
         "PORT": 19258,
         "TOPIC": b"room/light",
         # unique identifier of the chip
         "CLIENT_ID": b"esp8266_" + ubinascii.hexlify(machine.unique_id())
    }
    
    # Method to act based on message received   
    def onMessage(topic, msg):
        print("Topic: %s, Message: %s" % (topic, msg))
    
        if msg == b"1":
            bulbPin.low()
        elif msg == b"0":
            bulbPin.high()
    
    def listen():
        #Create an instance of MQTTClient 
        client = MQTTClient(CONFIG['CLIENT_ID'], CONFIG['MQTT_BROKER'], user=CONFIG['USER'], password=CONFIG['PASSWORD'], port=CONFIG['PORT'])
        # Attach call back handler to be called on receiving messages
        client.set_callback(onMessage)
        client.connect()
        client.subscribe(CONFIG['TOPIC'])
        print("ESP8266 is Connected to %s and subscribed to %s topic" % (CONFIG['MQTT_BROKER'], CONFIG['TOPIC']))
    
        try:
            while True:
                client.wait_msg()
        finally:
            client.disconnect() 
    
    Note:
    The relay used in my circuit gets on for low output of the GPIO Pin. That is why, I have called bulbPin.low() (line #26) for '1' message received from CloudMQTT and bulbPin.high() (line #28) for '0'. It may be opposite in your case.
  3. Call listen() in the REPL prompt.
    >>> listen()
    ESP8266 is Connected to m10.cloudmqtt.com and subscribed to b'room/light' topic
    
  4. If everything goes well, button switch on/off in IoT MQTT Dashboard android app will switch the bulb on/off accordingly.
    >>> listen()
    ESP8266 is Connected to m10.cloudmqtt.com and subscribed to b'room/light' topic         
    Topic: b'room/light', Message: b'1'                                                    
    Topic: b'room/light', Message: b'0'                                                    
    Topic: b'room/light', Message: b'1'                                                    
    Topic: b'room/light', Message: b'0'
    

Demo:

Note:
To configure ESP8266 to listen to the topic as soon as it starts, you need to append the code at the end of the main.py. It runs after the execution of boot.py. If main.py does not exist in the device, then create a new file named main.py and paste all the code. Finally, upload that file to ESP8266. Refer step #5 of my earlier post Configure STA_IF interface of ESP8266 (MycroPython firmware) to connect with WIFI network automatically on boot.

References