import struct from scrc import calculate as calc_scrc def encode_to_7bit(word): ret = [0] while word > 0x7F: ret[-1] = (word & 0xFF) | 0x80 ret.append(word) word >>= 7 ret[-1] = word return ret def decode_7bit(data): fmt = '<%dB' % len(data) ret = 0 for n,word in enumerate(struct.unpack(fmt, data)): ret |= (word&0x7f) << (n*7) if not word & 0x80: return ret,n+1 raise ValueError('All bytes have 0x80 up') def format_41_command(count, session, cmd): ret = encode_to_7bit(session) ret.extend([cmd & 0xFF, 0x41, count & 0xFF]) return struct.pack('<%dB' % len(ret), *ret) def unpack_41_command(data): session,n = decode_7bit(data[:10]) cmd = ord(data[n+1]) cmd, fmt, count = struct.unpack_from('<3B', data, n) if fmt != 0x41: raise ValueError('not 0x41 encoded but %x' % fmt) return (session, cmd, count), n +3 def unpack_41_blob(data, blob_pos=0): typ, idx = struct.unpack_from('<2B', data, blob_pos) blob_pos += 2 if typ == 0: # int val,inc = decode_7bit(data[blob_pos:]) blob_pos += inc elif typ == 1: # 64 bit num [val] = struct.unpack_from('' % (self.cmd, self.sid)