generated from bbostock/Switchbot_Py_Meter
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmeters.py
208 lines (185 loc) · 7.5 KB
/
meters.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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
#!/usr/bin/python3
from __future__ import print_function
import argparse
import binascii
import os
import sys
import time
import json
import datetime
import threading
from tinydb import TinyDB, Query
import time
from bluepy import btle
import flask
from flask import Response, request
# Database Configuration
# Storage location of the database file
databaseWritePath = "switchbot_data.json"
# TinyDb
database = TinyDB(databaseWritePath)
# Flask configuration
app = flask.Flask(__name__)
app.config["DEBUG"] = True
# API Configuration
API_HOST="192.168.1.233"
API_PORT=5000
# SwitchBot Meter Configuration
METER_ROOMS = ['Bedroom']
METER_MACS = ['e8:fe:50:d1:75:dd']
debug_level = 1
if os.getenv('C', '1') == '0':
ANSI_RED = ''
ANSI_GREEN = ''
ANSI_YELLOW = ''
ANSI_CYAN = ''
ANSI_WHITE = ''
ANSI_OFF = ''
else:
ANSI_CSI = "\033["
ANSI_RED = ANSI_CSI + '31m'
ANSI_GREEN = ANSI_CSI + '32m'
ANSI_YELLOW = ANSI_CSI + '33m'
ANSI_CYAN = ANSI_CSI + '36m'
ANSI_WHITE = ANSI_CSI + '37m'
ANSI_OFF = ANSI_CSI + '0m'
class MeterReading:
def __init__(self, time, temperature, humidity, battery):
self.time = time
self.temperature = temperature
self.humidity = humidity
self.battery = battery
# Responsible for scanning Bluetooth devices for SwitchBot Meter
class ScanProcessor():
def handleDiscovery(self, dev, isNewDev, isNewData):
try:
if dev.addr in METER_MACS:
i = 0
room = METER_ROOMS[METER_MACS.index(dev.addr)]
if debug_level == 1:
print ('\nRoom: %s Device: %s (%s), %d dBm %s. ' %(ANSI_WHITE + room + ANSI_OFF,ANSI_WHITE + dev.addr + ANSI_OFF,dev.addrType,dev.rssi,('' if dev.connectable else '(not connectable)')), end='')
for (sdid, desc, value) in dev.getScanData():
i=i+1
if debug_level == 1:
print( str(i) + ': ' + str(sdid) + ', '+ desc + ', ' + value)
#Model T (WOSensorTH) example Service Data: 000d54006400962c
if desc == '16b Service Data':
if value.startswith('000d'):
byte2 = int(value[8:10],16)
battery = (byte2 & 127)
byte3 = int(value[10:12],16)
byte4 = int(value[12:14],16)
byte5 = int(value[14:16],16)
tempc = float(byte4-128)+float(byte3 / 10.0)
humidity = byte5
self._publish(room, tempc, humidity, battery)
else:
if debug_level == 1:
print(value.len())
if not dev.scanData:
print ('(no data)')
print
except:
print("handleDiscovery: Oops!",sys.exc_info()[0],"occurred.")
def _publish(self, room, tempc, humidity, battery):
try:
now = datetime.datetime.now()
timeNow = now.strftime("%Y-%m-%d %H:%M:%S")
# Get the readings table
readingsTable = database.table('readings')
# Add the reading to the local database
readingsTable.insert({
'time': timeNow,
'room': room,
'temperature': tempc,
'humidity': humidity,
'battery': battery
})
except:
print("_publish: Oops!",sys.exc_info()[0],"occurred.")
# Runs in the background, getting data from SwitchBot Meters and then storing it in local memory
class ScanBackgroundWorker(object):
def __init__(self, interval=30):
self.interval = interval
thread = threading.Thread(target=self.run, args=())
thread.daemon = True # Daemonize thread
thread.start() # Start the execution
def run(self):
while True:
# Clear previously taken readings before scan
database.drop_table('readings')
# Get the latest readings from the SwitchBot Meter
scanner = btle.Scanner().withDelegate(ScanProcessor())
scanner.scan()
# Wait until the next interval to scan for the latest devices
time.sleep(self.interval)
# Shows all meter reading in local memory
@app.route('/meters', methods=['GET'])
def allMeters():
latestReadings = database.table('readings', cache_size=0)
latestReadingsJson = json.dumps(latestReadings.all())
return Response(latestReadingsJson, mimetype='application/json')
@app.route('/meters/<meter_name>', methods=['GET'])
def getMeterByRoom(meter_name):
# Get the room name
meterRoom = meter_name
# Get the readings table from the database
latestReadings = database.table('readings', cache_size=0)
# Query the table for readings matching the room name
readings = Query()
matchingReadingsByRoom = latestReadings.search(readings.room == meterRoom)
# Check if the query returned a result
if (len(matchingReadingsByRoom) > 0):
# Select the first item on the list
firstMatchingDevice = matchingReadingsByRoom[0]
# Dump the results into a JSON string
latestReadingsJson = json.dumps(firstMatchingDevice)
# Return the result of the query in the HTTP Response
return Response(latestReadingsJson, mimetype='application/json')
else:
return Response(json.dumps([]), status=204, mimetype='application/json')
@app.route('/humidity/<meter_name>', methods=['GET'])
def getHumidityByRoom(meter_name):
# Get the room name
meterRoom = meter_name
# Get the readings table from the database
latestReadings = database.table('readings', cache_size=0)
# Query the table for readings matching the room name
readings = Query()
matchingReadingsByRoom = latestReadings.search(readings.room == meterRoom)
# Check if the query returned a result
if (len(matchingReadingsByRoom) > 0):
# Select the first item on the list
firstMatchingDevice = matchingReadingsByRoom[0]
# Get the humidity value from the document
humidity = firstMatchingDevice["humidity"]
print('Humidity in ' + str(meterRoom) + " " + str(humidity))
# Return the result of the query in the HTTP Response
return Response(str(humidity))
else:
return Response(status=204)
@app.route('/temperature/<meter_name>', methods=['GET'])
def getTempByRoom(meter_name):
# Get the room name
meterRoom = meter_name
# Get the readings table from the database
latestReadings = database.table('readings', cache_size=0)
# Query the table for readings matching the room name
readings = Query()
matchingReadingsByRoom = latestReadings.search(readings.room == meterRoom)
# Check if the query returned a result
if (len(matchingReadingsByRoom) > 0):
# Select the first item on the list
firstMatchingDevice = matchingReadingsByRoom[0]
# Get the temperature value from the document
temperature = firstMatchingDevice["temperature"]
print('temperature in ' + str(meterRoom) + " " + str(temperature))
# Return the result of the query in the HTTP Response
return Response(str(temperature))
else:
return Response(status=204)
def main():
ScanBackgroundWorker()
app.run(host=API_HOST, port=API_PORT, debug=True)
if __name__ == "__main__":
main()