022 - ESP32 MicroPython: MQTT Part 2: Subscribe

Introduction

In the previous tutorial, I demonstrate the use of MQTT protocol by sending DHT sensor readings to Thingspeak as MQTT broker while the ESP32 serves as MQTT client. The act of MQTT client sending data to MQTT broker is called MQTT publish.

Now in this tutorial, I will demonstrate the other direction of MQTT communication which is MQTT subscribe where a client is waiting for a message from a broker. A client that subscribes to a certain topic will receive a data update from the broker when a new publish data is received from a certain publishing client.

Now to demonstrate that, I will be needing 3 components which are:

  1. A publishing client
  2. A broker and
  3. A subscribe client

Bill Of Materials

  1. ESP32 development board.
  2. 0.96 OLED display

Hardware Instruction

  1. Connect the OLED VCC pin to ESP32 3.3V pin.
  2. Connect the OLED GND pin to ESP32 GND pin.
  3. Connect the OLED SCL pin to ESP32 D22 pin.
  4. Connect the OLED SDA pin to ESP32 D21 pin.

Video Demonstration

Call To Action

For any concern, write your message in the comment section.

You might also like to support my journey on Youtube by Subscribing. Click this to Subscribe to TechToTinker.

Thank you and have a good days ahead.

See you,

– George Bantique | tech.to.tinker@gmail.com

Source Code

1. Basic demonstration of handling MQTT Subscribe message data payload:

 1# **************************************#  
 2#  MQTT in MicroPython with Thingspeak  #  
 3# **************************************#  
 4# Author: George Bantique               #  
 5#         TechToTinker Youtube Channel  #  
 6#         TechToTinker.blogspot.com     #  
 7#         tech.to.tinker@gmail.com      #  
 8# Date: Dec.13, 2020                    #  
 9# Please feel free to modify the code   #  
10# according to your needs.              #  
11# **************************************# 
12
13# **************************************#  
14# Load necessary libraries  
15import machine  
16import network  
17import wifi_credentials  
18from umqtt.robust import MQTTClient  
19import ssd1306  
20import time  
21import os  
22import sys 
23
24
25# **************************************#  
26# Objects:  
27led = machine.Pin(2,machine.Pin.OUT)  
28scl = machine.Pin(22, machine.Pin.OUT, machine.Pin.PULL_UP)  
29sda = machine.Pin(21, machine.Pin.OUT, machine.Pin.PULL_UP)  
30i2c = machine.I2C(scl=scl, sda=sda, freq=400000)  
31oled = ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C) 
32
33# **************************************#  
34# Configure the ESP32 wifi as STAtion.  
35sta = network.WLAN(network.STA_IF)  
36if not sta.isconnected():  
37  print('connecting to network...')  
38  sta.active(True)  
39  #sta.connect('wifi ssid', 'wifi password')  
40  sta.connect(wifi_credentials.ssid, wifi_credentials.password)  
41  while not sta.isconnected():  
42    pass  
43print('network config:', sta.ifconfig()) 
44
45# **************************************#  
46# Callback function, it is the function  
47# that will be called when a new msg  
48# is received from MQTT broker  
49def call_back_function(topic, msg):  
50    oled.fill(0)  
51    oled.text(msg.decode().strip("'n"), 5, 5)  
52    oled.show()  
53    print((topic, msg)) 
54        
55# **************************************#  
56# Global variables and constants  
57UNIQUE_CLIENT_ID = "ab06f0c1-1319-44bc-9534-04caea40af81"  
58THINGSPEAK_URL = b"mqtt.thingspeak.com"   
59THINGSPEAK_USERNAME = b'mwa0000020270097'  
60THINGSPEAK_MQTT_API_KEY = b'AWP9SRI6ED9ONGBO'  
61THINGSPEAK_CHANNEL_ID = b'1250656'  
62THINGSPEAK_CHANNEL_READ_API_KEY = b'TVRCWGZKKOVC2MQR'  
63TOPIC_SUB = bytes("channels/{:s}/subscribe/fields/field1/{:s}"
64                  .format(THINGSPEAK_CHANNEL_ID,
65                          THINGSPEAK_CHANNEL_READ_API_KEY),
66                  'utf-8')  
67
68# **************************************#  
69# MQTT client configuration:  
70# 1.Create the MQTT client      
71client = MQTTClient(client_id = UNIQUE_CLIENT_ID,   
72                    server = THINGSPEAK_URL,   
73                    user = THINGSPEAK_USERNAME,   
74                    password = THINGSPEAK_MQTT_API_KEY,   
75                    ssl = False)  
76# 2.Set the callback function  
77client.set_callback(call_back_function)  
78# 3.Connect to MQTT broker  
79try:  
80    client.connect()  
81except Exception as e:  
82    machine.reset  
83# 4.Subscribe to a specific topic      
84client.subscribe(TOPIC_SUB)  
85
86# **************************************#  
87# Main loop  
88while True:  
89    try:  
90        #client.wait_msg() #blocking  
91        client.check_msg() #non-blocking  
92    except KeyboardInterrupt:  
93        print('Ctrl-C pressed...exiting')  
94        client.disconnect()  
95        sys.exit()

2. How to use MQTT Subscribe message as command for controlling something:

  1# **************************************# 
  2#  MQTT in MicroPython with Thingspeak  # 
  3# **************************************# 
  4# Author: George Bantique               # 
  5#         TechToTinker Youtube Channel  # 
  6#         TechToTinker.blogspot.com     # 
  7#         tech.to.tinker@gmail.com      # 
  8# Date: Dec.13, 2020                    # 
  9# Please feel free to modify the code   # 
 10# according to your needs.              # 
 11# **************************************# 
 12
 13# **************************************# 
 14# Load necessary libraries 
 15import machine 
 16import network 
 17import wifi_credentials 
 18from umqtt.robust import MQTTClient 
 19import ssd1306 
 20import time 
 21import os 
 22import sys 
 23
 24# **************************************# 
 25# Objects: 
 26led = machine.Pin(2,machine.Pin.OUT) 
 27scl = machine.Pin(22, machine.Pin.OUT, machine.Pin.PULL_UP) 
 28sda = machine.Pin(21, machine.Pin.OUT, machine.Pin.PULL_UP) 
 29i2c = machine.I2C(scl=scl, sda=sda, freq=400000) 
 30oled = ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C) 
 31
 32# **************************************# 
 33# Configure the ESP32 wifi as STAtion. 
 34sta = network.WLAN(network.STA_IF) 
 35if not sta.isconnected(): 
 36  print('connecting to network...') 
 37  sta.active(True) 
 38  #sta.connect('wifi ssid', 'wifi password') 
 39  sta.connect(wifi_credentials.ssid, wifi_credentials.password) 
 40  while not sta.isconnected(): 
 41    pass 
 42print('network config:', sta.ifconfig()) 
 43
 44# **************************************# 
 45# Callback function, it is the function 
 46# that will be called when a new msg 
 47# is received from MQTT broker 
 48def call_back_function(topic, msg): 
 49     global message 
 50     oled.fill(0) 
 51     message = msg.decode().strip("'n") 
 52     oled.text(message, 5, 5) 
 53     oled.show() 
 54     print((topic, msg)) 
 55 
 56# **************************************# 
 57# Global variables and constants 
 58UNIQUE_CLIENT_ID = "ab06f0c1-1319-44bc-9534-04caea40af81" 
 59THINGSPEAK_URL = b"mqtt.thingspeak.com"  
 60THINGSPEAK_USERNAME = b'mwa0000020270097' 
 61THINGSPEAK_MQTT_API_KEY = b'AWP9SRI6ED9ONGBO' 
 62THINGSPEAK_CHANNEL_ID = b'1250656' 
 63THINGSPEAK_CHANNEL_READ_API_KEY = b'TVRCWGZKKOVC2MQR' 
 64TOPIC_SUB = bytes("channels/{:s}/subscribe/fields/field1/{:s}"
 65                  .format(THINGSPEAK_CHANNEL_ID,
 66                          THINGSPEAK_CHANNEL_READ_API_KEY),
 67                  'utf-8') 
 68message = "" 
 69
 70# **************************************# 
 71# MQTT client configuration: 
 72# 1.Create the MQTT client object    
 73client = MQTTClient(client_id = UNIQUE_CLIENT_ID,  
 74                    server = THINGSPEAK_URL,  
 75                    user = THINGSPEAK_USERNAME,  
 76                    password = THINGSPEAK_MQTT_API_KEY,  
 77                    ssl = False) 
 78# 2.Set the callback function 
 79client.set_callback(call_back_function) 
 80# 3.Connect to MQTT broker 
 81try: 
 82    client.connect() 
 83except Exception as e: 
 84    machine.reset 
 85# 4.Subscribe to a specific topic     
 86client.subscribe(TOPIC_SUB) 
 87
 88# **************************************# 
 89# Main loop 
 90while True: 
 91    try: 
 92        client.wait_msg() #blocking 
 93        #client.check_msg() #non-blocking 
 94         
 95        if message == 'led ON': 
 96            led.on() 
 97            print('led is now ON') 
 98        elif message == 'led OFF': 
 99            led.off() 
100            print('led is now OFF') 
101        elif message == 'oled WHITE': 
102            oled.invert(1) 
103            print('oled is now black on WHITE') 
104        elif message == 'oled BLACK': 
105            oled.invert(0) 
106            print('oled is now white on BLACK') 
107             
108    except KeyboardInterrupt: 
109        print('Ctrl-C pressed...exiting') 
110        client.disconnect() 
111        sys.exit()

References And Credits

  1. Thingspeak: thingspeak.com

  2. MQTT Box: http://workswithweb.com/html/mqttbox/downloads.html



Posts in this series



No comments yet!

GitHub-flavored Markdown & a sane subset of HTML is supported.