scalefix/scalesrv.py

90 lines
2.7 KiB
Python
Raw Normal View History

2020-03-12 02:30:41 +01:00
import http.server
import socketserver
import urllib.parse
import urllib.request
2020-03-12 09:37:16 +01:00
import paho.mqtt.publish as mq
import time
import json
import struct
2020-03-12 02:30:41 +01:00
2020-03-12 09:37:16 +01:00
PORT = 18001
DATA_SRV_PATH = "/devicedataservice/dataservice"
2020-03-12 02:30:41 +01:00
2020-03-12 09:37:16 +01:00
BROKER = ('homeproxy', 1883)
TOPIC_PREFIX = 'scalefix/raw'
2020-03-12 02:30:41 +01:00
RESPONSES = {
0x24:"A00000000000000001000000000000000000000000000000bec650a1",
0x22:"A20000000000000000000000000000000000000000000000c9950d3f",
0x25:"A00000000000000001000000000000000000000000000000bec650a1",
0x28:"A5000000000000000100000000000000000000000000000056e5abd9",
0x21:"A10000000000000009c4914c0000000000000000000000001d095ec4",
0x29:""
}
2020-03-12 09:37:16 +01:00
_last_msg = ''
def do_publish(data):
global _last_msg
if data != _last_msg:
now = int(time.time())
bridge = data[2:14]
unk_id = data[14:39]
unk_val = data[30:38]
2020-03-12 13:54:26 +01:00
weight = int(data[38:42],16) / 100
2020-03-12 09:37:16 +01:00
bia = (
int(data[42:50],16),
int(data[42:46],16),
int(data[46:50],16)
)
msgs = [
(TOPIC_PREFIX+'/weight', json.dumps({'timestamp':now, 'weight':weight, 'bia':[bia[1],bia[2]]})),
(TOPIC_PREFIX+'/all', json.dumps({'timestamp':now, 'bridge':bridge, 'unknown_id':unk_id,
'unkown_value':unk_val, 'weight':weight, 'bia':[bia[1],bia[2]], 'bia_long':bia[0], 'raw':data}))
]
mq.multiple(msgs, hostname=BROKER[0], port=BROKER[1])
_last_msg = data
2020-03-12 02:30:41 +01:00
class Handler(http.server.SimpleHTTPRequestHandler):
def do_GET(self):
2020-03-12 09:37:16 +01:00
#print ('do_GET:%s'%self.path)
2020-03-12 02:30:41 +01:00
parts = urllib.parse.urlsplit(self.path)
if parts.path == DATA_SRV_PATH:
self.do_dataservice(parts)
def do_dataservice(self, urlparts):
params = urllib.parse.parse_qs(urlparts.query)
if 'data' not in params:
print ('got message without data: ' + urlparts.query)
self.send_error(400,'invalid message')
data_str = params['data'][0]
2020-03-12 09:37:16 +01:00
msg_type=int(data_str[0:2],16)
2020-03-12 02:30:41 +01:00
if msg_type not in RESPONSES:
print ('got unknown message: ' + data_str)
self.send_error(400,'unknown message')
response = RESPONSES[msg_type]
2020-03-12 09:37:16 +01:00
#print('handle message:%d'%msg_type)
if msg_type == 0x24:
do_publish(data_str)
2020-03-12 02:30:41 +01:00
self.send_response(http.server.HTTPStatus.OK)
self.send_header("Content-type", "text/html")
self.send_header("Content-Length", len(response))
self.end_headers()
2020-03-12 09:37:16 +01:00
if response:
self.wfile.write(response.encode('utf-8'))
2020-03-12 02:30:41 +01:00
with socketserver.TCPServer(("",PORT), Handler) as httpd:
print('started at port %d'%PORT)
httpd.serve_forever()