-
Notifications
You must be signed in to change notification settings - Fork 5
/
app.py
executable file
·163 lines (137 loc) · 5.6 KB
/
app.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Body Composition Scale 2 (XMTZC05HM) Data to MQTT / Influxdb
# App to read weight measurements from Xiaomi Body Scales.
# Rootless Setup
# sudo apt-get install libcap2-bin
# sudo setcap 'cap_net_raw,cap_net_admin+eip' `readlink -f \`which python3\``
# sudo setcap 'cap_net_raw+ep' `readlink -f \`which hcitool\``
import sys
sys.path.append("..")
if sys.version_info[0] < 3:
raise Exception("Python 3 is required to run")
try:
import os
import signal
import subprocess
import asyncio
from bluepy import btle
from bluepy.btle import Scanner, BTLEDisconnectError, BTLEManagementError, DefaultDelegate
from datetime import datetime
import time
from conf import *
from lib import logger
from lib import mqtt
from lib.miscale2 import Miscale2Decoder
from lib.calcdata import CalcData
except Exception as e:
print(f"Import error: {str(e)} line {sys.exc_info()[-1].tb_lineno}, check requirements.txt")
sys.exit(1)
log = logger.Log('MI_SCALE2_APP', MI2_SHORTNAME, LOG_LEVEL)
def publishDeviceState(topicmode: str = 'Online', payload: dict = None):
mqtt_client = mqtt.client()
if mqtt_client and mqtt_client.ready:
if topicmode == 'Online':
mqtt_client.publish_simple(MQTT_AVAILABILITY_TOPIC, topicmode, True)
elif topicmode == 'Offline':
mqtt_client.publish_simple(MQTT_AVAILABILITY_TOPIC, topicmode, True)
else:
if payload:
mqtt_client.publish(topicmode, payload, True)
def handler(signum, frame):
publishDeviceState('Offline')
log.info("Xiaomi Mi Scale Service Application stopped.")
print('')
sys.exit(0)
class ScanProcessor():
def __init__(self):
log.debug("Init ScanProcessor")
def handleDiscovery(self, dev, isNewDev, isNewData):
# when this python script discovers a BLE broadcast packet, we can decode the data packet
# for each device in the list of devices
if dev.addr == MI2_MAC.lower() and isNewDev:
# ------------------------------------------
# decode data form the mi scale 2 device
# ------------------------------------------
log.debug("Device {}, New:{}, Newdata:{}".format(dev.addr, isNewDev, isNewData))
if isNewDev:
payload = {
'application': __name__,
'message': "new device",
'mac': dev.addr,
'error': False,
"timestamp": str(datetime.today().strftime(DATEFORMAT_MISCAN))
}
publishDeviceState(MQTT_PREFIX + '/info', payload)
if isNewData:
payload = {
'application': __name__,
'message': "new data",
'mac': dev.addr,
'error': False,
"timestamp": str(datetime.today().strftime(DATEFORMAT_MISCAN))
}
publishDeviceState(MQTT_PREFIX + '/info', payload)
mi2_decoder = Miscale2Decoder(dev)
mi_data = mi2_decoder.getData()
if mi_data:
log.debug("New data present, make calulations and publish...")
mCalc = CalcData(mi_data)
if mCalc.ready:
publishmode = {
"fulldata": True,
"scores": True,
"simpledata": True,
"influxdb": True
}
mCalc.publishdata(publishmode)
def main():
BluetoothFailCounter = 0
while True:
try:
scanner = btle.Scanner().withDelegate(ScanProcessor())
# create a list of unique devices that the scanner discovered during a 10-second scan
devices = scanner.scan(10)
time.sleep(TIME_INTERVAL)
except BTLEDisconnectError as e:
log.error("BTLE disconnected {}".format(e))
payload = {
'application': __name__,
'message': str(e),
'error': True,
"timestamp": str(datetime.today().strftime(DATEFORMAT_MISCAN))
}
publishDeviceState(MQTT_PREFIX + '/info', payload)
pass
except BTLEManagementError as e:
log.error("Bluetooth connection error:{}".format(e))
if BluetoothFailCounter >= 4:
publishDeviceState('Offline')
cmd = 'hciconfig ' + HCI_DEV + ' down'
log.info("shell command: {}".format(cmd))
ps = subprocess.Popen(cmd, shell=True)
time.sleep(1)
cmd = 'hciconfig hci' + HCI_DEV + ' up'
log.debug("shell command: {}".format(cmd))
ps = subprocess.Popen(cmd, shell=True)
time.sleep(30)
BluetoothFailCounter = 0
publishDeviceState('Online')
else:
BluetoothFailCounter += 1
except Exception as e:
payload = {
'application': __name__,
'message': str(e),
'error': True,
"timestamp": str(datetime.today().strftime(DATEFORMAT_MISCAN))
}
publishDeviceState(MQTT_PREFIX + '/info', payload)
log.error(f"Error while running the script: {str(e)}, line {sys.exc_info()[-1].tb_lineno}")
pass
if __name__ == "__main__":
log.info("Start Xiaomi Mi Scale Service Application")
signal.signal(signal.SIGINT, handler)
time.sleep(10)
publishDeviceState('Online')
main()