-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTED1001mon.py
439 lines (366 loc) · 14.3 KB
/
TED1001mon.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
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
#!/usr/bin/env python
# This is a Python module for The Energy Detective: A low-cost whole
# house energy monitoring system. For more information on TED, see
# http://theenergydetective.com
#
# This module was not created by Energy, Inc. nor is it supported by
# them in any way. It was created using information from two sources:
# David Satterfield's TED module for Misterhouse, and my own reverse
# engineering from examining the serial traffic between TED Footprints
# and my RDU.
#
# I have only tested this module with the model 1001 RDU, with
# firmware version 9.01U. The USB port is uses the very common FTDI
# USB-to-serial chip, so the RDU will show up as a serial device on
# Windows, Mac OS, or Linux.
#
#
# Copyright (c) 2008 Micah Dowty <[email protected]>
#
# NOT copyright Jake Mohin, 2015. <[email protected]>
#
# I edited Micah Dowty's code to upload to a few web services.
# She did all the hard work. I removed the SVN repository
# link because it hasn't been update for a few years. This code is freely available
# at my github. The below disclaimers still apply.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
import MySQLdb
import serial
import time
from datetime import datetime
import binascii
import sys
import struct
import urllib
import urllib2
import base64
import os
#print-to-terminal web upload messages or data sent to web
WEB_DEBUG=0
DATA_DEBUG=0
# Special bytes
PKT_REQUEST = "\xAA"
ESCAPE = "\x10"
PKT_BEGIN = "\x04"
PKT_END = "\x03"
# Web upload parameters; UPDATE_INT should be min 1 second, Upload freq (which is UPDATE_INT*DATA_PTS) should be min 60 seconds
DATA_PTS = 60
UPDATE_INT = 1 #seconds
#Bidgely
HOST = "http://api.bidgely.com"
API_URL = "v1/users/YOUR_API_KEY/homes/1/gateways/7/upload"
#PlotWatt
METER_ID="YOUR_METER_ID"
API_KEY="YOUR_API_KEY"
URL="http://plotwatt.com/api/v2/push_readings"
#WattVision
_WV_ELEC_URL_ = "http://www.wattvision.com/api/v0.2/elec/"
_WV_API_ID_ = 'YOUR API ID'
_WV_API_KEY_ = 'YOUR API KEY'
_SENSOR_ID_ = 'YOUR SENSOR ID'
#Phant online sensor database
server="http://data.sparkfun.com/input/"
# server='http://localhost:8080/input/' for those of you who install locally ;-)
publicKey='YOUR PUBLIC KEY'
privateKey='YOUR PRIVATE KEY'
#CSV file (currently linux format)
CSV_PATH = '/opt/powerData/'
CSV_PREFIX = 'powerDat'
# Mysql parameters
DBHOST = "localhost"
DBUSER = "username"
DBPASS = "password"
class ProtocolError(Exception):
pass
class TED(object):
def __init__(self, device):
self.port = serial.Serial(device, 19200, timeout=0)
self.escape_flag = False
# None indicates that the packet buffer is invalid:
# we are not receiving any valid packet at the moment.
self.packet_buffer = None
def poll(self):
"""Request a packet from the RDU, and flush the operating
system's receive buffer. Any complete packets we've
received will be decoded. Returns a list of Packet
instances.
Raises ProtocolError if we see anything from the RDU that
we don't expect.
"""
# Request a packet. The RDU will ignore this request if no
# data is available, and there doesn't seem to be any harm in
# sending the request more frequently than once per second.
self.port.write(PKT_REQUEST)
return self.decode(self.port.read(4096))
def decode(self, raw):
"""Decode some raw data from the RDU. Updates internal
state, and returns a list of any valid Packet() instances
we were able to extract from the raw data stream.
"""
packets = []
# The raw data from the RDU is framed and escaped. The byte
# 0x10 is the escape byte: It takes on different meanings,
# depending on the byte that follows it. These are the
# escape sequence I know about:
#
# 10 10: Encodes a literal 0x10 byte.
# 10 04: Beginning of packet
# 10 03: End of packet
#
# This code illustrates the most straightforward way to
# decode the packets. It's best in a low-level language like C
# or Assembly. In Python we'd get better performance by using
# string operations like split() or replace()- but that would
# make this code much harder to understand.
for byte in raw:
if self.escape_flag:
self.escape_flag = False
if byte == ESCAPE:
if self.packet_buffer is not None:
self.packet_buffer += ESCAPE
elif byte == PKT_BEGIN:
self.packet_buffer = ''
elif byte == PKT_END:
if self.packet_buffer is not None:
packets.append(Packet(self.packet_buffer))
self.packet_buffer = None
else:
raise ProtocolError("Unknown escape byte %r" % byte)
elif byte == ESCAPE:
self.escape_flag = True
elif self.packet_buffer is not None:
self.packet_buffer += byte
return packets
class Packet(object):
"""Decoder for TED packets. We use a lookup table to find individual
fields in the packet, convert them using the 'struct' module,
and scale them. The results are available in the 'fields'
dictionary, or as attributes of this object.
"""
# We only support one packet length. Any other is a protocol error.
_protocol_len = 278
_protocol_table = (
# TODO: Fill in the rest of this table.
#
# It needs verification on my firmware version, but so far the
# offsets in David Satterfield's code match mine. Since his
# code does not handle packet framing, his offsets are 2 bytes
# higher than mine. These offsets start counting at the
# beginning of the packet body. Packet start and packet end
# codes are omitted.
# Offset, name, fmt, scale
(82, 'kw_rate', "<H", 0.0001),
(247, 'KwNowDsp', "<H", 0.01),
(249, 'DlrNowDsp', "<H", 0.01),
(251, 'VrmsNowDsp', "<H", 0.1),
(253, 'DlrMtdDsp', "<H", 0.1),
(255, 'DlrMthProjDsp', "<H", 0.1),
(257, 'KwhMthProjDsp', "<H", 1),
(132, 'LoVrmsTdy', "<H", 0.1),
(136, 'HiVrmsTdy', "<H", 0.1),
(140, 'LoVrmsMtd', "<H", 0.1),
(143, 'HiVrmsMtd', "<H", 0.1),
(146, 'KwPeakTdy', "<H", 0.01),
(148, 'DlrPeakTdy', "<H", 0.01),
(150, 'KwPeakMtd', "<H", 0.01),
(152, 'DlrPeakMtd', "<H", 0.01),
(154, 'DlrTdySum', "<L", 0.00000167),
(158, 'KWhrTdySum', "<L", 0.0000167),
(166, 'KWhrMtdSum', "<L", 0.0000167),
(170, 'DlrMtdSum', "<L", 0.00000167),
)
def __init__(self, data):
self.data = data
self.fields = {}
if len(data) != self._protocol_len:
raise ProtocolError("Unsupported packet length %r" % len(data))
for offset, name, fmt, scale in self._protocol_table:
size = struct.calcsize(fmt)
field = data[offset:offset+size]
value = struct.unpack(fmt, field)[0] * scale
setattr(self, name, value)
self.fields[name] = value
def do_upload_bidgely(xml_data):
if(DATA_DEBUG):
print xml_data
request_body_encoded = xml_data.encode('utf-8')
request = urllib2.Request( url=(HOST+'/'+API_URL), data=xml_data , headers={'Content-Type': 'application/xml'})
try:
response = urllib2.urlopen( request )
except urllib2.URLError, e:
print "bidgely error:"
print e.reason
# return response
def make_xml_bidgely(kW_data):
xmlHead="""<upload version="1.0">
<meters>
<meter id=\"11:22:33:44:55:66" model="TED1001" type="0" description="TED1001 whole home device">
<streams>
<stream id="InstantaneousDemand" unit="kW" description="Real-Time Demand">"""
xmlDline="<data time=\"%(time)s\" value=\"%(kW)s\" />"
xmlTail="""</stream>
</streams>
<attributes>
</attributes>
<messages>
</messages>
</meter>
</meters>
<attributes>
<attribute id="LocalIP">192.168.1.101</attribute>
</attributes>
<messages>
</messages>
</upload>"""
xmlFin=xmlHead
for i in range(len(kW_data)):
tmpDat={'time':kW_data[i][0],'kW':kW_data[i][1]}
xmlFin = xmlFin + (xmlDline % tmpDat)
xmlFin = str(xmlFin + xmlTail)
return xmlFin
def writeToCSV(data):
st = datetime.fromtimestamp(time.time()).strftime('%m-%d-%y')
fnam=CSV_PATH + CSV_PREFIX + st + ".csv"
if not os.path.exists(fnam):
nf=open(fnam,'w')
nf.write("UTC Epoch, kW, Volts\n")
nf.close()
f = open(fnam,"a")
for i in range(len(data)):
f.write("%s, %s ,%s\n" % (data[i][0],data[i][1],data[i][2]))
f.close()
def do_upload_plotWatt(kW_data):
dUp="%(Mid)s, %(kW)s, %(time)s, "
fin=" "
for i in range(len(kW_data)):
tmpD={'Mid':METER_ID,'time':kW_data[i][0],'kW':kW_data[i][1]}
fin = fin + (dUp % tmpD)
fin=fin[1:-2]
if(DATA_DEBUG):
print fin
base64string = base64.encodestring('%s:%s' % (API_KEY, ''))[:-1]
authheader = "Basic %s" % base64string
req = urllib2.Request(URL)
req.add_header("Authorization", authheader)
try:
response = urllib2.urlopen( req,fin )
except urllib2.URLError, e:
print "plotwatt error:"
print e.reason
#print "PlotWatt: "
#print response.getcode()
#print response.info()
def doUploadWattvision(watts):
str_fmt = '{{"sensor_id": "{0}", "api_id": "{1}", "api_key": "{2}", "watts": {3} }}'
request_body = str_fmt.format(str(_SENSOR_ID_),str(_WV_API_ID_),str(_WV_API_KEY_),watts)
if (DATA_DEBUG):
print request_body
request_body_encoded = request_body.encode('utf-8')
request = urllib2.Request( url=_WV_ELEC_URL_, data=request_body_encoded )
try:
response = urllib2.urlopen( request )
except urllib2.URLError, e:
print "wattvision error:"
print e.reason
return e
# if(WEB_DEBUG):
# print "Wattvision: "
# print response.getcode()
# print response.info()
return response
def doUploadPhant(d1,d2):
fields = ["kw","volts"] # Your feed's data fields
data = {}
data[fields[0]] = d1
data[fields[1]] = d2
params = urllib.urlencode(data)
request = urllib2.Request( url=server+publicKey, data=params , headers=
{'Content-Type': 'application/x-www-form-urlencoded',
'Connection': 'close',
'Content-Length': len(params),
'Phant-Private-Key': privateKey
})
try:
response = urllib2.urlopen( request )
except urllib2.URLError, e:
print e.reason
# if(WEB_DEBUG):
# print "Phant: "
# print response.getcode()
# print response.info()
def printPacket(packet):
print
print "%d byte packet: %r" % (
len(packet.data), binascii.b2a_hex(packet.data))
print
for name, value in packet.fields.items():
print "%s = %s" % (name, value)
def mySQLsave(dbname,dbtable,fields,fieldspec,datArr):
#configure MySQL connection for database logging
db = MySQLdb.connect(host=DBHOST, user=DBUSER, passwd=DBPASS, db=dbname)
CURSOR = db.cursor()
sqlString='INSERT INTO '+ dbtable + fields+' VALUES '
#date field NEEDS TO BE FIRST!
#CHANGED to every 90 seconds update so as to not pollute the database :-)
for i in range(len(datArr)):
ts='("' + str(datetime.utcfromtimestamp(datArr[i][0])) + '",'
for j in range(1,len(datArr[i])):
ts=ts+fieldspec[j-1]%datArr[i][j]+','
sqlString = sqlString+ts[0:-1]+'),'
sqlString=sqlString[0:-1]
# print sqlString
try:
CURSOR.execute(sqlString)
db.commit()
except MySQLdb.Error as e:
print("MySql Error %d: %s" % (e.args[0], e.args[1]))
def main():
#instantiate serial packet grabber
t = TED(sys.argv[1])
#configure array and counter for periodic web upload
count=0
upCount=0
powerArr=[[0 for x in xrange(3)] for x in xrange(DATA_PTS)]
while True:
for packet in t.poll():
# printPacket(packet)
if len(packet.fields.items()[16]):
if (count)>DATA_PTS-1:
count=0
print "Caught a count out of bounds"
powerArr[count][0]=int(round(time.time()))
powerArr[count][1]=packet.fields.items()[16][1]
powerArr[count][2]=packet.fields.items()[3][1]
count+=1
doUploadWattvision(packet.fields.items()[16][1]*1000)
# doUploadPhant(packet.fields.items()[16][1],packet.fields.items()[3][1])
if (count*UPDATE_INT)%DATA_PTS == 0:
upCount+=1
if count==0:
print "cought a 0=count%freq error"
continue
do_upload_plotWatt(powerArr)
do_upload_bidgely(make_xml_bidgely(powerArr))
mySQLsave("sensor_data","power_data","(ts,kW,volts)",['%d','%d'],powerArr)
print "upload #: %s " % upCount
count=0
time.sleep(UPDATE_INT)
if __name__ == "__main__":
main()