75 lines
2.0 KiB
Python
75 lines
2.0 KiB
Python
import paho.mqtt.client as mqtt
|
|
import logging
|
|
import datetime
|
|
from collections import deque
|
|
|
|
MQTT_HOST = "mqtt.sik.party"
|
|
|
|
TOPIC_TEMP = "sik/kiltahuone/kahvivaaka/temperature"
|
|
TOPIC_WEIGHT = "sik/kiltahuone/kahvivaaka/weight"
|
|
|
|
BREWING_DIFFERENTIAL = 60
|
|
# setting down the pan creates at least 800 g of weight
|
|
BREWING_DIFFERENTIAL_ERROR_MAX = 800
|
|
WEIGHT_DEQUE_LENGTH = 20
|
|
weight_deque = deque(maxlen=WEIGHT_DEQUE_LENGTH)
|
|
latest = {
|
|
'last_brew': datetime.datetime.now()
|
|
}
|
|
|
|
|
|
def on_connect(client, userdata, flags, rc):
|
|
logging.info('Subscribing to all topics on mqtt.sik.party.')
|
|
client.subscribe("#")
|
|
|
|
|
|
def on_message(client, userdata, msg):
|
|
if msg.topic == TOPIC_TEMP:
|
|
latest['temp'] = float(msg.payload.decode('utf-8'))
|
|
elif msg.topic == TOPIC_WEIGHT:
|
|
weight = float(msg.payload.decode('utf-8'))
|
|
latest['weight'] = weight
|
|
weight_deque.appendleft(weight)
|
|
|
|
|
|
def on_disconnect(client, userdata, rc):
|
|
if rc != 0:
|
|
print("Unexpected disconnection.")
|
|
else:
|
|
client.loop_stop(force=False)
|
|
print("Disconnected")
|
|
|
|
|
|
def get_latest():
|
|
if len(weight_deque) > 2:
|
|
first = weight_deque[0]
|
|
last = weight_deque[len(weight_deque) - 1]
|
|
diff = first - last # reverse order
|
|
|
|
if len(weight_deque) < WEIGHT_DEQUE_LENGTH:
|
|
brewing = False
|
|
else:
|
|
if BREWING_DIFFERENTIAL < diff < BREWING_DIFFERENTIAL_ERROR_MAX:
|
|
brewing = True
|
|
latest['last_brew'] = datetime.datetime.now()
|
|
else:
|
|
brewing = False
|
|
|
|
latest['brewing'] = brewing
|
|
return latest
|
|
|
|
|
|
client = mqtt.Client()
|
|
client.on_connect = on_connect
|
|
client.on_message = on_message
|
|
client.on_disconnect = on_disconnect
|
|
|
|
|
|
try:
|
|
logging.info('Connecting to MQTT at {}...'.format(MQTT_HOST))
|
|
client.connect_async(MQTT_HOST, 1883, 60)
|
|
logging.info('Connected successfully to MQTT.')
|
|
except Exception as ex:
|
|
logging.error(ex)
|
|
logging.error('Failed to connect to MQTT at {}'.format(MQTT_HOST))
|