Exemplo n.º 1
0
 def _start_streaming(self):
     # send stream start requests to FW
     logger.debug(">Enable interrupt request")
     for request in self.request_message_list:
         resp = self.sensor._bus.enable_interrupt(*request.msg_req)
         self.msg_ind_dict[resp] = request
     logger.debug("<Enable interrupt request")
Exemplo n.º 2
0
    def _stop_streaming(self):

        logger.debug(">Disable interrupt request")

        self.sensor._bus._flush_input()

        # send stream stop requests to FW in reversed order
        for request in reversed(self.request_message_list):
            self.sensor._bus.disable_interrupt(request.gpio_pin)

        self.sensor._bus._flush_input()

        logger.debug("<Disable interrupt request")
Exemplo n.º 3
0
 def write_interrupt_tresholds(self, treshold_low, treshold_high):
     """
     :param uint16 threshold_low, uint16 threshold_high
     """
     if not ((treshold_high >= 0) and (treshold_high < 2**16)):
         logger.debug("treshold_high value out of bounds.")
         raise TypeError
     if not ((treshold_low >= 0) and (treshold_low < 2**16)):
         logger.debug("treshold_low value out of bounds.")
         raise TypeError
     thl = (treshold_high & 0xff)
     thh = (treshold_high >> 8) & 0xff
     tll = (treshold_low & 0xff)
     tlh = (treshold_low >> 8) & 0xff
     self.write_register(r.BH1749_TH_LSBS, thl)
     self.write_register(r.BH1749_TH_MSBS, thh)
     self.write_register(r.BH1749_TL_LSBS, tll)
     self.write_register(r.BH1749_TL_MSBS, tlh)
     return
Exemplo n.º 4
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