From 3e6a83e945b89bc7e9dee487587accbfc87090e0 Mon Sep 17 00:00:00 2001 From: Asaril Date: Thu, 12 Mar 2020 12:55:54 +0100 Subject: [PATCH] Add clustering --- cluster.py | 43 ++++++++++++++++++++++++++++++++----------- 1 file changed, 32 insertions(+), 11 deletions(-) diff --git a/cluster.py b/cluster.py index f47c15a..2192044 100644 --- a/cluster.py +++ b/cluster.py @@ -2,24 +2,45 @@ import paho.mqtt.subscribe as mqtt import json BROKER = ('homeproxy', 1883) -TOPIC_RAW = 'scalefix/raw/weight' -TOPIC_USERS = 'scalefix/users' - +TOPIC_PREFIX = 'scalefix' +TOPIC_RAW = TOPIC_PREFIX+'/raw/weight' +TOPIC_WEIGHT = TOPIC_PREFIX+'/weights' +TOPIC_USERS = TOPIC_PREFIX+'/users' _users={} +_SUFFIX_LAST='/last' +def match_user(weight): + found_user = 'Gast' + last_dev = 20 + for username, data in _users.items(): + dev = abs(data['weight'] - weight) + if dev < 5 and dev < last_dev: + found_user = username + return found_user def handle_weight(client, userdata, message): - pass - -def handle_user(client, userdata, message): - pass + data = json.loads(message.payload) + weight = data['weight'] + username = match_user(weight) + print(f'new value for user "{username}": {weight}') + client.publish(f'{TOPIC_USERS}/{username}/weight', data) + client.publish(f'{TOPIC_USERS}/{username}{_SUFFIX_LAST}', data, retain=True) + ext_data = data.copy() + ext_data['user'] = username + client.publish(TOPIC_WEIGHTS, ext_data) -TOPIC_LAST = TOPIC_USERS+'/last' +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 + def dispatch(client, userdata, message): if message.topic == TOPIC_RAW: handle_weight(client, userdata, message) - elif message.topic.startswith(TOPIC_LAST): - handle_user(client, userdata, message) + elif message.topic.startswith(TOPIC_USERS) and message.topic.endswith(_SUFFIX_LAST): + handle_user_last(client, userdata, message) -mq.callback(dispatch, [TOPIC_RAW, TOPIC_LAST+'/+'], hostname=BROKER[0], port=BROKER[1]) +mqtt.callback(dispatch, [TOPIC_RAW, f'{TOPIC_USERS}/+{_SUFFIX_LAST}'], hostname=BROKER[0], port=BROKER[1])