树莓派上的python mqtt脚本来发送和接收消息 [英] python mqtt script on raspberry pi to send and receive messages

查看:77
本文介绍了树莓派上的python mqtt脚本来发送和接收消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

MQTT 问题:

我正在尝试在多个 Raspberry Pi(从两个开始)之间建立一个 MQTT 网络.我有一个 raspberry pi (RPi-A) MQTT 客户端,连接了一个热敏电阻传感器和一个 raspberry (RPi-B),MQTT 代理/客户端,作为我的网络的集线器.通过 python 脚本,我希望每 30 分钟将温度从 RPi-A 通过 MQTT 发送到主题传感器/数据并由 RPi-B 接收.当 RPi-B 通过主题传感器/数据从 RPi-A 接收消息时,我希望它通过 MQTT 主题传感器/指令响应 RPi-A 的指令.下面是我的脚本,到目前为止,RPi-A 可以发送消息,而 RPi-B 可以接收它们,但我无法弄清楚 RPi-B 如何响应.

Hi, I’m trying to set up a MQTT network between multiple Raspberry Pis (starting with two). I have one raspberry pi (RPi-A), MQTT client, with a thermistor sensor attached and one raspberry (RPi-B), MQTT broker/client, acting as a hub for my network. Through python scripting I’d like the temperature to be sent every 30mins from RPi-A via MQTT to topic sensor/data and received by RPi-B. When RPi-B receives a message from RPi-A via topic sensor/data, I want it to respond with an instruction via MQTT topic sensor/instructions to RPi-A. Below is my script, so far RPi-A can send messages and RPi-B receive them but I cannot work out how RPi-B can respond.

基本上,我想了解的是,MQTT 设备是否可以同时充当代理和客户端?而且,客户端可以发送和接收消息吗?如果可以,如何通过 python 实现上述所有内容?我已经阅读了很多博客、官方 MQTT 文章和 paho 模块文档(对我来说很难理解),但仍然无法弄清楚这一点.您的帮助将是最有用/最感激的.

Basically, what I’m trying to understand is, is it possible for a MQTT device to act as both broker and client at the same time? And, can a client both send and receive messages and if so how to implement all the above via python? I’ve read a lot of blogs, official MQTT articles and the paho module documentation (which for me is very hard to fathom) but still cannot figure this out. Your help would be most useful/ appreciated.

代码 RPi-A(带热敏电阻传感器):

Code RPi-A ( with thermistor sensor):

from sense_hat import SenseHat
import time
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
sense = SenseHat()

Broker = "192.168.1.252"

sub_topic = "sensor/instructions"    # receive messages on this topic

pub_topic = "sensor/data"       # send messages to this topic


############### sensehat inputs ##################

def read_temp():
    t = sense.get_temperature()
    t = round(t)
    return t

def read_humidity():
    h = sense.get_humidity()
    h = round(h)
    return h

def read_pressure():
    p = sense.get_pressure()
    p = round(p)
    return p

def 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 code "+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 publish_mqtt(sensor_data):
    mqttc = mqtt.Client("python_pub")
    mqttc.connect(Broker, 1883)
    mqttc.publish(pub_topic, sensor_data)
    #mqttc.loop(2) //timeout = 2s

def on_publish(mosq, obj, mid):
    print("mid: " + str(mid))


client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(Broker, 1883, 60)


while True:
    sensor_data = [read_temp(), read_humidity(), read_pressure()]
    publish.single("monto/solar/sensors", str(sensor_data), hostname = Broker)
    time.sleep(1*60)

代码 RPi-B(网络集线器):

Code RPi-B (network hub):

import time
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish

Broker = "192.168.1.252"

sub_topic = "sensor/data"    # receive messages on this topic

pub_topic = "sensor/instructions"               # send messages to this topic


# mqtt section

# when connecting to mqtt do this;

def on_connect(client, userdata, flags, rc):
    print("Connected with result code "+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)
    publish_mqtt(‘got your message’)

# to send a message

def publish_mqtt(sensor_data):
    mqttc = mqtt.Client("monto_hub")
    mqttc.connect(Broker, 1883)
    mqttc.publish(pub_topic, "this is the master speaking")
    #mqttc.loop(2) //timeout = 2s

def on_publish(mosq, obj, mid):
    print("mid: " + str(mid))


client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(Broker, 1883, 60)
client.loop_forever()

推荐答案

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

The simplest way is to start the network loop on a separate thread using the client.loop_start() function, then use the normal client.publish method

from sense_hat import SenseHat
import time
import paho.mqtt.client as mqtt
import paho.mqtt.publish as publish
sense = SenseHat()

Broker = "192.168.1.252"

sub_topic = "sensor/instructions"    # receive messages on this topic

pub_topic = "sensor/data"       # send messages to this topic


############### sensehat inputs ##################

def read_temp():
    t = sense.get_temperature()
    t = round(t)
    return t

def read_humidity():
    h = sense.get_humidity()
    h = round(h)
    return h

def read_pressure():
    p = sense.get_pressure()
    p = round(p)
    return p

def 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 code "+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_connect
client.on_message = on_message
client.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)

这篇关于树莓派上的python mqtt脚本来发送和接收消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆