Exemplo n.º 1
0
    def setUpClass(cls):
        """
        Sets up _conn_config, _timeout, according to environment variables.
        """

        cls._skip_reason = None

        #
        # cls._conn_config
        #
        cls._conn_config = None
        vadcp = os.getenv('VADCP')
        if vadcp:
            filename = vadcp
            log.info("loading connection params from '%s'" % filename)
            try:
                f = open(filename)
                yml = yaml.load(f)
                f.close()

                def create_unit_conn_config(yml):
                    return AdcpUnitConnConfig(yml.get('host'),
                                              yml.get('port'),
                                              yml.get('ooi_digi_host'),
                                              yml.get('ooi_digi_port'))

                cls._conn_config = {
                    'four_beam': create_unit_conn_config(yml['four_beam']),
                    'fifth_beam': create_unit_conn_config(yml['fifth_beam'])
                }
            except Exception, e:
                cls._skip_reason = "Problem with connection config file: '%s': %s" % (
                                    filename, str(e))
                log.warn(cls._skip_reason)
    def end(self):
        """
        Ends the client.
        """
        if self._sock is None:
            log.warn("end() called again")
            return

        log.info("closing connection")
        try:
            if self._rt:
                self._rt.end()
#            self._sock.shutdown(socket.SHUT_RDWR)
            self._sock.close()
#            log.info("socket shutdown and closed")
            log.info("socket closed")
        finally:
            self._sock = None
Exemplo n.º 3
0
    def end(self):
        """
        Ends the client.
        """
        if self._sock is None:
            log.warn("end() called again")
            return

        log.info("closing connection")
        try:
            if self._rt:
                self._rt.end()


#            self._sock.shutdown(socket.SHUT_RDWR)
            self._sock.close()
            #            log.info("socket shutdown and closed")
            log.info("socket closed")
        finally:
            self._sock = None
Exemplo n.º 4
0
        #
        # cls._vadcp_unit
        #
        cls._vadcp_unit = os.getenv('VADCP_UNIT', 'four_beam')
        log.info("_adcp_unit set to: %s" % cls._vadcp_unit)

        #
        # cls._timeout
        #
        cls._timeout = 30
        timeout_str = os.getenv('timeout')
        if timeout_str:
            try:
                cls._timeout = int(timeout_str)
            except:
                log.warn("Malformed timeout environment variable value '%s'",
                         timeout_str)
        log.info("Generic timeout set to: %d" % cls._timeout)

    @classmethod
    def tearDownClass(self):
        ReceiverBuilder.use_default()

    def setUp(self):
        """
        """

        if self._skip_reason:
            self.skipTest(self._skip_reason)

        log.info("== VADCP _conn_config: %s" % self._conn_config)
Exemplo n.º 5
0
class VadcpProtocol(CommandResponseInstrumentProtocol):
    """
    """
    def __init__(self, callback=None):
        CommandResponseInstrumentProtocol.__init__(self, Prompt, EOLN,
                                                   callback)

        # TODO probably promote this convenience to super-class?
        # _timeout: Default timeout value for operations accepting an
        # optional timeout argument
        self._timeout = 30

        self._last_data_timestamp = None
        self.eoln = EOLN

        self._protocol_fsm = InstrumentFSM(ProtocolState, ProtocolEvent, None,
                                           None)

        # UNKNOWN
        self._protocol_fsm.add_handler(ProtocolState.UNKNOWN,
                                       ProtocolEvent.INITIALIZE,
                                       self._handler_initialize)

        # COMMAND_MODE
        self._protocol_fsm.add_handler(ProtocolState.COMMAND_MODE,
                                       ProtocolEvent.GET_LAST_ENSEMBLE,
                                       self._handler_command_get_latest_sample)
        self._protocol_fsm.add_handler(ProtocolState.COMMAND_MODE,
                                       ProtocolEvent.GET_METADATA,
                                       self._handler_command_get_metadata)
        self._protocol_fsm.add_handler(
            ProtocolState.COMMAND_MODE, ProtocolEvent.RUN_RECORDER_TESTS,
            self._handler_command_run_recorder_tests)
        self._protocol_fsm.add_handler(ProtocolState.COMMAND_MODE,
                                       ProtocolEvent.RUN_ALL_TESTS,
                                       self._handler_command_run_all_tests)
        self._protocol_fsm.add_handler(ProtocolState.COMMAND_MODE,
                                       ProtocolEvent.START_AUTOSAMPLE,
                                       self._handler_command_autosample)

        # AUTOSAMPLE_MODE
        self._protocol_fsm.add_handler(ProtocolState.AUTOSAMPLE_MODE,
                                       ProtocolEvent.STOP_AUTOSAMPLE,
                                       self._handler_autosample_stop)

        self._protocol_fsm.start(ProtocolState.UNKNOWN)

    def execute_init_protocol(self, *args, **kwargs):
        """
        """
        return self._protocol_fsm.on_event(ProtocolEvent.INITIALIZE, *args,
                                           **kwargs)

    def execute_get_latest_sample(self, *args, **kwargs):
        """
        """
        return self._protocol_fsm.on_event(ProtocolEvent.GET_LAST_ENSEMBLE,
                                           *args, **kwargs)

    def execute_get_metadata(self, *args, **kwargs):
        """
        """
        return self._protocol_fsm.on_event(ProtocolEvent.GET_METADATA, *args,
                                           **kwargs)

    def execute_run_recorder_tests(self, *args, **kwargs):
        """
        """
        return self._protocol_fsm.on_event(ProtocolEvent.RUN_RECORDER_TESTS,
                                           *args, **kwargs)

    def execute_run_all_tests(self, *args, **kwargs):
        """
        """
        return self._protocol_fsm.on_event(ProtocolEvent.RUN_ALL_TESTS, *args,
                                           **kwargs)

    ################
    # State handlers
    ################

    def _handler_initialize(self, *args, **kwargs):
        """
        Determines initial protocol state according to instrument's state
        """
        next_state = None
        result = None

        # TODO determine the state. For now, assume command mode

        self._driver_event(DriverAsyncEvent.STATE_CHANGE)
        next_state = ProtocolState.COMMAND_MODE

        return (next_state, result)

    def _handler_command_get_latest_sample(self, *args, **kwargs):
        """
        """
        if log.isEnabledFor(logging.DEBUG):
            log.debug("args=%s kwargs=%s" % (str(args), str(kwargs)))

        next_state = self._protocol_fsm.get_current_state()
        result = None

        timeout = kwargs.get('timeout', self._timeout)

        try:
            result = self._connection.get_latest_sample(timeout)
        except TimeoutException, e:
            raise InstrumentTimeoutException(msg=str(e))
        except ClientException, e:
            log.warn("ClientException while get_latest_sample: %s" % str(e))
            raise InstrumentException('ClientException: %s' % str(e))
Exemplo n.º 6
0
        """
        if log.isEnabledFor(logging.DEBUG):
            log.debug("args=%s kwargs=%s" % (str(args), str(kwargs)))

        next_state = self._protocol_fsm.get_current_state()
        result = None

        timeout = kwargs.get('timeout', self._timeout)
        sections = kwargs.get('sections', None)

        try:
            result = self._connection.get_metadata(sections, timeout)
        except TimeoutException, e:
            raise InstrumentTimeoutException(msg=str(e))
        except ClientException, e:
            log.warn("ClientException while get_metadata: %s" % str(e))
            raise InstrumentException('ClientException: %s' % str(e))

        return (next_state, result)

    def _handler_command_run_recorder_tests(self, *args, **kwargs):
        """
        """
        if log.isEnabledFor(logging.DEBUG):
            log.debug("args=%s kwargs=%s" % (str(args), str(kwargs)))

        next_state = self._protocol_fsm.get_current_state()
        result = None

        timeout = kwargs.get('timeout', self._timeout)
Exemplo n.º 7
0
    def execute_get_metadata(self, *args, **kwargs):
        if log.isEnabledFor(logging.DEBUG):
            log.debug("args=%s kwargs=%s" % (str(args), str(kwargs)))

        self._assert_state(DriverState.CONNECTED)

        timeout = kwargs.get('timeout', self._timeout)
        sections = kwargs.get('sections', None)

        try:
            result = self._client.get_metadata(sections, timeout)
            return result
        except TimeoutException, e:
            raise InstrumentTimeoutException(msg=str(e))
        except ClientException, e:
            log.warn("ClientException while get_metadata: %s" %
                     str(e))
            raise InstrumentException('ClientException: %s' % str(e))

    def execute_run_recorder_tests(self, *args, **kwargs):
        if log.isEnabledFor(logging.DEBUG):
            log.debug("args=%s kwargs=%s" % (str(args), str(kwargs)))

        self._assert_state(DriverState.CONNECTED)

        timeout = kwargs.get('timeout', self._timeout)

        try:
            result = self._client.run_recorder_tests(timeout)
            return result
        except TimeoutException, e:
            raise InstrumentTimeoutException(msg=str(e))
Exemplo n.º 8
0
class VadcpDriver(InstrumentDriver):
    """
    driver
    """
    def __init__(self, evt_callback):
        """
        Constructor.

        @param evt_callback Driver process event callback.
        """
        InstrumentDriver.__init__(self, evt_callback)

        self._ensembles_recd = 0

        # _client created in configure()
        self._client = None

        self._state = DriverState.UNCONFIGURED

        # TODO probably promote this convenience to super-class?
        self._timeout = 30
        """Default timeout value for operations accepting an optional timeout
        argument."""

    def _assert_state(self, obj):
        """
        Asserts that the current state is either the same as the one given (if
        not a list) or one of the elements of the given list.

        @raises InstrumentStateException if the assertion fails
        """
        cs = self.get_current_state()
        if isinstance(obj, list):
            if cs in obj:
                return  # OK
            else:
                raise InstrumentStateException(
                    msg="current state=%s not one of %s" % (cs, str(obj)))
        state = obj
        if cs != state:
            raise InstrumentStateException("current state=%s, expected=%s" %
                                           (cs, state))

    def _data_listener(self, pd0):
        self._ensembles_recd += 1
        log.info("_data_listener: received PD0=%s" % prefix(pd0))
        self._driver_event(DriverAsyncEvent.SAMPLE, val=pd0)

    #############################################################
    # Device connection interface.
    #############################################################

    def initialize(self, *args, **kwargs):
        """
        Initialize driver connection, bringing communications parameters
        into unconfigured state (no connection object).

        @raises InstrumentStateException if command not allowed in current
                 state
        """

        if log.isEnabledFor(logging.DEBUG):
            log.debug("args=%s kwargs=%s" % (str(args), str(kwargs)))

        if self._state == DriverState.UNCONFIGURED:
            assert self._client is None
            return

        if self._client is not None:
            try:
                self._client.end()
            finally:
                self._client = None

        self._driver_event(DriverAsyncEvent.STATE_CHANGE)
        self._state = DriverState.UNCONFIGURED

    def configure(self, *args, **kwargs):
        """
        Configure the driver for communications with the device via
        port agent / logger (valid but unconnected connection object).

        @param config comms config dict.

        @raises InstrumentStateException if command not allowed in current
                state
        @throws InstrumentParameterException if missing comms or invalid
                config dict.
        """

        if log.isEnabledFor(logging.DEBUG):
            log.debug("args=%s kwargs=%s" % (str(args), str(kwargs)))

        self._assert_state(DriverState.UNCONFIGURED)

        config = kwargs.get('config', None)
        if config is None:
            #            raise InstrumentParameterException(msg="'config' parameter required")
            config = args[0]

        c4 = config['four_beam']
        outfilename = 'vadcp_output_%s_%s.txt' % (c4.host, c4.port)
        u4_outfile = file(outfilename, 'w')
        c5 = config['fifth_beam']
        outfilename = 'vadcp_output_%s_%s.txt' % (c5.host, c5.port)
        u5_outfile = file(outfilename, 'w')

        # Verify dict and construct connection client.
        log.info("setting VadcpClient with config: %s" % config)
        try:
            self._client = VadcpClient(config, u4_outfile, u5_outfile)
        except (TypeError, KeyError):
            raise InstrumentParameterException('Invalid comms config dict.'
                                               ' config=%s' % config)

        self._driver_event(DriverAsyncEvent.STATE_CHANGE)
        self._state = DriverState.DISCONNECTED

    def connect(self, *args, **kwargs):
        """
        Establish communications with the device via port agent / logger
        (connected connection object).

        @raises InstrumentStateException if command not allowed in current
                state
        @throws InstrumentConnectionException if the connection failed.
        """

        if log.isEnabledFor(logging.DEBUG):
            log.debug("args=%s kwargs=%s" % (str(args), str(kwargs)))

        self._assert_state(DriverState.DISCONNECTED)

        self._client.set_data_listener(self._data_listener)
        self._client.connect()

        self._driver_event(DriverAsyncEvent.STATE_CHANGE)
        self._state = DriverState.CONNECTED

    def disconnect(self, *args, **kwargs):
        """
        Disconnect from device via port agent / logger.
        @raises InstrumentStateException if command not allowed in current
                state
        """

        if log.isEnabledFor(logging.DEBUG):
            log.debug("args=%s kwargs=%s" % (str(args), str(kwargs)))

        self._assert_state(DriverState.CONNECTED)

        self._client.end()

        self._driver_event(DriverAsyncEvent.STATE_CHANGE)
        self._state = DriverState.DISCONNECTED

    def execute_init_protocol(self, *args, **kwargs):
        # added here as part of the preparation using the general scheme
        # TODO
        pass

    def execute_get_latest_sample(self, *args, **kwargs):
        if log.isEnabledFor(logging.DEBUG):
            log.debug("args=%s kwargs=%s" % (str(args), str(kwargs)))

        self._assert_state(DriverState.CONNECTED)

        timeout = kwargs.get('timeout', self._timeout)

        try:
            result = self._client.get_latest_sample(timeout)
            return result
        except TimeoutException, e:
            raise InstrumentTimeoutException(msg=str(e))
        except ClientException, e:
            log.warn("ClientException while get_latest_sample: %s" % str(e))
            raise InstrumentException('ClientException: %s' % str(e))