46 lines
1.9 KiB
Python
46 lines
1.9 KiB
Python
import paho.mqtt.client as paho
|
|
import paho.mqtt.enums as paho_enums
|
|
|
|
class vqeMqttBroker:
|
|
def __init__(self, broker_address, broker_port, username="correct", password="any", use_tls=True, max_connection_attempts=30):
|
|
self.server = broker_address
|
|
self.port = broker_port
|
|
self.client = paho.Client(callback_api_version=paho.CallbackAPIVersion.VERSION2, client_id="my_python_client", reconnect_on_failure=True)
|
|
self.client.username_pw_set(username, password)
|
|
if use_tls:
|
|
self.client.tls_set()
|
|
self.client.on_connect = self.on_connect
|
|
self.client.on_message = self.on_message
|
|
self.client.on_connect_fail = self.on_connect_fail
|
|
self.client.on_disconnect = self.on_disconnect
|
|
self.max_connection_attempts=max_connection_attempts
|
|
self.connection_attempt_number=0
|
|
|
|
def connect_to_server(self):
|
|
self.connection_attempt_number=0
|
|
self.client.connect_async(self.server, self.port, 5)
|
|
self.client.loop_start()
|
|
|
|
def get_status(self):
|
|
|
|
return self.client._state #self.client.is_connected()
|
|
|
|
def on_connect(self, client, userdata, flags, reason_code, properties):
|
|
print(f"Connected with result code {reason_code}")
|
|
# Subscribe to topics here if needed
|
|
client.subscribe("my/topic")
|
|
|
|
def on_message(self, client, userdata, msg):
|
|
print(f"Received message: {msg.payload.decode()} on topic {msg.topic}")
|
|
|
|
def on_connect_fail(self, client, userdata):
|
|
self.connection_attempt_number+=1
|
|
print("fail")
|
|
|
|
def on_disconnect(self, client, userdata, disconnect_flags, reason_code, properties):
|
|
self.connection_attempt_number+=1
|
|
print("disconnected")
|
|
if (self.connection_attempt_number > self.max_connection_attempts):
|
|
self.client.disconnect()
|
|
self.client.loop_stop()
|
|
self.connection_attempt_number=0 |