Your question is not completely clear to me.
In the first place:
Please read the MQTT client (Python) documentation carefully:
https://eclipse.dev/paho/files/paho.mqt ... lient.html
One or more MQTT clients can establish a connection to an MQTT broker.
This can be done from different IP addresses or from the same IP address, or a combination of both.
So it is not the device/computer that connects, but every application of which an MQTT client is part, connects to the MQTT broker.
Note: All IP addresses must be correctly routed in the (local) subnetwork.
Each of these connected MQTT clients can "subscribe" and/or "publish" to the MQTT broker.
Of course, every MQTT client must correctly execute "message_callback_remove", "unsubscribe" and "disconnect" at the end.
Otherwise, "keep alive" and "will" will cause an error message.
Note: So also work out a good exception operation (try: except: finally:) in the program code.
Note: Remember that the on_message callback amounts to event driven programming and therefore communication between threads.
Here is the basics of an MQTT client with all call-backs.
There are two ways to link the call-backs to the client, via an assignment or via @decorations
========================================================================
Deine Frage ist mir nicht ganz klar.
An erster Stelle:
Bitte lesen Sie die Dokumentation zum MQTT-Client (Python) sorgfältig durch:
https://eclipse.dev/paho/files/paho.mqt ... lient.html
Ein oder mehrere MQTT-Clients können eine Verbindung zu einem MQTT-Broker aufbauen.
Dies kann von verschiedenen IP-Adressen oder von derselben IP-Adresse oder einer Kombination aus beidem erfolgen.
Es ist also nicht das Gerät/der Computer, der die Verbindung herstellt, sondern jede Anwendung, zu der ein MQTT-Client gehört, verbindet sich mit dem MQTT-Broker.
Hinweis: Alle IP-Adressen müssen im (lokalen) Subnetz korrekt geroutet sein.
Jeder dieser verbundenen MQTT-Clients kann den MQTT-Broker "subscribe" und/oder "publish".
Natürlich muss jeder MQTT-Client am Ende „message_callback_remove“, „unsubscribe“ und „disconnect“ korrekt ausführen.
Andernfalls führen „keep alive“ und „will“ zu einer Fehlermeldung.
Hinweis: Erarbeiten Sie also auch eine gute Ausnahmeoperation (try: except: finally:) im Programmcode.
Hinweis: Denken Sie daran, dass der on_message-Rückruf einer ereignisgesteuerten Programmierung und damit der Kommunikation zwischen Threads gleichkommt.
Hier sind die Grundlagen eines MQTT-Clients mit allen Rückrufen.
Es gibt zwei Möglichkeiten, die Rückrufe mit dem Kunden zu verknüpfen: über eine Zuweisung oder über @decorations
Code: Alles auswählen
class MyMQTTClass(mqtt.Client):
def on_subscribe(self, client: mqtt.Client, userdata, mid, reason_code_list, properties):
logger.debug(msg="MQTT_02_test: on_subscribe") # + " userdata:" + str(userdata))
if reason_code_list[0].is_failure:
logger.debug(f"MQTT_02_test: on_subscribe: Broker rejected you subscription: {reason_code_list[0]} {mid} {str(properties)}")
else:
logger.debug(f"MQTT_02_test: on_subscribe: Broker granted the following QoS: {reason_code_list[0].value} {mid} {str(properties)}")
def on_unsubscribe(self, client, userdata, mid, reason_code_list, properties):
logger.debug(msg="MQTT_02_test: on_unsubscribe" + " userdata:" + str(userdata))
# Be careful, the reason_code_list is only present in MQTTv5.
# In MQTTv3 it will always be empty
if len(reason_code_list) == 0 or not reason_code_list[0].is_failure:
logger.debug("MQTT_02_test: unsubscribe succeeded (if SUBACK is received in MQTTv3 it success)")
else:
logger.debug(f"MQTT_02_test: Broker replied with failure: {reason_code_list[0]}")
client.disconnect()
def on_message(self, client, userdata, message):
logger.debug(msg="MQTT_02_test: On message" + " message:" + str(message.payload) + " on topic '" + str(message.topic) + " userdata:" + str(userdata))
def on_connect(self, client, userdata, flags, reason_code, properties):
logger.debug(msg="MQTT_02_test: On connect" + " userdata:" + str(userdata))
if reason_code.is_failure:
print(f"Failed to connect: {reason_code}. loop_forever() will retry connection")
logger.error(
msg=f"MQTT_02_test: Failed to connect: {reason_code}. loop_forever() will retry connection")
else:
logger.debug(msg="MQTT_02_test: On connect Ok")
# we should always subscribe from on_connect callback to be sure
# our subscribed is persisted across reconnections.
# client.subscribe("$SYS/#")
def on_connect_fail(self, client, userdata, disconnect_flags, reason_code, properties):
logger.debug(msg="MQTT_02_test: on_connect_fail" + " flag:" +
str(disconnect_flags) + " userdata:" + str(userdata))
if reason_code.is_failure:
print(f"Failed to connect: {reason_code}. loop_forever() will retry connection")
logger.error(
msg=f"MQTT_02_test: on_connect_fail: {reason_code}. loop_forever() will retry connection")
else:
logger.debug(msg="MQTT_02_test: on_connect_fail Ok")
def on_pre_connect(self, client, userdata):
logger.debug(msg="MQTT_02_test: on_pre_connect" + " userdata:" + str(userdata))
def on_disconnect(self, client, userdata, disconnect_flags, reason_code, properties):
logger.debug(msg="MQTT_02_test: on_disconnect" + " userdata:" + str(userdata))
def on_publish(self, client, userdata, mid, reason_code, properties):
logger.debug(msg="MQTT_02_test: on_publish mid=" + str(mid) + " userdata:" + str(userdata))
def on_socket_close(self, client, userdata, socket):
logger.debug(msg="MQTT_02_test: on_socket_close," + " userdata:" + str(userdata)) # + str(socket.socket['fd'])
def on_socket_register_write(self, client, userdata, socket):
# logger.debug(msg="MQTT_02_test: on_socket_register_write," + " userdata:" + str(userdata))
return
def on_socket_unregister_write(self, client, userdata, socket):
# logger.debug(msg="MQTT_02_test: on_socket_unregister_write," + " userdata:" + str(userdata))
return
# There exist a second way in Python to connect to a callback, with decorations.
# def on_log(self, client, userdata, level, buf):
# self.logger.debug(msg="MQTT_02_test: on_log" + " userdata:" + str(userdata))
# def on_socket_open(self, userdata, socket, dummy):
# self.logger.debug(msg="MQTT_02_test: on_socket_open= " + str(socket) + " userdata:" + str(userdata))
'''
https://eclipse.dev/paho/files/paho.mqtt.python/html/client.html#paho.mqtt.client.Client.on_log
`on_connect`,
def on_connect_fail(client, userdata),
'''
def run(client_id: str ='me', ip_addr: str = "localhost" ):
broker = ip_addr
port = 1883
userDATA = {"info": 10} # for example
client: MyMQTTClass = MyMQTTClass(client_id=client_id, userdata=userDATA, callback_api_version= CallbackAPIVersion.VERSION2)
# client.enable_logger(logger=logger)
client.will_set(topic='/test/will', payload='I,am dying', qos=0, retain=False, properties=None)
client.username_pw_set("MyApp", None)
client.disable_logger()
client.connect_async(host=broker, port=port, keepalive=30)
# two examples of the use of decorators
@client.log_callback()
def on_log(client, userdata, level, buf):
logger.debug(msg="MQTT_02_test: on_log" + " l:[" + str(level) + "] b: " + str(buf)) # + " userdata:" + str(userdata))
@client.socket_open_callback()
def on_socket_open(client, userdata, socket):
logger.debug(msg="MQTT_02_test: on_socket_open, userdata:" + str(userdata))
return client