Fix publishing

This commit is contained in:
Asaril 2020-03-12 13:55:24 +01:00
parent ec7a7ded49
commit b8e964078a

View file

@ -1,10 +1,10 @@
import paho.mqtt.subscribe as mqtt import paho.mqtt.subscribe as sub
import json import json
BROKER = ('homeproxy', 1883) BROKER = ('homeproxy', 1883)
TOPIC_PREFIX = 'scalefix' TOPIC_PREFIX = 'scalefix'
TOPIC_RAW = TOPIC_PREFIX+'/raw/weight' TOPIC_RAW = TOPIC_PREFIX+'/raw/weight'
TOPIC_WEIGHT = TOPIC_PREFIX+'/weights' TOPIC_WEIGHTS = TOPIC_PREFIX+'/weights'
TOPIC_USERS = TOPIC_PREFIX+'/users' TOPIC_USERS = TOPIC_PREFIX+'/users'
_users={} _users={}
@ -13,9 +13,12 @@ def match_user(weight):
found_user = 'Gast' found_user = 'Gast'
last_dev = 20 last_dev = 20
for username, data in _users.items(): for username, data in _users.items():
if username == 'Gast':
continue
dev = abs(data['weight'] - weight) dev = abs(data['weight'] - weight)
if dev < 5 and dev < last_dev: if dev < 5 and dev < last_dev:
found_user = username found_user = username
last_dev = dev
return found_user return found_user
def handle_weight(client, userdata, message): def handle_weight(client, userdata, message):
@ -23,12 +26,12 @@ def handle_weight(client, userdata, message):
weight = data['weight'] weight = data['weight']
username = match_user(weight) username = match_user(weight)
print(f'new value for user "{username}": {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 = data.copy()
ext_data['user'] = username ext_data['user'] = username
client.publish(TOPIC_WEIGHTS, ext_data)
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))
def handle_user_last(client, userdata, message): def handle_user_last(client, userdata, message):
global _users global _users
@ -43,4 +46,4 @@ def dispatch(client, userdata, message):
elif message.topic.startswith(TOPIC_USERS) and message.topic.endswith(_SUFFIX_LAST): elif message.topic.startswith(TOPIC_USERS) and message.topic.endswith(_SUFFIX_LAST):
handle_user_last(client, userdata, message) handle_user_last(client, userdata, message)
mqtt.callback(dispatch, [TOPIC_RAW, f'{TOPIC_USERS}/+{_SUFFIX_LAST}'], hostname=BROKER[0], port=BROKER[1]) sub.callback(dispatch, [TOPIC_RAW, f'{TOPIC_USERS}/+{_SUFFIX_LAST}'], hostname=BROKER[0], port=BROKER[1])