Reyax MQTT with Database: Exploring RYC1001 with MicroPython | Part 2

Introduction

Recently, I created a blog post introducing the new Reyax RYC1001 IoT cloud platform. Unlike its competitors, RYC1001 provides additional database capability on top of its MQTT server. I only use free applications available in the internet for Windows and for android. I played with it and I find it easy to use so I decided to further explore the RYC1001 but this time using actual devices to simulate a home automation.

One of the ESP32 (ESP32 DOIT board) have a DHT22 temperature and humidity sensor and a relay arrays. This setup will serve as the Internet-of-Things setup in the home.

Another is the ESP32 Heltec board with OLED display with some buttons that will serve as user input. This setup will serve as the Internet-of-Things setup remotely which can be brought anywhere and will function as long as there is a WiFi internet to connect to.

The DHT22 sensor readings will be publish by ESP32 DOIT board through the notification message on a sub-topic /temperature. The sensor readings will be forwarded to ESP32 Heltec board to which in the end will be displayed in the OLED display.

The relay arrays is controlled by publishing the button-controlled state through the command message on a sub-topic /control_lights. The relays control will then be forwarded to ESP32 DOIT board which will be interpreted as a relay state.

Bill Of Materials

  1. 2 pcs of ESP32 development board with MicroPython firmware or any microcontroller capable of MicroPython.
  2. A DHT22 sensor or any alternative.
  3. 4 channel relay arrays.
  4. OLED display
  5. Some buttons.
  6. External power supply
  7. Breadboard
  8. Some dupont jumper wires.

Hardware Instruction

Relay Array:

  1. Connect the ESP32 D5 pin to Relay IN1 pin.
  2. Connect the ESP32 D18 pin to Relay IN2 pin.
  3. Connect the ESP32 D19 pin to Relay IN3 pin.
  4. Connect the ESP32 D21 pin to Relay IN4 pin.
  5. Power the relay array with 5V supply voltage.

DHT22 sensor:

  1. Connect the DHT signal pin to ESP32 D23 pin.
  2. Power the DHT22 with 3.3V supply voltage.

Buttons:

  1. Connect button_1 signal pin to ESP32 D13 pin.
  2. Connect button_2 signal pin to ESP32 D12 pin.
  3. Connect button_3 signal pin to ESP32 D14 pin.
  4. Connect button_4 signal pin to ESP32 D27 pin.

OLED:

  1. In ESP32 Heltec board, OLED display is onboard and it is configured as follows:
    • OLED sda pin to ESP32 D4 pin.
    • OLED scl pin to ESP32 D15 pin.
    • OLED rst pin to ESP32 D16 pin.
  2. It will be automatically power by ESP32 with 3.3V voltage supply.

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. ESP32 DOIT board:

  1# **************************************#
  2# Description:                          #
  3#   Contains a MicroPython source code  #
  4# exploring the Reyax RYC1001.          #
  5# In this ESP32 board connected are     #
  6# (1) DHT22 - D23 (publish)             #
  7# (2) 4 channel Relay (subscribe)       #
  8#     IN1 - D5                          #
  9#     IN2 - D18                         #
 10#     IN3 - D19                         #
 11#     IN4 - D21                         #
 12# --------------------------------------#
 13# Author: George Bantique               #  
 14#         TechToTinker Youtube Channel  # 
 15#         TechToTinker.blogspot.com     # 
 16#         tech.to.tinker@gmail.com      # 
 17# Date: Jan 5, 2021                     #
 18# --------------------------------------#
 19# Please feel free to modify the code   # 
 20# according to your needs.              # 
 21# **************************************#
 22
 23
 24# ************************************** 
 25# Load necessary libraries 
 26import machine 
 27import network
 28import dht
 29from umqtt.robust import MQTTClient
 30import ujson as json
 31import time 
 32
 33# ************************************** 
 34# Create objects:
 35# 1. dht22
 36d = dht.DHT22(machine.Pin(23)) 
 37# 2. relays
 38relay_1 = machine.Pin(5, machine.Pin.OUT)
 39relay_2 = machine.Pin(18, machine.Pin.OUT)
 40relay_3 = machine.Pin(19, machine.Pin.OUT)
 41relay_4 = machine.Pin(21, machine.Pin.OUT)
 42relay_1.on()
 43relay_2.on()
 44relay_3.on()
 45relay_4.on()
 46# 3. led
 47led = machine.Pin(2, machine.Pin.OUT)
 48# 4. emergency mqtt stop
 49press = False
 50def sw_press(pin):
 51    global press
 52    press = True
 53    
 54estop = machine.Pin(0, machine.Pin.IN, machine.Pin.PULL_UP)
 55estop.irq(trigger=machine.Pin.IRQ_FALLING, handler=sw_press)
 56
 57# # ************************************** 
 58# # Configure the ESP32 wifi as STAtion 
 59sta = network.WLAN(network.STA_IF) 
 60if not sta.isconnected():  
 61  print('connecting to network...')  
 62  sta.active(True)  
 63  sta.connect('your wifi ssid', 'your wifi password')  
 64  while not sta.isconnected():  
 65    pass  
 66print('network config:', sta.ifconfig()) 
 67
 68# **************************************# 
 69# Callback function, it is the function 
 70# that will be called when a new msg 
 71# is received from MQTT broker 
 72def call_back_function(topic, msg):
 73    global msg_flag, msg_data
 74    msg_flag = True
 75    msg_data = json.loads(msg.decode())
 76     
 77# # **************************************
 78# # Constants and variables:
 79UPDATE_TIME_INTERVAL = 5000  # in ms 
 80last_update = time.ticks_ms()
 81BLINK_TIME_INTERVAL = 1000  # in ms 
 82last_blink = time.ticks_ms()
 83msg_data = ""
 84msg_flag = False
 85stop_flag = False
 86
 87CLIENT_ID = b'REYAX_USERNAME0001'
 88REYAX_URL = b'iot.reyax.com'
 89REYAX_USERNAME = b'REYAX_USERNAME'
 90REYAX_PASSWORD = b'REYAX_PASSWORD'
 91
 92TOPIC_PUB = b'api/request'
 93TOPIC_SUB = b'api/command/35/5/gyBII8EdlDdlLXZDfirHAuOiryBIz2RR4zic/control_lights'
 94
 95client = MQTTClient(client_id = CLIENT_ID,   
 96            server = REYAX_URL,   
 97            user = REYAX_USERNAME,   
 98            password = REYAX_PASSWORD,   
 99            ssl = False)  
100try: 
101    client.connect() 
102except Exception as e:
103    client.disconnect()
104    machine.reset()
105    
106client.set_callback(call_back_function)
107client.subscribe(TOPIC_SUB)
108
109# **************************************
110# Main loop:
111while True:
112    if stop_flag == True:
113        led.value(not led.value())
114        time.sleep(0.1)
115    else:            
116        client.check_msg() #non-blocking
117        # msg_flag will be true when new message is received
118        if msg_flag == True:
119            msg_flag = False
120            # parse the individual values from json data
121            light_1 = msg_data['command']['result']['light_1']
122            light_2 = msg_data['command']['result']['light_2']
123            light_3 = msg_data['command']['result']['light_3']
124            light_4 = msg_data['command']['result']['light_4']
125
126            if light_1 == 'ON':
127                relay_1.value(0)
128            elif light_1 == 'OFF':
129                relay_1.value(1)
130            if light_2 == 'ON':
131                relay_2.value(0)
132            elif light_2 == 'OFF':
133                relay_2.value(1)     
134            if light_3 == 'ON':
135                relay_3.value(0)
136            elif light_3 == 'OFF':
137                relay_3.value(1)
138            if light_4 == 'ON':
139                relay_4.value(0)
140            elif light_4 == 'OFF':
141                relay_4.value(1)
142        
143        # this is for the blink interval
144        if time.ticks_ms() - last_blink >= BLINK_TIME_INTERVAL:
145            last_blink = time.ticks_ms()
146            led.value(not led.value()) 
147           
148        # this if for the DHT update interval
149        if time.ticks_ms() - last_update >= UPDATE_TIME_INTERVAL:
150            last_update = time.ticks_ms()
151            d.measure() 
152            temp = str(d.temperature())
153            humi = str(d.humidity())       
154
155            PAYLOAD_PUB = '''{
156                                "action": "notification/insert",
157                                "deviceId": "gyBII8EdlDdlLXZDfirHAuOiryBIz2RR4zic",
158                                "notification": 
159                                {
160                                    "notification": "temperature",
161                                    "parameters":
162                                    {
163                                        "temperature":''' + temp + ''',
164                                        "humidity":''' + humi + '''
165                                    }
166                                }
167                            }'''
168            client.publish(TOPIC_PUB, PAYLOAD_PUB)
169        
170        # checks the mqtt stop button is press
171        # if press, disconnect the mqtt client from the server
172        if press == True:
173            press = False
174            client.disconnect()
175            stop_flag = True
176            print('MQTT is now disconnected.')

2. ESP32 Heltec board:

  1# **************************************#
  2# Description:                          #
  3#   Contains a MicroPython source code  #
  4# exploring the Reyax RYC1001.          #
  5# In this ESP32 board connected are     #
  6# (1) OLED (subscribe)                  #
  7#     scl - 15                          #
  8#     sda - 4                           #
  9#     rst - 16                          #
 10# (2) 4 Buttons (publish)               #
 11#     button1 - D13                     #
 12#     button2 - D12                     #
 13#     button3 - D14                     #
 14#     button4 - D27                     #
 15# --------------------------------------#
 16# Author: George Bantique               #  
 17#         TechToTinker Youtube Channel  # 
 18#         TechToTinker.blogspot.com     # 
 19#         tech.to.tinker@gmail.com      # 
 20# Date: Jan 5, 2021                     #
 21# --------------------------------------#
 22# Please feel free to modify the code   # 
 23# according to your needs.              # 
 24# **************************************#
 25
 26
 27# ************************************** 
 28# Load necessary libraries 
 29import machine 
 30import ssd1306
 31import network  
 32from umqtt.robust import MQTTClient
 33import ujson as json
 34import time 
 35
 36# ************************************** 
 37# Create objects:
 38# 1. oled object
 39rst = machine.Pin(16, machine.Pin.OUT)
 40rst.value(1)
 41i2c = machine.I2C(scl=machine.Pin(15), sda=machine.Pin(4), freq=400000)
 42oled = ssd1306.SSD1306_I2C(128, 64, i2c, addr=0x3C)
 43
 44# 2. button switch object
 45press = False
 46irq_pin = 0
 47
 48def sw_press(pin):
 49    global press
 50    press = True
 51    global irq_pin
 52    irq_pin = int(str(pin)[4:-1])
 53    
 54but13 = machine.Pin(13, machine.Pin.IN, machine.Pin.PULL_UP)
 55but13.irq(trigger=machine.Pin.IRQ_FALLING, handler=sw_press)
 56but12 = machine.Pin(12, machine.Pin.IN, machine.Pin.PULL_UP)
 57but12.irq(trigger=machine.Pin.IRQ_FALLING, handler=sw_press)
 58but14 = machine.Pin(14, machine.Pin.IN, machine.Pin.PULL_UP)
 59but14.irq(trigger=machine.Pin.IRQ_FALLING, handler=sw_press)
 60but27 = machine.Pin(27, machine.Pin.IN, machine.Pin.PULL_UP)
 61but27.irq(trigger=machine.Pin.IRQ_FALLING, handler=sw_press)
 62estop = machine.Pin(0, machine.Pin.IN, machine.Pin.PULL_UP)
 63estop.irq(trigger=machine.Pin.IRQ_FALLING, handler=sw_press)
 64
 65# 3. led switch
 66led = machine.Pin(25, machine.Pin.OUT)
 67
 68# # ************************************** 
 69# # Configure the ESP32 wifi as STAtion 
 70sta = network.WLAN(network.STA_IF) 
 71if not sta.isconnected():  
 72  print('connecting to network...')  
 73  sta.active(True)  
 74  sta.connect('your wifi ssid', 'your wifi password')   
 75  while not sta.isconnected():  
 76    pass  
 77print('network config:', sta.ifconfig()) 
 78
 79# **************************************# 
 80# Callback function, it is the function 
 81# that will be called when a new msg 
 82# is received from MQTT broker 
 83def call_back_function(topic, msg):
 84    global msg_flag, msg_data
 85    msg_flag = True
 86    msg_data = json.loads(msg.decode())
 87     
 88# # **************************************
 89# # Constants and variables:
 90UPDATE_TIME_INTERVAL = 5000  # in ms 
 91last_update = time.ticks_ms()
 92BLINK_TIME_INTERVAL = 1000  # in ms 
 93last_blink = time.ticks_ms()
 94msg_data = ""
 95msg_flag = False
 96stop_flag = False
 97stop_mqtt = False
 98
 99light_1 = 'OFF'
100light_2 = 'OFF'
101light_3 = 'OFF'
102light_4 = 'OFF'
103
104CLIENT_ID = b'REYAX_USERNAME0002'
105REYAX_URL = b'iot.reyax.com'
106REYAX_USERNAME = b'REYAX_USERNAME'
107REYAX_PASSWORD = b'REYAX_PASSWORD'
108
109TOPIC_PUB = b'api/request'
110TOPIC_SUB = b'api/notification/35/5/gyBII8EdlDdlLXZDfirHAuOiryBIz2RR4zic/temperature'
111
112client = MQTTClient(client_id = CLIENT_ID,   
113            server = REYAX_URL,   
114            user = REYAX_USERNAME,   
115            password = REYAX_PASSWORD,   
116            ssl = False)  
117try: 
118    client.connect() 
119except Exception as e:
120    client.disconnect()
121    machine.reset() 
122client.set_callback(call_back_function)
123client.subscribe(TOPIC_SUB)
124
125# **************************************
126# Main loop:
127while True:
128    if stop_flag == True:
129        if stop_mqtt:
130            stop_mqtt = False
131            client.disconnect()
132            print('MQTT is now disconnected.')
133        led.value(not led.value())
134        time.sleep(0.1)
135    else:
136        client.check_msg() #non-blocking
137        if msg_flag == True:
138            msg_flag = False
139            temperature = str(msg_data['notification']['parameters']['temperature'])
140            humidity = str(msg_data['notification']['parameters']['humidity'])
141            oled.fill(0)
142            oled.text('Temperature:',  5,  5)
143            oled.text(temperature,     5, 15)
144            oled.text('oC',           40, 15)
145            oled.text('Humidity:',     5, 30)
146            oled.text(humidity,        5, 40)
147            oled.text('%',            40, 40)
148            oled.show()
149            
150        # this is for the blink interval
151        if time.ticks_ms() - last_blink >= BLINK_TIME_INTERVAL:
152            last_blink = time.ticks_ms()
153            led.value(not led.value()) 
154            
155        
156        # this if for the DHT update interval
157        if time.ticks_ms() - last_update >= UPDATE_TIME_INTERVAL:
158            last_update = time.ticks_ms()
159                
160            if press:
161                press = False
162                
163                if irq_pin == 13:
164                    if light_1 == 'ON':
165                        light_1 = 'OFF'
166                    else:
167                        light_1 = 'ON'
168                elif irq_pin == 12:
169                    if light_2 == 'ON':
170                        light_2 = 'OFF'
171                    else:
172                        light_2 = 'ON'
173                elif irq_pin == 14:
174                    if light_3 == 'ON':
175                        light_3 = 'OFF'
176                    else:
177                        light_3 = 'ON'
178                elif irq_pin == 27:
179                    if light_4 == 'ON':
180                        light_4 = 'OFF'
181                    else:
182                        light_4 = 'ON'
183                elif irq_pin == 0:
184                    stop_flag = True
185                    stop_mqtt = True
186            
187                PAYLOAD_PUB = '''{
188                                    "action":"command/insert",
189                                    "deviceId":"gyBII8EdlDdlLXZDfirHAuOiryBIz2RR4zic",
190                                    "command":
191                                    {
192                                        "command":"control_lights",
193                                        "parameters":
194                                        {
195                                            "Control":"Lights"
196                                        },
197                                        "status":"Done",
198                                        "result":
199                                        {
200                                            "light_1":''' + light_1 + ''',
201                                            "light_2":''' + light_2 + ''',
202                                            "light_3":''' + light_3 + ''',
203                                            "light_4":''' + light_4 + '''
204                                        }
205                                    }
206                                }'''
207                client.publish(TOPIC_PUB, PAYLOAD_PUB)

References And Credits

  1. Reyax RYC1001: http://reyax.com/products/ryc1001/




No comments yet!

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