上一篇写到了获取DHT11的数据,这次我们要通过MQTT下发指令,解析后获取DHT11传感器数据后,通过MQTT发送到服务端。

准备工作

模块联网请参考前面的文章,MQTT服务端需要提前准备好,我们假设通过两个TOPIC来实现命令监听和数据发布:

命令监听TOPIC:b'cat/esp32/01'

数据发送TOPIC:b'iot/esp32/01'

参考代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import utime
from machine import Pin
import dht
from umqtt.simple import MQTTClient
import ujson

SERVER = 'your_mqtt_server'
CLIENT_ID = 'esp32_dg_01'
TOPIC = b'cat/esp32/01'

RESPONSE_TOPIC = b'iot/esp32/01'

sensor = dht.DHT11(Pin(18))

client = MQTTClient(CLIENT_ID, SERVER)


def read_sensor():
global temp, hum
temp = hum = 0
try:
sensor.measure()
temp = sensor.temperature()
hum = sensor.humidity()
if (isinstance(temp, float) and isinstance(hum, float)) or (isinstance(temp, int) and isinstance(hum, int)):
msg = (b'{0:3.1f},{1:3.1f}'.format(temp, hum))

# uncomment for Fahrenheit
#temp = temp * (9/5) + 32.0

hum = round(hum, 2)
return(msg)
else:
return('Invalid sensor readings.')
except OSError as e:
return('Failed to read sensor.')

def mqtt_callback(topic, msg):
print('topic: {}'.format(topic))
print('msg: {}'.format(msg))
print(topic)
print(msg)
print(bytes.decode(msg))
if TOPIC == topic:
obj = ujson.loads(bytes.decode(msg))
print(obj["cmd"])
if obj["cmd"] == "dht":
sensor_readings = read_sensor()
print(sensor_readings)
print(temp)
print(hum)
print('{{"temp":{0:.2f}, "hum":{1:.2f}}}'.format(temp, hum))
client.publish(RESPONSE_TOPIC, '{{"temp":{0:.2f}, "hum":{1:.2f}}}'.format(temp, hum))
else:
print("Unkown Command")
else:
print("Other Topic")

client.set_callback(mqtt_callback)
client.connect()

client.subscribe(TOPIC)


while True:
client.check_msg()
utime.sleep(1)

实测

MQTT发送指令(并通过另外的TOPIC返回数据):

模块接收到指令并获取数据后发送: