예제 #1
0
def bme280init(li2c, addr=0x77):
    global i2c
    i2c = li2c
    dc = dcs[addr] = array.array("i", range(18))  # calibrations

    k = i2c.readfrom_mem(addr, 0xD0, 1)[0]
    assert k in [0x60, 0x55], ("chip not found", hex(k))

    i2c.writeto_mem(addr, 0xF2, b'\x01')  # switch on humidity (over)sampling=1
    i2c.writeto_mem(
        addr, 0xF4, b'\x27'
    )  # switch on temp and pressure (over)sampling=1, mode=normal(continuous readings)
    i2c.writeto_mem(addr, 0xF5, b'\x00')  # 0.5ms standby, no filtering, no-SPI

    dc[dT1], dc[dT2], dc[dT3] = ustruct.unpack("<Hhh",
                                               i2c.readfrom_mem(addr, 0x88, 6))
    dc[dP1], dc[dP2], dc[dP3], dc[dP4], dc[dP5], dc[dP6], dc[dP7], dc[dP8], dc[dP9] = \
            ustruct.unpack("<Hhhhhhhhh", i2c.readfrom_mem(addr, 0x8E, 18))

    dc[dH1] = i2c.readfrom_mem(addr, 0xA1, 1)[0]
    dig_e1_e7 = i2c.readfrom_mem(addr, 0xE1, 7)
    dc[dH2], dc[dH3] = ustruct.unpack("<hB", dig_e1_e7)
    e4_sign = ustruct.unpack_from("<b", dig_e1_e7, 3)[0]
    dc[dH4] = (e4_sign << 4) | (dig_e1_e7[4] & 0xF)
    e6_sign = ustruct.unpack_from("<b", dig_e1_e7, 5)[0]
    dc[dH5] = (e6_sign << 4) | (dig_e1_e7[4] >> 4)
    dc[dH6] = ustruct.unpack_from("<b", dig_e1_e7, 6)[0]
예제 #2
0
def _parse_activity_classifier_report(report_bytes):
    activities = [
        "Unknown",
        "In-Vehicle",  # look
        "On-Bicycle",  # at
        "On-Foot",  # all
        "Still",  # this
        "Tilting",  # room
        "Walking",  # for
        "Running",  # activities
        "OnStairs",
    ]

    end_and_page_number = unpack_from("<B", report_bytes, 4)[0]
    # last_page = (end_and_page_number & 0b10000000) > 0
    page_number = end_and_page_number & 0x7F
    most_likely = unpack_from("<B", report_bytes, 5)[0]
    confidences = unpack_from("<BBBBBBBBB", report_bytes, 6)

    classification = {}
    classification["most_likely"] = activities[most_likely]
    for idx, raw_confidence in enumerate(confidences):
        confidence = (10 * page_number) + raw_confidence
        activity_string = activities[idx]
        classification[activity_string] = confidence
    return classification
예제 #3
0
def readValues(deviceAddress=mag3110.MAG_ADDRESS):
    data = readI2cAddress(mag3110.OUT_X_MSB, 6)
    return [
        ustruct.unpack_from("<h", data, 0)[0],
        ustruct.unpack_from("<h", data, 2)[0],
        ustruct.unpack_from("<h", data, 4)[0]
    ]
예제 #4
0
def read_sensor(which_sensor, which_side):
    """
    Reads the GiggleBot onboard sensors, light or line sensors.

    :param int which_sensor: Reads the light sensors :py:attr:`~gigglebot.LIGHT_SENSOR` (6), or the line sensors :py:attr:`~gigglebot.LINE_SENSOR` (5). Values are from **0** to **1023**.
    :param int which_side: Reads :py:attr:`~gigglebot.LEFT` (0), :py:attr:`~gigglebot.RIGHT` (1), or :py:attr:`~gigglebot.BOTH` (2) sensors. When reading both sensors, an array will be returned.

    :returns: Either an integer or an array of integers (right, then left).

    You can read the sensors this way:

    .. code::

       right, left = read_sensor(LIGHT_SENSOR, BOTH)

    """
    i2c.write(0x04, pack('B', which_sensor))
    buf = i2c.read(0x04, 3)
    pack_into('>HH', _BUFFER, 0, 1023 - (buf[0] << 2 | ((buf[2] & 0xC0) >> 6)), 1023 - (buf[1] << 2 | ((buf[2] & 0x30) >> 4)))

    if which_side == LEFT: 
        return unpack_from('>H', _BUFFER, 2)[0]
    elif which_side == RIGHT: 
        return unpack_from('>H', _BUFFER, 0)[0]
    else: 
        return unpack_from('>HH', _BUFFER)
예제 #5
0
def readValues(i2cDev, deviceAddress=mag3110.MAG_ADDRESS):
    data = i2c.read(i2cDev, mag3110.OUT_X_MSB, 6)
    return [
        ustruct.unpack_from("<H", data, 0)[0],
        ustruct.unpack_from("<H", data, 2)[0],
        ustruct.unpack_from("<H", data, 4)[0]
    ]
예제 #6
0
def compare_q_and_a(q_buf, q_offset, a_buf, a_offset=0):
    if not compare_packed_names(q_buf, q_offset, a_buf, a_offset):
        return False
    (q_type, q_class) = unpack_from("!HH", q_buf, skip_name_at(q_buf, q_offset))
    (r_type, r_class) = unpack_from("!HH", a_buf, skip_name_at(a_buf, a_offset))
    if not (q_type == r_type or q_type == _TYPE_ANY):
        return False
    q_class &= _CLASS_MASK
    r_class &= _CLASS_MASK
    return (q_class == r_class or q_class == _TYPE_ANY)
예제 #7
0
    def header_from_buffer(cls, packet_bytes):
        """Creates a `PacketHeader` object from a given buffer"""
        packet_byte_count = unpack_from("<H", packet_bytes)[0]
        packet_byte_count &= ~0x8000
        channel_number = unpack_from("<B", packet_bytes, 2)[0]
        sequence_number = unpack_from("<B", packet_bytes, 3)[0]
        data_length = max(0, packet_byte_count - 4)

        header = (channel_number, sequence_number, data_length,
                  packet_byte_count)
        return header
예제 #8
0
파일: bme280.py 프로젝트: ks-tec/Hydroponic
    def __init__(self,
                 mode=BME280_OSAMPLE_1,
                 address=BME280_I2CADDR,
                 i2c=None,
                 unit="C",
                 **kwargs):
        """
        Constructor of BME280.

        Args:
            mode : BME280 sampling mode
            address : I2C address
            i2c : machine.I2C object
            unit : temperature unit
        """
        # Check that mode is valid.
        if mode not in [BME280_OSAMPLE_1, BME280_OSAMPLE_2, BME280_OSAMPLE_4,
                        BME280_OSAMPLE_8, BME280_OSAMPLE_16]:
            raise ValueError(
                'Unexpected mode value {0}. Set mode to one of '
                'BME280_ULTRALOWPOWER, BME280_STANDARD, BME280_HIGHRES, or '
                'BME280_ULTRAHIGHRES'.format(mode))
        self._mode = mode
        self.address = address
        if i2c is None:
            raise ValueError('An I2C object is required.')
        self.i2c = i2c
        self.unit = unit

        # load calibration data
        dig_88_a1 = self.i2c.readfrom_mem(self.address, 0x88, 26)
        dig_e1_e7 = self.i2c.readfrom_mem(self.address, 0xE1, 7)
        self.dig_T1, self.dig_T2, self.dig_T3, self.dig_P1, \
            self.dig_P2, self.dig_P3, self.dig_P4, self.dig_P5, \
            self.dig_P6, self.dig_P7, self.dig_P8, self.dig_P9, \
            _, self.dig_H1 = unpack("<HhhHhhhhhhhhBB", dig_88_a1)

        self.dig_H2, self.dig_H3 = unpack("<hB", dig_e1_e7)
        e4_sign = unpack_from("<b", dig_e1_e7, 3)[0]
        self.dig_H4 = (e4_sign << 4) | (dig_e1_e7[4] & 0xF)

        e6_sign = unpack_from("<b", dig_e1_e7, 5)[0]
        self.dig_H5 = (e6_sign << 4) | (dig_e1_e7[4] >> 4)

        self.dig_H6 = unpack_from("<b", dig_e1_e7, 6)[0]

        self.i2c.writeto_mem(self.address, BME280_REGISTER_CONTROL,
                             bytearray([0x3F]))
        self.t_fine = 0

        # temporary data holders which stay allocated
        self._l1_barray = bytearray(1)
        self._l8_barray = bytearray(8)
        self._l3_resultarray = array("i", [0, 0, 0])
예제 #9
0
def read_varint(v):
    # read "compact sized" int from a few bytes.
    assert not isinstance(v, tuple), v
    nit = v[0]
    if nit == 253:
        return unpack_from("<H", v, 1)[0]
    elif nit == 254:
        return unpack_from("<I", v, 1)[0]
    elif nit == 255:
        return unpack_from("<Q", v, 1)[0]
    return nit
예제 #10
0
 def read_raw(self):
     """Read the raw gyroscope readings.  Returns a 3-tuple of X, Y, Z axis
     16-bit signed values.  If you want the gyroscope values in friendly
     units consider using the gyroscope property!
     """
     # Read gyro data from the sensor.
     res = self._bus.read(self._address, _GYRO_REGISTER_OUT_X_MSB, 8)
     # Parse out the gyroscope data as 16-bit signed data.
     raw_x = struct.unpack_from(">h", res[0:2])[0]
     raw_y = struct.unpack_from(">h", res[2:4])[0]
     raw_z = struct.unpack_from(">h", res[4:6])[0]
     return (raw_x, raw_y, raw_z)
예제 #11
0
def _loads_tb(fp, tb, limit=None, depth=0, returntags=False):
    if tb == _CBOR_FLOAT16:
        # Adapted from cbor2 unpack_float16()
        data = fp.read(2)
        data = ustruct.unpack('>H', data)[0]

        value = (data & 0x7fff) << 13 | (data & 0x8000) << 16
        if data & 0x7c00 != 0x7c00:
            return math.ldexp(_decode_single(value), 112)
        return _decode_single(value | 0x7f800000)
    elif tb == _CBOR_FLOAT32:
        data = fp.read(4)
        return ustruct.unpack_from("!f", data, 0)[0]
    elif tb == _CBOR_FLOAT64:
        data = fp.read(8)
        return ustruct.unpack_from("!d", data, 0)[0]

    tag, tag_aux, aux = _tag_aux(fp, tb)

    if tag == _CBOR_UINT:
        return aux
    elif tag == _CBOR_NEGINT:
        return -1 - aux
    elif tag == _CBOR_BYTES:
        return loads_bytes(fp, aux)
    elif tag == _CBOR_TEXT:
        raw = loads_bytes(fp, aux, btag=_CBOR_TEXT)
        return raw.decode('utf8')
    elif tag == _CBOR_ARRAY:
        if aux is None:
            return _loads_var_array(fp, limit, depth, returntags)
        return _loads_array(fp, limit, depth, returntags, aux)
    elif tag == _CBOR_MAP:
        if aux is None:
            return _loads_var_map(fp, limit, depth, returntags)
        return _loads_map(fp, limit, depth, returntags, aux)
    elif tag == _CBOR_TAG:
        if returntags:
            # Don't interpret the tag, return it and the tagged object.
            return Tag(aux, _loads(fp))
        # attempt to interpet the tag and the value into a Python object.
        return tagify(_loads(fp), aux)
    elif tag == _CBOR_7:
        if tb == _CBOR_TRUE:
            return True
        if tb == _CBOR_FALSE:
            return False
        if tb == _CBOR_NULL:
            return None
        if tb == _CBOR_UNDEFINED:
            return None
        raise ValueError("unknown cbor tag 7 byte: {:02x}".format(tb))
예제 #12
0
    def __init__(self,
                 i2c=None,
                 mode=BME280_OSAMPLE_1,
                 address=None,
                 **kwargs):
        # Check that mode is valid.
        if mode < BME280_OSAMPLE_1 or mode > BME280_OSAMPLE_16:
            raise ValueError(
                'Unexpected mode value {0}. Set mode to one of '
                'BME280_OSAMPLE_1, BME280_OSAMPLE_2, BME280_OSAMPLE_4, '
                'BME280_OSAMPLE_8 or BME280_OSAMPLE_16'.format(mode))
        self._mode = mode
        if i2c is None:
            raise ValueError('An I2C object is required.')
        if address is not None:
            self.address = address
        else:
            addr = [a for a in i2c.scan() if a in BME280_I2CADDRS]
            if len(addr) == 0:
                raise RuntimeError('No BME280 found.')
            self.address = addr[0]  # 1st device found
        self.i2c = i2c

        # load calibration data
        dig_88_a1 = i2c.readfrom_mem(self.address, 0x88, 26)
        dig_e1_e7 = i2c.readfrom_mem(self.address, 0xE1, 7)
        self.dig_T1, self.dig_T2, self.dig_T3, self.dig_P1, \
        self.dig_P2, self.dig_P3, self.dig_P4, self.dig_P5, \
        self.dig_P6, self.dig_P7, self.dig_P8, self.dig_P9, \
        _, self.dig_H1 = unpack("<HhhHhhhhhhhhBB", dig_88_a1)

        self.dig_H2, self.dig_H3 = unpack("<hB", dig_e1_e7)
        e4_sign = unpack_from("<b", dig_e1_e7, 3)[0]
        self.dig_H4 = (e4_sign << 4) | (dig_e1_e7[4] & 0xF)

        e6_sign = unpack_from("<b", dig_e1_e7, 5)[0]
        self.dig_H5 = (e6_sign << 4) | (dig_e1_e7[4] >> 4)

        self.dig_H6 = unpack_from("<b", dig_e1_e7, 6)[0]

        i2c.writeto_mem(self.address, BME280_REGISTER_CONTROL,
                        bytearray([0x3F]))
        self.t_fine = 0

        # temporary data holders which stay allocated
        self._l1_barray = bytearray(1)
        self._l8_barray = bytearray(8)
        self._l3_resultarray = array("i", [0, 0, 0])

        # sea level pressure in millibar, because it's
        # easy to get from your local airport METAR
        self._slp = 1013.25
    def read_raw(self):
        """Read the raw gyroscope readings.  Returns a 3-tuple of X, Y, Z axis
        16-bit signed values.  If you want the gyroscope values in friendly
        units consider using the gyroscope property!
        """
        # Read gyro data from the sensor.
        self._BUFFER = self._device.readList(_GYRO_REGISTER_OUT_X_MSB, 6)

        # Parse out the gyroscope data as 16-bit signed data.
        raw_x = struct.unpack_from('>h', self._BUFFER[0:2])[0]
        raw_y = struct.unpack_from('>h', self._BUFFER[2:4])[0]
        raw_z = struct.unpack_from('>h', self._BUFFER[4:6])[0]
        return (raw_x, raw_y, raw_z)
예제 #14
0
 def load(self):
     #Load back loops state from flash IC.
     if self.f.state_read(0, 1)[0] == 255:
         if board.verbose:
             print("Loading failed: no loops recorded")
         #Check if there's anything written at all. Assume the flash is erased to value 0xFF, which is not a valid value for the 1st octet.
     else:
         self.recorded = ustruct.unpack_from("I", self.f.state_read(0,
                                                                    4))[0]
         for i in range(len(self.durations)):
             self.durations[i] = ustruct.unpack_from(
                 "I", self.f.state_read(i * 4 + 4, 4))[0]
         print("Loaded:", self.recorded, self.durations)
예제 #15
0
def parse_sensor_id(buffer):
    """Parse the fields of a product id report"""
    if not buffer[0] == _SHTP_REPORT_PRODUCT_ID_RESPONSE:
        raise AttributeError("Wrong report id for sensor id: %s" %
                             hex(buffer[0]))

    sw_major = unpack_from("<B", buffer, 2)[0]
    sw_minor = unpack_from("<B", buffer, 3)[0]
    sw_patch = unpack_from("<H", buffer, 12)[0]
    sw_part_number = unpack_from("<I", buffer, 4)[0]
    sw_build_number = unpack_from("<I", buffer, 8)[0]

    return (sw_part_number, sw_major, sw_minor, sw_patch, sw_build_number)
예제 #16
0
def _parse_command_response(report_bytes):

    # CMD response report:
    # 0 Report ID = 0xF1
    # 1 Sequence number
    # 2 Command
    # 3 Command sequence number
    # 4 Response sequence number
    # 5 R0-10 A set of response values. The interpretation of these values is specific
    # to the response for each command.
    report_body = unpack_from("<BBBBB", report_bytes)
    response_values = unpack_from("<BBBBBBBBBBB", report_bytes, 5)
    return (report_body, response_values)
 def read_raw(self):
     """Read the raw gyroscope readings.  Returns a 3-tuple of X, Y, Z axis
     16-bit signed values.  If you want the gyroscope values in friendly
     units consider using the gyroscope property!
     """
     # Read gyro data from the sensor.
     with self._device as i2c:
         self._BUFFER[0] = _GYRO_REGISTER_OUT_X_MSB
         i2c.write_then_readinto(self._BUFFER, self._BUFFER, out_end=1)
     # Parse out the gyroscope data as 16-bit signed data.
     raw_x = struct.unpack_from(">h", self._BUFFER[0:2])[0]
     raw_y = struct.unpack_from(">h", self._BUFFER[2:4])[0]
     raw_z = struct.unpack_from(">h", self._BUFFER[4:6])[0]
     return (raw_x, raw_y, raw_z)
예제 #18
0
    def __init__(self,
                 i2c=None,
                 mode=BME280_OSAMPLE_1,
                 address=BME280_I2CADDR,
                 **kwargs):
        # Check that mode is valid.
        if mode not in [
                BME280_OSAMPLE_1, BME280_OSAMPLE_2, BME280_OSAMPLE_4,
                BME280_OSAMPLE_8, BME280_OSAMPLE_16
        ]:
            raise ValueError(
                'Unexpected mode value {0}. Set mode to one of '
                'BME280_ULTRALOWPOWER, BME280_STANDARD, BME280_HIGHRES, or '
                'BME280_ULTRAHIGHRES'.format(mode))
        self._mode = mode
        self.address = address
        if i2c is None:
            raise ValueError('An I2C object is required.')
        self.i2c = i2c

        # load calibration data
        dig_88_a1 = self.i2c.readfrom_mem(self.address, 0x88, 26)
        dig_e1_e7 = self.i2c.readfrom_mem(self.address, 0xE1, 7)
        self.dig_T1, self.dig_T2, self.dig_T3, self.dig_P1, \
            self.dig_P2, self.dig_P3, self.dig_P4, self.dig_P5, \
            self.dig_P6, self.dig_P7, self.dig_P8, self.dig_P9, \
            _, self.dig_H1 = unpack("<HhhHhhhhhhhhBB", dig_88_a1)

        self.dig_H2, self.dig_H3 = unpack("<hB", dig_e1_e7)
        e4_sign = unpack_from("<b", dig_e1_e7, 3)[0]
        self.dig_H4 = (e4_sign << 4) | (dig_e1_e7[4] & 0xF)

        e6_sign = unpack_from("<b", dig_e1_e7, 5)[0]
        self.dig_H5 = (e6_sign << 4) | (dig_e1_e7[4] >> 4)

        self.dig_H6 = unpack_from("<b", dig_e1_e7, 6)[0]

        self.i2c.writeto_mem(self.address, BME280_REGISTER_CONTROL,
                             bytearray([0x3F]))
        self.t_fine = 0

        # temporary data holders which stay allocated
        self._l1_barray = bytearray(1)
        self._l8_barray = bytearray(8)
        self._l3_resultarray = array("i", [0, 0, 0])

        # sea level pressure in millibar, because it's
        # easy to get from your local airport METAR
        self._slp = 1013.25
예제 #19
0
 def read_raw(self):
     """Read the raw gyroscope readings.  Returns a 3-tuple of X, Y, Z axis
     16-bit signed values.  If you want the gyroscope values in friendly
     units consider using the gyroscope property!
     """
     # Read gyro data from the sensor.
     with self._device as i2c:
         self._BUFFER[0] = _GYRO_REGISTER_OUT_X_MSB
         i2c.write_then_readinto(self._BUFFER, self._BUFFER,
            	                    out_end=1, stop=False)
     # Parse out the gyroscope data as 16-bit signed data.
     raw_x = struct.unpack_from('>h', self._BUFFER[0:2])[0]
     raw_y = struct.unpack_from('>h', self._BUFFER[2:4])[0]
     raw_z = struct.unpack_from('>h', self._BUFFER[4:6])[0]
     return (raw_x, raw_y, raw_z)
예제 #20
0
def decoderesponsepacket(name, buf):
    hostipnumber = ''
    try:
        pkt_id, flags, qst_count, ans_count = ustruct.unpack_from("!HHHH", buf)
        o = 12
        for i in range(qst_count):
            o += lenpackedname(buf, o) + 4
        for i in range(ans_count):
            l = lenpackedname(buf, o)
            if name == extractpackedname(buf, o):
                hostipnumber = ".".join(map(str, buf[o + l + 10:o + l + 14]))
            o += 10 + l + ustruct.unpack_from("!H", buf, o + l + 8)[0]
    except IndexError:
        print("Index error processing packet; probably malformed data")
    return hostipnumber
def GetBME280calibrations(i2c):
    dc = array.array("i", range(18))
    dc[dT1], dc[dT2], dc[dT3] = ustruct.unpack("<Hhh",
                                               i2c.readfrom_mem(0x77, 0x88, 6))
    dc[dP1], dc[dP2], dc[dP3], dc[dP4], dc[dP5], dc[dP6], dc[dP7], dc[dP8], dc[dP9] = \
                            ustruct.unpack("<Hhhhhhhhh", i2c.readfrom_mem(0x77, 0x8E, 18))
    dc[dH1] = i2c.readfrom_mem(0x77, 0xA1, 1)[0]
    dig_e1_e7 = i2c.readfrom_mem(0x77, 0xE1, 7)
    dc[dH2], dc[dH3] = ustruct.unpack("<hB", dig_e1_e7)
    e4_sign = ustruct.unpack_from("<b", dig_e1_e7, 3)[0]
    dc[dH4] = (e4_sign << 4) | (dig_e1_e7[4] & 0xF)
    e6_sign = ustruct.unpack_from("<b", dig_e1_e7, 5)[0]
    dc[dH5] = (e6_sign << 4) | (dig_e1_e7[4] >> 4)
    dc[dH6] = ustruct.unpack_from("<b", dig_e1_e7, 6)[0]
    return dc
예제 #22
0
def compare_packed_names(buf, o, packed_name, po=0):
    while packed_name[po] != 0:
        while buf[o] & 0xC0:
            (o, ) = unpack_from("!H", buf, o)
            o &= 0x3FFF
        while packed_name[po] & 0xC0:
            (po, ) = unpack_from("!H", packed_name, po)
            po &= 0x3FFF
        l1 = buf[o] + 1
        l2 = packed_name[po] + 1
        if l1 != l2 or buf[o:o + l1] != packed_name[po:po + l2]:
            return False
        o += l1
        po += l2
    return buf[o] == 0
예제 #23
0
def sign16():  # read 16 bit signed data from eeprom
    i2c.writeto(slave_addr, data)
    utime.sleep(0.001)
    rawdata = i2c.readfrom(slave_addr, 3)  #1 ack byte and 2 data bytes
    value = ustruct.unpack_from(
        '>h', rawdata, 1)[0]  #use 2nd and 3rd bytes for signed integer
    return value
예제 #24
0
 def is_calibration_enabled(self):
     status = self.i2c.readfrom(self.address, 1)
     status_hex = struct.unpack_from(">b", status)
     if status_hex[0] & int('0x68', 16) == int('0x08', 16):
         return True
     else:
         return False
    def validate_psbt_xpubs(self, xpubs_list):
        # The xpubs provided in PSBT must be exactly right, compared to our record.
        # But we're going to use our own values from setup time anyway.
        # Check:
        # - chain codes match what we have stored already
        # - pubkey vs. path will be checked later
        # - xfp+path already checked when selecting this wallet
        # - some cases we cannot check, so count those for a warning
        # Any issue here is a fraud attempt in some way, not innocent.
        # But it would not have tricked us and so the attack targets some other signer.
        assert len(xpubs_list) == self.N

        for k, v in xpubs_list:
            xfp, *path = ustruct.unpack_from('<%dI' % (len(k)//4), k, 0)
            xpub = tcc.codecs.b58_encode(v)

            # cleanup and normalize xpub
            tmp = []
            self.check_xpub(xfp, xpub, keypath_to_str(path, skip=0), self.chain_type, 0, tmp)
            (_, deriv, xpub_reserialized) = tmp[0]
            assert deriv            # because given as arg

            # find in our records.
            for (x_xfp, x_deriv, x_xpub) in self.xpubs: 
                if x_xfp != xfp: continue
                # found matching XFP
                assert deriv == x_deriv

                assert xpub_reserialized == x_xpub, 'xpub wrong (xfp=%s)' % xfp2str(xfp)
                break
            else:
                assert False            # not reachable, since we picked wallet based on xfps
예제 #26
0
 def gyroReadReg16(r):
     buf2 = bytearray([0, 0])
     l = tbos.gyroReadReg(r)
     h = tbos.gyroReadReg(r + 1)
     buf2[0] = l
     buf2[1] = h
     t = ustruct.unpack_from('<h', buf2, 0)
     return t[0]
예제 #27
0
    def process_packet(self, buf, addr):
        # Process a single multicast DNS packet

        (pkt_id, flags, qst_count, ans_count, _,
         _) = unpack_from("!HHHHHH", buf, 0)
        o = 12
        matches = []
        reply_len = 12
        for i in range(qst_count):
            for a in self.adverts:
                if compare_q_and_a(buf, o, a):
                    matches.append(a)
                    reply_len += len(a)
            o = skip_question(buf, o)

        # In theory we could do known answer suppression here
        # We don't, BIWIOMS

        if self._pending_question:
            for i in range(ans_count):
                if compare_q_and_a(self._pending_question, 0, buf, o):
                    if self._answer_callback(buf[o:skip_answer(buf, o)]):
                        self.answered = True
                o = skip_answer(buf, o)

        if not matches:
            return

        # We could check for duplicates in the answers (which is
        # possible) but we don't, BIWIOMS

        # Since Micropython sockets don't currently support
        # recvfrom_into() we need to have our own buffer for the
        # reply, even though we are now done with the receiving buffer

        #我们可以检查答案是否重复(这是可能的),但是我们没有,biwioms,因为微丝子插座目前不支持recvfrom_o in to(),我们需要有自己的回复缓冲区,即使我们现在已经完成了接收缓冲区的工作。

        if not self._reply_buffer or len(self._reply_buffer) < reply_len:
            # print("Making new reply buffer of len {}".format(reply_len))
            self._reply_buffer = memoryview(bytearray(reply_len))

        buf = self._reply_buffer
        pack_into("!HHHHHH", buf, 0, pkt_id, _FLAGS_QR_RESPONSE | _FLAGS_AA, 0,
                  len(matches), 0, 0)
        o = 12
        for a in matches:
            l = len(a)
            buf[o:o + l] = a
            o += l

        # print("Sending packed reply: {}".format(bytes(buf[:o])))

        # We fake the handling of unicast replies. If the packet came
        # from the mutlicast port we multicast the reply but if it
        # came from any other port we unicast the reply.
        self.sock.sendto(buf[:o],
                         (_MDNS_ADDR,
                          _MDNS_PORT) if addr[0] == _MDNS_PORT else addr)
예제 #28
0
 def read(self, eeprom_addr):
     try:
         self.i2c.readfrom_mem_into(self.i2c_addr,
                                    eeprom_addr,
                                    self.i2c_buf,
                                    addrsize=8)
     except OSError:
         return 0
     return ustruct.unpack_from("<I", self.i2c_buf)[0]
예제 #29
0
def extractpackedname(buf, o):
    names = []
    while buf[o] != 0:
        if buf[o] & 0xc0:
            o = ustruct.unpack_from("!H", buf, o)[0] & 0x3FFF
        else:
            names.append(bytes(buf[o + 1:o + 1 + buf[o]]))
            o += 1 + buf[o]
    return b".".join(names).decode()
예제 #30
0
파일: bme280.py 프로젝트: eztmondom/test1
    def __init__(self,
                 mode=BME280_OSAMPLE_1,
                 address=BME280_I2CADDR,
                 i2c=None,
                 **kwargs):
        # Check that mode is valid.
        if mode not in [BME280_OSAMPLE_1, BME280_OSAMPLE_2, BME280_OSAMPLE_4,
                        BME280_OSAMPLE_8, BME280_OSAMPLE_16]:
            raise ValueError(
                'Unexpected mode value {0}. Set mode to one of '
                'BME280_ULTRALOWPOWER, BME280_STANDARD, BME280_HIGHRES, or '
                'BME280_ULTRAHIGHRES'.format(mode))
        self._mode = mode
        self.address = address
        if i2c is None:
            raise ValueError('An I2C object is required.')
        self.i2c = i2c

        # load calibration data
        dig_88_a1 = self.i2c.readfrom_mem(self.address, 0x88, 26)
        dig_e1_e7 = self.i2c.readfrom_mem(self.address, 0xE1, 7)
        self.dig_T1, self.dig_T2, self.dig_T3, self.dig_P1, \
            self.dig_P2, self.dig_P3, self.dig_P4, self.dig_P5, \
            self.dig_P6, self.dig_P7, self.dig_P8, self.dig_P9, \
            _, self.dig_H1 = unpack("<HhhHhhhhhhhhBB", dig_88_a1)

        self.dig_H2, self.dig_H3 = unpack("<hB", dig_e1_e7)
        e4_sign = unpack_from("<b", dig_e1_e7, 3)[0]
        self.dig_H4 = (e4_sign << 4) | (dig_e1_e7[4] & 0xF)

        e6_sign = unpack_from("<b", dig_e1_e7, 5)[0]
        self.dig_H5 = (e6_sign << 4) | (dig_e1_e7[4] >> 4)

        self.dig_H6 = unpack_from("<b", dig_e1_e7, 6)[0]

        self.i2c.writeto_mem(self.address, BME280_REGISTER_CONTROL,
                             bytearray([0x3F]))
        self.t_fine = 0

        # temporary data holders which stay allocated
        self._l1_barray = bytearray(1)
        self._l8_barray = bytearray(8)
        self._l3_resultarray = array("i", [0, 0, 0])
예제 #31
0
def get_header_value(fld_name):
    # get a single value, raw, from header; based on field name
    from sigheader import FLASH_HEADER_BASE, FW_HEADER_SIZE, FWH_PY_FORMAT, FWH_PY_VALUES
    import ustruct, uctypes

    idx = FWH_PY_VALUES.split().index(fld_name)

    hdr = uctypes.bytes_at(FLASH_HEADER_BASE, FW_HEADER_SIZE)

    return ustruct.unpack_from(FWH_PY_FORMAT, hdr)[idx]
예제 #32
0
    def __init__(self,
                 i2c,
                 mode=BME280_OSAMPLE_1,
                 address=BME280_I2CADDR,
                 **kwargs):
        # Check that mode is valid.
        if mode not in [
                BME280_OSAMPLE_1, BME280_OSAMPLE_2, BME280_OSAMPLE_4,
                BME280_OSAMPLE_8, BME280_OSAMPLE_16
        ]:
            raise ValueError(
                'Unexpected mode value {0}. Set mode to one of '
                'BME280_ULTRALOWPOWER, BME280_STANDARD, BME280_HIGHRES, or '
                'BME280_ULTRAHIGHRES'.format(mode))
        self._mode = mode
        self.address = address
        self.i2c = i2c

        # load calibration data
        dig_88_a1 = self.i2c.readfrom_mem(self.address, 0x88, 26)
        dig_e1_e7 = self.i2c.readfrom_mem(self.address, 0xE1, 7)
        self.dig_T1, self.dig_T2, self.dig_T3, self.dig_P1, \
            self.dig_P2, self.dig_P3, self.dig_P4, self.dig_P5, \
            self.dig_P6, self.dig_P7, self.dig_P8, self.dig_P9, \
            _, self.dig_H1 = unpack('<HhhHhhhhhhhhBB', dig_88_a1)

        self.dig_H2, self.dig_H3 = unpack('<hB', dig_e1_e7)
        e4_sign = unpack_from('<b', dig_e1_e7, 3)[0]
        self.dig_H4 = (e4_sign << 4) | (dig_e1_e7[4] & 0xF)

        e6_sign = unpack_from('<b', dig_e1_e7, 5)[0]
        self.dig_H5 = (e6_sign << 4) | (dig_e1_e7[4] >> 4)

        self.dig_H6 = unpack_from('<b', dig_e1_e7, 6)[0]

        self.i2c.writeto_mem(self.address, BME280_REGISTER_CONTROL,
                             bytearray([0x3F]))
        self.t_fine = 0

        # temporary data holders which stay allocated
        self._l1_barray = bytearray(1)
        self._l8_barray = bytearray(8)
        self._l3_resultarray = array('i', [0, 0, 0])
예제 #33
0
    def read_raw_accel_mag(self):
        """Read the raw accelerometer and magnetometer readings.  Returns a
        2-tuple of 3-tuples:

        - Accelerometer X, Y, Z axis 14-bit signed raw values
        - Magnetometer X, Y, Z axis 16-bit signed raw values

        If you want the acceleration or magnetometer values in friendly units
        consider using the accelerometer and magnetometer properties!
        """
        # Read accelerometer data from sensor.
        with self._device as i2c:
            self._BUFFER[0] = _FXOS8700_REGISTER_OUT_X_MSB
            i2c.write_then_readinto(self._BUFFER, self._BUFFER,
                                    out_end=1, in_end=6,
                                    stop=False)
        accel_raw_x = struct.unpack_from('>H', self._BUFFER[0:2])[0]
        accel_raw_y = struct.unpack_from('>H', self._BUFFER[2:4])[0]
        accel_raw_z = struct.unpack_from('>H', self._BUFFER[4:6])[0]
        # Convert accelerometer data to signed 14-bit value from 16-bit
        # left aligned 2's compliment value.
        accel_raw_x = _twos_comp(accel_raw_x >> 2, 14)
        accel_raw_y = _twos_comp(accel_raw_y >> 2, 14)
        accel_raw_z = _twos_comp(accel_raw_z >> 2, 14)
        # Read magnetometer data from sensor.  No need to convert as this is
        # 16-bit signed data so struct parsing can handle it directly.
        with self._device as i2c:
            self._BUFFER[0] = _FXOS8700_REGISTER_MOUT_X_MSB
            i2c.write_then_readinto(self._BUFFER, self._BUFFER,
                                    out_end=1, in_end=6,
                                    stop=False)
        mag_raw_x = struct.unpack_from('>h', self._BUFFER[0:2])[0]
        mag_raw_y = struct.unpack_from('>h', self._BUFFER[2:4])[0]
        mag_raw_z = struct.unpack_from('>h', self._BUFFER[4:6])[0]
        return ((accel_raw_x, accel_raw_y, accel_raw_z),
                (mag_raw_x, mag_raw_y, mag_raw_z))
예제 #34
0
print(struct.pack("<3B", 1, 2, 3))

# pack_into
buf = bytearray(b'>>>123<<<')
struct.pack_into('<bbb', buf, 3, 0x41, 0x42, 0x43)
print(buf)
struct.pack_into('<bbb', buf, -6, 0x44, 0x45, 0x46)
print(buf)

try:
    struct.pack_into('<bbb', buf, 7, 0x41, 0x42, 0x43)
except:
    print('struct.error')
try:
    struct.pack_into('<bbb', buf, -10, 0x41, 0x42, 0x43)
except:
    print('struct.error')

# unpack_from
buf = b'0123456789'
print(struct.unpack_from('<b', buf, 4))
print(struct.unpack_from('<b', buf, -4))
try:
    print(struct.unpack_from('<b', buf, 10))
except:
    print('struct.error')
try:
    print(struct.unpack_from('<b', buf, -11))
except:
    print('struct.error')
예제 #35
0
파일: imu.py 프로젝트: Giannie/Mk3-Firmware
 def _acceleration_raw_to_float(self, data, offset):
     input = ustruct.unpack_from("h", data, offset)[0];
     return input  * 0.061 * self.accuracy / 1000