#!/usr/bin/env python2

from time import time 

def readData():
	while True:
		data = f.read()
		if data != '':
			break
	return data

def readMessage(start):
	msg = start
	while True:
		before = time()
		data = readData()
		after = time()
		diff = after - before
		#print data.encode('hex'), '%f' % diff
		if diff > 0.005:
			return msg, data
		msg += data

def dump(msg):
	for i, c in enumerate(msg):
		print '%02X' % ord(c),
	print ''

#common messages observed on our bus which we wanted to ignore for the moment whilst we figure out things. probably polls?
common = [
	'1006c0',
	'11ec03c0000000006c',
	'11ec07c00000000070',
	'11f400b0',
	'11f410c0',
	'11feba',
	'21000fda',
	'251a00e9',
	'4b06fb',
	'4f000f09',
	'900641',
	'90070244',
	'910642',
	'91070245',
	]

with open('/dev/ttyUSB1', 'wb+') as f:
	# wait for a new message to start
	msg, start = readMessage('')
	while True:
		msg, start = readMessage(start)
		h = msg.encode('hex')
		if h.startswith('1007') or h.startswith('4b07'):
			print 'display:', h[0:2], h[4:6], h, msg[4:-1].replace('\x02', ' ')
		elif h.startswith('11edfa03e8'):
			print 'query:', h[10:12]
		elif h.startswith('251b02'):
			print 'reply:', h[6:8]
		elif h.startswith('251c1'):
			pass
		elif h not in common:
		#if h.startswith('11'):
			print h #dump(msg)
