[Digi-Key Follow Me Issue 3] Task 6-2: Temperature and Humidity Data Logger
[Copy link]
This post is based on the previous [Digi-Key Electronics Follow me Issue 3] Task 5: Using external sensors: Temperature and humidity sensors , plus MQTT, so that the temperature and humidity information is published to the server through MQTT, and then received and presented using the mobile app.
1. MQTT server
You can build your own mqtt server: https://www.emqx.io/zh/downloads?os=Ubuntu ; after building it, add a user in the management interface to facilitate the connection.
Of course, you can also use the public server officially provided by EMQX for testing: https://www.emqx.com/zh/mqtt/public-mqtt5-broker
2. Micropython connects to MQTT service
To connect to the MQTT service in the micropython of Seeed Studio XIAO ESP32C3, you can use the umqttsimple library, which can be downloaded from: https://raw.githubusercontent.com/RuiSantosdotme/ESP-MicroPython/master/code/MQTT/umqttsimple.py
Connect to MQTT and send information. You can use the following code to test:
import time
from umqttsimple import MQTTClient
import ubinascii
import machine
import micropython
import network
import esp
esp.osdebug(None)
import gc
gc.collect()
ssid = 'OpenBSD'
password = '********'
mqtt_server = '192.168.1.15'
mqtt_user = 'user_esp32c3'
mqtt_pass = '123456'
client_id = ubinascii.hexlify(machine.unique_id())
topic_sub = b'/device/cmd'
topic_pub = b'/device/report'
last_message = 0
message_interval = 5
counter = 0
station = network.WLAN(network.STA_IF)
station.active(True)
station.connect(ssid, password)
while station.isconnected() == False:
pass
print('Connection successful')
print(station.ifconfig())
def sub_cb(topic, msg):
print((topic, msg))
def connect_and_subscribe():
global client_id, mqtt_server, mqtt_user, mqtt_pass, topic_sub
client = MQTTClient(client_id, mqtt_server, user=mqtt_user, password=mqtt_pass)
client.set_callback(sub_cb)
client.connect()
client.subscribe(topic_sub)
print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub))
return client
def restart_and_reconnect():
print('Failed to connect to MQTT broker. Reconnecting...')
time.sleep(10)
machine.reset()
try:
client = connect_and_subscribe()
except OSError as e:
restart_and_reconnect()
while True:
try:
new_message = client.check_msg()
if new_message != 'None':
client.publish(topic_pub, b'received')
time.sleep(1)
except OSError as e:
restart_and_reconnect()
Note that in the above code, please modify the settings of the mqtt service to the corresponding ones:
mqtt_server = '192.168.1.15'
mqtt_user = 'user_esp32c3'
mqtt_pass = '123456'
After successfully connecting to the mqtt service, you can publish a message using the following call:
client.publish(topic_pub, b'需要发布的消息')
In the management backend of EMQX, use the WebSocket tool to view the published messages and send them to the development board:
3. Complete the release of temperature and humidity information
The complete code is based on the MQTT code above, and is based on Task 5: Using External Sensors: Temperature and Humidity Sensors in Digi-Key Follow Me Issue 3.
import utime
from machine import Pin, SoftI2C
import ahtx0
from color_setup import ssd
from color_setup import i2c
from gui.core.nanogui import refresh
from gui.core.writer import CWriter
from gui.widgets.textbox import Textbox
from gui.widgets.label import Label
from gui.core.colors import *
# 字体调用
import gui.fonts.arial10 as arial10
import machine
import network
from umqttsimple import MQTTClient
import ubinascii
import gc
gc.collect()
mqtt_server = '192.168.1.15'
mqtt_user = 'user_esp32c3'
mqtt_pass = '123456'
client_id = ubinascii.hexlify(machine.unique_id())
topic_sub = b'/device/cmd'
topic_pub = b'/device/report'
last_message = 0
message_interval = 5
counter = 0
# 无线连接设置
wifi_ssid = "OpenBSD"
wifi_password = "********"
def sub_cb(topic, msg):
print((topic, msg))
def connect_and_subscribe():
global client_id, mqtt_server, mqtt_user, mqtt_pass, topic_sub
client = MQTTClient(client_id, mqtt_server, user=mqtt_user, password=mqtt_pass)
client.set_callback(sub_cb)
client.connect()
client.subscribe(topic_sub)
print('Connected to %s MQTT broker, subscribed to %s topic' % (mqtt_server, topic_sub))
return client
def restart_and_reconnect():
print('Failed to connect to MQTT broker. Reconnecting...')
time.sleep(10)
machine.reset()
# 清屏
refresh(ssd, True)
# 显示输出
CWriter.set_textpos(ssd, 0, 0)
wri = CWriter(ssd, arial10, verbose=False)
wri.set_clip(True, True, False)
# 联网处理
def scan_and_connect():
station = network.WLAN(network.STA_IF)
station.active(True)
if not station.isconnected():
print("Scanning for WiFi networks, please wait...")
for ssid, bssid, channel, RSSI, authmode, hidden in station.scan():
print("* {:s}".format(ssid))
print(" - Channel: {}".format(channel))
print(" - RSSI: {}".format(RSSI))
print(" - BSSID: {:02x}:{:02x}:{:02x}:{:02x}:{:02x}:{:02x}".format(*bssid))
print()
while not station.isconnected():
print("Connecting...")
station.connect(wifi_ssid, wifi_password)
utime.sleep(10)
print("Connected!")
print("My IP Address:", station.ifconfig()[0])
# 联网
ssd.fill(0)
refresh(ssd)
Label(wri, 5, 0, "WiFi Connect...")
refresh(ssd)
scan_and_connect()
Label(wri, 5, 0, "WiFi Connect OK.")
refresh(ssd)
utime.sleep(2)
try:
Label(wri, 5, 0, "MQTT Connect...")
refresh(ssd)
client = connect_and_subscribe()
Label(wri, 5, 0, "MQTT Connect OK.")
refresh(ssd)
utime.sleep(2)
except OSError as e:
restart_and_reconnect()
ssd.fill(0)
refresh(ssd)
# 显示日期
txt = Label(wri, 0, 0, "Environmental information")
pargs = (13, 2, 124, 4) # Row, Col, Width, nlines
tb = Textbox(wri, *pargs, clip=False)
sensor = ahtx0.AHT10(i2c)
last_time = 0
cron_time = 10 # 定时间隔时间
while True:
if last_time == 0 or utime.time() - last_time == cron_time:
last_time = utime.time()
else:
utime.sleep(1)
continue
print("\nlast_time: %d" % last_time)
print("Temperature: %0.2f C" % sensor.temperature)
print("Humidity: %0.2f %%" % sensor.relative_humidity)
tb.clear()
tb.append("\n", ntrim = 100)
tb.append(" Temperature: %0.2f C" % sensor.temperature, ntrim = 100)
tb.append(" Humidity: %0.2f %%" % sensor.relative_humidity, ntrim = 100)
refresh(ssd)
client.publish(b"%s/temp" % topic_pub, b'{"value":%0.1f}' % sensor.temperature)
client.publish(b"%s/hum" % topic_pub, b'{"value":%0.1f}' % sensor.relative_humidity)
utime.sleep(5)
The core of the above code is the loop part, which used to be display, but now has more:
client.publish(b"%s/temp" % topic_pub, b'{"value":%0.1f}' % sensor.temperature)
client.publish(b"%s/hum" % topic_pub, b'{"value":%0.1f}' % sensor.relative_humidity)
These two lines of code are responsible for publishing temperature and humidity information to the MQTT service. Pay attention to the published topic:
- Temperature: /device/report/temp
- Humidity: /device/report/hum
After completing the above code and running it on the device, you can operate it on the mobile phone.
The demonstration timing time in the above code is cron_time=10 seconds, which can be set according to actual needs.
4. Mobile App accepts published information
On the mobile phone, you can use the mqtt dashboard tool to receive messages very conveniently.
The specific setting steps are as follows:
1. MQTT service settings:
2. Add temperature information:
3. Add humidity information:
4. View the acquired data:
After the settings are completed, you can directly view the temperature and humidity information sent by the development board through MQTT on the interface.
V. Conclusion
MQTT is the standard for Internet communication. Through the MQTT protocol and services, embedded devices can publish information quickly and easily, and then use other devices to receive and process it.
Seeed Studio XIAO ESP32C3's micropython can also access the MQTT service very well, so that the functions of the development board are not limited to the development board itself.
In addition, the above demonstration code also includes the part of receiving commands. Students who are interested can study it and send commands through the mobile phone App to control the light or buzzer.
|