你们好 因此,我是Python的新手,并且是MQTT的新手。因此,我试图通过MQTT建立两个程序的简单连接。程序之一是发布者:
import paho.mqtt.client as mqtt
import sys, tty, termios
## Publisher reads a keyboard input
def getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd,termios.TCSADRAIN, old_settings)
return ch
while True:
##Publisher connects to MQTT broker
mqttc= mqtt.Client("python_pub")
mqttc.connect("iot.eclipse.org", 1883)
char= getch()
mqttc.publish("Labbo/control", str(char))
mqtt.Client()
因此,基本上,发布者读取密钥输入并将其发送给代理。客户端程序应该读取按键并做出相应的反应:
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("Labbo/control")
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
## v v PROBLEM LINE v v ##
char=str(msg.payload)
## ^ ^ PROBLEM LINE ^ ^ ##
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("iot.eclipse.org", 1883, 60)
##The program just needs to close itself upon entering "x" on the Publisher
while True:
if char=="x":
break
这是一个简单的测试程序,但是尝试“读取” MQTT有效负载时遇到了很多麻烦。
您的订户代码正在循环,没有做任何有效果的工作。必须进行如下更改
import paho.mqtt.client as mqtt
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe("Labbo/control")
def on_message(client, userdata, msg):
print(msg.topic+" "+str(msg.payload))
char = str(msg.payload)
if char == 'x':
client.disconnect()
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect("iot.eclipse.org", 1883, 60)
client.loop_forever()
您的发布者代码也在其中,它在其中创建了一个新客户以发送一封信,这有点过头了
import paho.mqtt.client as mqtt
import sys, tty, termios
## Publisher reads a keyboard input
def getch():
fd = sys.stdin.fileno()
old_settings = termios.tcgetattr(fd)
try:
tty.setraw(sys.stdin.fileno())
ch = sys.stdin.read(1)
finally:
termios.tcsetattr(fd,termios.TCSADRAIN, old_settings)
return ch
##Publisher connects to MQTT broker
mqttc= mqtt.Client("python_pub")
mqttc.connect("iot.eclipse.org", 1883)
mqttc.loop_start()
while True:
char= getch()
mqttc.publish("Labbo/control", str(char))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句