2

よ、みんな。したがって、私は Python には比較的慣れておらず、MQTT の完全な初心者です。そこで、MQTT を介して 2 つのプログラムを簡単に接続しようとしています。プログラムの 1 つがパブリッシャーです。

   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 ペイロードを「読み取ろう」とするのに苦労しました。

4

1 に答える 1

2

サブスクライバーのコードは、生産的なことを何もせずにループしています。次のように変更する必要があります

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))
于 2015-05-19T07:36:56.433 に答える