本文整理汇总了Python中mi.core.instrument.protocol_param_dict.ProtocolParameterDict.get方法的典型用法代码示例。如果您正苦于以下问题:Python ProtocolParameterDict.get方法的具体用法?Python ProtocolParameterDict.get怎么用?Python ProtocolParameterDict.get使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类mi.core.instrument.protocol_param_dict.ProtocolParameterDict
的用法示例。
在下文中一共展示了ProtocolParameterDict.get方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: test_get
# 需要导入模块: from mi.core.instrument.protocol_param_dict import ProtocolParameterDict [as 别名]
# 或者: from mi.core.instrument.protocol_param_dict.ProtocolParameterDict import get [as 别名]
def test_get(self):
"""
test getting values with expiration
"""
# from mi.core.exceptions import InstrumentParameterExpirationException
pd = ProtocolParameterDict()
# No expiration, should work just fine
pd.add('noexp', r'', None, None, expiration=None)
pd.add('zeroexp', r'', None, None, expiration=0)
pd.add('lateexp', r'', None, None, expiration=2)
###
# Set and get with no expire
###
pd.set_value('noexp', 1)
self.assertEqual(pd.get('noexp'), 1)
###
# Set and get with a 0 expire
###
basetime = pd.get_current_timestamp()
pd.set_value('zeroexp', 2)
# We should fail because we are calculating exp against current time
with self.assertRaises(InstrumentParameterExpirationException):
pd.get('zeroexp')
# Should succeed because exp is calculated using basetime
self.assertEqual(pd.get('zeroexp', basetime), 2)
###
# Set and get with a delayed expire
###
basetime = pd.get_current_timestamp()
futuretime = pd.get_current_timestamp(3)
self.assertGreater(futuretime - basetime, 3)
pd.set_value('lateexp', 2)
# Success because data is not expired
self.assertEqual(pd.get('lateexp', basetime), 2)
# Fail because data is expired (simulated three seconds from now)
with self.assertRaises(InstrumentParameterExpirationException):
pd.get('lateexp', futuretime)
示例2: Protocol
# 需要导入模块: from mi.core.instrument.protocol_param_dict import ProtocolParameterDict [as 别名]
# 或者: from mi.core.instrument.protocol_param_dict.ProtocolParameterDict import get [as 别名]
class Protocol(CommandResponseInstrumentProtocol):
"""
Instrument protocol class
Subclasses CommandResponseInstrumentProtocol
"""
def __init__(self, prompts, newline, driver_event):
"""
Protocol constructor.
@param prompts A BaseEnum class containing instrument prompts.
@param newline The newline.
@param driver_event Driver process event callback.
"""
# Construct protocol superclass.
CommandResponseInstrumentProtocol.__init__(self, prompts, newline, driver_event)
# Build protocol state machine.
self._protocol_fsm = ThreadSafeFSM(ProtocolState, ProtocolEvent, ProtocolEvent.ENTER, ProtocolEvent.EXIT)
# Add event handlers for protocol state machine.
handlers = {
ProtocolState.UNKNOWN: [
(ProtocolEvent.ENTER, self._handler_unknown_enter),
(ProtocolEvent.EXIT, self._handler_unknown_exit),
(ProtocolEvent.DISCOVER, self._handler_unknown_discover),
],
ProtocolState.COMMAND: [
(ProtocolEvent.ENTER, self._handler_command_enter),
(ProtocolEvent.EXIT, self._handler_command_exit),
(ProtocolEvent.START_DIRECT, self._handler_command_start_direct),
(ProtocolEvent.ACQUIRE_SAMPLE, self._handler_sample),
(ProtocolEvent.START_AUTOSAMPLE, self._handler_command_autosample),
(ProtocolEvent.GET, self._handler_get),
(ProtocolEvent.SET, self._handler_command_set),
],
ProtocolState.AUTOSAMPLE: [
(ProtocolEvent.ENTER, self._handler_autosample_enter),
(ProtocolEvent.ACQUIRE_SAMPLE, self._handler_sample),
(ProtocolEvent.STOP_AUTOSAMPLE, self._handler_autosample_stop),
(ProtocolEvent.EXIT, self._handler_autosample_exit),
],
ProtocolState.DIRECT_ACCESS: [
(ProtocolEvent.ENTER, self._handler_direct_access_enter),
(ProtocolEvent.EXIT, self._handler_direct_access_exit),
(ProtocolEvent.EXECUTE_DIRECT, self._handler_direct_access_execute_direct),
(ProtocolEvent.STOP_DIRECT, self._handler_direct_access_stop_direct),
],
}
for state in handlers:
for event, handler in handlers[state]:
self._protocol_fsm.add_handler(state, event, handler)
# Add build handlers for device commands - we are only using simple commands
for cmd in Command.list():
self._add_build_handler(cmd, self._build_command)
self._add_response_handler(cmd, self._check_command)
self._add_build_handler(Command.SETUP, self._build_setup_command)
self._add_response_handler(Command.READ_SETUP, self._read_setup_response_handler)
# Add response handlers for device commands.
# self._add_response_handler(Command.xyz, self._parse_xyz_response)
# Construct the parameter dictionary containing device parameters,
# current parameter values, and set formatting functions.
self._build_param_dict()
self._build_command_dict()
self._build_driver_dict()
self._chunker = StringChunker(Protocol.sieve_function)
# Start state machine in UNKNOWN state.
self._protocol_fsm.start(ProtocolState.UNKNOWN)
self._sent_cmds = None
self.initialize_scheduler()
# unit identifiers - must match the setup command (SU31 - '1')
self._units = ['1', '2', '3']
self._setup = None # set by the read setup command handler for comparison to see if the config needs reset
@staticmethod
def sieve_function(raw_data):
"""
The method that splits samples and status
"""
matchers = []
return_list = []
matchers.append(D1000TemperatureDataParticle.regex_compiled())
for matcher in matchers:
for match in matcher.finditer(raw_data):
return_list.append((match.start(), match.end()))
if not return_list:
log.debug("sieve_function: raw_data=%r, return_list=%s", raw_data, return_list)
return return_list
def _got_chunk(self, chunk, timestamp):
#.........这里部分代码省略.........
示例3: DataSetDriver
# 需要导入模块: from mi.core.instrument.protocol_param_dict import ProtocolParameterDict [as 别名]
# 或者: from mi.core.instrument.protocol_param_dict.ProtocolParameterDict import get [as 别名]
class DataSetDriver(object):
"""
Base class for data set drivers. Provides:
- an interface via callback to publish data
- an interface via callback to persist driver state
- an interface via callback to handle exceptions
- an start and stop sampling
- a client interface for execute resource
Subclasses need to include harvesters and parsers and
be specialized to handle the interaction between the two.
Configurations should contain keys from the DataSetDriverConfigKey class
and should look something like this example (more full documentation in the
"Dataset Agent Architecture" page on the OOI wiki):
{
'harvester':
{
'directory': '/tmp/dsatest',
'pattern': '*.txt',
'frequency': 1,
},
'parser': {}
'driver': {
'records_per_second'
'harvester_polling_interval'
'batched_particle_count'
}
}
"""
def __init__(self, config, memento, data_callback, state_callback, exception_callback):
self._config = config
self._data_callback = data_callback
self._state_callback = state_callback
self._exception_callback = exception_callback
self._memento = memento
self._publisher_thread = None
self._verify_config()
# Updated my set_resource, defaults defined in build_param_dict
self._polling_interval = None
self._generate_particle_count = None
self._particle_count_per_second = None
self._param_dict = ProtocolParameterDict()
self._cmd_dict = ProtocolCommandDict()
self._driver_dict = DriverDict()
self._build_command_dict()
self._build_driver_dict()
self._build_param_dict()
def shutdown(self):
self.stop_sampling()
def start_sampling(self):
"""
Start a new thread to monitor for data
"""
self._start_sampling()
self._start_publisher_thread()
def stop_sampling(self):
"""
Stop the sampling thread
"""
log.debug("Stopping driver now")
self._stop_sampling()
self._stop_publisher_thread()
def _start_sampling(self):
raise NotImplementedException('virtual method needs to be specialized')
def _stop_sampling(self):
raise NotImplementedException('virtual method needs to be specialized')
def _is_sampling(self):
"""
Currently the drivers only have two states, command and streaming and
all resource commands are common, either start or stop autosample.
Therefore we didn't implement an enitre state machine to manage states
and commands. If it does get more complex than this we should take the
time to implement a state machine to add some flexibility
"""
raise NotImplementedException('virtual method needs to be specialized')
def cmd_dvr(self, cmd, *args, **kwargs):
log.warn("DRIVER: cmd_dvr %s", cmd)
if cmd == 'execute_resource':
resource_cmd = args[0]
if resource_cmd == DriverEvent.START_AUTOSAMPLE:
return (ResourceAgentState.STREAMING, None)
elif resource_cmd == DriverEvent.STOP_AUTOSAMPLE:
self.stop_sampling()
return (ResourceAgentState.COMMAND, None)
#.........这里部分代码省略.........
示例4: TestUnitProtocolParameterDict
# 需要导入模块: from mi.core.instrument.protocol_param_dict import ProtocolParameterDict [as 别名]
# 或者: from mi.core.instrument.protocol_param_dict.ProtocolParameterDict import get [as 别名]
class TestUnitProtocolParameterDict(TestUnitStringsDict):
"""
Test cases for instrument driver class. Functions in this class provide
instrument driver unit tests and provide a tutorial on use of
the driver interface.
"""
__test__ = True
@staticmethod
def pick_byte2(input_val):
""" Get the 2nd byte as an example of something tricky and
arbitrary"""
val = int(input_val) >> 8
val &= 255
return val
def setUp(self):
self.param_dict = ProtocolParameterDict()
self.param_dict.add("foo", r'.*foo=(\d+).*',
lambda match: int(match.group(1)),
lambda x: str(x),
direct_access=True,
startup_param=True,
default_value=10,
visibility=ParameterDictVisibility.READ_WRITE)
self.param_dict.add("bar", r'.*bar=(\d+).*',
lambda match: int(match.group(1)),
lambda x: str(x),
direct_access=False,
startup_param=True,
default_value=15,
visibility=ParameterDictVisibility.READ_WRITE)
self.param_dict.add("baz", r'.*baz=(\d+).*',
lambda match: int(match.group(1)),
lambda x: str(x),
direct_access=True,
default_value=20,
visibility=ParameterDictVisibility.DIRECT_ACCESS,
get_timeout=30,
set_timeout=40,
display_name="Baz",
description="The baz parameter",
type=ParameterDictType.INT,
units="nano-bazers",
value_description="Should be an integer between 2 and 2000")
self.param_dict.add("bat", r'.*bat=(\d+).*',
lambda match: int(match.group(1)),
lambda x: str(x),
startup_param=False,
default_value=20,
visibility=ParameterDictVisibility.READ_ONLY,
get_timeout=10,
set_timeout=20,
display_name="Bat",
description="The bat parameter",
type=ParameterDictType.INT,
units="nano-batbit",
value_description="Should be an integer between 1 and 1000")
self.param_dict.add("qux", r'.*qux=(\d+).*',
lambda match: int(match.group(1)),
lambda x: str(x),
startup_param=False,
visibility=ParameterDictVisibility.READ_ONLY)
self.param_dict.add("pho", r'.*qux=(\d+).*',
lambda match: int(match.group(1)),
lambda x: str(x),
startup_param=False,
visibility=ParameterDictVisibility.IMMUTABLE)
self.param_dict.add("dil", r'.*qux=(\d+).*',
lambda match: int(match.group(1)),
lambda x: str(x),
startup_param=False,
visibility=ParameterDictVisibility.IMMUTABLE)
self.param_dict.add("qut", r'.*qut=(\d+).*',
lambda match: int(match.group(1)),
lambda x: str(x),
direct_access=True,
default_value=[10, 100],
visibility=ParameterDictVisibility.DIRECT_ACCESS,
expiration=1,
get_timeout=10,
set_timeout=20,
display_name="Qut",
description="The qut list parameter",
type=ParameterDictType.LIST,
units="nano-qutters",
value_description="Should be a 2-10 element list of integers between 2 and 2000")
self.target_schema = {
"bar": {
"direct_access": False,
"get_timeout": 10,
"set_timeout": 10,
"startup": True,
"value": {
"default": 15
},
"visibility": "READ_WRITE",
#.........这里部分代码省略.........
示例5: Protocol
# 需要导入模块: from mi.core.instrument.protocol_param_dict import ProtocolParameterDict [as 别名]
# 或者: from mi.core.instrument.protocol_param_dict.ProtocolParameterDict import get [as 别名]
class Protocol(CommandResponseInstrumentProtocol):
"""
Instrument protocol class
Subclasses CommandResponseInstrumentProtocol
"""
__metaclass__ = META_LOGGER
def __init__(self, prompts, newline, driver_event):
"""
Protocol constructor.
@param prompts A BaseEnum class containing instrument prompts.
@param newline The newline.
@param driver_event Driver process event callback.
"""
# Construct protocol superclass.
CommandResponseInstrumentProtocol.__init__(self, prompts, newline, driver_event)
# Build protocol state machine.
self._protocol_fsm = ThreadSafeFSM(ProtocolState, ProtocolEvent, ProtocolEvent.ENTER, ProtocolEvent.EXIT)
# Add event handlers for protocol state machine.
handlers = {
ProtocolState.UNKNOWN: [
(ProtocolEvent.ENTER, self._handler_generic_enter),
(ProtocolEvent.EXIT, self._handler_generic_exit),
(ProtocolEvent.DISCOVER, self._handler_unknown_discover),
],
ProtocolState.AUTOSAMPLE: [
(ProtocolEvent.ENTER, self._handler_autosample_enter),
(ProtocolEvent.EXIT, self._handler_generic_exit),
(ProtocolEvent.GET, self._handler_command_get),
(ProtocolEvent.STOP_AUTOSAMPLE, self._handler_autosample_stop_autosample),
(ProtocolEvent.VERY_LONG_COMMAND, self._very_long_command),
],
ProtocolState.COMMAND: [
(ProtocolEvent.ENTER, self._handler_command_enter),
(ProtocolEvent.EXIT, self._handler_generic_exit),
(ProtocolEvent.GET, self._handler_command_get),
(ProtocolEvent.SET, self._handler_command_set),
(ProtocolEvent.START_AUTOSAMPLE, self._handler_command_start_autosample),
(ProtocolEvent.VERY_LONG_COMMAND, self._very_long_command),
],
}
for state in handlers:
for event, handler in handlers[state]:
self._protocol_fsm.add_handler(state, event, handler)
# Construct the metadata dictionaries
self._build_command_dict()
self._build_driver_dict()
# Start state machine in UNKNOWN state.
self._protocol_fsm.start(ProtocolState.UNKNOWN)
# set up scheduled event handling
self.initialize_scheduler()
self._schedulers = []
def _generate_particle(self, stream_name, count=1):
# we're faking it anyway, send these as fast as we can...
# the overall rate will be close enough
particle = VirtualParticle(stream_name, port_timestamp=0)
for x in range(count):
particle.contents["port_timestamp"] = ntplib.system_to_ntp_time(time.time())
self._driver_event(DriverAsyncEvent.SAMPLE, particle.generate())
time.sleep(0.001)
def _create_scheduler(self, stream_name, rate):
job_name = stream_name
if rate > 1:
interval = 1
else:
interval = 1 / rate
config = {
DriverConfigKey.SCHEDULER: {
job_name: {
DriverSchedulerConfigKey.TRIGGER: {
DriverSchedulerConfigKey.TRIGGER_TYPE: TriggerType.INTERVAL,
DriverSchedulerConfigKey.SECONDS: interval,
}
}
}
}
self.set_init_params(config)
self._schedulers.append(stream_name)
if rate > 1:
self._add_scheduler(stream_name, functools.partial(self._generate_particle, stream_name, count=rate))
else:
self._add_scheduler(stream_name, functools.partial(self._generate_particle, stream_name))
def _delete_all_schedulers(self):
for name in self._schedulers:
try:
self._remove_scheduler(name)
except:
#.........这里部分代码省略.........
示例6: TestUnitProtocolParameterDict
# 需要导入模块: from mi.core.instrument.protocol_param_dict import ProtocolParameterDict [as 别名]
# 或者: from mi.core.instrument.protocol_param_dict.ProtocolParameterDict import get [as 别名]
class TestUnitProtocolParameterDict(MiUnitTestCase):
@staticmethod
def pick_byte2(input):
""" Get the 2nd byte as an example of something tricky and
arbitrary"""
val = int(input) >> 8
val = val & 255
return val
"""
Test cases for instrument driver class. Functions in this class provide
instrument driver unit tests and provide a tutorial on use of
the driver interface.
"""
def setUp(self):
self.param_dict = ProtocolParameterDict()
self.param_dict.add("foo", r'.*foo=(\d+).*',
lambda match : int(match.group(1)),
lambda x : str(x),
direct_access=True,
startup_param=True,
default_value=10,
visibility=ParameterDictVisibility.READ_WRITE)
self.param_dict.add("bar", r'.*bar=(\d+).*',
lambda match : int(match.group(1)),
lambda x : str(x),
direct_access=False,
startup_param=True,
default_value=15,
visibility=ParameterDictVisibility.READ_WRITE)
self.param_dict.add("baz", r'.*baz=(\d+).*',
lambda match : int(match.group(1)),
lambda x : str(x),
direct_access=True,
default_value=20,
visibility=ParameterDictVisibility.DIRECT_ACCESS)
self.param_dict.add("bat", r'.*bat=(\d+).*',
lambda match : int(match.group(1)),
lambda x : str(x),
startup_param=False,
default_value=20,
visibility=ParameterDictVisibility.READ_ONLY)
self.param_dict.add("qux", r'.*qux=(\d+).*',
lambda match : int(match.group(1)),
lambda x : str(x),
startup_param=False,
visibility=ParameterDictVisibility.READ_ONLY)
def test_get_direct_access_list(self):
"""
Test to see we can get a list of direct access parameters
"""
result = self.param_dict.get_direct_access_list()
self.assertTrue(isinstance(result, list))
self.assertEquals(len(result), 2)
self.assert_("foo" in result)
self.assert_("baz" in result)
def test_get_startup_list(self):
"""
Test to see we can get a list of direct access parameters
"""
result = self.param_dict.get_startup_list()
self.assertTrue(isinstance(result, list))
self.assertEquals(len(result), 2)
self.assert_("foo" in result)
self.assert_("bar" in result)
def test_set_default(self):
"""
Test setting a default value
"""
result = self.param_dict.get_config()
self.assertEquals(result["foo"], None)
self.param_dict.set_default("foo")
self.assertEquals(self.param_dict.get("foo"), 10)
self.param_dict.update("foo=1000")
self.assertEquals(self.param_dict.get("foo"), 1000)
self.param_dict.set_default("foo")
self.assertEquals(self.param_dict.get("foo"), 10)
self.assertRaises(ValueError, self.param_dict.set_default, "qux")
def test_update_many(self):
"""
Test updating of multiple variables from the same input
"""
sample_input = """
foo=100
bar=200, baz=300
"""
self.assertNotEquals(self.param_dict.get("foo"), 100)
self.assertNotEquals(self.param_dict.get("bar"), 200)
self.assertNotEquals(self.param_dict.get("baz"), 300)
result = self.param_dict.update_many(sample_input)
log.debug("result: %s", result)
self.assertEquals(result["foo"], True)
self.assertEquals(result["bar"], True)
self.assertEquals(result["baz"], True)
#.........这里部分代码省略.........
示例7: InstrumentProtocol
# 需要导入模块: from mi.core.instrument.protocol_param_dict import ProtocolParameterDict [as 别名]
# 或者: from mi.core.instrument.protocol_param_dict.ProtocolParameterDict import get [as 别名]
class InstrumentProtocol(object):
"""
Base instrument protocol class.
"""
def __init__(self, driver_event):
"""
Base constructor.
@param driver_event The callback for asynchronous driver events.
"""
# Event callback to send asynchronous events to the agent.
self._driver_event = driver_event
# The connection used to talk to the device.
self._connection = None
# The protocol state machine.
self._protocol_fsm = None
# The parameter dictionary.
self._param_dict = ProtocolParameterDict()
# The spot to stash a configuration before going into direct access
# mode
self._pre_direct_access_config = None
# Driver configuration passed from the user
self._startup_config = {}
# scheduler config is a bit redundant now, but if we ever want to
# re-initialize a scheduler we will need it.
self._scheduler = None
self._scheduler_callback = {}
self._scheduler_config = {}
########################################################################
# Helper methods
########################################################################
def got_data(self, port_agent_packet):
"""
Called by the instrument connection when data is available.
Defined in subclasses.
"""
log.error("base got_data. Who called me?")
pass
def _extract_sample(self, particle_class, regex, line, publish=True):
"""
Extract sample from a response line if present and publish
parsed particle
@param particle_class The class to instantiate for this specific
data particle. Parameterizing this allows for simple, standard
behavior from this routine
@param regex The regular expression that matches a data sample
@param line string to match for sample.
@param publish boolean to publish samples (default True). If True,
two different events are published: one to notify raw data and
the other to notify parsed data.
@retval dict of dicts {'parsed': parsed_sample, 'raw': raw_sample} if
the line can be parsed for a sample. Otherwise, None.
@todo Figure out how the agent wants the results for a single poll
and return them that way from here
"""
sample = None
if regex.match(line):
particle = particle_class(line,
preferred_timestamp=DataParticleKey.DRIVER_TIMESTAMP)
parsed_sample = particle.generate()
if publish and self._driver_event:
self._driver_event(DriverAsyncEvent.SAMPLE, parsed_sample)
sample = json.loads(parsed_sample)
return sample
return sample
def get_current_state(self):
"""
Return current state of the protocol FSM.
"""
return self._protocol_fsm.get_current_state()
def get_resource_capabilities(self, current_state=True):
"""
"""
res_cmds = self._protocol_fsm.get_events(current_state)
res_cmds = self._filter_capabilities(res_cmds)
res_params = self._param_dict.get_keys()
return [res_cmds, res_params]
def _filter_capabilities(self, events):
"""
#.........这里部分代码省略.........
示例8: TestUnitProtocolParameterDict
# 需要导入模块: from mi.core.instrument.protocol_param_dict import ProtocolParameterDict [as 别名]
# 或者: from mi.core.instrument.protocol_param_dict.ProtocolParameterDict import get [as 别名]
class TestUnitProtocolParameterDict(MiUnitTestCase):
"""
Test cases for instrument driver class. Functions in this class provide
instrument driver unit tests and provide a tutorial on use of
the driver interface.
"""
def setUp(self):
self.param_dict = ProtocolParameterDict()
self.param_dict.add("foo", r'.*foo=(\d*).*',
lambda match : int(match.group(1)),
lambda x : str(x),
direct_access=True,
startup_param=True,
default_value=10,
visibility=ParameterDictVisibility.READ_WRITE)
self.param_dict.add("bar", r'.*bar=(\d*).*',
lambda match : int(match.group(1)),
lambda x : str(x),
direct_access=False,
startup_param=True,
default_value=15,
visibility=ParameterDictVisibility.READ_WRITE)
self.param_dict.add("baz", r'.*baz=(\d*).*',
lambda match : int(match.group(1)),
lambda x : str(x),
direct_access=True,
default_value=20,
visibility=ParameterDictVisibility.DIRECT_ACCESS)
self.param_dict.add("bat", r'.*bat=(\d*).*',
lambda match : int(match.group(1)),
lambda x : str(x),
startup_param=False,
default_value=20,
visibility=ParameterDictVisibility.READ_ONLY)
self.param_dict.add("qux", r'.*qux=(\d*).*',
lambda match : int(match.group(1)),
lambda x : str(x),
startup_param=False,
visibility=ParameterDictVisibility.READ_ONLY)
def test_get_direct_access_list(self):
"""
Test to see we can get a list of direct access parameters
"""
result = self.param_dict.get_direct_access_list()
self.assertTrue(isinstance(result, list))
self.assertEquals(len(result), 2)
self.assert_("foo" in result)
self.assert_("baz" in result)
def test_get_startup_list(self):
"""
Test to see we can get a list of direct access parameters
"""
result = self.param_dict.get_startup_list()
self.assertTrue(isinstance(result, list))
self.assertEquals(len(result), 2)
self.assert_("foo" in result)
self.assert_("bar" in result)
def test_set_default(self):
"""
Test setting a default value
"""
result = self.param_dict.get_config()
self.assertEquals(result["foo"], None)
self.param_dict.set_default("foo")
self.assertEquals(self.param_dict.get("foo"), 10)
self.param_dict.update("foo=1000")
self.assertEquals(self.param_dict.get("foo"), 1000)
self.param_dict.set_default("foo")
self.assertEquals(self.param_dict.get("foo"), 10)
self.assertRaises(ValueError, self.param_dict.set_default, "qux")
def test_update_many(self):
"""
Test updating of multiple variables from the same input
"""
sample_input = """
foo=100
bar=200, baz=300
"""
self.assertNotEquals(self.param_dict.get("foo"), 100)
self.assertNotEquals(self.param_dict.get("bar"), 200)
self.assertNotEquals(self.param_dict.get("baz"), 300)
result = self.param_dict.update_many(sample_input)
log.debug("result: %s", result)
self.assertEquals(result["foo"], True)
self.assertEquals(result["bar"], True)
self.assertEquals(result["baz"], True)
self.assertEquals(self.param_dict.get("foo"), 100)
self.assertEquals(self.param_dict.get("bar"), 200)
self.assertEquals(self.param_dict.get("baz"), 300)
def test_visibility_list(self):
lst = self.param_dict.get_visibility_list(ParameterDictVisibility.READ_WRITE)
self.assertEquals(lst, ["foo", "bar"])
lst = self.param_dict.get_visibility_list(ParameterDictVisibility.DIRECT_ACCESS)
#.........这里部分代码省略.........
示例9: DataSetDriver
# 需要导入模块: from mi.core.instrument.protocol_param_dict import ProtocolParameterDict [as 别名]
# 或者: from mi.core.instrument.protocol_param_dict.ProtocolParameterDict import get [as 别名]
class DataSetDriver(object):
"""
Base class for data set drivers. Provides:
- an interface via callback to publish data
- an interface via callback to persist driver state
- an interface via callback to handle exceptions
- an start and stop sampling
- a client interface for execute resource
Subclasses need to include harvesters and parsers and
be specialized to handle the interaction between the two.
Configurations should contain keys from the DataSetDriverConfigKey class
and should look something like this example (more full documentation in the
"Dataset Agent Architecture" page on the OOI wiki):
{
'harvester':
{
'directory': '/tmp/dsatest',
'pattern': '*.txt',
'frequency': 1,
},
'parser': {}
'driver': {
'records_per_second'
'harvester_polling_interval'
'batched_particle_count'
}
}
"""
def __init__(self, config, memento, data_callback, state_callback, exception_callback):
self._config = config
self._data_callback = data_callback
self._state_callback = state_callback
self._exception_callback = exception_callback
self._memento = memento
self._verify_config()
self._param_dict = ProtocolParameterDict()
# Updated my set_resource, defaults defined in build_param_dict
self._polling_interval = None
self._generate_particle_count = None
self._particle_count_per_second = None
self._build_param_dict()
def start_sampling(self):
"""
Start a new thread to monitor for data
"""
self._start_sampling()
self._start_publisher_thread()
def stop_sampling(self):
"""
Stop the sampling thread
"""
self._stop_publisher_thread()
def _start_sampling(self):
raise NotImplementedException('virtual methond needs to be specialized')
def _stop_sampling(self):
raise NotImplementedException('virtual methond needs to be specialized')
def cmd_dvr(self, cmd, *args, **kwargs):
log.warn("DRIVER: cmd_dvr %s", cmd)
if not cmd in ['execute_resource', 'get_resource_capabilities', 'set_resource', 'get_resource']:
log.error("Unhandled command: %s", cmd)
raise InstrumentStateException("Unhandled command: %s" % cmd)
resource_cmd = args[0]
if cmd == 'execute_resource':
if resource_cmd == DriverEvent.START_AUTOSAMPLE:
try:
log.debug("start autosample")
self.start_sampling()
except:
log.error("Failed to start sampling", exc_info=True)
raise
return (ResourceAgentState.STREAMING, None)
elif resource_cmd == DriverEvent.STOP_AUTOSAMPLE:
log.debug("stop autosample")
self.stop_sampling()
return (ResourceAgentState.COMMAND, None)
else:
log.error("Unhandled resource command: %s", resource_cmd)
raise
elif cmd == 'get_resource_capabilities':
return self.get_resource_capabilities()
elif cmd == 'set_resource':
return self.set_resource(*args, **kwargs)
#.........这里部分代码省略.........