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(TrhphDriverState.UNCONFIGURED) config = kwargs.get('config', None) if config is None: # raise InstrumentParameterException(msg="'config' parameter required") config = args[0] # Verify dict and construct connection client. try: addr = config['addr'] port = config['port'] if isinstance(addr, str) and \ isinstance(port, int) and len(addr) > 0: # self._connection = LoggerClient(addr, port) def _data_listener(sample): log.info("_data_listener: sample = %s" % str(sample)) host = addr outfile = file('trhph_output.txt', 'a') log.info("setting TrhphClient to connect to %s:%s" % (host, port)) self.trhph_client = TrhphClient(host, port, outfile, True) self.trhph_client.set_data_listener(_data_listener) else: raise InstrumentParameterException( msg='Invalid comms config dict') except (TypeError, KeyError): raise InstrumentParameterException( msg='Invalid comms config dict.') self._state = TrhphDriverState.DISCONNECTED
def setUp(self): """ Sets up and connects the _client. """ TrhphClientTest._end_client_if_any() super(TrhphClientTest, self).setUp() host = self.device_address port = self.device_port self._samples_recd = 0 outfile = file('trhph_output.txt', 'a') prefix_state = True _client = TrhphClient(host, port, outfile, prefix_state) # set the class and instance variables to refer to this object: TrhphClientTest._trhph_client = self._client = _client # prepare client including going to the main menu _client.set_data_listener(self._data_listener) _client.set_generic_timeout(self._timeout) log.info("connecting") _client.connect()
def setUp(self): """ Sets up and connects the _client. """ TrhphClientTest._end_client_if_any() super(TrhphClientTest, self).setUp() host = self.device_address port = self.device_port self._samples_recd = 0 outfile = file("trhph_output.txt", "a") prefix_state = True _client = TrhphClient(host, port, outfile, prefix_state) # set the class and instance variables to refer to this object: TrhphClientTest._trhph_client = self._client = _client # prepare client including going to the main menu _client.set_data_listener(self._data_listener) _client.set_generic_timeout(self._timeout) log.info("connecting") _client.connect()
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(TrhphDriverState.UNCONFIGURED) config = kwargs.get('config', None) if config is None: # raise InstrumentParameterException(msg="'config' parameter required") config = args[0] # Verify dict and construct connection client. try: addr = config['addr'] port = config['port'] if isinstance(addr, str) and \ isinstance(port, int) and len(addr) > 0: # self._connection = LoggerClient(addr, port) def _data_listener(sample): log.info("_data_listener: sample = %s" % str(sample)) host = addr outfile = file('trhph_output.txt', 'a') log.info("setting TrhphClient to connect to %s:%s" % (host, port)) self.trhph_client = TrhphClient(host, port, outfile, True) self.trhph_client.set_data_listener(_data_listener) else: raise InstrumentParameterException(msg='Invalid comms config dict') except (TypeError, KeyError): raise InstrumentParameterException(msg='Invalid comms config dict.') self._state = TrhphDriverState.DISCONNECTED
class TrhphInstrumentDriver(InstrumentDriver): """ TRHPH driver """ def __init__(self, evt_callback): """ Constructor. @param evt_callback Driver process event callback. """ InstrumentDriver.__init__(self, evt_callback) # _trhph_client created in configure() self._trhph_client = None self._state = TrhphDriverState.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)) ############################################################# # 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 """ # print # print("trhph driver: args=%s kwargs=%s" % (str(args), str(kwargs))) # print("trhph driver: state=%s" % str(self._state)) # print("trhph driver: _trhph_client=%s" % str(self._trhph_client)) # print if log.isEnabledFor(logging.DEBUG): log.debug("args=%s kwargs=%s" % (str(args), str(kwargs))) if self._state == TrhphDriverState.UNCONFIGURED: assert self._trhph_client is None return # assert self._trhph_client is not None # try: # self._trhph_client.end() # finally: # self._trhph_client = None if self._trhph_client is not None: try: self._trhph_client.end() finally: self._trhph_client = None self._state = TrhphDriverState.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(TrhphDriverState.UNCONFIGURED) config = kwargs.get("config", None) if config is None: # raise InstrumentParameterException(msg="'config' parameter required") config = args[0] # Verify dict and construct connection client. try: addr = config["addr"] port = config["port"] if isinstance(addr, str) and isinstance(port, int) and len(addr) > 0: # self._connection = LoggerClient(addr, port) def _data_listener(sample): log.info("_data_listener: sample = %s" % str(sample)) host = addr outfile = file("trhph_output.txt", "a") log.info("setting TrhphClient to connect to %s:%s" % (host, port)) self.trhph_client = TrhphClient(host, port, outfile, True) self.trhph_client.set_data_listener(_data_listener) else: raise InstrumentParameterException(msg="Invalid comms config dict") except (TypeError, KeyError): raise InstrumentParameterException(msg="Invalid comms config dict.") self._state = TrhphDriverState.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(TrhphDriverState.DISCONNECTED) self.trhph_client.connect() self._state = TrhphDriverState.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(TrhphDriverState.CONNECTED) self.trhph_client.end() self._state = TrhphDriverState.DISCONNECTED ############################################################# # Command and control interface. ############################################################# def get(self, *args, **kwargs): """ Retrieve device parameters. @param params DriverParameter.ALL or a list of parameters to retrieve. @param timeout Timeout for each involved instrument interation, self._timeout by default. @retval parameter : value dict. @raises InstrumentParameterException if missing or invalid get parameters. @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(TrhphDriverState.CONNECTED) params = kwargs.get("params", None) if params is None: # raise InstrumentParameterException(msg= # "'params' parameter required") params = args[0] if params == DriverParameter.ALL: params = TrhphParameter.list() elif not isinstance(params, (list, tuple)): raise InstrumentParameterException(msg="params must be list or tuple.") timeout = kwargs.get("timeout", self._timeout) # gather data collection params if any of them are requested: data_collec_params = {} if TrhphParameter.TIME_BETWEEN_BURSTS in params or TrhphParameter.VERBOSE_MODE in params: seconds, is_data_only = self._get_data_collection_params(timeout) verbose = not is_data_only data_collec_params[TrhphParameter.TIME_BETWEEN_BURSTS] = seconds data_collec_params[TrhphParameter.VERBOSE_MODE] = verbose params = list(set(params)) # remove any duplicates result = {} for param in params: if param == TrhphParameter.TIME_BETWEEN_BURSTS or param == TrhphParameter.VERBOSE_MODE: value = data_collec_params[param] else: # value = InstErrorCode.INVALID_PARAMETER raise InstrumentParameterException(msg="invalid parameter %s" % param) result[param] = value return result def _get_data_collection_params(self, timeout): """ Gets the get_data_collection_params. """ try: return self.trhph_client.get_data_collection_params(timeout) except TimeoutException, e: raise InstrumentTimeoutException(msg=str(e)) except TrhphClientException, e: raise InstrumentException(str(e))
class TrhphInstrumentDriver(InstrumentDriver): """ TRHPH driver """ def __init__(self, evt_callback): """ Constructor. @param evt_callback Driver process event callback. """ InstrumentDriver.__init__(self, evt_callback) # _trhph_client created in configure() self._trhph_client = None self._state = TrhphDriverState.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)) ############################################################# # 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 """ # print # print("trhph driver: args=%s kwargs=%s" % (str(args), str(kwargs))) # print("trhph driver: state=%s" % str(self._state)) # print("trhph driver: _trhph_client=%s" % str(self._trhph_client)) # print if log.isEnabledFor(logging.DEBUG): log.debug("args=%s kwargs=%s" % (str(args), str(kwargs))) if self._state == TrhphDriverState.UNCONFIGURED: assert self._trhph_client is None return # assert self._trhph_client is not None # try: # self._trhph_client.end() # finally: # self._trhph_client = None if self._trhph_client is not None: try: self._trhph_client.end() finally: self._trhph_client = None self._state = TrhphDriverState.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(TrhphDriverState.UNCONFIGURED) config = kwargs.get('config', None) if config is None: # raise InstrumentParameterException(msg="'config' parameter required") config = args[0] # Verify dict and construct connection client. try: addr = config['addr'] port = config['port'] if isinstance(addr, str) and \ isinstance(port, int) and len(addr) > 0: # self._connection = LoggerClient(addr, port) def _data_listener(sample): log.info("_data_listener: sample = %s" % str(sample)) host = addr outfile = file('trhph_output.txt', 'a') log.info("setting TrhphClient to connect to %s:%s" % (host, port)) self.trhph_client = TrhphClient(host, port, outfile, True) self.trhph_client.set_data_listener(_data_listener) else: raise InstrumentParameterException( msg='Invalid comms config dict') except (TypeError, KeyError): raise InstrumentParameterException( msg='Invalid comms config dict.') self._state = TrhphDriverState.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(TrhphDriverState.DISCONNECTED) self.trhph_client.connect() self._state = TrhphDriverState.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(TrhphDriverState.CONNECTED) self.trhph_client.end() self._state = TrhphDriverState.DISCONNECTED ############################################################# # Command and control interface. ############################################################# def get_resource(self, *args, **kwargs): """ Retrieve device parameters. @param params DriverParameter.ALL or a list of parameters to retrieve. @param timeout Timeout for each involved instrument interation, self._timeout by default. @retval parameter : value dict. @raises InstrumentParameterException if missing or invalid get parameters. @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(TrhphDriverState.CONNECTED) params = kwargs.get('params', None) if params is None: # raise InstrumentParameterException(msg= # "'params' parameter required") params = args[0] if params == DriverParameter.ALL: params = TrhphParameter.list() elif not isinstance(params, (list, tuple)): raise InstrumentParameterException( msg='params must be list or tuple.') timeout = kwargs.get('timeout', self._timeout) # gather data collection params if any of them are requested: data_collec_params = {} if TrhphParameter.TIME_BETWEEN_BURSTS in params or \ TrhphParameter.VERBOSE_MODE in params: seconds, is_data_only = self._get_data_collection_params(timeout) verbose = not is_data_only data_collec_params[TrhphParameter.TIME_BETWEEN_BURSTS] = seconds data_collec_params[TrhphParameter.VERBOSE_MODE] = verbose params = list(set(params)) # remove any duplicates result = {} for param in params: if param == TrhphParameter.TIME_BETWEEN_BURSTS or \ param == TrhphParameter.VERBOSE_MODE: value = data_collec_params[param] else: # value = InstErrorCode.INVALID_PARAMETER raise InstrumentParameterException(msg='invalid parameter %s' % param) result[param] = value return result def _get_data_collection_params(self, timeout): """ Gets the get_data_collection_params. """ try: return self.trhph_client.get_data_collection_params(timeout) except TimeoutException, e: raise InstrumentTimeoutException(msg=str(e)) except TrhphClientException, e: raise InstrumentException(str(e))