Ejemplo n.º 1
0
    def read_sensor_register(self, sensor_driver, register, length=1):
        """Read sensor register value(s)

        Args:
            sensor_driver(SensorDriver): sensor driver instance
            register(int): Register value where reading starts
            length(int): how many bytes to read. Defaults to 1

        Returns:
            array.array: sensor register values as binary array

        Note:
            Sensor must be first added with add_sensor() before this operation can be done.

        """

        _, sensor_resource = self.found_sensors[sensor_driver.name]
        bus1_name = sensor_driver.selected_connectivity

        if bus1_name == BUS1_I2C:
            target = sensor_resource[CFG_TARGET]
            sad = sensor_resource[CFG_SAD]

            with DelayedKeyboardInterrupt():
                return self.kx_adapter.adapter_read_sensor_register_i2c(
                    target, sad, register, length)

        elif bus1_name == BUS1_SPI:
            target = sensor_resource[CFG_TARGET]
            cs = sensor_resource[CFG_CS]

            if sensor_resource[CFG_SPI_PROTOCOL] == 1:
                # With Kionix components, MSB must be set 1 to indicate reading
                register = register | 1 << 7

            with DelayedKeyboardInterrupt():
                return self.kx_adapter.adapter_read_sensor_register_spi(
                    target, cs, register, length)

        raise EvaluationKitException('Unable read sensor register.')
Ejemplo n.º 2
0
    def write_sensor_register(self, sensor_driver, register, values):
        """Write sensor register value(s)

        Args:
            sensor_driver(SensorDriver): sensor driver instance
            register(int): Register value where writing starts
            values ?

        Note:
            Sensor must be first added with add_sensor() before this operation can be done.
        """
        # TODO 2 check that connection is active
        _, sensor_resource = self.found_sensors[sensor_driver.name]
        bus1_name = sensor_driver.selected_connectivity

        if bus1_name == BUS1_I2C:
            target = sensor_resource[CFG_TARGET]
            sad = sensor_resource[CFG_SAD]

            with DelayedKeyboardInterrupt():
                return self.kx_adapter.adapter_write_sensor_register_i2c(
                    target, sad, register, values)

        elif bus1_name == BUS1_SPI:
            target = sensor_resource[CFG_TARGET]
            cs = sensor_resource[CFG_CS]

            if sensor_resource[CFG_SPI_PROTOCOL] == 1:
                # When using SPI, Kionix sensors require that the address' MSB is
                # cleared to indicate that this is a write.
                register &= ~(1 << 7)

            with DelayedKeyboardInterrupt():
                # TODO 3 CS polarity is hard coded active low. Need to be configurable if active high devices in use
                return self.kx_adapter.adapter_write_sensor_register_spi(
                    target, cs, register, values)

        else:
            raise EvaluationKitException(
                'Unable write data to sensor register.')
Ejemplo n.º 3
0
    def write_gpio_pin(self, gpio_pin, value):
        """Set GPIO line value based don HW index

        Args:
            gpio_pin(int): pin index (physical index)
            value(int): 0 or 1

        """
        assert isinstance(gpio_pin, int)
        assert value in [0, 1]

        # Update _pin_mode_cache.
        current_state = self._pin_mode_cache.get(gpio_pin, None)
        if current_state != _GPIO_STATE_OUTPUT:
            LOGGER.debug("Changing pin %d mode from %s to %s" %
                         (gpio_pin, current_state, _GPIO_STATE_OUTPUT))
            self._pin_mode_cache[gpio_pin] = _GPIO_STATE_OUTPUT

        with DelayedKeyboardInterrupt():
            return self.kx_adapter.adapter_write_gpio(gpio_pin, value)
Ejemplo n.º 4
0
    def read_gpio_pin(self, gpio_pin, pull=NOPULL):
        """Read GPIO line value based on HW index

        Args:
            gpio_pin(int): pin index (physical index)
            pull(int): NOPULL, PULLDOWN, PULLUP = range(3). Defalults to NOPULL
        """
        current_state = self._pin_mode_cache.get(gpio_pin, None)
        if current_state != (_GPIO_STATE_INPUT, pull):

            LOGGER.debug("Changing pin %d mode from %s to %s" %
                         (gpio_pin, current_state, _GPIO_STATE_INPUT))
            LOGGER.debug("Changing pull to %s" % pull)

            self.kx_adapter.configure_pin_as_input(gpio_pin=gpio_pin,
                                                   drivemode=pull)
            self._pin_mode_cache[gpio_pin] = (_GPIO_STATE_INPUT, pull)

        with DelayedKeyboardInterrupt():
            return self.kx_adapter.adapter_read_gpio(gpio_pin)
Ejemplo n.º 5
0
    def read_data_stream(self,
                         loop=None,
                         console=True,
                         log_file_name=None,
                         callback=None,
                         max_timeout_count=0,
                         additional_info=None):
        """Main loop for reading stream data after data streams are activated.

        Args:
            loop(int/None): Number of values to read. If None then infinite loop until KeyboardInterrupt is received (defaults to None)
            concole(bool): print values to console (defaults to True)
            log_file_name(string/None): Log file to write. (defaults to None)
            callback(function): function to call after new data is received.
            max_timeout_count(int/None): break after bus2 time out count is reached. If none then loop forever regardless timeouts
            additional_info(string): info passed to SensorDataLogger instance

        """
        count = 0  # count of received data samples
        timeout_count = 0  # how many timeouts received

        data_logger = SensorDataLogger(console=console,
                                       log_file_name=log_file_name,
                                       additional_info=additional_info)

        # subscribe sensor data from FW
        self._start_streaming()

        # On FW1 channels are known only after that _start_streaming()
        # print out header text, replace text "ch" with channel number
        for channel, request in iter(self.msg_ind_dict.items()):
            data_logger.add_channel(request.msg_hdr, channel)

        data_logger.start()

        try:
            # main loop for reading the data
            while (loop is None) or (count < loop):
                with DelayedKeyboardInterrupt():
                    # TODO 3 error handling if message was not macro message : macro_index >= EVKIT_MSG_MACRO_IND_BASE etc. logic
                    macro_index, resp = self.adapter.receive_message()

                if resp is None:
                    LOGGER.debug("Timeout when receiving data")
                    timeout_count += 1

                    if max_timeout_count is not None \
                       and timeout_count >= max_timeout_count:

                        raise ProtocolBus1Exception(
                            'Timeout when receiving data. Max timeout count reached.'
                        )

                    continue

                # find correct message type to get information how message is interpreted
                received_messsage_type = self.msg_ind_dict[macro_index]

                if len(resp) != received_messsage_type.msg_size:
                    LOGGER.error(
                        "Length of received message was wrong (%d). Expected (%d)"
                        % (len(resp), received_messsage_type.msg_size))
                else:
                    fmt = self.msg_ind_dict[macro_index].msg_fmt
                    # unpack the raw data
                    data = struct.unpack(fmt, resp)
                    # rotate if 3d data
                    data = self.msg_ind_dict[
                        macro_index].axis_mapper.map_xyz_axis(data)
                    # log the data
                    data_logger.feed_values(data)

                    count += 1

                if callback is not None:
                    # callback function returns False if need to stop reading
                    if callback(data) is False:
                        break

        except KeyboardInterrupt:
            # CTRL+C will stop data reading
            pass

        finally:
            # after CTRL+C or other exception, print end time stamp and stop reading sensor data

            # unsibscribe data from FW
            self._stop_streaming()

            data_logger.stop()

            if count == 0:
                LOGGER.error("No stream data received.")