add app user management allauth
This commit is contained in:
58
wallet_api/mqtt_service.py
Normal file
58
wallet_api/mqtt_service.py
Normal file
@@ -0,0 +1,58 @@
|
||||
import paho.mqtt.client as mqtt
|
||||
import json
|
||||
import time
|
||||
from dotenv import dotenv_values
|
||||
|
||||
class MosquittoDynamicSecurity:
|
||||
def __init__(self):
|
||||
config = dotenv_values(".env")
|
||||
self.broker_url = config["MQTT_HOST"]
|
||||
self.broker_port = config["MQTT_PORT"]
|
||||
self.broker_keepalive = config["MQTT_KEEPALIVE"]
|
||||
self.user = config["MQTT_USER"]
|
||||
self.password = config["MQTT_PASSWORD"]
|
||||
self.topic = config["MQTT_DS_TOPIC"]
|
||||
self.resp_topic = config["MQTT_DS_RESP_TOPIC"]
|
||||
self.response = None
|
||||
self.client = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, protocol=mqtt.MQTTv5)
|
||||
self.client.on_connect = self.on_connect
|
||||
self.client.on_disconnect = self.on_disconnect
|
||||
self.client.on_message = self.on_message
|
||||
|
||||
def on_disconnect(self, mqtt_client, obj, flags, rc, properties):
|
||||
print('Disconnesso da Mosquitto con codice:', rc)
|
||||
|
||||
def on_connect(self, client, userdata, flags, rc, properties):
|
||||
if rc == 0:
|
||||
print("Connesso a Mosquitto con codice:", rc)
|
||||
# Sottoscriviti al topic di risposta
|
||||
client.subscribe(self.resp_topic)
|
||||
else:
|
||||
print("Errore di connessione a Mosquitto con codice:", rc)
|
||||
|
||||
def on_message(self, client, userdata, msg):
|
||||
|
||||
print('Response:', msg.payload.decode())
|
||||
# Memorizza la risposta
|
||||
self.response = msg.payload.decode()
|
||||
|
||||
def send_command(self, command):
|
||||
# Pubblica il comando sul topic di controllo
|
||||
self.client.username_pw_set(self.user, self.password)
|
||||
self.client.connect(self.broker_url, int(self.broker_port), int(self.broker_keepalive))
|
||||
self.client.loop_start()
|
||||
time.sleep(0.2)
|
||||
self.client.publish(self.topic, json.dumps(command))
|
||||
|
||||
# Attendi la risposta (timeout di 5 secondi)
|
||||
start_time = time.time()
|
||||
while self.response is None and time.time() - start_time < 5:
|
||||
time.sleep(0.2)
|
||||
|
||||
self.client.loop_stop()
|
||||
self.client.disconnect()
|
||||
|
||||
if self.response:
|
||||
return json.loads(self.response)
|
||||
else:
|
||||
return {"error": "Timeout: nessuna risposta da Mosquitto"}
|
||||
Reference in New Issue
Block a user