Exemplo n.º 1
0
def run():
    mqtt = threading.Thread(name='mqtt', target=runMqtt)
    mqtt.daemon = True
    mqtt.start()

    try:
        threading.Event().wait()
    except (KeyboardInterrupt, SystemExit):
        logger.info("Stopping server..")
    def on_connect(self, client, userdata, flags, rc, properties=None):
        self.Log.log("Connection returned {}".format(rc))
        self.subscribe(self.MQTT_TOPIC_DATA)
        self.connected = True

    def on_disconnect(self, client, userdata, rc):
        self.connected = False
        self.Log.log("Client disconected - {}".format(rc))

    def add_message_callback(self, func):
        self.on_message_callback = func

    def on_message(self, client, userdata, message):
        self.Log.log("Message Received: {} | On Topic: {}".format(
            message.payload.decode("utf-8"), message.topic))
        if (self.on_message_callback):
            self.Log.log("Calling on_message_callback")
            self.on_message_callback(client, userdata, message)
        else:
            self.Log.log("No message callback!")

    def is_connected(self):
        return self.connected


if __name__ == '__main__':
    mqtt = MqttIPC()
    mqtt.start()
    while 1:
        time.sleep(1)
Exemplo n.º 3
0
def main():
    mqtt=threading.Thread(target=mqtt_loop)
    mqtt.start()
    win.mainloop()
Exemplo n.º 4
0
        if rc == 0:
            self.connected = True
            print("Connected to MQTT Broker!")
        else:
            print("Failed to connect, return code %d\n", rc)

    def start(self):
        self.client.loop_start()
        self.client.connect(host_ip)

    def publish_to_topic(self, msg, topic=test_topic):
        result = self.client.publish(topic, msg)
        status = result[0]
        if status == 0:
            print(f"Send `{msg}` to topic `{topic}`")
        else:
            print(f"Failed to send message to topic {topic}")


if __name__ == "__main__":
    mqtt_client = MqttClient()
    mqtt_client.start()
    while not mqtt_client.connected:
        pass
    inp: str = ''
    while inp != 'exit':
        inp = input("Print a message to send: ")
        if inp == 'exit':
            pass
        mqtt_client.publish_to_topic(inp)