Python-多个MQTT订阅-限制

时间:2018-11-07 22:45:56

标签: multithreading networking raspberry-pi mqtt publish-subscribe

我有 n-raspberry pi's ,我希望他们每个人都订阅其余的,因为他们的行为都像坏了一样。服务器和客户端工作正常,但是我想知道是否存在一些限制。我计划在Threads中运行订阅脚本。这些是要求:

  • 速度(我发布了一些东西,很多pis同时收到了消息
  • 无限订阅(我希望网络中最多有50 pi)

该想法是创建去中心化网络。上面的内容可以很容易地用特殊pi代替,用作集中单元,因此所有pi都订阅该特殊pi,并且都将同时接收特定的消息。但是我更喜欢分散式架构。

是否可能,或者存在一些网络问题? ps:我没有足够的Pi来测试它。

我将在Subscription类中附加代码。它有效,但是我把它放在这里,因为我不想只问一个问题,但至少要有所贡献。它是我用于订阅的同一类

import paho.mqtt.client as mqtt
import threading
import json
# Define Variables
MQTT_BROKER = ""
MQTT_PORT = 1883
MQTT_KEEPALIVE_INTERVAL = 45
MQTT_TOPIC = ""

class sub:
    def __init__(self,MQTT_TOPIC,MQTT_BROKER, MQTT_PORT,MQTT_KEEPALIVE_INTERVAL,transport = ''):
        self.MQTT_TOPIC = MQTT_TOPIC
        self.MQTT_BROKER =MQTT_BROKER
        self.MQTT_PORT = MQTT_PORT
        self.MQTT_KEEPALIVE_INTERVAL = MQTT_KEEPALIVE_INTERVAL
        # Initiate MQTT Client
        if transport == 'websockets':
            self.mqttc = mqtt.Client(transport='websockets')
            print('Here')
        else:
            self.mqttc = mqtt.Client()
        self.load = True
        tr = threading.Thread(target=self.start)
        tr.daemon = True
        tr.start()



    # Define on_connect event Handler
    def on_connect(self,selfs,mosq, obj, rc):
        #Subscribe tox a the Topic
        self.mqttc.subscribe(self.MQTT_TOPIC, 0)

    # Define on_subscribe event Handler
    def on_subscribe(self,mosq, obj, mid, granted_qos):
        print("Subscribed to MQTT Topic")

    # Define on_message event Handler
    def on_message(self,mosq, obj, msg):
        print(msg.payload)
        if self.load == True:
            msg.payload = json.loads(msg.payload)

    def start(self):
        # Initiate MQTT Client
        #self.mqttc = mqtt.Client()

        # Register Event Handlers
        self.mqttc.on_message = self.on_message
        self.mqttc.on_connect = self.on_connect
        self.mqttc.on_subscribe = self.on_subscribe

        # Connect with MQTT Broker
        self.mqttc.connect(MQTT_BROKER, MQTT_PORT, MQTT_KEEPALIVE_INTERVAL )

        # Continue the network loop
        self.mqttc.loop_forever()


s=sub(MQTT_TOPIC,MQTT_BROKER,MQTT_PORT,MQTT_KEEPALIVE_INTERVAL)

0 个答案:

没有答案