summaryrefslogtreecommitdiff
path: root/mqtt_client/main.py
blob: 109ca49dbe822cee948c6cbd3f77d6a9197f1c01 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
import paho.mqtt.client as mqtt
from paho.mqtt.enums import MQTTProtocolVersion
import json
from time import sleep
from database import engine
from models import Base
import os

print("Creating ORM SQL Tables..")
Base.metadata.create_all(bind=engine)
print("Tables created successfully.")


def on_connect(client, userdata, flags, reason_code, properties):
    print(f"Conectado: {reason_code}")
    # Me inscrevo em todos os tópicos sobre clima
    client.subscribe("weather/#")

# Simplesmente imprime a mensagem como texto.
def on_message(client, userdata, msg):
    payload = json.loads(msg.payload)
    print(msg.topic)
    print(f"Value: {payload['value']}")
    print(f"Unit: {payload['unit']}")
    print(f"Timestamp: {payload['timestamp']}")

try:
    user_name = os.environ["MQTT_CLIENT_USER"]
    user_pass = os.environ["MQTT_CLIENT_PASSWORD"]
except KeyError:
    print("credentials not supplied in environment variables. Going unauthenticated...")
    user_name = None
    user_pass = None

mqttc = mqtt.Client(mqtt.CallbackAPIVersion.VERSION2, protocol=MQTTProtocolVersion.MQTTv5)
mqttc.on_connect = on_connect
mqttc.on_message = on_message
mqttc.username_pw_set(user_name, user_pass)

connected = False

while(not connected):
    try:
        mqttc.connect("mosquitto", 1883, 60, '', 0, True)
        connected = True
    except ConnectionRefusedError:
        print("Failed to connect. Retrying...")
        sleep(5)

mqttc.loop_forever()