|
| 1 | +import paho.mqtt.client as client |
| 2 | + |
| 3 | +class mqtt_client: |
| 4 | + |
| 5 | + def __init__(self, client_id, broker, port=1883, username=None, password=None): |
| 6 | + self.client_id = client_id |
| 7 | + self.broker = broker |
| 8 | + self.port = port |
| 9 | + self.username = username |
| 10 | + self.password = password |
| 11 | + |
| 12 | + self.client = client.Client(self.client_id) |
| 13 | + |
| 14 | + def connect(self): |
| 15 | + def on_connect_callback(client, userdata, flags, rc): |
| 16 | + if rc == 0: |
| 17 | + print("Connected to MQTT Broker!") |
| 18 | + else: |
| 19 | + print("Failed to connect, return code {}\n",format(rc)) |
| 20 | + |
| 21 | + if self.username is not None and self.password is not None: |
| 22 | + self.client.username_pw_set(self.username, self.password) |
| 23 | + |
| 24 | + self.client.on_connect = on_connect_callback |
| 25 | + self.client.connect(self.broker, self.port) |
| 26 | + self.client.loop_start() |
| 27 | + |
| 28 | + return self.client.is_connected() |
| 29 | + |
| 30 | + def disconnect(self): |
| 31 | + def on_disconnect_callback(client, userdata, rc): |
| 32 | + if rc == 0: |
| 33 | + print("Disconnected from MQTT Broker!") |
| 34 | + else: |
| 35 | + print("Failed to disconnect, return code {}\n",format(rc)) |
| 36 | + |
| 37 | + self.client.on_disconnect = on_disconnect_callback |
| 38 | + self.client.loop_stop() |
| 39 | + self.client.disconnect() |
| 40 | + |
| 41 | + return not self.client.is_connected |
| 42 | + |
| 43 | + |
| 44 | + def publish_message(self, topic, msg): |
| 45 | + result = self.client.publish(topic, msg) |
| 46 | + status = result[0] |
| 47 | + if status == 0: |
| 48 | + print("Sent '{}' to topic '{}'".format(msg, topic)) |
| 49 | + else: |
| 50 | + print("Failed to send message to topic {topic}".format(topic)) |
| 51 | + |
| 52 | + def subscribe_to_topic(self, topic, on_message): |
| 53 | + def on_message_callback(client, userdata, msg): |
| 54 | + on_message(msg) |
| 55 | + |
| 56 | + self.client.message_callback_add(topic, on_message_callback) |
| 57 | + self.client.subscribe(topic) |
| 58 | + |
| 59 | + def unsubscribe_from_topic(self, topic): |
| 60 | + self.client.unsubscribe(topic) |
| 61 | + self.client.message_callback_remove(topic) |
0 commit comments