Fix MQTT connection

This commit is contained in:
2025-12-29 15:10:27 +01:00
parent dd57019c99
commit 0a6081ee6e
4 changed files with 28 additions and 10 deletions

View File

@@ -7,11 +7,11 @@ COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
ENV PYTHONUNBUFFERED=1
ENV FLASK_APP=app.py
ENV FLASK_RUN_HOST=0.0.0.0
ENV FLASK_RUN_PORT=5000
EXPOSE 5000
CMD ["flask", "run"]
CMD ["python", "app.py"]

View File

@@ -1,3 +1,4 @@
import os
import uuid
from flask import Flask
@@ -8,21 +9,27 @@ client_id = "1"
app = Flask(__name__)
local_broker_address = os.environ.get("LOCAL_BROKER_ADDRESS", "127.0.0.1")
local_broker_port = int(os.environ.get("LOCAL_BROKER_PORT", 1883))
api_broker_address = os.environ.get("API_BROKER_ADDRESS", "127.0.0.1")
api_broker_port = int(os.environ.get("API_BROKER_PORT", 1883))
@app.route('/')
def hello_world():
return 'Hello World!'
if __name__ == '__main__':
local_broker = MQTTService(
"127.0.0.1",
1883,
local_broker_address,
local_broker_port,
username="pi-1",
password="hepl",
)
api_broker = MQTTService(
"192.168.15.120",
1883,
api_broker_address,
api_broker_port,
username="rpi",
password="hepl",
)

View File

@@ -11,6 +11,10 @@ services:
- mosquitto
environment:
- MONGO_URI=mongodb://mongo:27017/mydb
- LOCAL_BROKER_ADDRESS=customer-broker
- LOCAL_BROKER_PORT=1883
- API_BROKER_ADDRESS=192.168.15.120
- API_BROKER_PORT=1883
mongo:
image: mongo:latest

View File

@@ -5,19 +5,24 @@ from typing import Callable, Optional
import paho.mqtt.client as mqtt
class MQTTService:
client : mqtt.Client
def __init__(self, address: str, port: int, client_id: Optional[str] = None,
username: Optional[str] = None, password: Optional[str] = None,
ca_certs: Optional[str] = None):
ca_certs: Optional[str] = None, insecure : bool = False):
self.address = address
self.port = port
self.client = mqtt.Client(client_id=client_id)
if username and password:
self.client.username_pw_set(username, password)
if ca_certs:
self.client.tls_set(ca_certs=ca_certs)
else:
self.client.tls_set()
self.client.tls_insecure_set(True)
self.client.tls_insecure_set(insecure)
self._connected = False
self.client.on_connect = self._on_connect
self.client.on_disconnect = self._on_disconnect
@@ -37,16 +42,18 @@ class MQTTService:
def connect(self):
if not self._connected:
print(f"Connecting to {self.address}...")
self.client.connect(self.address, self.port)
self.client.loop_start()
timeout = 5
start = time.time()
while not self._connected and time.time() - start < timeout:
print(f"Connecting to {self.address}...")
time.sleep(0.1)
if not self._connected:
raise ConnectionError(f"Cannot connect to MQTT broker at {self.address}:{self.port}")
print(f"Successfully connected to {self.address}")
else :
print(f"Already connected to {self.address}...")
def disconnect(self):
if self._connected: