树莓派上的python mqtt脚本发送和接收消息

树莓派上的python mqtt脚本发送和接收消息,第1张

树莓派上的python mqtt脚本发送和接收消息

最简单的方法是使用

client.loop_start()
函数在单独的线程上启动网络循环,然后使用常规
client.publish
方法

from sense_hat import SenseHatimport timeimport paho.mqtt.client as mqttimport paho.mqtt.publish as publishsense = SenseHat()Broker = "192.168.1.252"sub_topic = "sensor/instructions"    # receive messages on this topicpub_topic = "sensor/data"       # send messages to this topic############### sensehat inputs ##################def read_temp():    t = sense.get_temperature()    t = round(t)    return tdef read_humidity():    h = sense.get_humidity()    h = round(h)    return hdef read_pressure():    p = sense.get_pressure()    p = round(p)    return pdef display_sensehat(message):    sense.show_message(message)    time.sleep(10)############### MQTT section ################### when connecting to mqtt do this;def on_connect(client, userdata, flags, rc):    print("Connected with result pre "+str(rc))    client.subscribe(sub_topic)# when receiving a mqtt message do this;def on_message(client, userdata, msg):    message = str(msg.payload)    print(msg.topic+" "+message)    display_sensehat(message)def on_publish(mosq, obj, mid):    print("mid: " + str(mid))client = mqtt.Client()client.on_connect = on_connectclient.on_message = on_messageclient.connect(Broker, 1883, 60)client.loop_start()while True:    sensor_data = [read_temp(), read_humidity(), read_pressure()]    client.publish("monto/solar/sensors", str(sensor_data))    time.sleep(1*60)


欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/zaji/5632157.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-15
下一篇 2022-12-15

发表评论

登录后才能评论

评论列表(0条)

保存