59 lines
1.5 KiB
Python
59 lines
1.5 KiB
Python
import paho.mqtt.client as mqtt
|
|
import logging
|
|
import datetime
|
|
from collections import deque
|
|
|
|
from django.conf import settings
|
|
|
|
HOST = settings.MQTT_SETTINGS['HOST']
|
|
PORT = settings.MQTT_SETTINGS['PORT']
|
|
TOPICS = settings.MQTT_SETTINGS['TOPICS']
|
|
latest = {}
|
|
|
|
|
|
def on_connect(client, userdata, flags, rc):
|
|
logging.info('Connected successfully to MQTT.')
|
|
logging.info('Subscribing to all topics on {}.'.format(HOST))
|
|
client.subscribe('sik/kiltahuone/kahvivaaka/#')
|
|
|
|
|
|
def update_latest(msg):
|
|
payload = msg.payload.decode('utf-8')
|
|
if msg.topic == TOPICS['WEIGHT']:
|
|
weight = float(payload)
|
|
latest['weight'] = weight
|
|
elif msg.topic == TOPICS['CUPS']:
|
|
cups = float(payload)
|
|
latest['cups'] = cups
|
|
elif msg.topic == TOPICS['BREWING']:
|
|
brewing = bool(int(payload))
|
|
latest['brewing'] = brewing
|
|
elif msg.topic == TOPICS['BREW_TIME']:
|
|
brew_time = datetime.datetime.fromtimestamp(float(payload))
|
|
latest['brew_time'] = brew_time
|
|
|
|
|
|
def on_message(client, userdata, msg):
|
|
try:
|
|
update_latest(msg)
|
|
except Exception as ex:
|
|
logging.exception('Failed to parse MQTT payload.')
|
|
|
|
|
|
def on_disconnect(client, userdata, rc):
|
|
if rc != 0:
|
|
logging.warning('MQTT unexpectedly disconnected.')
|
|
else:
|
|
client.loop_stop(force=False)
|
|
logging.warning('MQTT disconnected.')
|
|
|
|
|
|
def get_latest():
|
|
return latest
|
|
|
|
|
|
client = mqtt.Client()
|
|
client.on_connect = on_connect
|
|
client.on_message = on_message
|
|
client.on_disconnect = on_disconnect
|