Python ustruct.unpack() Examples
The following are 30
code examples of ustruct.unpack().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
ustruct
, or try the search function
.
Example #1
Source File: seesaw.py From Adafruit_CircuitPython_seesaw with MIT License | 6 votes |
def moisture_read(self): """Read the value of the moisture sensor""" buf = bytearray(2) self.read(_TOUCH_BASE, _TOUCH_CHANNEL_OFFSET, buf, 0.005) ret = struct.unpack(">H", buf)[0] time.sleep(0.001) # retry if reading was bad count = 0 while ret > 4095: self.read(_TOUCH_BASE, _TOUCH_CHANNEL_OFFSET, buf, 0.005) ret = struct.unpack(">H", buf)[0] time.sleep(0.001) count += 1 if count > 3: raise RuntimeError("Could not get a valid moisture reading.") return ret
Example #2
Source File: AM2320.py From OctoPrint-Enclosure with GNU General Public License v3.0 | 6 votes |
def getTemp(bus): for _ in range(3): try: bus.write_byte(0x5C, 0x00) except: pass bus.write_i2c_block_data(0x5C, 0x03, [0x02, 2]) time.sleep(0.001) result = bytearray(bus.read_i2c_block_data(0x5C, 0x00, 6)) if result[0] != 0x3 or result[1] != 2: raise AM2320ReadError("Command does not match returned data") temp = struct.unpack(">H", result[2:-2])[0] crc1 = struct.unpack("<H", bytes(result[-2:]))[0] crc2 = _crc16(result[0:-2]) if crc1 != crc2: raise AM2320ReadError("CRC Mismatch") if temp >= 32768: temp = 32768 - temp return (temp / 10.0)
Example #3
Source File: adafruit_bme680.py From Adafruit_CircuitPython_BME680 with MIT License | 6 votes |
def _read_calibration(self): """Read & save the calibration coefficients""" coeff = self._read(_BME680_BME680_COEFF_ADDR1, 25) coeff += self._read(_BME680_BME680_COEFF_ADDR2, 16) coeff = list(struct.unpack("<hbBHhbBhhbbHhhBBBHbbbBbHhbb", bytes(coeff[1:39]))) # print("\n\n",coeff) coeff = [float(i) for i in coeff] self._temp_calibration = [coeff[x] for x in [23, 0, 1]] self._pressure_calibration = [ coeff[x] for x in [3, 4, 5, 7, 8, 10, 9, 12, 13, 14] ] self._humidity_calibration = [coeff[x] for x in [17, 16, 18, 19, 20, 21, 22]] self._gas_calibration = [coeff[x] for x in [25, 24, 26]] # flip around H1 & H2 self._humidity_calibration[1] *= 16 self._humidity_calibration[1] += self._humidity_calibration[0] % 16 self._humidity_calibration[0] /= 16 self._heat_range = (self._read_byte(0x02) & 0x30) / 16 self._heat_val = self._read_byte(0x00) self._sw_err = (self._read_byte(0x04) & 0xF0) / 16
Example #4
Source File: AM2320.py From OctoPrint-Enclosure with GNU General Public License v3.0 | 6 votes |
def getHumi(bus): for _ in range(3): try: bus.write_byte(0x5C, 0x00) except: pass bus.write_i2c_block_data(0x5C, 0x03, [0x00, 2]) time.sleep(0.001) result = bytearray(bus.read_i2c_block_data(0x5C, 0x00, 6)) if result[0] != 0x3 or result[1] != 2: raise AM2320ReadError("Command does not match returned data") humi = struct.unpack(">H", result[2:-2])[0] crc1 = struct.unpack("<H", bytes(result[-2:]))[0] crc2 = _crc16(result[0:-2]) if crc1 != crc2: raise AM2320ReadError("CRC Mismatch") return (humi / 10.0)
Example #5
Source File: l2cap.py From uble with MIT License | 6 votes |
def from_buffer(data): """ Parse the signaling channel data. The signaling channel is a L2CAP packet with channel id 0x0001 (L2CAP CID_SCH) or 0x0005 (L2CAP_CID_LE_SCH) 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 ----------------------------------------------------------------- | code | cid | length | ----------------------------------------------------------------- References can be found here: * https://www.bluetooth.org/en-us/specification/adopted-specifications ** Core specification 4.1 ** [vol 3] Part A (Section 4) - Signaling Packet Formats """ code, cid, _ = ustruct.unpack( L2CAP_SCH.struct_format, data[:L2CAP_SCH.struct_size] ) data = data[L2CAP_SCH.struct_size:] return L2CAP_SCH(code, cid, data)
Example #6
Source File: event.py From uble with MIT License | 6 votes |
def from_buffer(data): """ Parse HCI event data References can be found here: * https://www.bluetooth.org/en-us/specification/adopted-specifications - Core specification 4.1 ** [vol 2] Part E (Section 5) - HCI Data Formats ** [vol 2] Part E (Section 5.4) - Exchange of HCI-specific information ** [vol 2] Part E (Section 7.7) - Events ** [vol 2] Part E (Section 7.7.65) - Le Meta Event All integer values are stored in "little-endian" order. """ evtcode, _ = ustruct.unpack( HCI_EVENT.struct_format, data[:HCI_EVENT._struct_size] ) data = data[HCI_EVENT._struct_size:] return HCI_EVENT(evtcode, data=data)
Example #7
Source File: smp.py From uble with MIT License | 6 votes |
def from_buffer(data): """ SMP code is the first octet of the PDU 0 1 2 3 4 5 6 7 ----------------- | code | ----------------- References can be found here: * https://www.bluetooth.org/en-us/specification/adopted-specifications ** Core specification 4.1 ** [vol 3] Part H (Section 3.3) - Command Format """ code = ustruct.unpack(SMP.struct_format, data[:SMP.struct_size])[0] data = data[SMP.struct_size:] return SMP(code, data)
Example #8
Source File: am2320.py From MicroPython-ESP8266-DHT-Nokia-5110 with MIT License | 6 votes |
def measure(self): buf = self.buf address = self.address # wake sensor try: self.i2c.writeto(address, b'') except OSError: pass # read 4 registers starting at offset 0x00 self.i2c.writeto(address, b'\x03\x00\x04') # wait at least 1.5ms time.sleep_ms(2) # read data self.i2c.readfrom_mem_into(address, 0, buf) # debug print print(ustruct.unpack('BBBBBBBB', buf)) crc = ustruct.unpack('<H', bytearray(buf[-2:]))[0] if (crc != self.crc16(buf[:-2])): raise Exception("checksum error")
Example #9
Source File: adafruit_fingerprint.py From Adafruit_CircuitPython_Fingerprint with MIT License | 6 votes |
def finger_fast_search(self): """Asks the sensor to search for a matching fingerprint template to the last model generated. Stores the location and confidence in self.finger_id and self.confidence. Returns the packet error code or OK success""" # high speed search of slot #1 starting at page 0x0000 and page #0x00A3 # self._send_packet([_HISPEEDSEARCH, 0x01, 0x00, 0x00, 0x00, 0xA3]) # or page #0x03E9 to accommodate modules with up to 1000 capacity # self._send_packet([_HISPEEDSEARCH, 0x01, 0x00, 0x00, 0x03, 0xE9]) # or base the page on module's capacity self.read_sysparam() capacity = self.library_size self._send_packet( [_HISPEEDSEARCH, 0x01, 0x00, 0x00, capacity >> 8, capacity & 0xFF] ) r = self._get_packet(16) self.finger_id, self.confidence = struct.unpack(">HH", bytes(r[1:5])) # print(r) return r[0] ##################################################
Example #10
Source File: blynklib_mp.py From lib-python with MIT License | 6 votes |
def parse_response(self, rsp_data, msg_buffer): msg_args = [] try: msg_type, msg_id, h_data = struct.unpack('!BHH', rsp_data[:self.MSG_HEAD_LEN]) except Exception as p_err: raise BlynkError('Message parse error: {}'.format(p_err)) if msg_id == 0: raise BlynkError('invalid msg_id == 0') elif h_data >= msg_buffer: raise BlynkError('Command too long. Length = {}'.format(h_data)) elif msg_type in (self.MSG_RSP, self.MSG_PING): pass elif msg_type in (self.MSG_HW, self.MSG_BRIDGE, self.MSG_INTERNAL, self.MSG_REDIRECT): msg_body = rsp_data[self.MSG_HEAD_LEN: self.MSG_HEAD_LEN + h_data] msg_args = [itm.decode('utf-8') for itm in msg_body.split(b'\0')] else: raise BlynkError("Unknown message type: '{}'".format(msg_type)) return msg_type, msg_id, h_data, msg_args
Example #11
Source File: lis3dh.py From tinypico-micropython with MIT License | 6 votes |
def acceleration(self): """The x, y, z acceleration values returned in a 3-tuple and are in m / s ^ 2.""" divider = 1 accel_range = self.range if accel_range == RANGE_16_G: divider = 1365 elif accel_range == RANGE_8_G: divider = 4096 elif accel_range == RANGE_4_G: divider = 8190 elif accel_range == RANGE_2_G: divider = 16380 x, y, z = struct.unpack('<hhh', self._read_register(_REG_OUT_X_L | 0x80, 6)) # convert from Gs to m / s ^ 2 and adjust for the range x = (x / divider) * STANDARD_GRAVITY y = (y / divider) * STANDARD_GRAVITY z = (z / divider) * STANDARD_GRAVITY return AccelerationTuple(x, y, z)
Example #12
Source File: adafruit_bme280.py From Adafruit_CircuitPython_BME280 with MIT License | 6 votes |
def _read_coefficients(self): """Read & save the calibration coefficients""" coeff = self._read_register(_BME280_REGISTER_DIG_T1, 24) coeff = list(struct.unpack("<HhhHhhhhhhhh", bytes(coeff))) coeff = [float(i) for i in coeff] self._temp_calib = coeff[:3] self._pressure_calib = coeff[3:] self._humidity_calib = [0] * 6 self._humidity_calib[0] = self._read_byte(_BME280_REGISTER_DIG_H1) coeff = self._read_register(_BME280_REGISTER_DIG_H2, 7) coeff = list(struct.unpack("<hBbBbb", bytes(coeff))) self._humidity_calib[1] = float(coeff[0]) self._humidity_calib[2] = float(coeff[1]) self._humidity_calib[3] = float((coeff[2] << 4) | (coeff[3] & 0xF)) self._humidity_calib[4] = float((coeff[4] << 4) | (coeff[3] >> 4)) self._humidity_calib[5] = float(coeff[5])
Example #13
Source File: vl53l0x.py From uPySensors with Apache License 2.0 | 5 votes |
def _registers(self, register, values=None, struct='B'): if values is None: size = ustruct.calcsize(struct) data = self.i2c.readfrom_mem(self.address, register, size) values = ustruct.unpack(struct, data) return values data = ustruct.pack(struct, *values) self.i2c.writeto_mem(self.address, register, data)
Example #14
Source File: seesaw.py From Adafruit_CircuitPython_seesaw with MIT License | 5 votes |
def get_temp(self): """Read the temperature""" buf = bytearray(4) self.read(_STATUS_BASE, _STATUS_TEMP, buf, 0.005) buf[0] = buf[0] & 0x3F ret = struct.unpack(">I", buf)[0] return 0.00001525878 * ret
Example #15
Source File: l2cap.py From uble with MIT License | 5 votes |
def from_buffer(data): """ Parse L2CAP packet 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7 ----------------------------------------------------------------- | length | channel id | ----------------------------------------------------------------- L2CAP is packet-based but follows a communication model based on channels. A channel represents a data flow between L2CAP entities in remote devices. Channels may be connection-oriented or connectionless. Fixed channels other than the L2CAP connectionless channel (CID 0x0002) and the two L2CAP signaling channels (CIDs 0x0001 and 0x0005) are considered connection-oriented. All L2CAP layer packet fields shall use Little Endian byte order with the exception of the information payload field. The endian-ness of higher layer protocols encapsulated within L2CAP information payload is protocol-specific References can be found here: * https://www.bluetooth.org/en-us/specification/adopted-specifications ** Core specification 4.1 ** [vol 3] Part A (Section 3) - Data Packet Format """ _, cid = ustruct.unpack( L2CAP.struct_format, data[:L2CAP.struct_size] ) data = data[L2CAP.struct_size:] return L2CAP(cid, data)
Example #16
Source File: seesaw.py From Adafruit_CircuitPython_seesaw with MIT License | 5 votes |
def analog_read(self, pin): """Read the value of an analog pin by number""" buf = bytearray(2) if pin not in self.pin_mapping.analog_pins: raise ValueError("Invalid ADC pin") self.read( _ADC_BASE, _ADC_CHANNEL_OFFSET + self.pin_mapping.analog_pins.index(pin), buf, ) ret = struct.unpack(">H", buf)[0] time.sleep(0.001) return ret
Example #17
Source File: bme680.py From uPySensors with Apache License 2.0 | 5 votes |
def _load_calibration(self): # read calibration data # < little-endian # H unsigned short # h signed short self._T1 = unp('<H', self._read(BME680_REG_DIG_T1, 2))[0] self._T2 = unp('<h', self._read(BME680_REG_DIG_T2, 2))[0] self._T3 = unp('<b', self._read(BME680_REG_DIG_T3, 1))[0] self._P1 = unp('<H', self._read(BME680_REG_DIG_P1, 2))[0] self._P2 = unp('<h', self._read(BME680_REG_DIG_P2, 2))[0] self._P3 = unp('<b', self._read(BME680_REG_DIG_P3, 1))[0] self._P4 = unp('<h', self._read(BME680_REG_DIG_P4, 2))[0] self._P5 = unp('<h', self._read(BME680_REG_DIG_P5, 2))[0] self._P6 = unp('<h', self._read(BME680_REG_DIG_P6, 2))[0] self._P7 = unp('<b', self._read(BME680_REG_DIG_P7, 2))[0] self._P8 = unp('<h', self._read(BME680_REG_DIG_P8, 2))[0] self._P9 = unp('<h', self._read(BME680_REG_DIG_P9, 2))[0] self._P10 = unp('<b', self._read(BME680_REG_DIG_P10, 1))[0] self._H1 = ((unp('<b', self._read(BME680_REG_DIG_H1_MSB, 1))[0] << 4) | (unp('<b', self._read(BME680_REG_DIG_H1_LSB, 1))[0] & 0x0F)) self._H2 = ((unp('<b', self._read(BME680_REG_DIG_H2_MSB, 1))[0] << 4) | (unp('<b', self._read(BME680_REG_DIG_H2_LSB, 1))[0] & 0x0F)) self._H3 = unp('<b', self._read(BME680_REG_DIG_H3, 1))[0] self._H4 = unp('<b', self._read(BME680_REG_DIG_H4, 1))[0] self._H5 = unp('<b', self._read(BME680_REG_DIG_H5, 1))[0] self._H6 = unp('<b', self._read(BME680_REG_DIG_H6, 1))[0] self._H7 = unp('<b', self._read(BME680_REG_DIG_H7, 1))[0] self._G1 = unp('<b', self._read(BME680_REG_DIG_G1, 1))[0] self._G2 = unp('<h', self._read(BME680_REG_DIG_G2, 2))[0] self._G3 = unp('<b', self._read(BME680_REG_DIG_G3, 1))[0] self._heat_range = (unp('<b', self._read(0x02, 1))[0] & 0x30) / 16 self._heat_val = unp('<b', self._read(0x00, 1))[0] self._sw_err = (unp('<b', self._read(0x04, 1))[0] & 0xF0) / 16
Example #18
Source File: lvgl_img_png.py From MaixPy_scripts with MIT License | 5 votes |
def get_png_info(decoder, src, header): # Only handle variable image types if lv.img.src_get_type(src) != lv.img.SRC.VARIABLE: return lv.RES.INV png_header = bytes(lv.img_dsc_t.cast(src).data.__dereference__(24)) if png_header.startswith(b'\211PNG\r\n\032\n'): if png_header[12:16] == b'IHDR': start = 16 # Maybe this is for an older PNG version. else: start = 8 try: width, height = struct.unpack(">LL", png_header[start:start+8]) except struct.error: return lv.RES.INV else: return lv.RES.INV header.always_zero = 0 header.w = width header.h = height header.cf = lv.img.CF.TRUE_COLOR_ALPHA return lv.RES.OK # Convert color formats
Example #19
Source File: bme680.py From uPySensors with Apache License 2.0 | 5 votes |
def chip_id(self): ''' Returns Chip ID ''' try: chip_id = unp('<b',self._read(const(0xD0), 1))[0] except OSError: raise MPUException(self._I2Cerror) if chip_id != self._chip_id: raise ValueError('Bad chip ID ({0}!={1}) retrieved: MPU communication failure'.format(chip_id, self._chip_id)) return chip_id
Example #20
Source File: pca9685.py From 1ZLAB_Face_Track_Robot with GNU General Public License v3.0 | 5 votes |
def pwm(self, index, on=None, off=None): if on is None or off is None: data = self.i2c.readfrom_mem(self.address, 0x06 + 4 * index, 4) return ustruct.unpack('<HH', data) data = ustruct.pack('<HH', on, off) self.i2c.writeto_mem(self.address, 0x06 + 4 * index, data)
Example #21
Source File: mpu6050.py From py-mpu6050 with GNU General Public License v3.0 | 5 votes |
def read_sensors(self): self.bus.readfrom_mem_into(self.address, MPU6050_RA_ACCEL_XOUT_H, self.sensors) data = unpack('>hhhhhhh', self.sensors) # apply calibration values return [data[i] + self.calibration[i] for i in range(7)]
Example #22
Source File: mpu6050.py From py-mpu6050 with GNU General Public License v3.0 | 5 votes |
def read_word2(self, reg): self.bus.readfrom_mem_into(self.address, reg, self.wordbuf) return unpack('>h', self.wordbuf)[0]
Example #23
Source File: mpu6050.py From py-mpu6050 with GNU General Public License v3.0 | 5 votes |
def read_word(self, reg): self.bus.readfrom_mem_into(self.address, reg, self.wordbuf) return unpack('>H', self.wordbuf)[0]
Example #24
Source File: adafruit_bmp280.py From Adafruit_CircuitPython_BMP280 with MIT License | 5 votes |
def _read_coefficients(self): """Read & save the calibration coefficients""" coeff = self._read_register(_REGISTER_DIG_T1, 24) coeff = list(struct.unpack("<HhhHhhhhhhhh", bytes(coeff))) coeff = [float(i) for i in coeff] # The temp_calib lines up with DIG_T# registers. self._temp_calib = coeff[:3] self._pressure_calib = coeff[3:] # print("%d %d %d" % (self._temp_calib[0], self._temp_calib[1], self._temp_calib[2])) # print("%d %d %d" % (self._pressure_calib[0], self._pressure_calib[1], # self._pressure_calib[2])) # print("%d %d %d" % (self._pressure_calib[3], self._pressure_calib[4], # self._pressure_calib[5])) # print("%d %d %d" % (self._pressure_calib[6], self._pressure_calib[7], # self._pressure_calib[8]))
Example #25
Source File: att.py From uble with MIT License | 5 votes |
def from_buffer(data): """ Attribute opcode is the first octet of the PDU 0 1 2 3 4 5 6 7 ----------------- | att opcode | ----------------- | a |b|c| ----------------- a - method b - command flag c - authentication signature flag References can be found here: * https://www.bluetooth.org/en-us/specification/adopted-specifications ** Core specification 4.1 ** [vol 3] Part F (Section 3.3) - Attribute PDU """ opcode = ustruct.unpack(ATT.struct_format, data[:ATT.struct_size])[0] # att = uctypes.struct( # uctypes.addressof(data[:ATT.struct_size]), # ATT_STRUCT, # uctypes.LITTLE_ENDIAN # ) data = data[ATT.struct_size:] return ATT(opcode, data)
Example #26
Source File: pca9685.py From openmv-projects with MIT License | 5 votes |
def pwm(self, index, on=None, off=None): if on is None or off is None: data = self.i2c.readfrom_mem(self.address, 0x06 + 4 * index, 4) return ustruct.unpack('<HH', data) data = ustruct.pack('<HH', on, off) self.i2c.writeto_mem(self.address, 0x06 + 4 * index, data)
Example #27
Source File: time.py From microdot with MIT License | 5 votes |
def _c_tm_to_tuple(tm): t = ustruct.unpack("@iiiiiiiii", tm) return _struct_time(t[5] + 1900, t[4] + 1, t[3], t[2], t[1], t[0], (t[6] - 1) % 7, t[7] + 1, t[8])
Example #28
Source File: adafruit_fingerprint.py From Adafruit_CircuitPython_Fingerprint with MIT License | 5 votes |
def _get_packet(self, expected): """ Helper to parse out a packet from the UART and check structure. Returns just the data payload from the packet""" res = self._uart.read(expected) # print("Got", res) if (not res) or (len(res) != expected): raise RuntimeError("Failed to read data from sensor") # first two bytes are start code start = struct.unpack(">H", res[0:2])[0] if start != _STARTCODE: raise RuntimeError("Incorrect packet data") # next 4 bytes are address addr = list(i for i in res[2:6]) if addr != self.address: raise RuntimeError("Incorrect address") packet_type, length = struct.unpack(">BH", res[6:9]) if packet_type != _ACKPACKET: raise RuntimeError("Incorrect packet data") # we should check the checksum # but i don't know how # not yet anyway # packet_sum = struct.unpack('>H', res[9+(length-2):9+length])[0] # print(packet_sum) # print(packet_type + length + struct.unpack('>HHHH', res[9:9+(length-2)])) reply = list(i for i in res[9 : 9 + (length - 2)]) # print(reply) return reply
Example #29
Source File: adafruit_fingerprint.py From Adafruit_CircuitPython_Fingerprint with MIT License | 5 votes |
def read_sysparam(self): """Returns the system parameters on success via attributes.""" self._send_packet([_READSYSPARA]) r = self._get_packet(28) if r[0] != OK: raise RuntimeError("Command failed.") self.library_size = struct.unpack(">H", bytes(r[5:7]))[0] self.security_level = struct.unpack(">H", bytes(r[7:9]))[0] self.device_address = bytes(r[9:13]) self.data_packet_size = struct.unpack(">H", bytes(r[13:15]))[0] self.baudrate = struct.unpack(">H", bytes(r[15:17]))[0] return r[0]
Example #30
Source File: adafruit_fingerprint.py From Adafruit_CircuitPython_Fingerprint with MIT License | 5 votes |
def count_templates(self): """Requests the sensor to count the number of templates and stores it in ``self.template_count``. Returns the packet error code or OK success""" self._send_packet([_TEMPLATECOUNT]) r = self._get_packet(14) self.template_count = struct.unpack(">H", bytes(r[1:3]))[0] return r[0]