最简单的方法是使用
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)
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)