def open(self, port_index=0):
        "Connect to bus adapter"
        _i2c_bus.open(self)

        # TODO, need to support multiple instances of bus_aadvark_i2c with single adapter.
        # This way it is possible to connect multiple i2c slaves to same bus.

        self._handle = aa.aa_open(port_index)
        if self._handle < 0:
            if (self._handle == -7):
                raise BusException(
                    'bus_aadvark_i2c.open failed with error code %d (Aardvark disconnected)'
                    % self._handle)
            else:
                raise BusException(
                    'bus_aadvark_i2c.open failed with error code %d' %
                    self._handle)

        # IO direction now all input, do this before AA_CONFIG_GPIO_I2C
        aa.aa_gpio_direction(
            self._handle,
            int(evkit_config.get('aardvark_i2c', 'aa_gpio_direction'), 16))

        ## select pullup or floating
        #aa.aa_gpio_pullup(self._handle, aa.AA_GPIO_SCK | aa.AA_GPIO_MOSI) # pullup for gpio lines
        aa.aa_gpio_pullup(
            self._handle,
            int(evkit_config.get('aardvark_i2c', 'aa_gpio_pullup'), 16))

        #todo slave address selection GPIO to output

        # Ensure that the I2C subsystem is enabled
        aa.aa_configure(self._handle, aa.AA_CONFIG_GPIO_I2C)

        # Enable the I2C bus pullup resistors (2.2k resistors).
        # This command is only effective on v2.0 hardware or greater.
        # The pullup resistors on the v1.02 hardware are enabled by default.
        aa.aa_i2c_pullup(
            self._handle,
            self.aa_i2c_pullup[evkit_config.get('aardvark_i2c',
                                                'aa_i2c_pullup')])

        # Power the board using the Aardvark adapter's power supply.
        # This command is only effective on v2.0 hardware or greater.
        # The power pins on the v1.02 hardware are not enabled by default.
        aa.aa_target_power(
            self._handle,
            self.aa_target_power[evkit_config.get('aardvark_i2c',
                                                  'aa_target_power')])

        # Set the bitrate
        requested = self._bitrate
        self._bitrate = aa.aa_i2c_bitrate(self._handle, self._bitrate)
        if requested != self._bitrate:
            logger.warning('Bitrate set to %d kHz. Wanted to set %d kHz' %
                           (self._bitrate, requested))
    def open(self, port_index=0):
        assert evkit_config.get(
            'spi', 'ss_polarity') in ['ACTIVE_LOW', 'ACTIVE_HIGH']
        assert evkit_config.get('spi', 'bitorder') in ['MSB', 'LSB']
        _spi_bus.open(self)

        self._handle = aa.aa_open(port_index)
        if self._handle < 0:
            if (self._handle == -7):
                raise BusException(
                    'bus_aadvark_spi.open failed with error code %d (Aardvark disconnected)'
                    % self._handle)
            else:
                raise BusException(
                    'bus_aadvark_spi.open failed with error code %d' %
                    self._handle)

        aa.aa_gpio_direction(self._handle,
                             int(
                                 evkit_config.get('aardvark_spi',
                                                  'aa_gpio_direction'),
                                 16))  # IO direction

        ## select pullup or floating
        #aa.aa_gpio_pullup(self._handle, aa.AA_GPIO_SCL | aa.AA_GPIO_SDA)             # pullup
        aa.aa_gpio_pullup(
            self._handle,
            int(evkit_config.get('aardvark_spi', 'aa_gpio_pullup'), 16))

        aa.aa_configure(self._handle,
                        aa.AA_CONFIG_SPI_GPIO)  # SPI subsystem is enabled

        aa.aa_target_power(
            self._handle,
            self._aa_target_power[evkit_config.get('aardvark_spi',
                                                   'aa_target_power')])

        aa.aa_spi_configure(
            self._handle, self._cpol, self._cpha,
            self._bitorder[evkit_config.get('spi', 'bitorder')])

        aa.aa_spi_master_ss_polarity(
            self._handle,
            self._ss_polarity[evkit_config.get('spi', 'ss_polarity')])

        requested = self._bitrate
        self._bitrate = aa.aa_spi_bitrate(self._handle,
                                          self._bitrate)  # Set the bitrate

        if requested != self._bitrate:
            logger.warning(
                "Warning Bitrate set to %d kHz. Wanted to set %d kHz" %
                (self._bitrate, requested))
def open_bus_or_exit(sensor, skip_board_init=False):
    # FIXME remove this function.
    try:
        bus = setup_default_connection(sensor=sensor,
                                       skip_board_init=skip_board_init)

    except Exception, e:
        if str(e) == 'Bus not assigned to sensor.':
            logger.error(e)
        else:
            logger.critical(e)

        logger.warning('Try again.')
        raise
        exit()
    def __init__(self, aadvark_index=None):
        _i2c_bus.__init__(self)
        self.bus_gpio_list = [1, 2]
        self._has_gpio = True
        self._handle = None
        self._bitrate = None

        if not aardvark_found:
            raise BusException('Aardvark libraries not found/installed.')

        (num, ports, unique_ids) = aa.aa_find_devices_ext(16, 16)
        if (num == 0):
            raise BusException('Aardvark i2c/spi host adapter not connected.')
        elif (num == -2):
            raise BusException(
                'Aardvark i2c/spi host adapter never connected.')
        else:
            self._ports = ports[0]
            if (num > 1):
                logger.warning(
                    'More that 1 Aardvark ports found. Selecting 1st one.')
    def __init__(self):
        _spi_bus.__init__(self)
        self.bus_gpio_list = [1, 2]
        self._has_gpio = True
        self._handle = None
        self._bitrate = None

        if not aardvark_found:
            raise BusException('Aardvark libraries not found/installed.')

        (num, ports, unique_ids) = aa.aa_find_devices_ext(16, 16)
        if (num == 0):
            raise BusException('Aardvark i2c/spi host adapter not connected.')
        elif (num == -2):
            raise BusException(
                'Aardvark i2c/spi host adapter never connected.')
        else:
            self._ports = ports[0]
            if (num > 1):
                logger.warning(
                    'More that 1 Aardvark ports found. Selecting 1st one.')

        self.MASKR = int(evkit_config.get('spi', 'maskr'),
                         2)  # SPI's read address mask
        sensor.set_default_on()
        #sensor.register_dump()

        timing.reset()

        for t in range(10):
            print t,sensor.read_data()

            # wait for new data
            ## todo use definition from settings.cfg
            try:
                sensor.drdy_function()
            except NotImplementedError:
                time.sleep(0.1)
                pass

        print 'Data received at %0.2fHz' % ( 10.0 / timing.time_elapsed())

    except Exception, e:
        print 'Exception received',e

    finally:
        sensor.set_power_off()


if __name__ == '__main__':
    if evkit_config.get('generic', 'drdy_operation') != 'INTERVAL_READ':
        logger.warning('***** drdy_operation != INTERVAL_READ. If interrupts not configured properly then data is not received')

    test_default()
Ejemplo n.º 7
0
    def read_data_stream(self,
                         loop=None,
                         console=True,
                         log_file_name=None,
                         callback=None,
                         max_timeout_count=0,
                         additional_info=None):

        # set max_timeout_count to None if infinite amount of timeout allowed

        count = 0  # count of received data samples
        timeout_count = 0  # how many timeouts received
        file = None  # handle to file

        # create file object form string or function which generates file name
        if isinstance(log_file_name, types.StringType):
            file = open(log_file_name, 'w')

        # log_file_name is types.FunctionType if providing function which generates file name
        elif isinstance(log_file_name, types.FunctionType):
            file = open(log_file_name(), 'w')

        # subscribe sensor data from FW
        self._start_streaming()
        timing.reset()

        if console:
            print(start_time_str())

        if file:
            file.write(start_time_str() + NEW_LINE)
            if additional_info:
                file.write(
                    '# Additional information = ' + additional_info + NEW_LINE
                )  #optional: more information about the logging setup

        # print out header text, replace text "ch" with channel number
        for channel, request in self.msg_ind_dict.iteritems():
            if console:
                print(request.py_headerstr.replace('ch', str(channel)))

            if file:
                file.write(
                    request.py_headerstr.replace('ch', str(channel)) +
                    NEW_LINE)
        try:
            # main loop for reading the data
            while count < loop or loop is None:
                resp = self.sensor._bus.wait_indication()

                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 BusException(
                            'Timeout when receiving data. Max timeout count reached.'
                        )

                    continue

                # find correct message type to get information how message is interpreted
                # resp[0] has the channel number

                received_messsage_type = self.msg_ind_dict[resp[0]]

                if len(resp) != received_messsage_type.msg_size:
                    logger.warning("Wrong message length %d" % len(resp))
                else:
                    now = timing.time_elapsed()
                    data = struct.unpack(received_messsage_type.msg_fmt, resp)
                    text = '{:.6f}{}'.format(now, DELIMITER)

                    # TODO support for float values
                    text += DELIMITER.join('{:d}'.format(t) for t in data)

                    if console:
                        print(text)

                    if file:
                        file.write(text + NEW_LINE)

                    count += 1

                if callback is not None:
                    # callback function returns False if need to stop reading
                    if callback(data) == 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
            if console:
                print(end_time_str())

            if file:
                file.write(end_time_str() + NEW_LINE)
                file.close()

            # unsibscribe data from FW
            self._stop_streaming()

            if count == 0:
                logger.error("No stream data received.")
def setup_default_connection(sensor=None, skip_board_init=False):
    # This will create connection using connection defined in settings.cfg
    bus_index_dict = {
        1: setup_aardvark_i2c,
        2: setup_aardvark_spi,
        3: setup_socket_i2c,
        4: setup_linux_i2c,
        5: setup_socket_adb_i2c,
        6: setup_serial_i2c,
        7: setup_linux_ble,
        8: setup_raspberry_socket,
    }

    logger.debug('Python {}'.format(sys.version))
    bus_index = evkit_config.get('connection', 'bus_index')
    if bus_index.startswith('serial_com'):
        evkit_config.remove_section('__com__')
        evkit_config.add_section('__com__')
        evkit_config.set('__com__', 'config', bus_index)
        logger.info('Bus %s selected', bus_index)
        bus_index = 6
    else:
        bus_index = int(bus_index)
        logger.info('Bus index %d selected', bus_index)

    bus = bus_index_dict[bus_index](sensor)

    if not skip_board_init:
        ## Sensors in Kionix IoT node must be initialized to active low
        if evkit_config.get('connection', 'bus_index') in [
                '3', '5', '7', 'serial_com_kx_iot'
        ]:
            # FIXME nRF51-DK + BLE will cause board init, it is not needed

            logger.info('Kionix  IoT node init start')

            # FIXME add-on board detection with 1.4 firmware or later
            #addon_board = bus.gpio_read(8) # check if addon board is connected
            #if addon_board:
            #    print "Add-on board found"
            addon_board = True  # FIXME remove this for firmware 1.4 and later

            # FIXME do HW board config functionality and move this functionality there

            if evkit_config.get('generic', 'int1_active_high')!='FALSE' or \
               evkit_config.get('generic', 'int2_active_high')!='FALSE':
                logger.warning(
                    'Kionix IoT Board requires active low interrupts. Please update settings.cfg'
                )

            import kxg03
            from kxg03 import kxg03_driver
            kxg03 = kxg03_driver.kxg03_driver()
            if (bus.probe_sensor(kxg03)):
                logger.debug('Reset KXG03 and set interrupt to active low')
                kxg03.por()

                ## KXG03 inital settings for Kionix IoT Board
                kxg03.set_interrupt_polarity(intpin=1, polarity=ACTIVE_LOW)
                kxg03.set_interrupt_polarity(intpin=2, polarity=ACTIVE_LOW)

            from kxg08 import kxg08_driver
            kxg08 = kxg08_driver.kxg08_driver()
            if (bus.probe_sensor(kxg08)):
                logger.debug('Reset KXG07/08 and set interrupt to active low')
                kxg08.por()

                ## KXG08 inital settings for Kionix IoT Board
                kxg08.set_interrupt_polarity(intpin=1, polarity=ACTIVE_LOW)
                kxg08.set_interrupt_polarity(intpin=2, polarity=ACTIVE_LOW)

            from kx022_kx122 import kx022_driver
            kx122 = kx022_driver.kx022_driver()
            if (bus.probe_sensor(kx122)):
                logger.debug('Reset KX122 set interrupt to active low')
                kx122.por()

                ## KX122 inital settings for Kionix IoT Board
                kx122.set_interrupt_polarity(intpin=1, polarity=ACTIVE_LOW)
                kx122.set_interrupt_polarity(intpin=2, polarity=ACTIVE_LOW)

            from kx126 import kx126_driver
            kx126 = kx126_driver.kx126_driver()
            if (bus.probe_sensor(kx126)):
                logger.debug('Reset KX126 and set interrupt to active low')
                kx126.por()

                #KX126 inital settings for Kionix IoT Board
                kx126.set_interrupt_polarity(intpin=1, polarity=ACTIVE_LOW)
                kx126.set_interrupt_polarity(intpin=2, polarity=ACTIVE_LOW)

            from bm1383aglv import bm1383aglv_driver
            bm1383aglv = bm1383aglv_driver.bm1383aglv_driver()
            if (bus.probe_sensor(bm1383aglv)):
                logger.debug(
                    'Reset BM1383AGLV on main board and set interrupt to active low'
                )
                bm1383aglv.por()

            ## sensor components on add-on boards, set needed settings for them
            if addon_board:
                # setup all found add-on board sensors
                # NOTE: List of supported add-on sensors is located in import_addon_board_sensors - function
                for addon_board_sensor_module, addon_board_sensor in import_addon_board_sensors(
                        False):
                    if bus.probe_sensor(addon_board_sensor):
                        addon_board_sensor.por()  # common por for all sensors

                        if addon_board_sensor.name.startswith('kxtj3'):
                            logger.debug(
                                'Reset KXTJ3 on add-on board and set interrupt to active low'
                            )

                            ## KXTJ3 initial settings for Kionix IoT/Add-on Board
                            addon_board_sensor.reset_bit(
                                addon_board_sensor_module.r.
                                KXTJ3_INT_CTRL_REG1, addon_board_sensor_module.
                                b.KXTJ3_INT_CTRL_REG1_IEA)  # active low
                        elif addon_board_sensor.name.startswith('kx03a'):
                            logger.debug(
                                'Reset KX03A on add-on board and set interrupt to active low'
                            )

                            ## KX03A initial settings for Kionix IoT/Add-on Board
                            addon_board_sensor.reset_bit(
                                addon_board_sensor_module.r.KX03A_INC1,
                                addon_board_sensor_module.b.
                                KX03A_INC1_DRDY_POL_ACTIVE_HIGH)  # active low
                            addon_board_sensor.reset_bit(
                                addon_board_sensor_module.r.KX03A_INC1,
                                addon_board_sensor_module.b.
                                KX03A_INC1_INT_POL_ACTIVE_HIGH)  # active low
                        else:
                            logger.debug(
                                'Reset %s and set interrupt to active low' %
                                addon_board_sensor.name)

                            ## initial settings for Kionix IoT/Add-on Board
                            addon_board_sensor.set_interrupt_polarity(
                                intpin=1,
                                polarity=ACTIVE_LOW)  # active low int1
                            addon_board_sensor.set_interrupt_polarity(
                                intpin=2,
                                polarity=ACTIVE_LOW)  # active low int2

            logger.info('Kionix  IoT board init done')

    return bus