-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain.py
248 lines (217 loc) · 9.15 KB
/
main.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
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
import asyncio
import base64
import logging
from collections import deque
from datetime import datetime, timedelta
from threading import Thread
import aiosqlite
import paho.mqtt.client as mqtt
import serial
import sqlite3
from colorlog import ColoredFormatter
USB_PORT = "/dev/ttyUSB1"
DB_PATH = 'sqlite.db'
MQTT_HOST = '192.168.80.170'
MQTT_USERNAME = ''
MQTT_PASSWORD = ''
MQTT_PORT = 1883
MQTT_TIMEOUT = 60
FEND = '7E7E'
fmt = '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
colorfmt = "%(log_color)s{}%(reset)s".format(fmt)
datefmt = '%Y-%m-%d %H:%M:%S'
logging.basicConfig(level=logging.DEBUG)
logging.getLogger().handlers[0].setFormatter(ColoredFormatter(
colorfmt,
datefmt=datefmt,
reset=True,
log_colors={
'DEBUG': 'cyan',
'INFO': 'green',
'WARNING': 'yellow',
'ERROR': 'red',
'CRITICAL': 'red',
}
))
_LOGGER = logging.getLogger(__name__)
class DataHandler(object):
def __init__(self):
self.meter_id = None
self.effect = deque(maxlen=30)
self.avg_hourly_effect = 0
self.current_hour = datetime.now().replace(minute=0, second=0, microsecond=0)
self.last_effect_time = datetime.now()
self.mqtt_client = None
self.connected = False
self.prev_meter_value = None
self.db_path = DB_PATH
self._last_mqtt = datetime.now() - timedelta(hours=10)
self.loop = asyncio.new_event_loop()
def f(loop):
asyncio.set_event_loop(loop)
loop.run_forever()
t = Thread(target=f, args=(self.loop,))
t.start()
if MQTT_HOST:
self.mqtt_client = mqtt.Client()
self.mqtt_client.username_pw_set(MQTT_USERNAME, MQTT_PASSWORD)
def _on_connect(client, _, flags, return_code):
self.connected = True
self.mqtt_client.on_connect = _on_connect
self.mqtt_client.connect_async(MQTT_HOST, MQTT_PORT, MQTT_TIMEOUT)
self.mqtt_client.loop_start()
def add_data(self, txt_buf):
_LOGGER.info("meter id: %s", self.meter_id)
txt_buf = txt_buf[34:]
decoded_data = self.decode(txt_buf)
effect = decoded_data.get('Effect')
if effect:
self.effect.append(effect)
date = "%02d%02d%02d_%02d%02d%02d" % (decoded_data['second'], decoded_data['minute'], decoded_data['hour'],
decoded_data['day'], decoded_data['month'], decoded_data['year'])
try:
ts = datetime.strptime(date, '%S%M%H_%d%m%Y')
except ValueError:
_LOGGER.error(txt_buf, exc_info=True)
return
if self.current_hour.hour < ts.hour or self.current_hour.date() < ts.date():
self.current_hour = ts.replace(minute=0, second=0, microsecond=0)
self.avg_hourly_effect = 0
self.avg_hourly_effect += effect * (ts - self.last_effect_time).total_seconds()
self.last_effect_time = ts
meter_id = decoded_data.get('Meter-ID')
if meter_id:
self.meter_id = meter_id
_LOGGER.info("Decoded data %s:", decoded_data)
self.loop.call_soon_threadsafe(asyncio.async, self.send_to_mqtt(decoded_data))
self.loop.call_soon_threadsafe(asyncio.async, self.send_to_db(decoded_data))
async def send_to_db(self, data):
if not self.db_path:
return
effect = data.get('Effect')
if not effect:
return
date = "%02d%02d%02d_%02d%02d%02d" % (data['second'], data['minute'], data['hour'],
data['day'], data['month'], data['year'])
async with aiosqlite.connect(self.db_path) as db:
cur = await db.execute('''INSERT INTO HANdata(date, effect) VALUES(?, ?)''', (date, effect))
await cur.close()
await db.commit()
async def send_to_mqtt(self, data):
if not self.connected or not self.meter_id:
return
val = data.get('Effect')
if val:
prefix = '{}/{}/{}'.format(str(self.meter_id), 'effect', 'watt')
self.mqtt_client.publish(prefix, val, qos=1, retain=True)
now = datetime.now()
if 'Cumulative_hourly_active_import_energy' in data:
val = data.get('Cumulative_hourly_active_import_energy')
prefix = '{}/{}/{}'.format(str(self.meter_id),
'Cumulative_hourly_active_import_energy', 'wh')
self.mqtt_client.publish(prefix, val, qos=1, retain=True)
if self.prev_meter_value:
prefix = '{}/{}/{}'.format(str(self.meter_id),
'Diff_cumulative_hourly_active_import_energy', 'wh')
self.mqtt_client.publish(prefix, val - self.prev_meter_value, qos=1, retain=True)
self.prev_meter_value = val
if 'Cumulative_hourly_reactive_import_energy' in data:
val = data.get('Cumulative_hourly_reactive_import_energy')
prefix = '{}/{}/{}'.format(str(self.meter_id),
'Cumulative_hourly_reactive_import_energy', 'wh')
self.mqtt_client.publish(prefix, val, qos=1, retain=True)
if now - self._last_mqtt < timedelta(minutes=1):
return
self._last_mqtt = now
prefix = '{}/{}/{}'.format(str(self.meter_id), 'effect_avg', 'watt')
val = round(sum(self.effect) / len(self.effect), 1)
self.mqtt_client.publish(prefix, val, qos=1, retain=True)
prefix = '{}/{}/{}'.format(str(self.meter_id), 'hourly_cons', 'ws')
val = self.avg_hourly_effect
self.mqtt_client.publish(prefix, val, qos=1, retain=True)
_LOGGER.info("Watt: %s", val)
@staticmethod
def decode_date(date_str):
return {
'year': int(date_str[4:8], 16),
'month': int(date_str[8:10], 16),
'day': int(date_str[10:12], 16),
'hour': int(date_str[14:16], 16),
'minute': int(date_str[16:18], 16),
'second': int(date_str[18:20], 16),
}
def decode(self, txt_buf):
try:
res = self.decode_date(txt_buf)
txt_buf = txt_buf[28:]
if txt_buf[:2] != '02':
_LOGGER.error("Unknown data %s", txt_buf[:2])
return {}
pkt_type = txt_buf[2:4]
txt_buf = txt_buf[4:]
if pkt_type == '01':
res['Effect'] = int(txt_buf[2:10], 16)
elif pkt_type in ['09', '0E']:
res['Version identifier'] = base64.b16decode(txt_buf[4:18]).decode("utf-8")
txt_buf = txt_buf[18:]
res['Meter-ID'] = base64.b16decode(txt_buf[4:36]).decode("utf-8")
txt_buf = txt_buf[36:]
res['Meter type'] = base64.b16decode(txt_buf[4:20]).decode("utf-8")
txt_buf = txt_buf[20:]
res['Effect'] = int(txt_buf[2:10], 16)
if pkt_type == '0E':
txt_buf = txt_buf[10:]
txt_buf = txt_buf[78:]
res['Cumulative_hourly_active_import_energy'] = int(txt_buf[2:10], 16)
txt_buf = txt_buf[10:]
res['Cumulative_hourly_active_export_energy'] = int(txt_buf[2:10], 16)
txt_buf = txt_buf[10:]
res['Cumulative_hourly_reactive_import_energy'] = int(txt_buf[2:10], 16)
txt_buf = txt_buf[10:]
res['Cumulative_hourly_reactive_export_energy'] = int(txt_buf[2:10], 16)
else:
_LOGGER.warning("Unknown type %s", txt_buf[2:4])
return {}
except ValueError:
return {}
return res
def create_db():
"""Make the database"""
loop = asyncio.get_event_loop()
async def _execute():
async with aiosqlite.connect(DB_PATH) as db:
try:
cur = await db.execute('''CREATE TABLE "HANdata" (
`id` INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT UNIQUE,
'date' STRING,
'effect' REAL
)''')
await cur.close()
except sqlite3.OperationalError:
pass
loop.run_until_complete(_execute())
def run():
txt_buf = ''
try:
ser = serial.Serial(USB_PORT, baudrate=2400, timeout=0, parity=serial.PARITY_NONE)
except:
_LOGGER.error("Failed to connect: ", exc_info=True)
return
data_handler = DataHandler()
while True:
if ser.inWaiting():
txt_buf += "".join("{0:02x}".format(x).upper() for x in bytearray(ser.read(200)))
if len(txt_buf) < 6 or txt_buf[:2] != '7E':
continue
pos = txt_buf[2:].find(FEND)
if pos < 0:
continue
current_buf = txt_buf[:pos + 2]
_LOGGER.debug(current_buf)
txt_buf = txt_buf[pos + 4:]
_LOGGER.debug(txt_buf)
data_handler.add_data(current_buf)
if __name__ == '__main__':
if DB_PATH:
create_db()
run()