Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Update library to work with Python 3 #3

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 33 additions & 23 deletions ib/victron/mk2.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ def __get__(self, inst, objtype=None):
return val

def D(d, data):
print d, ' '.join(['%02X' % ord(x) for x in data])
print(d, ' '.join(['%02X' % x for x in data]))

states = {
(0, 0): 'down',
Expand Down Expand Up @@ -90,7 +90,7 @@ def start(self):
self.port.write(self.makeCommand('V'))
sleep(0.5)
self.port.reset_input_buffer()
for i in xrange(0, 3):
for i in range(0, 3):
try:
self.communicate('A', '\x01' + chr(self.address))
except (ValueError, struct_error):
Expand Down Expand Up @@ -206,22 +206,32 @@ def load_offset(self):

def makeCommand(self, command, data=''):
length = len(command) + len(data) + 1
buf = [chr(length), chr(0xFF)]
buf.extend(command)
buf.extend(data)
checksum = 256 - sum([ord(x) for x in buf])%256
buf.append(chr(checksum))
return ''.join(buf)
buf = [length, 0xFF]
buf.extend(map(ord, command))
buf.extend(map(ord, data))
checksum = 256 - sum(buf) % 256
buf.append(checksum)
return bytes(buf)

def readResult(self):
l = ord(self.port.read(1))
length_byte = self.port.read(1)

if not len(length_byte):
raise ValueError("No response length read from device")

length = ord(length_byte)

# Read l+1 bytes, +1 for the checksum
data = self.port.read(l+1)
data = self.port.read(length + 1)

if len(data) != (length + 1):
raise ValueError("Response from device did not match expected length")

full_message = length_byte + data

# Check checksum
if sum([ord(x) for x in (data + chr(l))])%256 != 0:
D('<e', chr(l) + data)
if sum([x for x in full_message])%256 != 0:
D('<e', full_message)
raise ValueError("Checksum failed")

return data
Expand All @@ -232,7 +242,7 @@ def communicate(self, cmd, params=''):
self.port.write(v)
while True:
data = self.readResult()
if data[0] != '\xFF' or data[1] != 'V':
if data[0] != 0xFF or data[1:2] != b'V':
# It's not a version frame
break
return data
Expand All @@ -246,8 +256,8 @@ def scale(self, factor):
def dc_info(self):
data = self.communicate('F', '\x00')
ubat = unpack('<H', data[6:8])[0]
ibat = unpack('<i', data[8:11] + ('\0' if data[10] < '\x80' else '\xff'))[0]
icharge = unpack('<i', data[11:14] + ('\0' if data[13] < '\x80' else '\xff'))[0]
ibat = unpack('<i', data[8:11] + bytes([0x0] if data[10] < 0x80 else [0xff]))[0]
icharge = unpack('<i', data[11:14] + bytes([0x0] if data[13] < 0x80 else [0xff]))[0]
return DataObject({
'ubat': (ubat+self.ubat_offset) * self.scale(self.ubat_scale),
'ibat': (ibat+self.ibat_offset) * self.scale(self.ibat_scale),
Expand Down Expand Up @@ -276,8 +286,8 @@ def master_multi_led_info(self):

def led_info(self):
data = self.communicate('L')
status = ord(data[2])
flash = ord(data[3])
status = data[2]
flash = data[3]
return DataObject({
'mains': bool(status & 1),
'absorption': bool(status & 2),
Expand Down Expand Up @@ -325,13 +335,13 @@ def version(self):
data = self.port.read(9)

# Check length and marker
assert data[0] == '\x07'
assert data[1] == '\xFF'
assert data[2] == 'V'
assert data[0] == 0x07
assert data[1] == 0xFF
assert data[2:3] == b'V'

# Check checksum
if sum([ord(x) for x in data])%256 != 0:
D('<e', chr(l) + data)
if sum([x for x in data])%256 != 0:
D('<e', data)
raise ValueError("Checksum failed")

return unpack('<I', data[3:7])[0]
Expand All @@ -346,7 +356,7 @@ def flush(self):
self.port.reset_input_buffer()
break

if data[0] != '\xFF' or data[1] != 'V':
if data[0] != 0xFF or data[1:2] != b'V':
D('discarded non-version frame', data)

class MK2Thread(Thread, MK2):
Expand Down
2 changes: 1 addition & 1 deletion ib/victron/scripts/getlimit.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@
def main():
port = Serial(options.port, options.baudrate, timeout=options.timeout)
mk2 = MK2(port).start()
print mk2.master_multi_led_info()
print(mk2.master_multi_led_info())

port.close()
2 changes: 1 addition & 1 deletion ib/victron/scripts/getstate.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ def main():
mk2 = MK2(port).start()

#mk2.set_state(3)
print mk2.get_state()
print(mk2.get_state())

port.close()
20 changes: 10 additions & 10 deletions ib/victron/scripts/monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,16 +13,16 @@ def main():
ac_info = mk2.ac_info()
dc_info = mk2.dc_info()
state = mk2.get_state()
print 'Time ', datetime.now().strftime('%Y-%m-%d %H:%M')
print '--------------------------------'
print 'Inverter mode ', state.capitalize()
print 'Mains Voltage ', ac_info['umains'], 'V'
print 'AC output Voltage', ac_info['uinv'], 'V'
print 'Battery Voltage ', dc_info['ubat'], 'V'
print 'Discharge current', dc_info['ibat'], 'A'
print 'DC Power draw ', dc_info['ibat'] * dc_info['ubat'], 'W'
print 'AC Power draw ', ac_info['uinv'] * ac_info['iinv'], 'VA'
print ''
print('Time ', datetime.now().strftime('%Y-%m-%d %H:%M'))
print('--------------------------------')
print('Inverter mode ', state.capitalize())
print('Mains Voltage ', ac_info['umains'], 'V')
print('AC output Voltage', ac_info['uinv'], 'V')
print('Battery Voltage ', dc_info['ubat'], 'V')
print('Discharge current', dc_info['ibat'], 'A')
print('DC Power draw ', dc_info['ibat'] * dc_info['ubat'], 'W')
print('AC Power draw ', ac_info['uinv'] * ac_info['iinv'], 'VA')
print('')
sleep(5)
except KeyboardInterrupt:
pass
Expand Down