2020-03-12 13:55:24 +01:00
|
|
|
import paho.mqtt.subscribe as sub
|
2020-03-12 09:57:07 +01:00
|
|
|
import json
|
|
|
|
|
|
|
|
BROKER = ('homeproxy', 1883)
|
2020-03-12 12:55:54 +01:00
|
|
|
TOPIC_PREFIX = 'scalefix'
|
|
|
|
TOPIC_RAW = TOPIC_PREFIX+'/raw/weight'
|
2020-03-12 13:55:24 +01:00
|
|
|
TOPIC_WEIGHTS = TOPIC_PREFIX+'/weights'
|
2020-03-12 12:55:54 +01:00
|
|
|
TOPIC_USERS = TOPIC_PREFIX+'/users'
|
2020-03-12 09:57:07 +01:00
|
|
|
|
|
|
|
_users={}
|
2020-03-12 12:55:54 +01:00
|
|
|
_SUFFIX_LAST='/last'
|
|
|
|
def match_user(weight):
|
|
|
|
found_user = 'Gast'
|
|
|
|
last_dev = 20
|
|
|
|
for username, data in _users.items():
|
2020-03-12 13:55:24 +01:00
|
|
|
if username == 'Gast':
|
|
|
|
continue
|
2020-03-12 12:55:54 +01:00
|
|
|
dev = abs(data['weight'] - weight)
|
|
|
|
if dev < 5 and dev < last_dev:
|
|
|
|
found_user = username
|
2020-03-12 13:55:24 +01:00
|
|
|
last_dev = dev
|
2020-03-12 12:55:54 +01:00
|
|
|
return found_user
|
2020-03-12 09:57:07 +01:00
|
|
|
|
|
|
|
def handle_weight(client, userdata, message):
|
2020-03-12 12:55:54 +01:00
|
|
|
data = json.loads(message.payload)
|
|
|
|
weight = data['weight']
|
|
|
|
username = match_user(weight)
|
|
|
|
print(f'new value for user "{username}": {weight}')
|
|
|
|
ext_data = data.copy()
|
|
|
|
ext_data['user'] = username
|
|
|
|
|
2020-03-12 13:55:24 +01:00
|
|
|
client.publish(f'{TOPIC_USERS}/{username}/weight', message.payload)
|
|
|
|
client.publish(f'{TOPIC_USERS}/{username}{_SUFFIX_LAST}', message.payload, retain=True)
|
|
|
|
client.publish(TOPIC_WEIGHTS, json.dumps(ext_data))
|
2020-03-12 12:55:54 +01:00
|
|
|
|
|
|
|
def handle_user_last(client, userdata, message):
|
|
|
|
global _users
|
|
|
|
data = json.loads(message.payload)
|
|
|
|
username = message.topic[len(TOPIC_USERS)+1:-len(_SUFFIX_LAST)]
|
|
|
|
print(f'got last weight for user "{username}": {data}')
|
|
|
|
_users[username] = data
|
2020-03-12 09:57:07 +01:00
|
|
|
|
|
|
|
def dispatch(client, userdata, message):
|
|
|
|
if message.topic == TOPIC_RAW:
|
|
|
|
handle_weight(client, userdata, message)
|
2020-03-12 12:55:54 +01:00
|
|
|
elif message.topic.startswith(TOPIC_USERS) and message.topic.endswith(_SUFFIX_LAST):
|
|
|
|
handle_user_last(client, userdata, message)
|
2020-03-12 09:57:07 +01:00
|
|
|
|
2020-03-12 13:55:24 +01:00
|
|
|
sub.callback(dispatch, [TOPIC_RAW, f'{TOPIC_USERS}/+{_SUFFIX_LAST}'], hostname=BROKER[0], port=BROKER[1])
|