if __name__=='__main__': try: ConnectWifi(SSID,PASSWORD) client = MQTTClient(CLIENT_ID, SERVER,1883,username,password,60) #create a mqtt client print(client) client.set_callback(sub_cb) #set callback client.connect() #connect mqtt client.subscribe(subscribe_TOPIC) #client subscribes to a topic i=0 while True: d.measure() t = d.temperature() h = d.humidity() time.sleep(0.5) mymessage='{"method":"thing.service.property.set","params":{"Humidity":%.1f,"temperature":%.1f},"version":"1.0.0"}'%(h,t) client.publish(topic=publish_TOPIC,msg= mymessage, retain=False, qos=0) print('temperature: {:.1f} °C,Humidity: {:.1f} %'.format(t,h)) client.wait_msg() time.sleep_ms(3) if t > 30: for tone in melody: freq = tones[tone] if freq: beeper.init(duty=1000, freq=freq) else: beeper.duty(0) utime.sleep_ms(400) beeper.duty(0) utime.sleep_ms(100) beeper.deinit() if AlarmSwitch == 1: yly.value(0) jm.value(0) else: yly.value(1) jm.value(1) except Exception as ex_results: print('exception1',ex_results) finally: if(client is not None): client.disconnect() wlan.disconnect() wlan.active(False)
时间: 2024-02-10 12:20:14 浏览: 164
Cayenne-MQTT-ESP-master.zip_ESP MQTT_MQTT-master_mqtt_mqtt 10060
这段代码使用 DHT11 传感器测量温湿度,并将数据发布到 MQTT 服务器上。同时,如果温度超过 30 度,蜂鸣器会发出警报声。如果接收到的 MQTT 消息中包含 AlarmSwitch 为 1,则会关闭一个 LED 和一个继电器。如果不是 1,则会打开它们。最后,无论是否出现异常,都会断开 MQTT 和 WiFi 连接。
阅读全文