Files
web2.0-backend/coffee_scale/mqtt.py
T
2017-09-19 21:04:48 +03:00

90 lines
2.3 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_MIN = 60
# setting down the pan creates at least 800 g of weight
BREWING_DIFFERENTIAL_MAX = 180
WEIGHT_DEQUE_LENGTH = 20
weight_deque = deque(maxlen=WEIGHT_DEQUE_LENGTH)
latest = {
'last_brew': datetime.datetime.now()
}
def calc_averaged_weight():
if len(weight_deque) > 2:
half = []
for i in range(0, int(len(weight_deque) / 2)):
half.append(weight_deque[i])
return sum(half) / len(half)
else:
return 0
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'))
# avoid showing erroneous data from an empty scale
if weight > 50: # g
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_MIN < diff < BREWING_DIFFERENTIAL_MAX:
brewing = True
latest['last_brew'] = datetime.datetime.now()
else:
brewing = False
latest['brewing'] = brewing
latest['weight'] = calc_averaged_weight()
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))