def __init__(self, the_set, rule): BinStruct.__init__(self, the_set, rule) if not self.is_group(): raise ValueError("not a group") self.size = len(the_set) self.orders = {} for x in the_set: self.orders[x] = self.find_order(x) self.generators = [ x for x in self.the_set if self.orders[x] == self.size ]
def test_unpack(): for test_input in test_inputs: # Prepare the input and the expected result (fields, field_names, values, format) = split_test_input(test_input) buffer = bytearray(struct.pack(format, *values)) ReturnType = namedtuple(test_input['name'], field_names) expected_value = ReturnType(*values) # Create a new object meas_data = BinStruct(test_input['name'], test_input['endian'], fields) # Unpack a buffer into a namedtuple unpacked_data = meas_data.unpack(buffer) assert(unpacked_data == expected_value)
def loop(ser): '''Print data received over serial connection `ser` in a loop.''' iter = 0 buffer = [] raw_data = BinStruct('MeasData', '<', [ ('current_millis', 'L'), ('current_micros', 'L'), ('leftAnalog', 'H'), ('rightAnalog', 'H'), ('leftDigital', '?'), ('rightDigital', '?'), ('led_state', '?'), ]) while 1: iter += 1 print('\n### %s\n### Iteration #%i\n### %s' % ('-'*70, iter, '-'*70)) n_incoming_bytes = ser.in_waiting if n_incoming_bytes > 0: incoming_bytes = ser.read(n_incoming_bytes) buffer += incoming_bytes print(hexdump('Received %i bytes: ' % n_incoming_bytes, incoming_bytes)) while len(buffer) >= raw_data.size: print(hexdump('Internal buffer: ', buffer)) bits = buffer[0:raw_data.size] buffer = buffer[raw_data.size:] print(hexdump('Decoding: ', bits)) measdata = raw_data.unpack(bits) print('Decoded measurement data:\n%s' % format_measdata(measdata)) print(hexdump('Internal buffer: ', buffer)) if 0 < len(buffer) < raw_data.size: print('ERROR: Buffer smaller than one data packet; dropped') buffer = [] else: print('Receive buffer empty') print('Going to sleep for %0.3fs...' % sleep_duration) time.sleep(sleep_duration) print('...woke up')