使用MQTT和Python控制程序

时间:2015-05-19 06:29:55

标签: python mqtt payload paho

哟,伙计们。所以我对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有效负载方面遇到了很多麻烦。

1 个答案:

答案 0 :(得分:0)

您的订阅者代码正在循环而不做任何有效的工作。必须按如下方式进行更改

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))