id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
16,300
ska-sa/katcp-python
katcp/resource_client.py
KATCPClientResourceContainer.set_sampling_strategies
def set_sampling_strategies(self, filter, strategy_and_parms): """Set sampling strategies for filtered sensors - these sensors have to exsist""" result_list = yield self.list_sensors(filter=filter) sensor_dict = {} for result in result_list: sensor_name = result.object.normalised_name resource_name = result.object.parent_name if resource_name not in sensor_dict: sensor_dict[resource_name] = {} try: resource_obj = self.children[resource_name] yield resource_obj.set_sampling_strategy(sensor_name, strategy_and_parms) sensor_dict[resource_name][sensor_name] = strategy_and_parms self._logger.debug( 'Set sampling strategy on resource %s for %s' % (resource_name, sensor_name)) except Exception as exc: self._logger.error( 'Cannot set sampling strategy on resource %s for %s (%s)' % (resource_name, sensor_name, exc)) sensor_dict[resource_name][sensor_name] = None raise tornado.gen.Return(sensor_dict)
python
def set_sampling_strategies(self, filter, strategy_and_parms): result_list = yield self.list_sensors(filter=filter) sensor_dict = {} for result in result_list: sensor_name = result.object.normalised_name resource_name = result.object.parent_name if resource_name not in sensor_dict: sensor_dict[resource_name] = {} try: resource_obj = self.children[resource_name] yield resource_obj.set_sampling_strategy(sensor_name, strategy_and_parms) sensor_dict[resource_name][sensor_name] = strategy_and_parms self._logger.debug( 'Set sampling strategy on resource %s for %s' % (resource_name, sensor_name)) except Exception as exc: self._logger.error( 'Cannot set sampling strategy on resource %s for %s (%s)' % (resource_name, sensor_name, exc)) sensor_dict[resource_name][sensor_name] = None raise tornado.gen.Return(sensor_dict)
[ "def", "set_sampling_strategies", "(", "self", ",", "filter", ",", "strategy_and_parms", ")", ":", "result_list", "=", "yield", "self", ".", "list_sensors", "(", "filter", "=", "filter", ")", "sensor_dict", "=", "{", "}", "for", "result", "in", "result_list", ...
Set sampling strategies for filtered sensors - these sensors have to exsist
[ "Set", "sampling", "strategies", "for", "filtered", "sensors", "-", "these", "sensors", "have", "to", "exsist" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource_client.py#L1445-L1466
16,301
ska-sa/katcp-python
katcp/resource_client.py
KATCPClientResourceContainer.add_child_resource_client
def add_child_resource_client(self, res_name, res_spec): """Add a resource client to the container and start the resource connection""" res_spec = dict(res_spec) res_spec['name'] = res_name res = self.client_resource_factory( res_spec, parent=self, logger=self._logger) self.children[resource.escape_name(res_name)] = res; self._children_dirty = True res.set_ioloop(self.ioloop) res.start() return res
python
def add_child_resource_client(self, res_name, res_spec): res_spec = dict(res_spec) res_spec['name'] = res_name res = self.client_resource_factory( res_spec, parent=self, logger=self._logger) self.children[resource.escape_name(res_name)] = res; self._children_dirty = True res.set_ioloop(self.ioloop) res.start() return res
[ "def", "add_child_resource_client", "(", "self", ",", "res_name", ",", "res_spec", ")", ":", "res_spec", "=", "dict", "(", "res_spec", ")", "res_spec", "[", "'name'", "]", "=", "res_name", "res", "=", "self", ".", "client_resource_factory", "(", "res_spec", ...
Add a resource client to the container and start the resource connection
[ "Add", "a", "resource", "client", "to", "the", "container", "and", "start", "the", "resource", "connection" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource_client.py#L1516-L1526
16,302
ska-sa/katcp-python
katcp/resource_client.py
KATCPClientResourceContainer.stop
def stop(self): """Stop all child resources""" for child_name, child in dict.items(self.children): # Catch child exceptions when stopping so we make sure to stop all children # that want to listen. try: child.stop() except Exception: self._logger.exception('Exception stopping child {!r}' .format(child_name))
python
def stop(self): for child_name, child in dict.items(self.children): # Catch child exceptions when stopping so we make sure to stop all children # that want to listen. try: child.stop() except Exception: self._logger.exception('Exception stopping child {!r}' .format(child_name))
[ "def", "stop", "(", "self", ")", ":", "for", "child_name", ",", "child", "in", "dict", ".", "items", "(", "self", ".", "children", ")", ":", "# Catch child exceptions when stopping so we make sure to stop all children", "# that want to listen.", "try", ":", "child", ...
Stop all child resources
[ "Stop", "all", "child", "resources" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource_client.py#L1541-L1550
16,303
eight04/pyAPNG
apng/__init__.py
make_chunk
def make_chunk(chunk_type, chunk_data): """Create a raw chunk by composing chunk type and data. It calculates chunk length and CRC for you. :arg str chunk_type: PNG chunk type. :arg bytes chunk_data: PNG chunk data, **excluding chunk length, type, and CRC**. :rtype: bytes """ out = struct.pack("!I", len(chunk_data)) chunk_data = chunk_type.encode("latin-1") + chunk_data out += chunk_data + struct.pack("!I", binascii.crc32(chunk_data) & 0xffffffff) return out
python
def make_chunk(chunk_type, chunk_data): out = struct.pack("!I", len(chunk_data)) chunk_data = chunk_type.encode("latin-1") + chunk_data out += chunk_data + struct.pack("!I", binascii.crc32(chunk_data) & 0xffffffff) return out
[ "def", "make_chunk", "(", "chunk_type", ",", "chunk_data", ")", ":", "out", "=", "struct", ".", "pack", "(", "\"!I\"", ",", "len", "(", "chunk_data", ")", ")", "chunk_data", "=", "chunk_type", ".", "encode", "(", "\"latin-1\"", ")", "+", "chunk_data", "o...
Create a raw chunk by composing chunk type and data. It calculates chunk length and CRC for you. :arg str chunk_type: PNG chunk type. :arg bytes chunk_data: PNG chunk data, **excluding chunk length, type, and CRC**. :rtype: bytes
[ "Create", "a", "raw", "chunk", "by", "composing", "chunk", "type", "and", "data", ".", "It", "calculates", "chunk", "length", "and", "CRC", "for", "you", "." ]
b4d2927f7892a1de967b5cf57d434ed65f6a017e
https://github.com/eight04/pyAPNG/blob/b4d2927f7892a1de967b5cf57d434ed65f6a017e/apng/__init__.py#L43-L54
16,304
eight04/pyAPNG
apng/__init__.py
PNG.init
def init(self): """Extract some info from chunks""" for type_, data in self.chunks: if type_ == "IHDR": self.hdr = data elif type_ == "IEND": self.end = data if self.hdr: # grab w, h info self.width, self.height = struct.unpack("!II", self.hdr[8:16])
python
def init(self): for type_, data in self.chunks: if type_ == "IHDR": self.hdr = data elif type_ == "IEND": self.end = data if self.hdr: # grab w, h info self.width, self.height = struct.unpack("!II", self.hdr[8:16])
[ "def", "init", "(", "self", ")", ":", "for", "type_", ",", "data", "in", "self", ".", "chunks", ":", "if", "type_", "==", "\"IHDR\"", ":", "self", ".", "hdr", "=", "data", "elif", "type_", "==", "\"IEND\"", ":", "self", ".", "end", "=", "data", "...
Extract some info from chunks
[ "Extract", "some", "info", "from", "chunks" ]
b4d2927f7892a1de967b5cf57d434ed65f6a017e
https://github.com/eight04/pyAPNG/blob/b4d2927f7892a1de967b5cf57d434ed65f6a017e/apng/__init__.py#L185-L195
16,305
eight04/pyAPNG
cute.py
readme
def readme(): """Live reload readme""" from livereload import Server server = Server() server.watch("README.rst", "py cute.py readme_build") server.serve(open_url_delay=1, root="build/readme")
python
def readme(): from livereload import Server server = Server() server.watch("README.rst", "py cute.py readme_build") server.serve(open_url_delay=1, root="build/readme")
[ "def", "readme", "(", ")", ":", "from", "livereload", "import", "Server", "server", "=", "Server", "(", ")", "server", ".", "watch", "(", "\"README.rst\"", ",", "\"py cute.py readme_build\"", ")", "server", ".", "serve", "(", "open_url_delay", "=", "1", ",",...
Live reload readme
[ "Live", "reload", "readme" ]
b4d2927f7892a1de967b5cf57d434ed65f6a017e
https://github.com/eight04/pyAPNG/blob/b4d2927f7892a1de967b5cf57d434ed65f6a017e/cute.py#L6-L11
16,306
ska-sa/katcp-python
bench/benchserver.py
BenchmarkServer.request_add_sensor
def request_add_sensor(self, sock, msg): """ add a sensor """ self.add_sensor(Sensor(int, 'int_sensor%d' % len(self._sensors), 'descr', 'unit', params=[-10, 10])) return Message.reply('add-sensor', 'ok')
python
def request_add_sensor(self, sock, msg): self.add_sensor(Sensor(int, 'int_sensor%d' % len(self._sensors), 'descr', 'unit', params=[-10, 10])) return Message.reply('add-sensor', 'ok')
[ "def", "request_add_sensor", "(", "self", ",", "sock", ",", "msg", ")", ":", "self", ".", "add_sensor", "(", "Sensor", "(", "int", ",", "'int_sensor%d'", "%", "len", "(", "self", ".", "_sensors", ")", ",", "'descr'", ",", "'unit'", ",", "params", "=", ...
add a sensor
[ "add", "a", "sensor" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/bench/benchserver.py#L17-L22
16,307
ska-sa/katcp-python
katcp/resource.py
normalize_strategy_parameters
def normalize_strategy_parameters(params): """Normalize strategy parameters to be a list of strings. Parameters ---------- params : (space-delimited) string or sequence of strings/numbers Parameters expected by :class:`SampleStrategy` object, in various forms, where the first parameter is the name of the strategy. Returns ------- params : tuple of strings Strategy parameters as a list of strings """ def fixup_numbers(val): try: # See if it is a number return str(float(val)) except ValueError: # ok, it is not a number we know of, perhaps a string return str(val) if isinstance(params, basestring): params = params.split(' ') # No number return tuple(fixup_numbers(p) for p in params)
python
def normalize_strategy_parameters(params): def fixup_numbers(val): try: # See if it is a number return str(float(val)) except ValueError: # ok, it is not a number we know of, perhaps a string return str(val) if isinstance(params, basestring): params = params.split(' ') # No number return tuple(fixup_numbers(p) for p in params)
[ "def", "normalize_strategy_parameters", "(", "params", ")", ":", "def", "fixup_numbers", "(", "val", ")", ":", "try", ":", "# See if it is a number", "return", "str", "(", "float", "(", "val", ")", ")", "except", "ValueError", ":", "# ok, it is not a number we kno...
Normalize strategy parameters to be a list of strings. Parameters ---------- params : (space-delimited) string or sequence of strings/numbers Parameters expected by :class:`SampleStrategy` object, in various forms, where the first parameter is the name of the strategy. Returns ------- params : tuple of strings Strategy parameters as a list of strings
[ "Normalize", "strategy", "parameters", "to", "be", "a", "list", "of", "strings", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource.py#L59-L84
16,308
ska-sa/katcp-python
katcp/resource.py
KATCPResource.wait
def wait(self, sensor_name, condition_or_value, timeout=5): """Wait for a sensor in this resource to satisfy a condition. Parameters ---------- sensor_name : string The name of the sensor to check condition_or_value : obj or callable, or seq of objs or callables If obj, sensor.value is compared with obj. If callable, condition_or_value(reading) is called, and must return True if its condition is satisfied. Since the reading is passed in, the value, status, timestamp or received_timestamp attributes can all be used in the check. timeout : float or None The timeout in seconds (None means wait forever) Returns ------- This command returns a tornado Future that resolves with True when the sensor value satisfies the condition, or False if the condition is still not satisfied after a given timeout period. Raises ------ :class:`KATCPSensorError` If the sensor does not have a strategy set, or if the named sensor is not present """ sensor_name = escape_name(sensor_name) sensor = self.sensor[sensor_name] try: yield sensor.wait(condition_or_value, timeout) except tornado.gen.TimeoutError: raise tornado.gen.Return(False) else: raise tornado.gen.Return(True)
python
def wait(self, sensor_name, condition_or_value, timeout=5): sensor_name = escape_name(sensor_name) sensor = self.sensor[sensor_name] try: yield sensor.wait(condition_or_value, timeout) except tornado.gen.TimeoutError: raise tornado.gen.Return(False) else: raise tornado.gen.Return(True)
[ "def", "wait", "(", "self", ",", "sensor_name", ",", "condition_or_value", ",", "timeout", "=", "5", ")", ":", "sensor_name", "=", "escape_name", "(", "sensor_name", ")", "sensor", "=", "self", ".", "sensor", "[", "sensor_name", "]", "try", ":", "yield", ...
Wait for a sensor in this resource to satisfy a condition. Parameters ---------- sensor_name : string The name of the sensor to check condition_or_value : obj or callable, or seq of objs or callables If obj, sensor.value is compared with obj. If callable, condition_or_value(reading) is called, and must return True if its condition is satisfied. Since the reading is passed in, the value, status, timestamp or received_timestamp attributes can all be used in the check. timeout : float or None The timeout in seconds (None means wait forever) Returns ------- This command returns a tornado Future that resolves with True when the sensor value satisfies the condition, or False if the condition is still not satisfied after a given timeout period. Raises ------ :class:`KATCPSensorError` If the sensor does not have a strategy set, or if the named sensor is not present
[ "Wait", "for", "a", "sensor", "in", "this", "resource", "to", "satisfy", "a", "condition", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource.py#L186-L222
16,309
ska-sa/katcp-python
katcp/resource.py
KATCPResource.set_sampling_strategies
def set_sampling_strategies(self, filter, strategy_and_params): """Set a sampling strategy for all sensors that match the specified filter. Parameters ---------- filter : string The regular expression filter to use to select the sensors to which to apply the specified strategy. Use "" to match all sensors. Is matched using :meth:`list_sensors`. strategy_and_params : seq of str or str As tuple contains (<strat_name>, [<strat_parm1>, ...]) where the strategy names and parameters are as defined by the KATCP spec. As str contains the same elements in space-separated form. **list_sensor_args : keyword arguments Passed to the :meth:`list_sensors` call as kwargs Returns ------- sensors_strategies : tornado Future resolves with a dict with the Python identifier names of the sensors as keys and the value a tuple: (success, info) with sucess : bool True if setting succeeded for this sensor, else False info : tuple normalised sensor strategy and parameters as tuple if success == True else, sys.exc_info() tuple for the error that occured. """ sensors_strategies = {} sensor_results = yield self.list_sensors(filter) for sensor_reslt in sensor_results: norm_name = sensor_reslt.object.normalised_name try: sensor_strat = yield self.set_sampling_strategy(norm_name, strategy_and_params) sensors_strategies[norm_name] = sensor_strat[norm_name] except Exception: sensors_strategies[norm_name] = ( False, sys.exc_info()) raise tornado.gen.Return(sensors_strategies)
python
def set_sampling_strategies(self, filter, strategy_and_params): sensors_strategies = {} sensor_results = yield self.list_sensors(filter) for sensor_reslt in sensor_results: norm_name = sensor_reslt.object.normalised_name try: sensor_strat = yield self.set_sampling_strategy(norm_name, strategy_and_params) sensors_strategies[norm_name] = sensor_strat[norm_name] except Exception: sensors_strategies[norm_name] = ( False, sys.exc_info()) raise tornado.gen.Return(sensors_strategies)
[ "def", "set_sampling_strategies", "(", "self", ",", "filter", ",", "strategy_and_params", ")", ":", "sensors_strategies", "=", "{", "}", "sensor_results", "=", "yield", "self", ".", "list_sensors", "(", "filter", ")", "for", "sensor_reslt", "in", "sensor_results",...
Set a sampling strategy for all sensors that match the specified filter. Parameters ---------- filter : string The regular expression filter to use to select the sensors to which to apply the specified strategy. Use "" to match all sensors. Is matched using :meth:`list_sensors`. strategy_and_params : seq of str or str As tuple contains (<strat_name>, [<strat_parm1>, ...]) where the strategy names and parameters are as defined by the KATCP spec. As str contains the same elements in space-separated form. **list_sensor_args : keyword arguments Passed to the :meth:`list_sensors` call as kwargs Returns ------- sensors_strategies : tornado Future resolves with a dict with the Python identifier names of the sensors as keys and the value a tuple: (success, info) with sucess : bool True if setting succeeded for this sensor, else False info : tuple normalised sensor strategy and parameters as tuple if success == True else, sys.exc_info() tuple for the error that occured.
[ "Set", "a", "sampling", "strategy", "for", "all", "sensors", "that", "match", "the", "specified", "filter", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource.py#L262-L302
16,310
ska-sa/katcp-python
katcp/resource.py
KATCPResource.set_sampling_strategy
def set_sampling_strategy(self, sensor_name, strategy_and_params): """Set a sampling strategy for a specific sensor. Parameters ---------- sensor_name : string The specific sensor. strategy_and_params : seq of str or str As tuple contains (<strat_name>, [<strat_parm1>, ...]) where the strategy names and parameters are as defined by the KATCP spec. As str contains the same elements in space-separated form. Returns ------- sensors_strategies : tornado Future resolves with a dict with the Python identifier names of the sensors as keys and the value a tuple: (success, info) with sucess : bool True if setting succeeded for this sensor, else False info : tuple normalised sensor strategy and parameters as tuple if success == True else, sys.exc_info() tuple for the error that occured. """ sensors_strategies = {} try: sensor_obj = self.sensor.get(sensor_name) yield sensor_obj.set_sampling_strategy(strategy_and_params) sensors_strategies[sensor_obj.normalised_name] = ( True, sensor_obj.sampling_strategy) except Exception: sensors_strategies[sensor_obj.normalised_name] = ( False, sys.exc_info()) raise tornado.gen.Return(sensors_strategies)
python
def set_sampling_strategy(self, sensor_name, strategy_and_params): sensors_strategies = {} try: sensor_obj = self.sensor.get(sensor_name) yield sensor_obj.set_sampling_strategy(strategy_and_params) sensors_strategies[sensor_obj.normalised_name] = ( True, sensor_obj.sampling_strategy) except Exception: sensors_strategies[sensor_obj.normalised_name] = ( False, sys.exc_info()) raise tornado.gen.Return(sensors_strategies)
[ "def", "set_sampling_strategy", "(", "self", ",", "sensor_name", ",", "strategy_and_params", ")", ":", "sensors_strategies", "=", "{", "}", "try", ":", "sensor_obj", "=", "self", ".", "sensor", ".", "get", "(", "sensor_name", ")", "yield", "sensor_obj", ".", ...
Set a sampling strategy for a specific sensor. Parameters ---------- sensor_name : string The specific sensor. strategy_and_params : seq of str or str As tuple contains (<strat_name>, [<strat_parm1>, ...]) where the strategy names and parameters are as defined by the KATCP spec. As str contains the same elements in space-separated form. Returns ------- sensors_strategies : tornado Future resolves with a dict with the Python identifier names of the sensors as keys and the value a tuple: (success, info) with sucess : bool True if setting succeeded for this sensor, else False info : tuple normalised sensor strategy and parameters as tuple if success == True else, sys.exc_info() tuple for the error that occured.
[ "Set", "a", "sampling", "strategy", "for", "a", "specific", "sensor", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource.py#L305-L340
16,311
ska-sa/katcp-python
katcp/resource.py
KATCPSensor.set_strategy
def set_strategy(self, strategy, params=None): """Set current sampling strategy for sensor. Add this footprint for backwards compatibility. Parameters ---------- strategy : seq of str or str As tuple contains (<strat_name>, [<strat_parm1>, ...]) where the strategy names and parameters are as defined by the KATCP spec. As str contains the same elements in space-separated form. params : seq of str or str (<strat_name>, [<strat_parm1>, ...]) Returns ------- done : tornado Future that resolves when done or raises KATCPSensorError """ if not params: param_args = [] elif isinstance(params, basestring): param_args = [str(p) for p in params.split(' ')] else: if not isinstance(params, collections.Iterable): params = (params,) param_args = [str(p) for p in params] samp_strategy = " ".join([strategy] + param_args) return self._manager.set_sampling_strategy(self.name, samp_strategy)
python
def set_strategy(self, strategy, params=None): if not params: param_args = [] elif isinstance(params, basestring): param_args = [str(p) for p in params.split(' ')] else: if not isinstance(params, collections.Iterable): params = (params,) param_args = [str(p) for p in params] samp_strategy = " ".join([strategy] + param_args) return self._manager.set_sampling_strategy(self.name, samp_strategy)
[ "def", "set_strategy", "(", "self", ",", "strategy", ",", "params", "=", "None", ")", ":", "if", "not", "params", ":", "param_args", "=", "[", "]", "elif", "isinstance", "(", "params", ",", "basestring", ")", ":", "param_args", "=", "[", "str", "(", ...
Set current sampling strategy for sensor. Add this footprint for backwards compatibility. Parameters ---------- strategy : seq of str or str As tuple contains (<strat_name>, [<strat_parm1>, ...]) where the strategy names and parameters are as defined by the KATCP spec. As str contains the same elements in space-separated form. params : seq of str or str (<strat_name>, [<strat_parm1>, ...]) Returns ------- done : tornado Future that resolves when done or raises KATCPSensorError
[ "Set", "current", "sampling", "strategy", "for", "sensor", ".", "Add", "this", "footprint", "for", "backwards", "compatibility", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource.py#L704-L732
16,312
ska-sa/katcp-python
katcp/resource.py
KATCPSensor.register_listener
def register_listener(self, listener, reading=False): """Add a callback function that is called when sensor value is updated. The callback footprint is received_timestamp, timestamp, status, value. Parameters ---------- listener : function Callback signature: if reading listener(katcp_sensor, reading) where `katcp_sensor` is this KATCPSensor instance `reading` is an instance of :class:`KATCPSensorReading` Callback signature: default, if not reading listener(received_timestamp, timestamp, status, value) """ listener_id = hashable_identity(listener) self._listeners[listener_id] = (listener, reading) logger.debug( 'Register listener for {}' .format(self.name))
python
def register_listener(self, listener, reading=False): listener_id = hashable_identity(listener) self._listeners[listener_id] = (listener, reading) logger.debug( 'Register listener for {}' .format(self.name))
[ "def", "register_listener", "(", "self", ",", "listener", ",", "reading", "=", "False", ")", ":", "listener_id", "=", "hashable_identity", "(", "listener", ")", "self", ".", "_listeners", "[", "listener_id", "]", "=", "(", "listener", ",", "reading", ")", ...
Add a callback function that is called when sensor value is updated. The callback footprint is received_timestamp, timestamp, status, value. Parameters ---------- listener : function Callback signature: if reading listener(katcp_sensor, reading) where `katcp_sensor` is this KATCPSensor instance `reading` is an instance of :class:`KATCPSensorReading` Callback signature: default, if not reading listener(received_timestamp, timestamp, status, value)
[ "Add", "a", "callback", "function", "that", "is", "called", "when", "sensor", "value", "is", "updated", ".", "The", "callback", "footprint", "is", "received_timestamp", "timestamp", "status", "value", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource.py#L761-L779
16,313
ska-sa/katcp-python
katcp/resource.py
KATCPSensor.set_value
def set_value(self, value, status=Sensor.NOMINAL, timestamp=None): """Set sensor value with optinal specification of status and timestamp""" if timestamp is None: timestamp = self._manager.time() self.set(timestamp, status, value)
python
def set_value(self, value, status=Sensor.NOMINAL, timestamp=None): if timestamp is None: timestamp = self._manager.time() self.set(timestamp, status, value)
[ "def", "set_value", "(", "self", ",", "value", ",", "status", "=", "Sensor", ".", "NOMINAL", ",", "timestamp", "=", "None", ")", ":", "if", "timestamp", "is", "None", ":", "timestamp", "=", "self", ".", "_manager", ".", "time", "(", ")", "self", ".",...
Set sensor value with optinal specification of status and timestamp
[ "Set", "sensor", "value", "with", "optinal", "specification", "of", "status", "and", "timestamp" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource.py#L824-L828
16,314
ska-sa/katcp-python
katcp/resource.py
KATCPSensor.get_reading
def get_reading(self): """Get a fresh sensor reading from the KATCP resource Returns ------- reply : tornado Future resolving with :class:`KATCPSensorReading` object Note ---- As a side-effect this will update the reading stored in this object, and result in registered listeners being called. """ yield self._manager.poll_sensor(self._name) # By now the sensor manager should have set the reading raise Return(self._reading)
python
def get_reading(self): yield self._manager.poll_sensor(self._name) # By now the sensor manager should have set the reading raise Return(self._reading)
[ "def", "get_reading", "(", "self", ")", ":", "yield", "self", ".", "_manager", ".", "poll_sensor", "(", "self", ".", "_name", ")", "# By now the sensor manager should have set the reading", "raise", "Return", "(", "self", ".", "_reading", ")" ]
Get a fresh sensor reading from the KATCP resource Returns ------- reply : tornado Future resolving with :class:`KATCPSensorReading` object Note ---- As a side-effect this will update the reading stored in this object, and result in registered listeners being called.
[ "Get", "a", "fresh", "sensor", "reading", "from", "the", "KATCP", "resource" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource.py#L840-L855
16,315
ska-sa/katcp-python
katcp/resource.py
KATCPSensor.get_value
def get_value(self): """Get a fresh sensor value from the KATCP resource Returns ------- reply : tornado Future resolving with :class:`KATCPSensorReading` object Note ---- As a side-effect this will update the reading stored in this object, and result in registered listeners being called. """ yield self._manager.poll_sensor(self._name) # By now the sensor manager should have set the reading raise Return(self._reading.value)
python
def get_value(self): yield self._manager.poll_sensor(self._name) # By now the sensor manager should have set the reading raise Return(self._reading.value)
[ "def", "get_value", "(", "self", ")", ":", "yield", "self", ".", "_manager", ".", "poll_sensor", "(", "self", ".", "_name", ")", "# By now the sensor manager should have set the reading", "raise", "Return", "(", "self", ".", "_reading", ".", "value", ")" ]
Get a fresh sensor value from the KATCP resource Returns ------- reply : tornado Future resolving with :class:`KATCPSensorReading` object Note ---- As a side-effect this will update the reading stored in this object, and result in registered listeners being called.
[ "Get", "a", "fresh", "sensor", "value", "from", "the", "KATCP", "resource" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource.py#L858-L873
16,316
ska-sa/katcp-python
katcp/resource.py
KATCPSensor.get_status
def get_status(self): """Get a fresh sensor status from the KATCP resource Returns ------- reply : tornado Future resolving with :class:`KATCPSensorReading` object Note ---- As a side-effect this will update the reading stored in this object, and result in registered listeners being called. """ yield self._manager.poll_sensor(self._name) # By now the sensor manager should have set the reading raise Return(self._reading.status)
python
def get_status(self): yield self._manager.poll_sensor(self._name) # By now the sensor manager should have set the reading raise Return(self._reading.status)
[ "def", "get_status", "(", "self", ")", ":", "yield", "self", ".", "_manager", ".", "poll_sensor", "(", "self", ".", "_name", ")", "# By now the sensor manager should have set the reading", "raise", "Return", "(", "self", ".", "_reading", ".", "status", ")" ]
Get a fresh sensor status from the KATCP resource Returns ------- reply : tornado Future resolving with :class:`KATCPSensorReading` object Note ---- As a side-effect this will update the reading stored in this object, and result in registered listeners being called.
[ "Get", "a", "fresh", "sensor", "status", "from", "the", "KATCP", "resource" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource.py#L876-L891
16,317
ska-sa/katcp-python
katcp/resource.py
KATCPSensor.wait
def wait(self, condition_or_value, timeout=None): """Wait for the sensor to satisfy a condition. Parameters ---------- condition_or_value : obj or callable, or seq of objs or callables If obj, sensor.value is compared with obj. If callable, condition_or_value(reading) is called, and must return True if its condition is satisfied. Since the reading is passed in, the value, status, timestamp or received_timestamp attributes can all be used in the check. TODO: Sequences of conditions (use SensorTransitionWaiter thingum?) timeout : float or None The timeout in seconds (None means wait forever) Returns ------- This command returns a tornado Future that resolves with True when the sensor value satisfies the condition. It will never resolve with False; if a timeout is given a TimeoutError happens instead. Raises ------ :class:`KATCPSensorError` If the sensor does not have a strategy set :class:`tornado.gen.TimeoutError` If the sensor condition still fails after a stated timeout period """ if (isinstance(condition_or_value, collections.Sequence) and not isinstance(condition_or_value, basestring)): raise NotImplementedError( 'Currently only single conditions are supported') condition_test = (condition_or_value if callable(condition_or_value) else lambda s: s.value == condition_or_value) ioloop = tornado.ioloop.IOLoop.current() f = Future() if self.sampling_strategy == ('none', ): raise KATCPSensorError( 'Cannot wait on a sensor that does not have a strategy set') def handle_update(sensor, reading): # This handler is called whenever a sensor update is received try: assert sensor is self if condition_test(reading): self.unregister_listener(handle_update) # Try and be idempotent if called multiple times after the # condition is matched. This should not happen unless the # sensor object is being updated in a thread outside of the # ioloop. if not f.done(): ioloop.add_callback(f.set_result, True) except Exception: f.set_exc_info(sys.exc_info()) self.unregister_listener(handle_update) self.register_listener(handle_update, reading=True) # Handle case where sensor is already at the desired value ioloop.add_callback(handle_update, self, self._reading) if timeout: to = ioloop.time() + timeout timeout_f = with_timeout(to, f) # Make sure we stop listening if the wait times out to prevent a # buildup of listeners timeout_f.add_done_callback( lambda f: self.unregister_listener(handle_update)) return timeout_f else: return f
python
def wait(self, condition_or_value, timeout=None): if (isinstance(condition_or_value, collections.Sequence) and not isinstance(condition_or_value, basestring)): raise NotImplementedError( 'Currently only single conditions are supported') condition_test = (condition_or_value if callable(condition_or_value) else lambda s: s.value == condition_or_value) ioloop = tornado.ioloop.IOLoop.current() f = Future() if self.sampling_strategy == ('none', ): raise KATCPSensorError( 'Cannot wait on a sensor that does not have a strategy set') def handle_update(sensor, reading): # This handler is called whenever a sensor update is received try: assert sensor is self if condition_test(reading): self.unregister_listener(handle_update) # Try and be idempotent if called multiple times after the # condition is matched. This should not happen unless the # sensor object is being updated in a thread outside of the # ioloop. if not f.done(): ioloop.add_callback(f.set_result, True) except Exception: f.set_exc_info(sys.exc_info()) self.unregister_listener(handle_update) self.register_listener(handle_update, reading=True) # Handle case where sensor is already at the desired value ioloop.add_callback(handle_update, self, self._reading) if timeout: to = ioloop.time() + timeout timeout_f = with_timeout(to, f) # Make sure we stop listening if the wait times out to prevent a # buildup of listeners timeout_f.add_done_callback( lambda f: self.unregister_listener(handle_update)) return timeout_f else: return f
[ "def", "wait", "(", "self", ",", "condition_or_value", ",", "timeout", "=", "None", ")", ":", "if", "(", "isinstance", "(", "condition_or_value", ",", "collections", ".", "Sequence", ")", "and", "not", "isinstance", "(", "condition_or_value", ",", "basestring"...
Wait for the sensor to satisfy a condition. Parameters ---------- condition_or_value : obj or callable, or seq of objs or callables If obj, sensor.value is compared with obj. If callable, condition_or_value(reading) is called, and must return True if its condition is satisfied. Since the reading is passed in, the value, status, timestamp or received_timestamp attributes can all be used in the check. TODO: Sequences of conditions (use SensorTransitionWaiter thingum?) timeout : float or None The timeout in seconds (None means wait forever) Returns ------- This command returns a tornado Future that resolves with True when the sensor value satisfies the condition. It will never resolve with False; if a timeout is given a TimeoutError happens instead. Raises ------ :class:`KATCPSensorError` If the sensor does not have a strategy set :class:`tornado.gen.TimeoutError` If the sensor condition still fails after a stated timeout period
[ "Wait", "for", "the", "sensor", "to", "satisfy", "a", "condition", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/resource.py#L893-L964
16,318
ska-sa/katcp-python
katcp/fake_clients.py
fake_KATCP_client_resource_factory
def fake_KATCP_client_resource_factory( KATCPClientResourceClass, fake_options, resource_spec, *args, **kwargs): """Create a fake KATCPClientResource-like class and a fake-manager Parameters ---------- KATCPClientResourceClass : class Subclass of :class:`katcp.resource_client.KATCPClientResource` fake_options : dict Options for the faking process. Keys: allow_any_request : bool, default False (TODO not implemented behaves as if it were True) resource_spec, *args, **kwargs : passed to KATCPClientResourceClass A subclass of the passed-in KATCPClientResourceClass is created that replaces the internal InspecingClient instances with fakes using fake_inspecting_client_factory() based on the InspectingClient class used by KATCPClientResourceClass. Returns ------- (fake_katcp_client_resource, fake_katcp_client_resource_manager): fake_katcp_client_resource : instance of faked subclass of KATCPClientResourceClass fake_katcp_client_resource_manager : :class:`FakeKATCPClientResourceManager` instance Bound to the `fake_katcp_client_resource` instance. """ # TODO Implement allow_any_request functionality. When True, any unknown request (even # if there is no fake implementation) should succeed allow_any_request = fake_options.get('allow_any_request', False) class FakeKATCPClientResource(KATCPClientResourceClass): def inspecting_client_factory(self, host, port, ioloop_set_to): real_instance = (super(FakeKATCPClientResource, self) .inspecting_client_factory(host, port, ioloop_set_to) ) fic, fic_manager = fake_inspecting_client_factory( real_instance.__class__, fake_options, host, port, ioloop=ioloop_set_to, auto_reconnect=self.auto_reconnect) self.fake_inspecting_client_manager = fic_manager return fic fkcr = FakeKATCPClientResource(resource_spec, *args, **kwargs) fkcr_manager = FakeKATCPClientResourceManager(fkcr) return (fkcr, fkcr_manager)
python
def fake_KATCP_client_resource_factory( KATCPClientResourceClass, fake_options, resource_spec, *args, **kwargs): # TODO Implement allow_any_request functionality. When True, any unknown request (even # if there is no fake implementation) should succeed allow_any_request = fake_options.get('allow_any_request', False) class FakeKATCPClientResource(KATCPClientResourceClass): def inspecting_client_factory(self, host, port, ioloop_set_to): real_instance = (super(FakeKATCPClientResource, self) .inspecting_client_factory(host, port, ioloop_set_to) ) fic, fic_manager = fake_inspecting_client_factory( real_instance.__class__, fake_options, host, port, ioloop=ioloop_set_to, auto_reconnect=self.auto_reconnect) self.fake_inspecting_client_manager = fic_manager return fic fkcr = FakeKATCPClientResource(resource_spec, *args, **kwargs) fkcr_manager = FakeKATCPClientResourceManager(fkcr) return (fkcr, fkcr_manager)
[ "def", "fake_KATCP_client_resource_factory", "(", "KATCPClientResourceClass", ",", "fake_options", ",", "resource_spec", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# TODO Implement allow_any_request functionality. When True, any unknown request (even", "# if there is n...
Create a fake KATCPClientResource-like class and a fake-manager Parameters ---------- KATCPClientResourceClass : class Subclass of :class:`katcp.resource_client.KATCPClientResource` fake_options : dict Options for the faking process. Keys: allow_any_request : bool, default False (TODO not implemented behaves as if it were True) resource_spec, *args, **kwargs : passed to KATCPClientResourceClass A subclass of the passed-in KATCPClientResourceClass is created that replaces the internal InspecingClient instances with fakes using fake_inspecting_client_factory() based on the InspectingClient class used by KATCPClientResourceClass. Returns ------- (fake_katcp_client_resource, fake_katcp_client_resource_manager): fake_katcp_client_resource : instance of faked subclass of KATCPClientResourceClass fake_katcp_client_resource_manager : :class:`FakeKATCPClientResourceManager` instance Bound to the `fake_katcp_client_resource` instance.
[ "Create", "a", "fake", "KATCPClientResource", "-", "like", "class", "and", "a", "fake", "-", "manager" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/fake_clients.py#L16-L59
16,319
ska-sa/katcp-python
katcp/fake_clients.py
fake_KATCP_client_resource_container_factory
def fake_KATCP_client_resource_container_factory( KATCPClientResourceContainerClass, fake_options, resources_spec, *args, **kwargs): """Create a fake KATCPClientResourceContainer-like class and a fake-manager Parameters ---------- KATCPClientResourceContainerClass : class Subclass of :class:`katcp.resource_client.KATCPClientResourceContainer` fake_options : dict Options for the faking process. Keys: allow_any_request : bool, default False (TODO not implemented behaves as if it were True) resources_spec, *args, **kwargs : passed to KATCPClientResourceContainerClass A subclass of the passed-in KATCPClientResourceClassContainer is created that replaces the KATCPClientResource child instances with fakes using fake_KATCP_client_resource_factory() based on the KATCPClientResource class used by `KATCPClientResourceContainerClass`. Returns ------- (fake_katcp_client_resource_container, fake_katcp_client_resource_container_manager): fake_katcp_client_resource_container : instance of faked subclass of KATCPClientResourceContainerClass fake_katcp_client_resource_manager : :class:`FakeKATCPClientResourceContainerManager` instance Bound to the `fake_katcp_client_resource_container` instance. """ # TODO allow_any_request see comment in fake_KATCP_client_resource_factory() allow_any_request = fake_options.get('allow_any_request', False) class FakeKATCPClientResourceContainer(KATCPClientResourceContainerClass): def __init__(self, *args, **kwargs): self.fake_client_resource_managers = {} super(FakeKATCPClientResourceContainer, self).__init__(*args, **kwargs) def client_resource_factory(self, res_spec, parent, logger): real_instance = (super(FakeKATCPClientResourceContainer, self) .client_resource_factory(res_spec, parent, logger) ) fkcr, fkcr_manager = fake_KATCP_client_resource_factory( real_instance.__class__, fake_options, res_spec, parent=self, logger=logger) self.fake_client_resource_managers[ resource.escape_name(fkcr.name)] = fkcr_manager return fkcr fkcrc = FakeKATCPClientResourceContainer(resources_spec, *args, **kwargs) fkcrc_manager = FakeKATCPClientResourceContainerManager(fkcrc) return (fkcrc, fkcrc_manager)
python
def fake_KATCP_client_resource_container_factory( KATCPClientResourceContainerClass, fake_options, resources_spec, *args, **kwargs): # TODO allow_any_request see comment in fake_KATCP_client_resource_factory() allow_any_request = fake_options.get('allow_any_request', False) class FakeKATCPClientResourceContainer(KATCPClientResourceContainerClass): def __init__(self, *args, **kwargs): self.fake_client_resource_managers = {} super(FakeKATCPClientResourceContainer, self).__init__(*args, **kwargs) def client_resource_factory(self, res_spec, parent, logger): real_instance = (super(FakeKATCPClientResourceContainer, self) .client_resource_factory(res_spec, parent, logger) ) fkcr, fkcr_manager = fake_KATCP_client_resource_factory( real_instance.__class__, fake_options, res_spec, parent=self, logger=logger) self.fake_client_resource_managers[ resource.escape_name(fkcr.name)] = fkcr_manager return fkcr fkcrc = FakeKATCPClientResourceContainer(resources_spec, *args, **kwargs) fkcrc_manager = FakeKATCPClientResourceContainerManager(fkcrc) return (fkcrc, fkcrc_manager)
[ "def", "fake_KATCP_client_resource_container_factory", "(", "KATCPClientResourceContainerClass", ",", "fake_options", ",", "resources_spec", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# TODO allow_any_request see comment in fake_KATCP_client_resource_factory()", "allow...
Create a fake KATCPClientResourceContainer-like class and a fake-manager Parameters ---------- KATCPClientResourceContainerClass : class Subclass of :class:`katcp.resource_client.KATCPClientResourceContainer` fake_options : dict Options for the faking process. Keys: allow_any_request : bool, default False (TODO not implemented behaves as if it were True) resources_spec, *args, **kwargs : passed to KATCPClientResourceContainerClass A subclass of the passed-in KATCPClientResourceClassContainer is created that replaces the KATCPClientResource child instances with fakes using fake_KATCP_client_resource_factory() based on the KATCPClientResource class used by `KATCPClientResourceContainerClass`. Returns ------- (fake_katcp_client_resource_container, fake_katcp_client_resource_container_manager): fake_katcp_client_resource_container : instance of faked subclass of KATCPClientResourceContainerClass fake_katcp_client_resource_manager : :class:`FakeKATCPClientResourceContainerManager` instance Bound to the `fake_katcp_client_resource_container` instance.
[ "Create", "a", "fake", "KATCPClientResourceContainer", "-", "like", "class", "and", "a", "fake", "-", "manager" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/fake_clients.py#L61-L111
16,320
ska-sa/katcp-python
katcp/fake_clients.py
FakeInspectingClientManager.add_sensors
def add_sensors(self, sensor_infos): """Add fake sensors sensor_infos is a dict <sensor-name> : ( <description>, <unit>, <sensor-type>, <params>*) The sensor info is string-reprs of whatever they are, as they would be on the wire in a real KATCP connection. Values are passed to a katcp.Message object, so some automatic conversions are done, hence it is OK to pass numbers without stringifying them. """ # Check sensor validity. parse_type() and parse_params should raise if not OK for s_name, s_info in sensor_infos.items(): s_type = Sensor.parse_type(s_info[2]) s_params = Sensor.parse_params(s_type, s_info[3:]) self.fake_sensor_infos.update(sensor_infos) self._fic._interface_changed.set()
python
def add_sensors(self, sensor_infos): # Check sensor validity. parse_type() and parse_params should raise if not OK for s_name, s_info in sensor_infos.items(): s_type = Sensor.parse_type(s_info[2]) s_params = Sensor.parse_params(s_type, s_info[3:]) self.fake_sensor_infos.update(sensor_infos) self._fic._interface_changed.set()
[ "def", "add_sensors", "(", "self", ",", "sensor_infos", ")", ":", "# Check sensor validity. parse_type() and parse_params should raise if not OK", "for", "s_name", ",", "s_info", "in", "sensor_infos", ".", "items", "(", ")", ":", "s_type", "=", "Sensor", ".", "parse_t...
Add fake sensors sensor_infos is a dict <sensor-name> : ( <description>, <unit>, <sensor-type>, <params>*) The sensor info is string-reprs of whatever they are, as they would be on the wire in a real KATCP connection. Values are passed to a katcp.Message object, so some automatic conversions are done, hence it is OK to pass numbers without stringifying them.
[ "Add", "fake", "sensors" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/fake_clients.py#L253-L269
16,321
ska-sa/katcp-python
katcp/fake_clients.py
FakeInspectingClientManager.add_request_handlers_dict
def add_request_handlers_dict(self, rh_dict): """Add fake request handler functions from a dict keyed by request name Note the keys must be the KATCP message name (i.e. "the-request", not "the_request") The request-handler interface is more or less compatible with request handler API in :class:`katcp.server.DeviceServerBase`. The fake ClientRequestConnection req object does not support mass_inform() or reply_with_message. """ # Check that all the callables have docstrings as strings for req_func in rh_dict.values(): assert req_func.__doc__, "Even fake request handlers must have docstrings" self._fkc.request_handlers.update(rh_dict) self._fic._interface_changed.set()
python
def add_request_handlers_dict(self, rh_dict): # Check that all the callables have docstrings as strings for req_func in rh_dict.values(): assert req_func.__doc__, "Even fake request handlers must have docstrings" self._fkc.request_handlers.update(rh_dict) self._fic._interface_changed.set()
[ "def", "add_request_handlers_dict", "(", "self", ",", "rh_dict", ")", ":", "# Check that all the callables have docstrings as strings", "for", "req_func", "in", "rh_dict", ".", "values", "(", ")", ":", "assert", "req_func", ".", "__doc__", ",", "\"Even fake request hand...
Add fake request handler functions from a dict keyed by request name Note the keys must be the KATCP message name (i.e. "the-request", not "the_request") The request-handler interface is more or less compatible with request handler API in :class:`katcp.server.DeviceServerBase`. The fake ClientRequestConnection req object does not support mass_inform() or reply_with_message.
[ "Add", "fake", "request", "handler", "functions", "from", "a", "dict", "keyed", "by", "request", "name" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/fake_clients.py#L288-L303
16,322
ska-sa/katcp-python
katcp/inspecting_client.py
ExponentialRandomBackoff.failed
def failed(self): """Call whenever an action has failed, grows delay exponentially After calling failed(), the `delay` property contains the next delay """ try: self._validate_parameters() self._base_delay = min( self._base_delay * self.exp_fac, self.delay_max) self._update_delay() except Exception: ic_logger.exception( 'Unhandled exception trying to calculate a retry timout')
python
def failed(self): try: self._validate_parameters() self._base_delay = min( self._base_delay * self.exp_fac, self.delay_max) self._update_delay() except Exception: ic_logger.exception( 'Unhandled exception trying to calculate a retry timout')
[ "def", "failed", "(", "self", ")", ":", "try", ":", "self", ".", "_validate_parameters", "(", ")", "self", ".", "_base_delay", "=", "min", "(", "self", ".", "_base_delay", "*", "self", ".", "exp_fac", ",", "self", ".", "delay_max", ")", "self", ".", ...
Call whenever an action has failed, grows delay exponentially After calling failed(), the `delay` property contains the next delay
[ "Call", "whenever", "an", "action", "has", "failed", "grows", "delay", "exponentially" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/inspecting_client.py#L71-L84
16,323
ska-sa/katcp-python
katcp/inspecting_client.py
_InformHookDeviceClient.hook_inform
def hook_inform(self, inform_name, callback): """Hookup a function to be called when an inform is received. Useful for interface-changed and sensor-status informs. Parameters ---------- inform_name : str The name of the inform. callback : function The function to be called. """ # Do not hook the same callback multiple times if callback not in self._inform_hooks[inform_name]: self._inform_hooks[inform_name].append(callback)
python
def hook_inform(self, inform_name, callback): # Do not hook the same callback multiple times if callback not in self._inform_hooks[inform_name]: self._inform_hooks[inform_name].append(callback)
[ "def", "hook_inform", "(", "self", ",", "inform_name", ",", "callback", ")", ":", "# Do not hook the same callback multiple times", "if", "callback", "not", "in", "self", ".", "_inform_hooks", "[", "inform_name", "]", ":", "self", ".", "_inform_hooks", "[", "infor...
Hookup a function to be called when an inform is received. Useful for interface-changed and sensor-status informs. Parameters ---------- inform_name : str The name of the inform. callback : function The function to be called.
[ "Hookup", "a", "function", "to", "be", "called", "when", "an", "inform", "is", "received", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/inspecting_client.py#L135-L150
16,324
ska-sa/katcp-python
katcp/inspecting_client.py
_InformHookDeviceClient.handle_inform
def handle_inform(self, msg): """Call callbacks on hooked informs followed by normal processing""" try: for func in self._inform_hooks.get(msg.name, []): func(msg) except Exception: self._logger.warning('Call to function "{0}" with message "{1}".' .format(func, msg), exc_info=True) super(_InformHookDeviceClient, self).handle_inform(msg)
python
def handle_inform(self, msg): try: for func in self._inform_hooks.get(msg.name, []): func(msg) except Exception: self._logger.warning('Call to function "{0}" with message "{1}".' .format(func, msg), exc_info=True) super(_InformHookDeviceClient, self).handle_inform(msg)
[ "def", "handle_inform", "(", "self", ",", "msg", ")", ":", "try", ":", "for", "func", "in", "self", ".", "_inform_hooks", ".", "get", "(", "msg", ".", "name", ",", "[", "]", ")", ":", "func", "(", "msg", ")", "except", "Exception", ":", "self", "...
Call callbacks on hooked informs followed by normal processing
[ "Call", "callbacks", "on", "hooked", "informs", "followed", "by", "normal", "processing" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/inspecting_client.py#L152-L160
16,325
ska-sa/katcp-python
katcp/inspecting_client.py
InspectingClientAsync.until_state
def until_state(self, desired_state, timeout=None): """ Wait until state is desired_state, InspectingClientStateType instance Returns a future """ return self._state.until_state(desired_state, timeout=timeout)
python
def until_state(self, desired_state, timeout=None): return self._state.until_state(desired_state, timeout=timeout)
[ "def", "until_state", "(", "self", ",", "desired_state", ",", "timeout", "=", "None", ")", ":", "return", "self", ".", "_state", ".", "until_state", "(", "desired_state", ",", "timeout", "=", "timeout", ")" ]
Wait until state is desired_state, InspectingClientStateType instance Returns a future
[ "Wait", "until", "state", "is", "desired_state", "InspectingClientStateType", "instance" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/inspecting_client.py#L336-L343
16,326
ska-sa/katcp-python
katcp/inspecting_client.py
InspectingClientAsync.connect
def connect(self, timeout=None): """Connect to KATCP interface, starting what is needed Parameters ---------- timeout : float, None Time to wait until connected. No waiting if None. Raises ------ :class:`tornado.gen.TimeoutError` if the connect timeout expires """ # Start KATCP device client. assert not self._running maybe_timeout = future_timeout_manager(timeout) self._logger.debug('Starting katcp client') self.katcp_client.start() try: yield maybe_timeout(self.katcp_client.until_running()) self._logger.debug('Katcp client running') except tornado.gen.TimeoutError: self.katcp_client.stop() raise if timeout: yield maybe_timeout(self.katcp_client.until_connected()) self._logger.debug('Katcp client connected') self._running = True self._state_loop()
python
def connect(self, timeout=None): # Start KATCP device client. assert not self._running maybe_timeout = future_timeout_manager(timeout) self._logger.debug('Starting katcp client') self.katcp_client.start() try: yield maybe_timeout(self.katcp_client.until_running()) self._logger.debug('Katcp client running') except tornado.gen.TimeoutError: self.katcp_client.stop() raise if timeout: yield maybe_timeout(self.katcp_client.until_connected()) self._logger.debug('Katcp client connected') self._running = True self._state_loop()
[ "def", "connect", "(", "self", ",", "timeout", "=", "None", ")", ":", "# Start KATCP device client.", "assert", "not", "self", ".", "_running", "maybe_timeout", "=", "future_timeout_manager", "(", "timeout", ")", "self", ".", "_logger", ".", "debug", "(", "'St...
Connect to KATCP interface, starting what is needed Parameters ---------- timeout : float, None Time to wait until connected. No waiting if None. Raises ------ :class:`tornado.gen.TimeoutError` if the connect timeout expires
[ "Connect", "to", "KATCP", "interface", "starting", "what", "is", "needed" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/inspecting_client.py#L346-L378
16,327
ska-sa/katcp-python
katcp/inspecting_client.py
InspectingClientAsync.inspect
def inspect(self): """Inspect device requests and sensors, update model Returns ------- Tornado future that resolves with: model_changes : Nested AttrDict or None Contains sets of added/removed request/sensor names Example structure: {'requests': { 'added': set(['req1', 'req2']), 'removed': set(['req10', 'req20'])} 'sensors': { 'added': set(['sens1', 'sens2']), 'removed': set(['sens10', 'sens20'])} } If there are no changes keys may be omitted. If an item is in both the 'added' and 'removed' sets that means that it changed. If neither request not sensor changes are present, None is returned instead of a nested structure. """ timeout_manager = future_timeout_manager(self.sync_timeout) sensor_index_before = copy.copy(self._sensors_index) request_index_before = copy.copy(self._requests_index) try: request_changes = yield self.inspect_requests( timeout=timeout_manager.remaining()) sensor_changes = yield self.inspect_sensors( timeout=timeout_manager.remaining()) except Exception: # Ensure atomicity of sensor and request updates ; if the one # fails, the other should act as if it has failed too. self._sensors_index = sensor_index_before self._requests_index = request_index_before raise model_changes = AttrDict() if request_changes: model_changes.requests = request_changes if sensor_changes: model_changes.sensors = sensor_changes if model_changes: raise Return(model_changes)
python
def inspect(self): timeout_manager = future_timeout_manager(self.sync_timeout) sensor_index_before = copy.copy(self._sensors_index) request_index_before = copy.copy(self._requests_index) try: request_changes = yield self.inspect_requests( timeout=timeout_manager.remaining()) sensor_changes = yield self.inspect_sensors( timeout=timeout_manager.remaining()) except Exception: # Ensure atomicity of sensor and request updates ; if the one # fails, the other should act as if it has failed too. self._sensors_index = sensor_index_before self._requests_index = request_index_before raise model_changes = AttrDict() if request_changes: model_changes.requests = request_changes if sensor_changes: model_changes.sensors = sensor_changes if model_changes: raise Return(model_changes)
[ "def", "inspect", "(", "self", ")", ":", "timeout_manager", "=", "future_timeout_manager", "(", "self", ".", "sync_timeout", ")", "sensor_index_before", "=", "copy", ".", "copy", "(", "self", ".", "_sensors_index", ")", "request_index_before", "=", "copy", ".", ...
Inspect device requests and sensors, update model Returns ------- Tornado future that resolves with: model_changes : Nested AttrDict or None Contains sets of added/removed request/sensor names Example structure: {'requests': { 'added': set(['req1', 'req2']), 'removed': set(['req10', 'req20'])} 'sensors': { 'added': set(['sens1', 'sens2']), 'removed': set(['sens10', 'sens20'])} } If there are no changes keys may be omitted. If an item is in both the 'added' and 'removed' sets that means that it changed. If neither request not sensor changes are present, None is returned instead of a nested structure.
[ "Inspect", "device", "requests", "and", "sensors", "update", "model" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/inspecting_client.py#L541-L590
16,328
ska-sa/katcp-python
katcp/inspecting_client.py
InspectingClientAsync.inspect_requests
def inspect_requests(self, name=None, timeout=None): """Inspect all or one requests on the device. Update requests index. Parameters ---------- name : str or None, optional Name of the request or None to get all requests. timeout : float or None, optional Timeout for request inspection, None for no timeout Returns ------- Tornado future that resolves with: changes : :class:`~katcp.core.AttrDict` AttrDict with keys ``added`` and ``removed`` (of type :class:`set`), listing the requests that have been added or removed respectively. Modified requests are listed in both. If there are no changes, returns ``None`` instead. Example structure: {'added': set(['req1', 'req2']), 'removed': set(['req10', 'req20'])} """ maybe_timeout = future_timeout_manager(timeout) if name is None: msg = katcp.Message.request('help') else: msg = katcp.Message.request('help', name) reply, informs = yield self.katcp_client.future_request( msg, timeout=maybe_timeout.remaining()) if not reply.reply_ok(): # If an unknown request is specified the desired result is to return # an empty list even though the request will fail if name is None or 'Unknown request' not in reply.arguments[1]: raise SyncError( 'Error reply during sync process for {}: {}' .format(self.bind_address_string, reply)) # Get recommended timeouts hints for slow requests if the server # provides them timeout_hints_available = ( self.katcp_client.protocol_flags.request_timeout_hints) if timeout_hints_available: timeout_hints = yield self._get_request_timeout_hints( name, timeout=maybe_timeout.remaining()) else: timeout_hints = {} requests_old = set(self._requests_index.keys()) requests_updated = set() for msg in informs: req_name = msg.arguments[0] req = {'name': req_name, 'description': msg.arguments[1], 'timeout_hint': timeout_hints.get(req_name)} requests_updated.add(req_name) self._update_index(self._requests_index, req_name, req) added, removed = self._difference( requests_old, requests_updated, name, self._requests_index) if added or removed: raise Return(AttrDict(added=added, removed=removed))
python
def inspect_requests(self, name=None, timeout=None): maybe_timeout = future_timeout_manager(timeout) if name is None: msg = katcp.Message.request('help') else: msg = katcp.Message.request('help', name) reply, informs = yield self.katcp_client.future_request( msg, timeout=maybe_timeout.remaining()) if not reply.reply_ok(): # If an unknown request is specified the desired result is to return # an empty list even though the request will fail if name is None or 'Unknown request' not in reply.arguments[1]: raise SyncError( 'Error reply during sync process for {}: {}' .format(self.bind_address_string, reply)) # Get recommended timeouts hints for slow requests if the server # provides them timeout_hints_available = ( self.katcp_client.protocol_flags.request_timeout_hints) if timeout_hints_available: timeout_hints = yield self._get_request_timeout_hints( name, timeout=maybe_timeout.remaining()) else: timeout_hints = {} requests_old = set(self._requests_index.keys()) requests_updated = set() for msg in informs: req_name = msg.arguments[0] req = {'name': req_name, 'description': msg.arguments[1], 'timeout_hint': timeout_hints.get(req_name)} requests_updated.add(req_name) self._update_index(self._requests_index, req_name, req) added, removed = self._difference( requests_old, requests_updated, name, self._requests_index) if added or removed: raise Return(AttrDict(added=added, removed=removed))
[ "def", "inspect_requests", "(", "self", ",", "name", "=", "None", ",", "timeout", "=", "None", ")", ":", "maybe_timeout", "=", "future_timeout_manager", "(", "timeout", ")", "if", "name", "is", "None", ":", "msg", "=", "katcp", ".", "Message", ".", "requ...
Inspect all or one requests on the device. Update requests index. Parameters ---------- name : str or None, optional Name of the request or None to get all requests. timeout : float or None, optional Timeout for request inspection, None for no timeout Returns ------- Tornado future that resolves with: changes : :class:`~katcp.core.AttrDict` AttrDict with keys ``added`` and ``removed`` (of type :class:`set`), listing the requests that have been added or removed respectively. Modified requests are listed in both. If there are no changes, returns ``None`` instead. Example structure: {'added': set(['req1', 'req2']), 'removed': set(['req10', 'req20'])}
[ "Inspect", "all", "or", "one", "requests", "on", "the", "device", ".", "Update", "requests", "index", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/inspecting_client.py#L593-L657
16,329
ska-sa/katcp-python
katcp/inspecting_client.py
InspectingClientAsync._get_request_timeout_hints
def _get_request_timeout_hints(self, name=None, timeout=None): """Get request timeout hints from device Parameters ========= name : str or None, optional Name of the request or None to get all request timeout hints. timeout : float seconds Timeout for ?request-timeout-hint Returns ------- Tornado future that resolves with: timeout_hints : dict request_name -> timeout_hint where request_name : str Name of the request timeout_hint : float Suggested request timeout hint from device ?request-timeout_hint Note, if there is no request hint, there will be no entry in the dict. If you request the hint for a named request that has no hint, an empty dict will be returned. """ timeout_hints = {} req_msg_args = ['request-timeout-hint'] if name: req_msg_args.append(name) req_msg = katcp.Message.request(*req_msg_args) reply, informs = yield self.katcp_client.future_request( req_msg, timeout=timeout) if not reply.reply_ok(): raise SyncError('Error retrieving request timeout hints: "{}"\n' 'in reply to request {}, continuing with sync' .format(reply, req_msg)) for inform in informs: request_name = inform.arguments[0] timeout_hint = float(inform.arguments[1]) if timeout_hint > 0: timeout_hints[request_name] = timeout_hint raise Return(timeout_hints)
python
def _get_request_timeout_hints(self, name=None, timeout=None): timeout_hints = {} req_msg_args = ['request-timeout-hint'] if name: req_msg_args.append(name) req_msg = katcp.Message.request(*req_msg_args) reply, informs = yield self.katcp_client.future_request( req_msg, timeout=timeout) if not reply.reply_ok(): raise SyncError('Error retrieving request timeout hints: "{}"\n' 'in reply to request {}, continuing with sync' .format(reply, req_msg)) for inform in informs: request_name = inform.arguments[0] timeout_hint = float(inform.arguments[1]) if timeout_hint > 0: timeout_hints[request_name] = timeout_hint raise Return(timeout_hints)
[ "def", "_get_request_timeout_hints", "(", "self", ",", "name", "=", "None", ",", "timeout", "=", "None", ")", ":", "timeout_hints", "=", "{", "}", "req_msg_args", "=", "[", "'request-timeout-hint'", "]", "if", "name", ":", "req_msg_args", ".", "append", "(",...
Get request timeout hints from device Parameters ========= name : str or None, optional Name of the request or None to get all request timeout hints. timeout : float seconds Timeout for ?request-timeout-hint Returns ------- Tornado future that resolves with: timeout_hints : dict request_name -> timeout_hint where request_name : str Name of the request timeout_hint : float Suggested request timeout hint from device ?request-timeout_hint Note, if there is no request hint, there will be no entry in the dict. If you request the hint for a named request that has no hint, an empty dict will be returned.
[ "Get", "request", "timeout", "hints", "from", "device" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/inspecting_client.py#L660-L704
16,330
ska-sa/katcp-python
katcp/inspecting_client.py
InspectingClientAsync.inspect_sensors
def inspect_sensors(self, name=None, timeout=None): """Inspect all or one sensor on the device. Update sensors index. Parameters ---------- name : str or None, optional Name of the sensor or None to get all sensors. timeout : float or None, optional Timeout for sensors inspection, None for no timeout Returns ------- Tornado future that resolves with: changes : :class:`~katcp.core.AttrDict` AttrDict with keys ``added`` and ``removed`` (of type :class:`set`), listing the sensors that have been added or removed respectively. Modified sensors are listed in both. If there are no changes, returns ``None`` instead. Example structure: {'added': set(['sens1', 'sens2']), 'removed': set(['sens10', 'sens20'])} """ if name is None: msg = katcp.Message.request('sensor-list') else: msg = katcp.Message.request('sensor-list', name) reply, informs = yield self.katcp_client.future_request( msg, timeout=timeout) self._logger.debug('{} received {} sensor-list informs, reply: {}' .format(self.bind_address_string, len(informs), reply)) if not reply.reply_ok(): # If an unknown sensor is specified the desired result is to return # an empty list, even though the request will fail if name is None or 'Unknown sensor' not in reply.arguments[1]: raise SyncError('Error reply during sync process: {}' .format(reply)) sensors_old = set(self._sensors_index.keys()) sensors_updated = set() for msg in informs: sen_name = msg.arguments[0] sensors_updated.add(sen_name) sen = {'description': msg.arguments[1], 'units': msg.arguments[2], 'sensor_type': msg.arguments[3], 'params': msg.arguments[4:]} self._update_index(self._sensors_index, sen_name, sen) added, removed = self._difference( sensors_old, sensors_updated, name, self._sensors_index) for sensor_name in removed: if sensor_name in self._sensor_object_cache: del self._sensor_object_cache[sensor_name] if added or removed: raise Return(AttrDict(added=added, removed=removed))
python
def inspect_sensors(self, name=None, timeout=None): if name is None: msg = katcp.Message.request('sensor-list') else: msg = katcp.Message.request('sensor-list', name) reply, informs = yield self.katcp_client.future_request( msg, timeout=timeout) self._logger.debug('{} received {} sensor-list informs, reply: {}' .format(self.bind_address_string, len(informs), reply)) if not reply.reply_ok(): # If an unknown sensor is specified the desired result is to return # an empty list, even though the request will fail if name is None or 'Unknown sensor' not in reply.arguments[1]: raise SyncError('Error reply during sync process: {}' .format(reply)) sensors_old = set(self._sensors_index.keys()) sensors_updated = set() for msg in informs: sen_name = msg.arguments[0] sensors_updated.add(sen_name) sen = {'description': msg.arguments[1], 'units': msg.arguments[2], 'sensor_type': msg.arguments[3], 'params': msg.arguments[4:]} self._update_index(self._sensors_index, sen_name, sen) added, removed = self._difference( sensors_old, sensors_updated, name, self._sensors_index) for sensor_name in removed: if sensor_name in self._sensor_object_cache: del self._sensor_object_cache[sensor_name] if added or removed: raise Return(AttrDict(added=added, removed=removed))
[ "def", "inspect_sensors", "(", "self", ",", "name", "=", "None", ",", "timeout", "=", "None", ")", ":", "if", "name", "is", "None", ":", "msg", "=", "katcp", ".", "Message", ".", "request", "(", "'sensor-list'", ")", "else", ":", "msg", "=", "katcp",...
Inspect all or one sensor on the device. Update sensors index. Parameters ---------- name : str or None, optional Name of the sensor or None to get all sensors. timeout : float or None, optional Timeout for sensors inspection, None for no timeout Returns ------- Tornado future that resolves with: changes : :class:`~katcp.core.AttrDict` AttrDict with keys ``added`` and ``removed`` (of type :class:`set`), listing the sensors that have been added or removed respectively. Modified sensors are listed in both. If there are no changes, returns ``None`` instead. Example structure: {'added': set(['sens1', 'sens2']), 'removed': set(['sens10', 'sens20'])}
[ "Inspect", "all", "or", "one", "sensor", "on", "the", "device", ".", "Update", "sensors", "index", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/inspecting_client.py#L707-L769
16,331
ska-sa/katcp-python
katcp/inspecting_client.py
InspectingClientAsync.future_check_sensor
def future_check_sensor(self, name, update=None): """Check if the sensor exists. Used internally by future_get_sensor. This method is aware of synchronisation in progress and if inspection of the server is allowed. Parameters ---------- name : str Name of the sensor to verify. update : bool or None, optional If a katcp request to the server should be made to check if the sensor is on the server now. Notes ----- Ensure that self.state.data_synced == True if yielding to future_check_sensor from a state-change callback, or a deadlock will occur. """ exist = False yield self.until_data_synced() if name in self._sensors_index: exist = True else: if update or (update is None and self._update_on_lookup): yield self.inspect_sensors(name) exist = yield self.future_check_sensor(name, False) raise tornado.gen.Return(exist)
python
def future_check_sensor(self, name, update=None): exist = False yield self.until_data_synced() if name in self._sensors_index: exist = True else: if update or (update is None and self._update_on_lookup): yield self.inspect_sensors(name) exist = yield self.future_check_sensor(name, False) raise tornado.gen.Return(exist)
[ "def", "future_check_sensor", "(", "self", ",", "name", ",", "update", "=", "None", ")", ":", "exist", "=", "False", "yield", "self", ".", "until_data_synced", "(", ")", "if", "name", "in", "self", ".", "_sensors_index", ":", "exist", "=", "True", "else"...
Check if the sensor exists. Used internally by future_get_sensor. This method is aware of synchronisation in progress and if inspection of the server is allowed. Parameters ---------- name : str Name of the sensor to verify. update : bool or None, optional If a katcp request to the server should be made to check if the sensor is on the server now. Notes ----- Ensure that self.state.data_synced == True if yielding to future_check_sensor from a state-change callback, or a deadlock will occur.
[ "Check", "if", "the", "sensor", "exists", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/inspecting_client.py#L772-L802
16,332
ska-sa/katcp-python
katcp/inspecting_client.py
InspectingClientAsync.future_get_sensor
def future_get_sensor(self, name, update=None): """Get the sensor object. Check if we have information for this sensor, if not connect to server and update (if allowed) to get information. Parameters ---------- name : string Name of the sensor. update : bool or None, optional True allow inspect client to inspect katcp server if the sensor is not known. Returns ------- Sensor created by :meth:`sensor_factory` or None if sensor not found. Notes ----- Ensure that self.state.data_synced == True if yielding to future_get_sensor from a state-change callback, or a deadlock will occur. """ obj = None exist = yield self.future_check_sensor(name, update) if exist: sensor_info = self._sensors_index[name] obj = sensor_info.get('obj') if obj is None: sensor_type = katcp.Sensor.parse_type( sensor_info.get('sensor_type')) sensor_params = katcp.Sensor.parse_params( sensor_type, sensor_info.get('params')) obj = self.sensor_factory( name=name, sensor_type=sensor_type, description=sensor_info.get('description'), units=sensor_info.get('units'), params=sensor_params) self._sensors_index[name]['obj'] = obj self._sensor_object_cache[name] = obj raise tornado.gen.Return(obj)
python
def future_get_sensor(self, name, update=None): obj = None exist = yield self.future_check_sensor(name, update) if exist: sensor_info = self._sensors_index[name] obj = sensor_info.get('obj') if obj is None: sensor_type = katcp.Sensor.parse_type( sensor_info.get('sensor_type')) sensor_params = katcp.Sensor.parse_params( sensor_type, sensor_info.get('params')) obj = self.sensor_factory( name=name, sensor_type=sensor_type, description=sensor_info.get('description'), units=sensor_info.get('units'), params=sensor_params) self._sensors_index[name]['obj'] = obj self._sensor_object_cache[name] = obj raise tornado.gen.Return(obj)
[ "def", "future_get_sensor", "(", "self", ",", "name", ",", "update", "=", "None", ")", ":", "obj", "=", "None", "exist", "=", "yield", "self", ".", "future_check_sensor", "(", "name", ",", "update", ")", "if", "exist", ":", "sensor_info", "=", "self", ...
Get the sensor object. Check if we have information for this sensor, if not connect to server and update (if allowed) to get information. Parameters ---------- name : string Name of the sensor. update : bool or None, optional True allow inspect client to inspect katcp server if the sensor is not known. Returns ------- Sensor created by :meth:`sensor_factory` or None if sensor not found. Notes ----- Ensure that self.state.data_synced == True if yielding to future_get_sensor from a state-change callback, or a deadlock will occur.
[ "Get", "the", "sensor", "object", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/inspecting_client.py#L805-L849
16,333
ska-sa/katcp-python
katcp/inspecting_client.py
InspectingClientAsync.future_check_request
def future_check_request(self, name, update=None): """Check if the request exists. Used internally by future_get_request. This method is aware of synchronisation in progress and if inspection of the server is allowed. Parameters ---------- name : str Name of the request to verify. update : bool or None, optional If a katcp request to the server should be made to check if the sensor is on the server. True = Allow, False do not Allow, None use the class default. Notes ----- Ensure that self.state.data_synced == True if yielding to future_check_request from a state-change callback, or a deadlock will occur. """ exist = False yield self.until_data_synced() if name in self._requests_index: exist = True else: if update or (update is None and self._update_on_lookup): yield self.inspect_requests(name) exist = yield self.future_check_request(name, False) raise tornado.gen.Return(exist)
python
def future_check_request(self, name, update=None): exist = False yield self.until_data_synced() if name in self._requests_index: exist = True else: if update or (update is None and self._update_on_lookup): yield self.inspect_requests(name) exist = yield self.future_check_request(name, False) raise tornado.gen.Return(exist)
[ "def", "future_check_request", "(", "self", ",", "name", ",", "update", "=", "None", ")", ":", "exist", "=", "False", "yield", "self", ".", "until_data_synced", "(", ")", "if", "name", "in", "self", ".", "_requests_index", ":", "exist", "=", "True", "els...
Check if the request exists. Used internally by future_get_request. This method is aware of synchronisation in progress and if inspection of the server is allowed. Parameters ---------- name : str Name of the request to verify. update : bool or None, optional If a katcp request to the server should be made to check if the sensor is on the server. True = Allow, False do not Allow, None use the class default. Notes ----- Ensure that self.state.data_synced == True if yielding to future_check_request from a state-change callback, or a deadlock will occur.
[ "Check", "if", "the", "request", "exists", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/inspecting_client.py#L852-L881
16,334
ska-sa/katcp-python
katcp/inspecting_client.py
InspectingClientAsync.future_get_request
def future_get_request(self, name, update=None): """Get the request object. Check if we have information for this request, if not connect to server and update (if allowed). Parameters ---------- name : string Name of the request. update : bool or None, optional True allow inspect client to inspect katcp server if the request is not known. Returns ------- Request created by :meth:`request_factory` or None if request not found. Notes ----- Ensure that self.state.data_synced == True if yielding to future_get_request from a state-change callback, or a deadlock will occur. """ obj = None exist = yield self.future_check_request(name, update) if exist: request_info = self._requests_index[name] obj = request_info.get('obj') if obj is None: obj = self.request_factory(**request_info) self._requests_index[name]['obj'] = obj raise tornado.gen.Return(obj)
python
def future_get_request(self, name, update=None): obj = None exist = yield self.future_check_request(name, update) if exist: request_info = self._requests_index[name] obj = request_info.get('obj') if obj is None: obj = self.request_factory(**request_info) self._requests_index[name]['obj'] = obj raise tornado.gen.Return(obj)
[ "def", "future_get_request", "(", "self", ",", "name", ",", "update", "=", "None", ")", ":", "obj", "=", "None", "exist", "=", "yield", "self", ".", "future_check_request", "(", "name", ",", "update", ")", "if", "exist", ":", "request_info", "=", "self",...
Get the request object. Check if we have information for this request, if not connect to server and update (if allowed). Parameters ---------- name : string Name of the request. update : bool or None, optional True allow inspect client to inspect katcp server if the request is not known. Returns ------- Request created by :meth:`request_factory` or None if request not found. Notes ----- Ensure that self.state.data_synced == True if yielding to future_get_request from a state-change callback, or a deadlock will occur.
[ "Get", "the", "request", "object", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/inspecting_client.py#L884-L917
16,335
ska-sa/katcp-python
katcp/inspecting_client.py
InspectingClientAsync._cb_inform_sensor_status
def _cb_inform_sensor_status(self, msg): """Update received for an sensor.""" timestamp = msg.arguments[0] num_sensors = int(msg.arguments[1]) assert len(msg.arguments) == 2 + num_sensors * 3 for n in xrange(num_sensors): name = msg.arguments[2 + n * 3] status = msg.arguments[3 + n * 3] value = msg.arguments[4 + n * 3] self.update_sensor(name, timestamp, status, value)
python
def _cb_inform_sensor_status(self, msg): timestamp = msg.arguments[0] num_sensors = int(msg.arguments[1]) assert len(msg.arguments) == 2 + num_sensors * 3 for n in xrange(num_sensors): name = msg.arguments[2 + n * 3] status = msg.arguments[3 + n * 3] value = msg.arguments[4 + n * 3] self.update_sensor(name, timestamp, status, value)
[ "def", "_cb_inform_sensor_status", "(", "self", ",", "msg", ")", ":", "timestamp", "=", "msg", ".", "arguments", "[", "0", "]", "num_sensors", "=", "int", "(", "msg", ".", "arguments", "[", "1", "]", ")", "assert", "len", "(", "msg", ".", "arguments", ...
Update received for an sensor.
[ "Update", "received", "for", "an", "sensor", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/inspecting_client.py#L945-L954
16,336
ska-sa/katcp-python
katcp/inspecting_client.py
InspectingClientAsync._cb_inform_interface_change
def _cb_inform_interface_change(self, msg): """Update the sensors and requests available.""" self._logger.debug('cb_inform_interface_change(%s)', msg) self._interface_changed.set()
python
def _cb_inform_interface_change(self, msg): self._logger.debug('cb_inform_interface_change(%s)', msg) self._interface_changed.set()
[ "def", "_cb_inform_interface_change", "(", "self", ",", "msg", ")", ":", "self", ".", "_logger", ".", "debug", "(", "'cb_inform_interface_change(%s)'", ",", "msg", ")", "self", ".", "_interface_changed", ".", "set", "(", ")" ]
Update the sensors and requests available.
[ "Update", "the", "sensors", "and", "requests", "available", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/inspecting_client.py#L956-L959
16,337
ska-sa/katcp-python
katcp/inspecting_client.py
InspectingClientAsync._difference
def _difference(self, original_keys, updated_keys, name, item_index): """Calculate difference between the original and updated sets of keys. Removed items will be removed from item_index, new items should have been added by the discovery process. (?help or ?sensor-list) This method is for use in inspect_requests and inspect_sensors only. Returns ------- (added, removed) added : set of str Names of the keys that were added removed : set of str Names of the keys that were removed """ original_keys = set(original_keys) updated_keys = set(updated_keys) added_keys = updated_keys.difference(original_keys) removed_keys = set() if name is None: removed_keys = original_keys.difference(updated_keys) elif name not in updated_keys and name in original_keys: removed_keys = set([name]) for key in removed_keys: if key in item_index: del(item_index[key]) # Check the keys that was not added now or not lined up for removal, # and see if they changed. for key in updated_keys.difference(added_keys.union(removed_keys)): if item_index[key].get('_changed'): item_index[key]['_changed'] = False removed_keys.add(key) added_keys.add(key) return added_keys, removed_keys
python
def _difference(self, original_keys, updated_keys, name, item_index): original_keys = set(original_keys) updated_keys = set(updated_keys) added_keys = updated_keys.difference(original_keys) removed_keys = set() if name is None: removed_keys = original_keys.difference(updated_keys) elif name not in updated_keys and name in original_keys: removed_keys = set([name]) for key in removed_keys: if key in item_index: del(item_index[key]) # Check the keys that was not added now or not lined up for removal, # and see if they changed. for key in updated_keys.difference(added_keys.union(removed_keys)): if item_index[key].get('_changed'): item_index[key]['_changed'] = False removed_keys.add(key) added_keys.add(key) return added_keys, removed_keys
[ "def", "_difference", "(", "self", ",", "original_keys", ",", "updated_keys", ",", "name", ",", "item_index", ")", ":", "original_keys", "=", "set", "(", "original_keys", ")", "updated_keys", "=", "set", "(", "updated_keys", ")", "added_keys", "=", "updated_ke...
Calculate difference between the original and updated sets of keys. Removed items will be removed from item_index, new items should have been added by the discovery process. (?help or ?sensor-list) This method is for use in inspect_requests and inspect_sensors only. Returns ------- (added, removed) added : set of str Names of the keys that were added removed : set of str Names of the keys that were removed
[ "Calculate", "difference", "between", "the", "original", "and", "updated", "sets", "of", "keys", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/inspecting_client.py#L1013-L1052
16,338
ska-sa/katcp-python
katcp/sampling.py
SampleStrategy.get_strategy
def get_strategy(cls, strategyName, inform_callback, sensor, *params, **kwargs): """Factory method to create a strategy object. Parameters ---------- strategyName : str Name of strategy. inform_callback : callable, signature inform_callback(sensor, reading) Callback to receive inform messages. sensor : Sensor object Sensor to sample. params : list of objects Custom sampling parameters for specified strategy. Keyword Arguments ----------------- ioloop : tornado.ioloop.IOLoop instance, optional Tornado ioloop to use, otherwise tornado.ioloop.IOLoop.current() Returns ------- strategy : :class:`SampleStrategy` object The created sampling strategy. """ if strategyName not in cls.SAMPLING_LOOKUP_REV: raise ValueError("Unknown sampling strategy '%s'. " "Known strategies are %s." % (strategyName, cls.SAMPLING_LOOKUP.values())) strategyType = cls.SAMPLING_LOOKUP_REV[strategyName] if strategyType == cls.NONE: return SampleNone(inform_callback, sensor, *params, **kwargs) elif strategyType == cls.AUTO: return SampleAuto(inform_callback, sensor, *params, **kwargs) elif strategyType == cls.EVENT: return SampleEvent(inform_callback, sensor, *params, **kwargs) elif strategyType == cls.DIFFERENTIAL: return SampleDifferential(inform_callback, sensor, *params, **kwargs) elif strategyType == cls.PERIOD: return SamplePeriod(inform_callback, sensor, *params, **kwargs) elif strategyType == cls.EVENT_RATE: return SampleEventRate(inform_callback, sensor, *params, **kwargs) elif strategyType == cls.DIFFERENTIAL_RATE: return SampleDifferentialRate(inform_callback, sensor, *params, **kwargs)
python
def get_strategy(cls, strategyName, inform_callback, sensor, *params, **kwargs): if strategyName not in cls.SAMPLING_LOOKUP_REV: raise ValueError("Unknown sampling strategy '%s'. " "Known strategies are %s." % (strategyName, cls.SAMPLING_LOOKUP.values())) strategyType = cls.SAMPLING_LOOKUP_REV[strategyName] if strategyType == cls.NONE: return SampleNone(inform_callback, sensor, *params, **kwargs) elif strategyType == cls.AUTO: return SampleAuto(inform_callback, sensor, *params, **kwargs) elif strategyType == cls.EVENT: return SampleEvent(inform_callback, sensor, *params, **kwargs) elif strategyType == cls.DIFFERENTIAL: return SampleDifferential(inform_callback, sensor, *params, **kwargs) elif strategyType == cls.PERIOD: return SamplePeriod(inform_callback, sensor, *params, **kwargs) elif strategyType == cls.EVENT_RATE: return SampleEventRate(inform_callback, sensor, *params, **kwargs) elif strategyType == cls.DIFFERENTIAL_RATE: return SampleDifferentialRate(inform_callback, sensor, *params, **kwargs)
[ "def", "get_strategy", "(", "cls", ",", "strategyName", ",", "inform_callback", ",", "sensor", ",", "*", "params", ",", "*", "*", "kwargs", ")", ":", "if", "strategyName", "not", "in", "cls", ".", "SAMPLING_LOOKUP_REV", ":", "raise", "ValueError", "(", "\"...
Factory method to create a strategy object. Parameters ---------- strategyName : str Name of strategy. inform_callback : callable, signature inform_callback(sensor, reading) Callback to receive inform messages. sensor : Sensor object Sensor to sample. params : list of objects Custom sampling parameters for specified strategy. Keyword Arguments ----------------- ioloop : tornado.ioloop.IOLoop instance, optional Tornado ioloop to use, otherwise tornado.ioloop.IOLoop.current() Returns ------- strategy : :class:`SampleStrategy` object The created sampling strategy.
[ "Factory", "method", "to", "create", "a", "strategy", "object", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/sampling.py#L109-L156
16,339
ska-sa/katcp-python
katcp/sampling.py
SampleStrategy.get_sampling_formatted
def get_sampling_formatted(self): """The current sampling strategy and parameters. The strategy is returned as a string and the values in the parameter list are formatted as strings using the formatter for this sensor type. Returns ------- strategy_name : string KATCP name for the strategy. params : list of strings KATCP formatted parameters for the strategy. """ strategy = self.get_sampling() strategy = self.SAMPLING_LOOKUP[strategy] params = [str(p) for p in self._params] return strategy, params
python
def get_sampling_formatted(self): strategy = self.get_sampling() strategy = self.SAMPLING_LOOKUP[strategy] params = [str(p) for p in self._params] return strategy, params
[ "def", "get_sampling_formatted", "(", "self", ")", ":", "strategy", "=", "self", ".", "get_sampling", "(", ")", "strategy", "=", "self", ".", "SAMPLING_LOOKUP", "[", "strategy", "]", "params", "=", "[", "str", "(", "p", ")", "for", "p", "in", "self", "...
The current sampling strategy and parameters. The strategy is returned as a string and the values in the parameter list are formatted as strings using the formatter for this sensor type. Returns ------- strategy_name : string KATCP name for the strategy. params : list of strings KATCP formatted parameters for the strategy.
[ "The", "current", "sampling", "strategy", "and", "parameters", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/sampling.py#L196-L214
16,340
ska-sa/katcp-python
katcp/sampling.py
SampleStrategy.attach
def attach(self): """Attach strategy to its sensor and send initial update.""" s = self._sensor self.update(s, s.read()) self._sensor.attach(self)
python
def attach(self): s = self._sensor self.update(s, s.read()) self._sensor.attach(self)
[ "def", "attach", "(", "self", ")", ":", "s", "=", "self", ".", "_sensor", "self", ".", "update", "(", "s", ",", "s", ".", "read", "(", ")", ")", "self", ".", "_sensor", ".", "attach", "(", "self", ")" ]
Attach strategy to its sensor and send initial update.
[ "Attach", "strategy", "to", "its", "sensor", "and", "send", "initial", "update", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/sampling.py#L216-L220
16,341
ska-sa/katcp-python
katcp/sampling.py
SampleStrategy.cancel
def cancel(self): """Detach strategy from its sensor and cancel ioloop callbacks.""" if self.OBSERVE_UPDATES: self.detach() self.ioloop.add_callback(self.cancel_timeouts)
python
def cancel(self): if self.OBSERVE_UPDATES: self.detach() self.ioloop.add_callback(self.cancel_timeouts)
[ "def", "cancel", "(", "self", ")", ":", "if", "self", ".", "OBSERVE_UPDATES", ":", "self", ".", "detach", "(", ")", "self", ".", "ioloop", ".", "add_callback", "(", "self", ".", "cancel_timeouts", ")" ]
Detach strategy from its sensor and cancel ioloop callbacks.
[ "Detach", "strategy", "from", "its", "sensor", "and", "cancel", "ioloop", "callbacks", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/sampling.py#L226-L230
16,342
ska-sa/katcp-python
katcp/sampling.py
SampleStrategy.start
def start(self): """Start operating the strategy. Subclasses that override start() should call the super method before it does anything that uses the ioloop. This will attach to the sensor as an observer if :attr:`OBSERVE_UPDATES` is True, and sets :attr:`_ioloop_thread_id` using `thread.get_ident()`. """ def first_run(): self._ioloop_thread_id = get_thread_ident() if self.OBSERVE_UPDATES: self.attach() self.ioloop.add_callback(first_run)
python
def start(self): def first_run(): self._ioloop_thread_id = get_thread_ident() if self.OBSERVE_UPDATES: self.attach() self.ioloop.add_callback(first_run)
[ "def", "start", "(", "self", ")", ":", "def", "first_run", "(", ")", ":", "self", ".", "_ioloop_thread_id", "=", "get_thread_ident", "(", ")", "if", "self", ".", "OBSERVE_UPDATES", ":", "self", ".", "attach", "(", ")", "self", ".", "ioloop", ".", "add_...
Start operating the strategy. Subclasses that override start() should call the super method before it does anything that uses the ioloop. This will attach to the sensor as an observer if :attr:`OBSERVE_UPDATES` is True, and sets :attr:`_ioloop_thread_id` using `thread.get_ident()`.
[ "Start", "operating", "the", "strategy", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/sampling.py#L232-L245
16,343
ska-sa/katcp-python
katcp/sampling.py
SampleStrategy.inform
def inform(self, reading): """Inform strategy creator of the sensor status.""" try: self._inform_callback(self._sensor, reading) except Exception: log.exception('Unhandled exception trying to send {!r} ' 'for sensor {!r} of type {!r}' .format(reading, self._sensor.name, self._sensor.type))
python
def inform(self, reading): try: self._inform_callback(self._sensor, reading) except Exception: log.exception('Unhandled exception trying to send {!r} ' 'for sensor {!r} of type {!r}' .format(reading, self._sensor.name, self._sensor.type))
[ "def", "inform", "(", "self", ",", "reading", ")", ":", "try", ":", "self", ".", "_inform_callback", "(", "self", ".", "_sensor", ",", "reading", ")", "except", "Exception", ":", "log", ".", "exception", "(", "'Unhandled exception trying to send {!r} '", "'for...
Inform strategy creator of the sensor status.
[ "Inform", "strategy", "creator", "of", "the", "sensor", "status", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/sampling.py#L247-L254
16,344
ska-sa/katcp-python
katcp/ioloop_manager.py
IOLoopManager.start
def start(self, timeout=None): """Start managed ioloop thread, or do nothing if not managed. If a timeout is passed, it will block until the the event loop is alive (or the timeout expires) even if the ioloop is not managed. """ if not self._ioloop: raise RuntimeError('Call get_ioloop() or set_ioloop() first') self._ioloop.add_callback(self._running.set) if self._ioloop_managed: self._run_managed_ioloop() else: # TODO this seems inconsistent with what the docstring describes self._running.set() if timeout: return self._running.wait(timeout)
python
def start(self, timeout=None): if not self._ioloop: raise RuntimeError('Call get_ioloop() or set_ioloop() first') self._ioloop.add_callback(self._running.set) if self._ioloop_managed: self._run_managed_ioloop() else: # TODO this seems inconsistent with what the docstring describes self._running.set() if timeout: return self._running.wait(timeout)
[ "def", "start", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "not", "self", ".", "_ioloop", ":", "raise", "RuntimeError", "(", "'Call get_ioloop() or set_ioloop() first'", ")", "self", ".", "_ioloop", ".", "add_callback", "(", "self", ".", "_run...
Start managed ioloop thread, or do nothing if not managed. If a timeout is passed, it will block until the the event loop is alive (or the timeout expires) even if the ioloop is not managed.
[ "Start", "managed", "ioloop", "thread", "or", "do", "nothing", "if", "not", "managed", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/ioloop_manager.py#L99-L117
16,345
ska-sa/katcp-python
katcp/ioloop_manager.py
IOLoopManager.join
def join(self, timeout=None): """Join managed ioloop thread, or do nothing if not managed.""" if not self._ioloop_managed: # Do nothing if the loop is not managed return try: self._ioloop_thread.join(timeout) except AttributeError: raise RuntimeError('Cannot join if not started')
python
def join(self, timeout=None): if not self._ioloop_managed: # Do nothing if the loop is not managed return try: self._ioloop_thread.join(timeout) except AttributeError: raise RuntimeError('Cannot join if not started')
[ "def", "join", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "not", "self", ".", "_ioloop_managed", ":", "# Do nothing if the loop is not managed", "return", "try", ":", "self", ".", "_ioloop_thread", ".", "join", "(", "timeout", ")", "except", "...
Join managed ioloop thread, or do nothing if not managed.
[ "Join", "managed", "ioloop", "thread", "or", "do", "nothing", "if", "not", "managed", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/ioloop_manager.py#L162-L170
16,346
ska-sa/katcp-python
katcp/sensortree.py
GenericSensorTree.update
def update(self, sensor, reading): """Update callback used by sensors to notify obervers of changes. Parameters ---------- sensor : :class:`katcp.Sensor` object The sensor whose value has changed. reading : (timestamp, status, value) tuple Sensor reading as would be returned by sensor.read() """ parents = list(self._child_to_parents[sensor]) for parent in parents: self.recalculate(parent, (sensor,))
python
def update(self, sensor, reading): parents = list(self._child_to_parents[sensor]) for parent in parents: self.recalculate(parent, (sensor,))
[ "def", "update", "(", "self", ",", "sensor", ",", "reading", ")", ":", "parents", "=", "list", "(", "self", ".", "_child_to_parents", "[", "sensor", "]", ")", "for", "parent", "in", "parents", ":", "self", ".", "recalculate", "(", "parent", ",", "(", ...
Update callback used by sensors to notify obervers of changes. Parameters ---------- sensor : :class:`katcp.Sensor` object The sensor whose value has changed. reading : (timestamp, status, value) tuple Sensor reading as would be returned by sensor.read()
[ "Update", "callback", "used", "by", "sensors", "to", "notify", "obervers", "of", "changes", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/sensortree.py#L41-L54
16,347
ska-sa/katcp-python
katcp/sensortree.py
GenericSensorTree._add_sensor
def _add_sensor(self, sensor): """Add a new sensor to the tree. Parameters ---------- sensor : :class:`katcp.Sensor` object New sensor to add to the tree. """ self._parent_to_children[sensor] = set() self._child_to_parents[sensor] = set()
python
def _add_sensor(self, sensor): self._parent_to_children[sensor] = set() self._child_to_parents[sensor] = set()
[ "def", "_add_sensor", "(", "self", ",", "sensor", ")", ":", "self", ".", "_parent_to_children", "[", "sensor", "]", "=", "set", "(", ")", "self", ".", "_child_to_parents", "[", "sensor", "]", "=", "set", "(", ")" ]
Add a new sensor to the tree. Parameters ---------- sensor : :class:`katcp.Sensor` object New sensor to add to the tree.
[ "Add", "a", "new", "sensor", "to", "the", "tree", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/sensortree.py#L77-L87
16,348
ska-sa/katcp-python
katcp/sensortree.py
GenericSensorTree.add_links
def add_links(self, parent, children): """Create dependency links from parent to child. Any sensors not in the tree are added. After all dependency links have been created, the parent is recalculated and the tree attaches to any sensors it was not yet attached to. Links that already exist are ignored. Parameters ---------- parent : :class:`katcp.Sensor` object The sensor that depends on children. children : sequence of :class:`katcp.Sensor` objects The sensors parent depends on. """ new_sensors = [] if parent not in self: self._add_sensor(parent) new_sensors.append(parent) for child in children: if child not in self: self._add_sensor(child) new_sensors.append(child) self._parent_to_children[parent].add(child) self._child_to_parents[child].add(parent) self.recalculate(parent, children) for sensor in new_sensors: sensor.attach(self)
python
def add_links(self, parent, children): new_sensors = [] if parent not in self: self._add_sensor(parent) new_sensors.append(parent) for child in children: if child not in self: self._add_sensor(child) new_sensors.append(child) self._parent_to_children[parent].add(child) self._child_to_parents[child].add(parent) self.recalculate(parent, children) for sensor in new_sensors: sensor.attach(self)
[ "def", "add_links", "(", "self", ",", "parent", ",", "children", ")", ":", "new_sensors", "=", "[", "]", "if", "parent", "not", "in", "self", ":", "self", ".", "_add_sensor", "(", "parent", ")", "new_sensors", ".", "append", "(", "parent", ")", "for", ...
Create dependency links from parent to child. Any sensors not in the tree are added. After all dependency links have been created, the parent is recalculated and the tree attaches to any sensors it was not yet attached to. Links that already exist are ignored. Parameters ---------- parent : :class:`katcp.Sensor` object The sensor that depends on children. children : sequence of :class:`katcp.Sensor` objects The sensors parent depends on.
[ "Create", "dependency", "links", "from", "parent", "to", "child", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/sensortree.py#L101-L130
16,349
ska-sa/katcp-python
katcp/sensortree.py
GenericSensorTree.remove_links
def remove_links(self, parent, children): """Remove dependency links from parent to child. Any sensors that have no dependency links are removed from the tree and the tree detaches from each sensor removed. After all dependency links have been removed the parent is recalculated. Links that don't exist are ignored. Parameters ---------- parent : :class:`katcp.Sensor` object The sensor that used to depend on children. children : sequence of :class:`katcp.Sensor` objects The sensors that parent used to depend on. """ old_sensors = [] if parent in self: for child in children: if child not in self: continue self._parent_to_children[parent].discard(child) self._child_to_parents[child].discard(parent) if not self._child_to_parents[child] and \ not self._parent_to_children[child]: self._remove_sensor(child) old_sensors.append(child) if not self._child_to_parents[parent] and \ not self._parent_to_children[parent]: self._remove_sensor(parent) old_sensors.append(parent) for sensor in old_sensors: sensor.detach(self) self.recalculate(parent, children)
python
def remove_links(self, parent, children): old_sensors = [] if parent in self: for child in children: if child not in self: continue self._parent_to_children[parent].discard(child) self._child_to_parents[child].discard(parent) if not self._child_to_parents[child] and \ not self._parent_to_children[child]: self._remove_sensor(child) old_sensors.append(child) if not self._child_to_parents[parent] and \ not self._parent_to_children[parent]: self._remove_sensor(parent) old_sensors.append(parent) for sensor in old_sensors: sensor.detach(self) self.recalculate(parent, children)
[ "def", "remove_links", "(", "self", ",", "parent", ",", "children", ")", ":", "old_sensors", "=", "[", "]", "if", "parent", "in", "self", ":", "for", "child", "in", "children", ":", "if", "child", "not", "in", "self", ":", "continue", "self", ".", "_...
Remove dependency links from parent to child. Any sensors that have no dependency links are removed from the tree and the tree detaches from each sensor removed. After all dependency links have been removed the parent is recalculated. Links that don't exist are ignored. Parameters ---------- parent : :class:`katcp.Sensor` object The sensor that used to depend on children. children : sequence of :class:`katcp.Sensor` objects The sensors that parent used to depend on.
[ "Remove", "dependency", "links", "from", "parent", "to", "child", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/sensortree.py#L132-L166
16,350
ska-sa/katcp-python
katcp/sensortree.py
GenericSensorTree.children
def children(self, parent): """Return set of children of parent. Parameters ---------- parent : :class:`katcp.Sensor` object Parent whose children to return. Returns ------- children : set of :class:`katcp.Sensor` objects The child sensors of parent. """ if parent not in self._parent_to_children: raise ValueError("Parent sensor %r not in tree." % parent) return self._parent_to_children[parent].copy()
python
def children(self, parent): if parent not in self._parent_to_children: raise ValueError("Parent sensor %r not in tree." % parent) return self._parent_to_children[parent].copy()
[ "def", "children", "(", "self", ",", "parent", ")", ":", "if", "parent", "not", "in", "self", ".", "_parent_to_children", ":", "raise", "ValueError", "(", "\"Parent sensor %r not in tree.\"", "%", "parent", ")", "return", "self", ".", "_parent_to_children", "[",...
Return set of children of parent. Parameters ---------- parent : :class:`katcp.Sensor` object Parent whose children to return. Returns ------- children : set of :class:`katcp.Sensor` objects The child sensors of parent.
[ "Return", "set", "of", "children", "of", "parent", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/sensortree.py#L168-L184
16,351
ska-sa/katcp-python
katcp/sensortree.py
GenericSensorTree.parents
def parents(self, child): """Return set of parents of child. Parameters ---------- child : :class:`katcp.Sensor` object Child whose parents to return. Returns ------- parents : set of :class:`katcp.Sensor` objects The parent sensors of child. """ if child not in self._child_to_parents: raise ValueError("Child sensor %r not in tree." % child) return self._child_to_parents[child].copy()
python
def parents(self, child): if child not in self._child_to_parents: raise ValueError("Child sensor %r not in tree." % child) return self._child_to_parents[child].copy()
[ "def", "parents", "(", "self", ",", "child", ")", ":", "if", "child", "not", "in", "self", ".", "_child_to_parents", ":", "raise", "ValueError", "(", "\"Child sensor %r not in tree.\"", "%", "child", ")", "return", "self", ".", "_child_to_parents", "[", "child...
Return set of parents of child. Parameters ---------- child : :class:`katcp.Sensor` object Child whose parents to return. Returns ------- parents : set of :class:`katcp.Sensor` objects The parent sensors of child.
[ "Return", "set", "of", "parents", "of", "child", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/sensortree.py#L186-L202
16,352
ska-sa/katcp-python
katcp/sensortree.py
BooleanSensorTree.add
def add(self, parent, child): """Add a pair of boolean sensors. Parent depends on child. Parameters ---------- parent : boolean instance of :class:`katcp.Sensor` The sensor that depends on child. child : boolean instance of :class:`katcp.Sensor` The sensor parent depends on. """ if parent not in self: if parent.stype != "boolean": raise ValueError("Parent sensor %r is not boolean" % child) self._parent_to_not_ok[parent] = set() if child not in self: if child.stype != "boolean": raise ValueError("Child sensor %r is not booelan" % child) self._parent_to_not_ok[child] = set() self.add_links(parent, (child,))
python
def add(self, parent, child): if parent not in self: if parent.stype != "boolean": raise ValueError("Parent sensor %r is not boolean" % child) self._parent_to_not_ok[parent] = set() if child not in self: if child.stype != "boolean": raise ValueError("Child sensor %r is not booelan" % child) self._parent_to_not_ok[child] = set() self.add_links(parent, (child,))
[ "def", "add", "(", "self", ",", "parent", ",", "child", ")", ":", "if", "parent", "not", "in", "self", ":", "if", "parent", ".", "stype", "!=", "\"boolean\"", ":", "raise", "ValueError", "(", "\"Parent sensor %r is not boolean\"", "%", "child", ")", "self"...
Add a pair of boolean sensors. Parent depends on child. Parameters ---------- parent : boolean instance of :class:`katcp.Sensor` The sensor that depends on child. child : boolean instance of :class:`katcp.Sensor` The sensor parent depends on.
[ "Add", "a", "pair", "of", "boolean", "sensors", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/sensortree.py#L244-L265
16,353
ska-sa/katcp-python
katcp/sensortree.py
BooleanSensorTree.remove
def remove(self, parent, child): """Remove a dependency between parent and child. Parameters ---------- parent : boolean instance of :class:`katcp.Sensor` The sensor that used to depend on child. child : boolean instance of :class:`katcp.Sensor` or None The sensor parent used to depend on. """ self.remove_links(parent, (child,)) if parent not in self and parent in self._parent_to_not_ok: del self._parent_to_not_ok[parent] if child not in self and child in self._parent_to_not_ok: del self._parent_to_not_ok[child]
python
def remove(self, parent, child): self.remove_links(parent, (child,)) if parent not in self and parent in self._parent_to_not_ok: del self._parent_to_not_ok[parent] if child not in self and child in self._parent_to_not_ok: del self._parent_to_not_ok[child]
[ "def", "remove", "(", "self", ",", "parent", ",", "child", ")", ":", "self", ".", "remove_links", "(", "parent", ",", "(", "child", ",", ")", ")", "if", "parent", "not", "in", "self", "and", "parent", "in", "self", ".", "_parent_to_not_ok", ":", "del...
Remove a dependency between parent and child. Parameters ---------- parent : boolean instance of :class:`katcp.Sensor` The sensor that used to depend on child. child : boolean instance of :class:`katcp.Sensor` or None The sensor parent used to depend on.
[ "Remove", "a", "dependency", "between", "parent", "and", "child", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/sensortree.py#L267-L282
16,354
ska-sa/katcp-python
katcp/sensortree.py
AggregateSensorTree.add
def add(self, parent, rule_function, children): """Create an aggregation rule. Parameters ---------- parent : :class:`katcp.Sensor` object The aggregate sensor. rule_function : f(parent, children) Function to update the parent sensor value. children : sequence of :class:`katcp.Sensor` objects The sensors the aggregate sensor depends on. """ if parent in self._aggregates or parent in self._incomplete_aggregates: raise ValueError("Sensor %r already has an aggregate rule " "associated" % parent) self._aggregates[parent] = (rule_function, children) self.add_links(parent, children)
python
def add(self, parent, rule_function, children): if parent in self._aggregates or parent in self._incomplete_aggregates: raise ValueError("Sensor %r already has an aggregate rule " "associated" % parent) self._aggregates[parent] = (rule_function, children) self.add_links(parent, children)
[ "def", "add", "(", "self", ",", "parent", ",", "rule_function", ",", "children", ")", ":", "if", "parent", "in", "self", ".", "_aggregates", "or", "parent", "in", "self", ".", "_incomplete_aggregates", ":", "raise", "ValueError", "(", "\"Sensor %r already has ...
Create an aggregation rule. Parameters ---------- parent : :class:`katcp.Sensor` object The aggregate sensor. rule_function : f(parent, children) Function to update the parent sensor value. children : sequence of :class:`katcp.Sensor` objects The sensors the aggregate sensor depends on.
[ "Create", "an", "aggregation", "rule", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/sensortree.py#L365-L382
16,355
ska-sa/katcp-python
katcp/sensortree.py
AggregateSensorTree.add_delayed
def add_delayed(self, parent, rule_function, child_names): """Create an aggregation rule before child sensors are present. Parameters ---------- parent : :class:`katcp.Sensor` object The aggregate sensor. rule_function : f(parent, children) Function to update the parent sensor value. child_names : sequence of str The names of the sensors the aggregate sensor depends on. These sensor must be registered using :meth:`register_sensor` to become active. """ if parent in self._aggregates or parent in self._incomplete_aggregates: raise ValueError("Sensor %r already has an aggregate rule" " associated" % parent) reg = self._registered_sensors names = set(name for name in child_names if name not in reg) sensors = set(reg[name] for name in child_names if name in reg) if names: self._incomplete_aggregates[parent] = (rule_function, names, sensors) else: self.add(parent, rule_function, sensors)
python
def add_delayed(self, parent, rule_function, child_names): if parent in self._aggregates or parent in self._incomplete_aggregates: raise ValueError("Sensor %r already has an aggregate rule" " associated" % parent) reg = self._registered_sensors names = set(name for name in child_names if name not in reg) sensors = set(reg[name] for name in child_names if name in reg) if names: self._incomplete_aggregates[parent] = (rule_function, names, sensors) else: self.add(parent, rule_function, sensors)
[ "def", "add_delayed", "(", "self", ",", "parent", ",", "rule_function", ",", "child_names", ")", ":", "if", "parent", "in", "self", ".", "_aggregates", "or", "parent", "in", "self", ".", "_incomplete_aggregates", ":", "raise", "ValueError", "(", "\"Sensor %r a...
Create an aggregation rule before child sensors are present. Parameters ---------- parent : :class:`katcp.Sensor` object The aggregate sensor. rule_function : f(parent, children) Function to update the parent sensor value. child_names : sequence of str The names of the sensors the aggregate sensor depends on. These sensor must be registered using :meth:`register_sensor` to become active.
[ "Create", "an", "aggregation", "rule", "before", "child", "sensors", "are", "present", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/sensortree.py#L384-L409
16,356
ska-sa/katcp-python
katcp/sensortree.py
AggregateSensorTree.register_sensor
def register_sensor(self, child): """Register a sensor required by an aggregate sensor registered with add_delayed. Parameters ---------- child : :class:`katcp.Sensor` object A child sensor required by one or more delayed aggregate sensors. """ child_name = self._get_sensor_reference(child) if child_name in self._registered_sensors: raise ValueError("Sensor %r already registered with aggregate" " tree" % child) self._registered_sensors[child_name] = child completed = [] for parent, (_rule, names, sensors) in \ self._incomplete_aggregates.iteritems(): if child_name in names: names.remove(child_name) sensors.add(child) if not names: completed.append(parent) for parent in completed: rule_function, _names, sensors = \ self._incomplete_aggregates[parent] del self._incomplete_aggregates[parent] self.add(parent, rule_function, sensors)
python
def register_sensor(self, child): child_name = self._get_sensor_reference(child) if child_name in self._registered_sensors: raise ValueError("Sensor %r already registered with aggregate" " tree" % child) self._registered_sensors[child_name] = child completed = [] for parent, (_rule, names, sensors) in \ self._incomplete_aggregates.iteritems(): if child_name in names: names.remove(child_name) sensors.add(child) if not names: completed.append(parent) for parent in completed: rule_function, _names, sensors = \ self._incomplete_aggregates[parent] del self._incomplete_aggregates[parent] self.add(parent, rule_function, sensors)
[ "def", "register_sensor", "(", "self", ",", "child", ")", ":", "child_name", "=", "self", ".", "_get_sensor_reference", "(", "child", ")", "if", "child_name", "in", "self", ".", "_registered_sensors", ":", "raise", "ValueError", "(", "\"Sensor %r already registere...
Register a sensor required by an aggregate sensor registered with add_delayed. Parameters ---------- child : :class:`katcp.Sensor` object A child sensor required by one or more delayed aggregate sensors.
[ "Register", "a", "sensor", "required", "by", "an", "aggregate", "sensor", "registered", "with", "add_delayed", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/sensortree.py#L411-L438
16,357
ska-sa/katcp-python
katcp/sensortree.py
AggregateSensorTree._child_from_reference
def _child_from_reference(self, reference): """Returns the child sensor from its reference. Parameters ---------- reference : str Reference to sensor (typically its name). Returns ------- child : :class:`katcp.Sensor` object A child sensor linked to one or more aggregate sensors. """ for child in self._child_to_parents: if self._get_sensor_reference(child) == reference: return child
python
def _child_from_reference(self, reference): for child in self._child_to_parents: if self._get_sensor_reference(child) == reference: return child
[ "def", "_child_from_reference", "(", "self", ",", "reference", ")", ":", "for", "child", "in", "self", ".", "_child_to_parents", ":", "if", "self", ".", "_get_sensor_reference", "(", "child", ")", "==", "reference", ":", "return", "child" ]
Returns the child sensor from its reference. Parameters ---------- reference : str Reference to sensor (typically its name). Returns ------- child : :class:`katcp.Sensor` object A child sensor linked to one or more aggregate sensors.
[ "Returns", "the", "child", "sensor", "from", "its", "reference", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/sensortree.py#L466-L482
16,358
ska-sa/katcp-python
katcp/sensortree.py
AggregateSensorTree.remove
def remove(self, parent): """Remove an aggregation rule. Parameters ---------- parent : :class:`katcp.Sensor` object The aggregate sensor to remove. """ if parent not in self._aggregates: raise ValueError("Sensor %r does not have an aggregate rule " "associated" % parent) children = self.children(parent) try: self.remove_links(parent, children) except Exception: pass del self._aggregates[parent]
python
def remove(self, parent): if parent not in self._aggregates: raise ValueError("Sensor %r does not have an aggregate rule " "associated" % parent) children = self.children(parent) try: self.remove_links(parent, children) except Exception: pass del self._aggregates[parent]
[ "def", "remove", "(", "self", ",", "parent", ")", ":", "if", "parent", "not", "in", "self", ".", "_aggregates", ":", "raise", "ValueError", "(", "\"Sensor %r does not have an aggregate rule \"", "\"associated\"", "%", "parent", ")", "children", "=", "self", ".",...
Remove an aggregation rule. Parameters ---------- parent : :class:`katcp.Sensor` object The aggregate sensor to remove.
[ "Remove", "an", "aggregation", "rule", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/sensortree.py#L484-L501
16,359
ska-sa/katcp-python
katcp/kattypes.py
request
def request(*types, **options): """Decorator for request handler methods. The method being decorated should take a req argument followed by arguments matching the list of types. The decorator will unpack the request message into the arguments. Parameters ---------- types : list of kattypes The types of the request message parameters (in order). A type with multiple=True has to be the last type. Keyword Arguments ----------------- include_msg : bool, optional Pass the request message as the third parameter to the decorated request handler function (default is False). major : int, optional Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP version. Examples -------- >>> class MyDevice(DeviceServer): ... @request(Int(), Float(), Bool()) ... @return_reply(Int(), Float()) ... def request_myreq(self, req, my_int, my_float, my_bool): ... '''?myreq my_int my_float my_bool''' ... return ("ok", my_int + 1, my_float / 2.0) ... ... @request(Int(), include_msg=True) ... @return_reply(Bool()) ... def request_is_odd(self, req, msg, my_int): '''?is-odd <my_int>, reply '1' if <my_int> is odd, else 0''' ... req.inform('Checking oddity of %d' % my_int) ... return ("ok", my_int % 2) ... """ include_msg = options.pop('include_msg', False) has_req = options.pop('has_req', True) major = options.pop('major', DEFAULT_KATCP_MAJOR) check_req = options.pop('_check_req', True) if len(options) > 0: raise TypeError('does not take keyword argument(s) %r.' % options.keys()) # Check that only the last type has multiple=True if len(types) > 1: for type_ in types[:-1]: if type_._multiple: raise TypeError('Only the last parameter type ' 'can accept multiple arguments.') def decorator(handler): argnames = [] # If this decorator is on the outside, get the parameter names which # have been preserved by the other decorator all_argnames = getattr(handler, "_orig_argnames", None) if all_argnames is None: # We must be on the inside. Introspect the parameter names. all_argnames = inspect.getargspec(handler)[0] params_start = 1 # Skip 'self' parameter if has_req: # Skip 'req' parameter params_start += 1 if include_msg: params_start += 1 # Get other parameter names argnames = all_argnames[params_start:] if has_req and include_msg: def raw_handler(self, req, msg): new_args = unpack_types(types, msg.arguments, argnames, major) return handler(self, req, msg, *new_args) elif has_req and not include_msg: def raw_handler(self, req, msg): new_args = unpack_types(types, msg.arguments, argnames, major) return handler(self, req, *new_args) elif not has_req and include_msg: def raw_handler(self, msg): new_args = unpack_types(types, msg.arguments, argnames, major) return handler(self, msg, *new_args) elif not has_req and not include_msg: def raw_handler(self, msg): new_args = unpack_types(types, msg.arguments, argnames, major) return handler(self, *new_args) update_wrapper(raw_handler, handler) # explicitly note that this decorator has been run, so that # return_reply can know if it's on the outside. raw_handler._request_decorated = True return raw_handler return decorator
python
def request(*types, **options): include_msg = options.pop('include_msg', False) has_req = options.pop('has_req', True) major = options.pop('major', DEFAULT_KATCP_MAJOR) check_req = options.pop('_check_req', True) if len(options) > 0: raise TypeError('does not take keyword argument(s) %r.' % options.keys()) # Check that only the last type has multiple=True if len(types) > 1: for type_ in types[:-1]: if type_._multiple: raise TypeError('Only the last parameter type ' 'can accept multiple arguments.') def decorator(handler): argnames = [] # If this decorator is on the outside, get the parameter names which # have been preserved by the other decorator all_argnames = getattr(handler, "_orig_argnames", None) if all_argnames is None: # We must be on the inside. Introspect the parameter names. all_argnames = inspect.getargspec(handler)[0] params_start = 1 # Skip 'self' parameter if has_req: # Skip 'req' parameter params_start += 1 if include_msg: params_start += 1 # Get other parameter names argnames = all_argnames[params_start:] if has_req and include_msg: def raw_handler(self, req, msg): new_args = unpack_types(types, msg.arguments, argnames, major) return handler(self, req, msg, *new_args) elif has_req and not include_msg: def raw_handler(self, req, msg): new_args = unpack_types(types, msg.arguments, argnames, major) return handler(self, req, *new_args) elif not has_req and include_msg: def raw_handler(self, msg): new_args = unpack_types(types, msg.arguments, argnames, major) return handler(self, msg, *new_args) elif not has_req and not include_msg: def raw_handler(self, msg): new_args = unpack_types(types, msg.arguments, argnames, major) return handler(self, *new_args) update_wrapper(raw_handler, handler) # explicitly note that this decorator has been run, so that # return_reply can know if it's on the outside. raw_handler._request_decorated = True return raw_handler return decorator
[ "def", "request", "(", "*", "types", ",", "*", "*", "options", ")", ":", "include_msg", "=", "options", ".", "pop", "(", "'include_msg'", ",", "False", ")", "has_req", "=", "options", ".", "pop", "(", "'has_req'", ",", "True", ")", "major", "=", "opt...
Decorator for request handler methods. The method being decorated should take a req argument followed by arguments matching the list of types. The decorator will unpack the request message into the arguments. Parameters ---------- types : list of kattypes The types of the request message parameters (in order). A type with multiple=True has to be the last type. Keyword Arguments ----------------- include_msg : bool, optional Pass the request message as the third parameter to the decorated request handler function (default is False). major : int, optional Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP version. Examples -------- >>> class MyDevice(DeviceServer): ... @request(Int(), Float(), Bool()) ... @return_reply(Int(), Float()) ... def request_myreq(self, req, my_int, my_float, my_bool): ... '''?myreq my_int my_float my_bool''' ... return ("ok", my_int + 1, my_float / 2.0) ... ... @request(Int(), include_msg=True) ... @return_reply(Bool()) ... def request_is_odd(self, req, msg, my_int): '''?is-odd <my_int>, reply '1' if <my_int> is odd, else 0''' ... req.inform('Checking oddity of %d' % my_int) ... return ("ok", my_int % 2) ...
[ "Decorator", "for", "request", "handler", "methods", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/kattypes.py#L610-L709
16,360
ska-sa/katcp-python
katcp/kattypes.py
return_reply
def return_reply(*types, **options): """Decorator for returning replies from request handler methods. The method being decorated should return an iterable of result values. If the first value is 'ok', the decorator will check the remaining values against the specified list of types (if any). If the first value is 'fail' or 'error', there must be only one remaining parameter, and it must be a string describing the failure or error In both cases, the decorator will pack the values into a reply message. Parameters ---------- types : list of kattypes The types of the reply message parameters (in order). Keyword Arguments ----------------- major : int, optional Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP version. Examples -------- >>> class MyDevice(DeviceServer): ... @request(Int()) ... @return_reply(Int(), Float()) ... def request_myreq(self, req, my_int): ... return ("ok", my_int + 1, my_int * 2.0) ... """ major = options.pop('major', DEFAULT_KATCP_MAJOR) if len(options) > 0: raise TypeError('return_reply does not take keyword argument(s) %r.' % options.keys()) # Check that only the last type has multiple=True if len(types) > 1: for type_ in types[:-1]: if type_._multiple: raise TypeError('Only the last parameter type ' 'can accept multiple arguments.') def decorator(handler): if not handler.__name__.startswith("request_"): raise ValueError("This decorator can only be used on a katcp" " request handler (method name should start" " with 'request_').") msgname = convert_method_name('request_', handler.__name__) @wraps(handler) def raw_handler(self, *args): reply_args = handler(self, *args) if gen.is_future(reply_args): return async_make_reply(msgname, types, reply_args, major) else: return make_reply(msgname, types, reply_args, major) # TODO NM 2017-01-12 Consider using the decorator module to create # signature preserving decorators that would avoid the need for this # trickery if not getattr(handler, "_request_decorated", False): # We are on the inside. # We must preserve the original function parameter names for the # request decorator raw_handler._orig_argnames = inspect.getargspec(handler)[0] return raw_handler return decorator
python
def return_reply(*types, **options): major = options.pop('major', DEFAULT_KATCP_MAJOR) if len(options) > 0: raise TypeError('return_reply does not take keyword argument(s) %r.' % options.keys()) # Check that only the last type has multiple=True if len(types) > 1: for type_ in types[:-1]: if type_._multiple: raise TypeError('Only the last parameter type ' 'can accept multiple arguments.') def decorator(handler): if not handler.__name__.startswith("request_"): raise ValueError("This decorator can only be used on a katcp" " request handler (method name should start" " with 'request_').") msgname = convert_method_name('request_', handler.__name__) @wraps(handler) def raw_handler(self, *args): reply_args = handler(self, *args) if gen.is_future(reply_args): return async_make_reply(msgname, types, reply_args, major) else: return make_reply(msgname, types, reply_args, major) # TODO NM 2017-01-12 Consider using the decorator module to create # signature preserving decorators that would avoid the need for this # trickery if not getattr(handler, "_request_decorated", False): # We are on the inside. # We must preserve the original function parameter names for the # request decorator raw_handler._orig_argnames = inspect.getargspec(handler)[0] return raw_handler return decorator
[ "def", "return_reply", "(", "*", "types", ",", "*", "*", "options", ")", ":", "major", "=", "options", ".", "pop", "(", "'major'", ",", "DEFAULT_KATCP_MAJOR", ")", "if", "len", "(", "options", ")", ">", "0", ":", "raise", "TypeError", "(", "'return_rep...
Decorator for returning replies from request handler methods. The method being decorated should return an iterable of result values. If the first value is 'ok', the decorator will check the remaining values against the specified list of types (if any). If the first value is 'fail' or 'error', there must be only one remaining parameter, and it must be a string describing the failure or error In both cases, the decorator will pack the values into a reply message. Parameters ---------- types : list of kattypes The types of the reply message parameters (in order). Keyword Arguments ----------------- major : int, optional Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP version. Examples -------- >>> class MyDevice(DeviceServer): ... @request(Int()) ... @return_reply(Int(), Float()) ... def request_myreq(self, req, my_int): ... return ("ok", my_int + 1, my_int * 2.0) ...
[ "Decorator", "for", "returning", "replies", "from", "request", "handler", "methods", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/kattypes.py#L786-L857
16,361
ska-sa/katcp-python
katcp/kattypes.py
send_reply
def send_reply(*types, **options): """Decorator for sending replies from request callback methods. This decorator constructs a reply from a list or tuple returned from a callback method, but unlike the return_reply decorator it also sends the reply rather than returning it. The list/tuple returned from the callback method must have req (a ClientRequestConnection instance) as its first parameter and the original message as the second. The original message is needed to determine the message name and ID. The device with the callback method must have a reply method. Parameters ---------- types : list of kattypes The types of the reply message parameters (in order). Keyword Arguments ----------------- major : int, optional Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP version. Examples -------- >>> class MyDevice(DeviceServer): ... @send_reply(Int(), Float()) ... def my_callback(self, req): ... return (req, "ok", 5, 2.0) ... """ major = options.pop('major', DEFAULT_KATCP_MAJOR) if len(options) > 0: raise TypeError('send_reply does not take keyword argument(s) %r.' % options.keys()) def decorator(handler): @wraps(handler) def raw_handler(self, *args): reply_args = handler(self, *args) req = reply_args[0] reply = make_reply(req.msg.name, types, reply_args[1:], major) req.reply_with_message(reply) return raw_handler return decorator
python
def send_reply(*types, **options): major = options.pop('major', DEFAULT_KATCP_MAJOR) if len(options) > 0: raise TypeError('send_reply does not take keyword argument(s) %r.' % options.keys()) def decorator(handler): @wraps(handler) def raw_handler(self, *args): reply_args = handler(self, *args) req = reply_args[0] reply = make_reply(req.msg.name, types, reply_args[1:], major) req.reply_with_message(reply) return raw_handler return decorator
[ "def", "send_reply", "(", "*", "types", ",", "*", "*", "options", ")", ":", "major", "=", "options", ".", "pop", "(", "'major'", ",", "DEFAULT_KATCP_MAJOR", ")", "if", "len", "(", "options", ")", ">", "0", ":", "raise", "TypeError", "(", "'send_reply d...
Decorator for sending replies from request callback methods. This decorator constructs a reply from a list or tuple returned from a callback method, but unlike the return_reply decorator it also sends the reply rather than returning it. The list/tuple returned from the callback method must have req (a ClientRequestConnection instance) as its first parameter and the original message as the second. The original message is needed to determine the message name and ID. The device with the callback method must have a reply method. Parameters ---------- types : list of kattypes The types of the reply message parameters (in order). Keyword Arguments ----------------- major : int, optional Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP version. Examples -------- >>> class MyDevice(DeviceServer): ... @send_reply(Int(), Float()) ... def my_callback(self, req): ... return (req, "ok", 5, 2.0) ...
[ "Decorator", "for", "sending", "replies", "from", "request", "callback", "methods", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/kattypes.py#L860-L908
16,362
ska-sa/katcp-python
katcp/kattypes.py
make_reply
def make_reply(msgname, types, arguments, major): """Helper method for constructing a reply message from a list or tuple. Parameters ---------- msgname : str Name of the reply message. types : list of kattypes The types of the reply message parameters (in order). arguments : list of objects The (unpacked) reply message parameters. major : integer Major version of KATCP to use when packing types """ status = arguments[0] if status == "fail": return Message.reply( msgname, *pack_types((Str(), Str()), arguments, major)) if status == "ok": return Message.reply( msgname, *pack_types((Str(),) + types, arguments, major)) raise ValueError("First returned value must be 'ok' or 'fail'.")
python
def make_reply(msgname, types, arguments, major): status = arguments[0] if status == "fail": return Message.reply( msgname, *pack_types((Str(), Str()), arguments, major)) if status == "ok": return Message.reply( msgname, *pack_types((Str(),) + types, arguments, major)) raise ValueError("First returned value must be 'ok' or 'fail'.")
[ "def", "make_reply", "(", "msgname", ",", "types", ",", "arguments", ",", "major", ")", ":", "status", "=", "arguments", "[", "0", "]", "if", "status", "==", "\"fail\"", ":", "return", "Message", ".", "reply", "(", "msgname", ",", "*", "pack_types", "(...
Helper method for constructing a reply message from a list or tuple. Parameters ---------- msgname : str Name of the reply message. types : list of kattypes The types of the reply message parameters (in order). arguments : list of objects The (unpacked) reply message parameters. major : integer Major version of KATCP to use when packing types
[ "Helper", "method", "for", "constructing", "a", "reply", "message", "from", "a", "list", "or", "tuple", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/kattypes.py#L911-L933
16,363
ska-sa/katcp-python
katcp/kattypes.py
minimum_katcp_version
def minimum_katcp_version(major, minor=0): """Decorator; exclude handler if server's protocol version is too low Useful for including default handler implementations for KATCP features that are only present in certain KATCP protocol versions Examples -------- >>> class MyDevice(DeviceServer): ... '''This device server will expose ?myreq''' ... PROTOCOL_INFO = katcp.core.ProtocolFlags(5, 1) ... ... @minimum_katcp_version(5, 1) ... def request_myreq(self, req, msg): ... '''A request that should only be present for KATCP >v5.1''' ... # Request handler implementation here. ... >>> class MyOldDevice(MyDevice): ... '''This device server will not expose ?myreq''' ... ... PROTOCOL_INFO = katcp.core.ProtocolFlags(5, 0) ... """ version_tuple = (major, minor) def decorator(handler): handler._minimum_katcp_version = version_tuple return handler return decorator
python
def minimum_katcp_version(major, minor=0): version_tuple = (major, minor) def decorator(handler): handler._minimum_katcp_version = version_tuple return handler return decorator
[ "def", "minimum_katcp_version", "(", "major", ",", "minor", "=", "0", ")", ":", "version_tuple", "=", "(", "major", ",", "minor", ")", "def", "decorator", "(", "handler", ")", ":", "handler", ".", "_minimum_katcp_version", "=", "version_tuple", "return", "ha...
Decorator; exclude handler if server's protocol version is too low Useful for including default handler implementations for KATCP features that are only present in certain KATCP protocol versions Examples -------- >>> class MyDevice(DeviceServer): ... '''This device server will expose ?myreq''' ... PROTOCOL_INFO = katcp.core.ProtocolFlags(5, 1) ... ... @minimum_katcp_version(5, 1) ... def request_myreq(self, req, msg): ... '''A request that should only be present for KATCP >v5.1''' ... # Request handler implementation here. ... >>> class MyOldDevice(MyDevice): ... '''This device server will not expose ?myreq''' ... ... PROTOCOL_INFO = katcp.core.ProtocolFlags(5, 0) ...
[ "Decorator", ";", "exclude", "handler", "if", "server", "s", "protocol", "version", "is", "too", "low" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/kattypes.py#L962-L992
16,364
ska-sa/katcp-python
katcp/kattypes.py
request_timeout_hint
def request_timeout_hint(timeout_hint): """Decorator; add recommended client timeout hint to a request for request Useful for requests that take longer than average to reply. Hint is provided to clients via ?request-timeout-hint. Note this is only exposed if the device server sets the protocol version to KATCP v5.1 or higher and enables the REQUEST_TIMEOUT_HINTS flag in its PROTOCOL_INFO class attribute Parameters ---------- timeout_hint : float (seconds) or None How long the decorated request should reasonably take to reply. No timeout hint if None, similar to never using the decorator, provided for consistency. Examples -------- >>> class MyDevice(DeviceServer): ... @return_reply(Int()) ... @request_timeout_hint(15) # Set request timeout hint to 15 seconds ... @tornado.gen.coroutine ... def request_myreq(self, req): ... '''A slow request''' ... result = yield self.slow_operation() ... raise tornado.gen.Return((req, result)) ... """ if timeout_hint is not None: timeout_hint = float(timeout_hint) def decorator(handler): handler.request_timeout_hint = timeout_hint return handler return decorator
python
def request_timeout_hint(timeout_hint): if timeout_hint is not None: timeout_hint = float(timeout_hint) def decorator(handler): handler.request_timeout_hint = timeout_hint return handler return decorator
[ "def", "request_timeout_hint", "(", "timeout_hint", ")", ":", "if", "timeout_hint", "is", "not", "None", ":", "timeout_hint", "=", "float", "(", "timeout_hint", ")", "def", "decorator", "(", "handler", ")", ":", "handler", ".", "request_timeout_hint", "=", "ti...
Decorator; add recommended client timeout hint to a request for request Useful for requests that take longer than average to reply. Hint is provided to clients via ?request-timeout-hint. Note this is only exposed if the device server sets the protocol version to KATCP v5.1 or higher and enables the REQUEST_TIMEOUT_HINTS flag in its PROTOCOL_INFO class attribute Parameters ---------- timeout_hint : float (seconds) or None How long the decorated request should reasonably take to reply. No timeout hint if None, similar to never using the decorator, provided for consistency. Examples -------- >>> class MyDevice(DeviceServer): ... @return_reply(Int()) ... @request_timeout_hint(15) # Set request timeout hint to 15 seconds ... @tornado.gen.coroutine ... def request_myreq(self, req): ... '''A slow request''' ... result = yield self.slow_operation() ... raise tornado.gen.Return((req, result)) ...
[ "Decorator", ";", "add", "recommended", "client", "timeout", "hint", "to", "a", "request", "for", "request" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/kattypes.py#L1025-L1060
16,365
ska-sa/katcp-python
katcp/kattypes.py
unpack_types
def unpack_types(types, args, argnames, major): """Parse arguments according to types list. Parameters ---------- types : list of kattypes The types of the arguments (in order). args : list of strings The arguments to parse. argnames : list of strings The names of the arguments. major : integer Major version of KATCP to use when packing types """ if len(types) > 0: multiple = types[-1]._multiple else: multiple = False if len(types) < len(args) and not multiple: raise FailReply("Too many parameters given.") # Wrap the types in parameter objects params = [] for i, kattype in enumerate(types): name = "" if i < len(argnames): name = argnames[i] params.append(Parameter(i+1, name, kattype, major)) if len(args) > len(types) and multiple: for i in range(len(types), len(args)): params.append(Parameter(i+1, name, kattype, major)) # if len(args) < len(types) this passes in None for missing args return map(lambda param, arg: param.unpack(arg), params, args)
python
def unpack_types(types, args, argnames, major): if len(types) > 0: multiple = types[-1]._multiple else: multiple = False if len(types) < len(args) and not multiple: raise FailReply("Too many parameters given.") # Wrap the types in parameter objects params = [] for i, kattype in enumerate(types): name = "" if i < len(argnames): name = argnames[i] params.append(Parameter(i+1, name, kattype, major)) if len(args) > len(types) and multiple: for i in range(len(types), len(args)): params.append(Parameter(i+1, name, kattype, major)) # if len(args) < len(types) this passes in None for missing args return map(lambda param, arg: param.unpack(arg), params, args)
[ "def", "unpack_types", "(", "types", ",", "args", ",", "argnames", ",", "major", ")", ":", "if", "len", "(", "types", ")", ">", "0", ":", "multiple", "=", "types", "[", "-", "1", "]", ".", "_multiple", "else", ":", "multiple", "=", "False", "if", ...
Parse arguments according to types list. Parameters ---------- types : list of kattypes The types of the arguments (in order). args : list of strings The arguments to parse. argnames : list of strings The names of the arguments. major : integer Major version of KATCP to use when packing types
[ "Parse", "arguments", "according", "to", "types", "list", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/kattypes.py#L1069-L1105
16,366
ska-sa/katcp-python
katcp/kattypes.py
pack_types
def pack_types(types, args, major): """Pack arguments according the the types list. Parameters ---------- types : list of kattypes The types of the arguments (in order). args : list of objects The arguments to format. major : integer Major version of KATCP to use when packing types """ if len(types) > 0: multiple = types[-1]._multiple else: multiple = False if len(types) < len(args) and not multiple: raise ValueError("Too many arguments to pack.") if len(args) < len(types): # this passes in None for missing args retvals = map(lambda ktype, arg: ktype.pack(arg, major=major), types, args) else: retvals = [ktype.pack(arg, major=major) for ktype, arg in zip(types, args)] if len(args) > len(types) and multiple: last_ktype = types[-1] for arg in args[len(types):]: retvals.append(last_ktype.pack(arg, major=major)) return retvals
python
def pack_types(types, args, major): if len(types) > 0: multiple = types[-1]._multiple else: multiple = False if len(types) < len(args) and not multiple: raise ValueError("Too many arguments to pack.") if len(args) < len(types): # this passes in None for missing args retvals = map(lambda ktype, arg: ktype.pack(arg, major=major), types, args) else: retvals = [ktype.pack(arg, major=major) for ktype, arg in zip(types, args)] if len(args) > len(types) and multiple: last_ktype = types[-1] for arg in args[len(types):]: retvals.append(last_ktype.pack(arg, major=major)) return retvals
[ "def", "pack_types", "(", "types", ",", "args", ",", "major", ")", ":", "if", "len", "(", "types", ")", ">", "0", ":", "multiple", "=", "types", "[", "-", "1", "]", ".", "_multiple", "else", ":", "multiple", "=", "False", "if", "len", "(", "types...
Pack arguments according the the types list. Parameters ---------- types : list of kattypes The types of the arguments (in order). args : list of objects The arguments to format. major : integer Major version of KATCP to use when packing types
[ "Pack", "arguments", "according", "the", "the", "types", "list", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/kattypes.py#L1108-L1142
16,367
ska-sa/katcp-python
katcp/kattypes.py
KatcpType.pack
def pack(self, value, nocheck=False, major=DEFAULT_KATCP_MAJOR): """Return the value formatted as a KATCP parameter. Parameters ---------- value : object The value to pack. nocheck : bool, optional Whether to check that the value is valid before packing it. major : int, optional Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP version. Returns ------- packed_value : str The unescaped KATCP string representing the value. """ if value is None: value = self.get_default() if value is None: raise ValueError("Cannot pack a None value.") if not nocheck: self.check(value, major) return self.encode(value, major)
python
def pack(self, value, nocheck=False, major=DEFAULT_KATCP_MAJOR): if value is None: value = self.get_default() if value is None: raise ValueError("Cannot pack a None value.") if not nocheck: self.check(value, major) return self.encode(value, major)
[ "def", "pack", "(", "self", ",", "value", ",", "nocheck", "=", "False", ",", "major", "=", "DEFAULT_KATCP_MAJOR", ")", ":", "if", "value", "is", "None", ":", "value", "=", "self", ".", "get_default", "(", ")", "if", "value", "is", "None", ":", "raise...
Return the value formatted as a KATCP parameter. Parameters ---------- value : object The value to pack. nocheck : bool, optional Whether to check that the value is valid before packing it. major : int, optional Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP version. Returns ------- packed_value : str The unescaped KATCP string representing the value.
[ "Return", "the", "value", "formatted", "as", "a", "KATCP", "parameter", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/kattypes.py#L88-L114
16,368
ska-sa/katcp-python
katcp/kattypes.py
KatcpType.unpack
def unpack(self, packed_value, major=DEFAULT_KATCP_MAJOR): """Parse a KATCP parameter into an object. Parameters ---------- packed_value : str The unescaped KATCP string to parse into a value. major : int, optional Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP version. Returns ------- value : object The value the KATCP string represented. """ if packed_value is None: value = self.get_default() else: try: value = self.decode(packed_value, major) except Exception: raise if value is not None: self.check(value, major) return value
python
def unpack(self, packed_value, major=DEFAULT_KATCP_MAJOR): if packed_value is None: value = self.get_default() else: try: value = self.decode(packed_value, major) except Exception: raise if value is not None: self.check(value, major) return value
[ "def", "unpack", "(", "self", ",", "packed_value", ",", "major", "=", "DEFAULT_KATCP_MAJOR", ")", ":", "if", "packed_value", "is", "None", ":", "value", "=", "self", ".", "get_default", "(", ")", "else", ":", "try", ":", "value", "=", "self", ".", "dec...
Parse a KATCP parameter into an object. Parameters ---------- packed_value : str The unescaped KATCP string to parse into a value. major : int, optional Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP version. Returns ------- value : object The value the KATCP string represented.
[ "Parse", "a", "KATCP", "parameter", "into", "an", "object", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/kattypes.py#L116-L142
16,369
ska-sa/katcp-python
katcp/kattypes.py
Int.check
def check(self, value, major): """Check whether the value is between the minimum and maximum. Raise a ValueError if it is not. """ if self._min is not None and value < self._min: raise ValueError("Integer %d is lower than minimum %d." % (value, self._min)) if self._max is not None and value > self._max: raise ValueError("Integer %d is higher than maximum %d." % (value, self._max))
python
def check(self, value, major): if self._min is not None and value < self._min: raise ValueError("Integer %d is lower than minimum %d." % (value, self._min)) if self._max is not None and value > self._max: raise ValueError("Integer %d is higher than maximum %d." % (value, self._max))
[ "def", "check", "(", "self", ",", "value", ",", "major", ")", ":", "if", "self", ".", "_min", "is", "not", "None", "and", "value", "<", "self", ".", "_min", ":", "raise", "ValueError", "(", "\"Integer %d is lower than minimum %d.\"", "%", "(", "value", "...
Check whether the value is between the minimum and maximum. Raise a ValueError if it is not.
[ "Check", "whether", "the", "value", "is", "between", "the", "minimum", "and", "maximum", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/kattypes.py#L172-L183
16,370
ska-sa/katcp-python
katcp/kattypes.py
Discrete.check
def check(self, value, major): """Check whether the value in the set of allowed values. Raise a ValueError if it is not. """ if self._case_insensitive: value = value.lower() values = self._valid_values_lower caseflag = " (case-insensitive)" else: values = self._valid_values caseflag = "" if value not in values: raise ValueError("Discrete value '%s' is not one of %s%s." % (value, list(self._values), caseflag))
python
def check(self, value, major): if self._case_insensitive: value = value.lower() values = self._valid_values_lower caseflag = " (case-insensitive)" else: values = self._valid_values caseflag = "" if value not in values: raise ValueError("Discrete value '%s' is not one of %s%s." % (value, list(self._values), caseflag))
[ "def", "check", "(", "self", ",", "value", ",", "major", ")", ":", "if", "self", ".", "_case_insensitive", ":", "value", "=", "value", ".", "lower", "(", ")", "values", "=", "self", ".", "_valid_values_lower", "caseflag", "=", "\" (case-insensitive)\"", "e...
Check whether the value in the set of allowed values. Raise a ValueError if it is not.
[ "Check", "whether", "the", "value", "in", "the", "set", "of", "allowed", "values", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/kattypes.py#L272-L287
16,371
ska-sa/katcp-python
katcp/kattypes.py
DiscreteMulti.check
def check(self, value, major): """Check that each item in the value list is in the allowed set.""" for v in value: super(DiscreteMulti, self).check(v, major)
python
def check(self, value, major): for v in value: super(DiscreteMulti, self).check(v, major)
[ "def", "check", "(", "self", ",", "value", ",", "major", ")", ":", "for", "v", "in", "value", ":", "super", "(", "DiscreteMulti", ",", "self", ")", ".", "check", "(", "v", ",", "major", ")" ]
Check that each item in the value list is in the allowed set.
[ "Check", "that", "each", "item", "in", "the", "value", "list", "is", "in", "the", "allowed", "set", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/kattypes.py#L542-L545
16,372
ska-sa/katcp-python
katcp/kattypes.py
Parameter.unpack
def unpack(self, value): """Unpack the parameter using its kattype. Parameters ---------- packed_value : str The unescaped KATCP string to unpack. Returns ------- value : object The unpacked value. """ # Wrap errors in FailReplies with information identifying the parameter try: return self._kattype.unpack(value, self.major) except ValueError, message: raise FailReply("Error in parameter %s (%s): %s" % (self.position, self.name, message))
python
def unpack(self, value): # Wrap errors in FailReplies with information identifying the parameter try: return self._kattype.unpack(value, self.major) except ValueError, message: raise FailReply("Error in parameter %s (%s): %s" % (self.position, self.name, message))
[ "def", "unpack", "(", "self", ",", "value", ")", ":", "# Wrap errors in FailReplies with information identifying the parameter", "try", ":", "return", "self", ".", "_kattype", ".", "unpack", "(", "value", ",", "self", ".", "major", ")", "except", "ValueError", ","...
Unpack the parameter using its kattype. Parameters ---------- packed_value : str The unescaped KATCP string to unpack. Returns ------- value : object The unpacked value.
[ "Unpack", "the", "parameter", "using", "its", "kattype", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/kattypes.py#L586-L605
16,373
ska-sa/katcp-python
katcp/server.py
return_future
def return_future(fn): """Decorator that turns a synchronous function into one returning a future. This should only be applied to non-blocking functions. Will do set_result() with the return value, or set_exc_info() if an exception is raised. """ @wraps(fn) def decorated(*args, **kwargs): return gen.maybe_future(fn(*args, **kwargs)) return decorated
python
def return_future(fn): @wraps(fn) def decorated(*args, **kwargs): return gen.maybe_future(fn(*args, **kwargs)) return decorated
[ "def", "return_future", "(", "fn", ")", ":", "@", "wraps", "(", "fn", ")", "def", "decorated", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "gen", ".", "maybe_future", "(", "fn", "(", "*", "args", ",", "*", "*", "kwargs", ")", ...
Decorator that turns a synchronous function into one returning a future. This should only be applied to non-blocking functions. Will do set_result() with the return value, or set_exc_info() if an exception is raised.
[ "Decorator", "that", "turns", "a", "synchronous", "function", "into", "one", "returning", "a", "future", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L68-L79
16,374
ska-sa/katcp-python
katcp/server.py
construct_name_filter
def construct_name_filter(pattern): """Return a function for filtering sensor names based on a pattern. Parameters ---------- pattern : None or str If None, the returned function matches all names. If pattern starts and ends with '/' the text between the slashes is used as a regular expression to search the names. Otherwise the pattern must match the name of the sensor exactly. Returns ------- exact : bool Return True if pattern is expected to match exactly. Used to determine whether having no matching sensors constitutes an error. filter_func : f(str) -> bool Function for determining whether a name matches the pattern. """ if pattern is None: return False, lambda name: True if pattern.startswith('/') and pattern.endswith('/'): name_re = re.compile(pattern[1:-1]) return False, lambda name: name_re.search(name) is not None return True, lambda name: name == pattern
python
def construct_name_filter(pattern): if pattern is None: return False, lambda name: True if pattern.startswith('/') and pattern.endswith('/'): name_re = re.compile(pattern[1:-1]) return False, lambda name: name_re.search(name) is not None return True, lambda name: name == pattern
[ "def", "construct_name_filter", "(", "pattern", ")", ":", "if", "pattern", "is", "None", ":", "return", "False", ",", "lambda", "name", ":", "True", "if", "pattern", ".", "startswith", "(", "'/'", ")", "and", "pattern", ".", "endswith", "(", "'/'", ")", ...
Return a function for filtering sensor names based on a pattern. Parameters ---------- pattern : None or str If None, the returned function matches all names. If pattern starts and ends with '/' the text between the slashes is used as a regular expression to search the names. Otherwise the pattern must match the name of the sensor exactly. Returns ------- exact : bool Return True if pattern is expected to match exactly. Used to determine whether having no matching sensors constitutes an error. filter_func : f(str) -> bool Function for determining whether a name matches the pattern.
[ "Return", "a", "function", "for", "filtering", "sensor", "names", "based", "on", "a", "pattern", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L82-L107
16,375
ska-sa/katcp-python
katcp/server.py
ClientConnection.disconnect
def disconnect(self, reason): """Disconnect this client connection for specified reason""" self._server._disconnect_client(self._conn_key, self, reason)
python
def disconnect(self, reason): self._server._disconnect_client(self._conn_key, self, reason)
[ "def", "disconnect", "(", "self", ",", "reason", ")", ":", "self", ".", "_server", ".", "_disconnect_client", "(", "self", ".", "_conn_key", ",", "self", ",", "reason", ")" ]
Disconnect this client connection for specified reason
[ "Disconnect", "this", "client", "connection", "for", "specified", "reason" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L130-L132
16,376
ska-sa/katcp-python
katcp/server.py
KATCPServer.start
def start(self, timeout=None): """Install the server on its IOLoop, optionally starting the IOLoop. Parameters ---------- timeout : float or None, optional Time in seconds to wait for server thread to start. """ if self._running.isSet(): raise RuntimeError('Server already started') self._stopped.clear() # Make sure we have an ioloop self.ioloop = self._ioloop_manager.get_ioloop() self._ioloop_manager.start() # Set max_buffer_size to ensure streams are closed # if too-large messages are received self._tcp_server = tornado.tcpserver.TCPServer( self.ioloop, max_buffer_size=self.MAX_MSG_SIZE) self._tcp_server.handle_stream = self._handle_stream self._server_sock = self._bind_socket(self._bindaddr) self._bindaddr = self._server_sock.getsockname() self.ioloop.add_callback(self._install) if timeout: return self._running.wait(timeout)
python
def start(self, timeout=None): if self._running.isSet(): raise RuntimeError('Server already started') self._stopped.clear() # Make sure we have an ioloop self.ioloop = self._ioloop_manager.get_ioloop() self._ioloop_manager.start() # Set max_buffer_size to ensure streams are closed # if too-large messages are received self._tcp_server = tornado.tcpserver.TCPServer( self.ioloop, max_buffer_size=self.MAX_MSG_SIZE) self._tcp_server.handle_stream = self._handle_stream self._server_sock = self._bind_socket(self._bindaddr) self._bindaddr = self._server_sock.getsockname() self.ioloop.add_callback(self._install) if timeout: return self._running.wait(timeout)
[ "def", "start", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "self", ".", "_running", ".", "isSet", "(", ")", ":", "raise", "RuntimeError", "(", "'Server already started'", ")", "self", ".", "_stopped", ".", "clear", "(", ")", "# Make sure w...
Install the server on its IOLoop, optionally starting the IOLoop. Parameters ---------- timeout : float or None, optional Time in seconds to wait for server thread to start.
[ "Install", "the", "server", "on", "its", "IOLoop", "optionally", "starting", "the", "IOLoop", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L369-L394
16,377
ska-sa/katcp-python
katcp/server.py
KATCPServer._bind_socket
def _bind_socket(self, bindaddr): """Create a listening server socket.""" sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setblocking(0) try: sock.bind(bindaddr) except Exception: self._logger.exception("Unable to bind to %s" % str(bindaddr)) raise sock.listen(self.BACKLOG) return sock
python
def _bind_socket(self, bindaddr): sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) sock.setblocking(0) try: sock.bind(bindaddr) except Exception: self._logger.exception("Unable to bind to %s" % str(bindaddr)) raise sock.listen(self.BACKLOG) return sock
[ "def", "_bind_socket", "(", "self", ",", "bindaddr", ")", ":", "sock", "=", "socket", ".", "socket", "(", "socket", ".", "AF_INET", ",", "socket", ".", "SOCK_STREAM", ")", "sock", ".", "setsockopt", "(", "socket", ".", "SOL_SOCKET", ",", "socket", ".", ...
Create a listening server socket.
[ "Create", "a", "listening", "server", "socket", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L441-L452
16,378
ska-sa/katcp-python
katcp/server.py
KATCPServer._handle_stream
def _handle_stream(self, stream, address): """Handle a new connection as a tornado.iostream.IOStream instance.""" try: assert get_thread_ident() == self.ioloop_thread_id stream.set_close_callback(partial(self._stream_closed_callback, stream)) # Our message packets are small, don't delay sending them. stream.set_nodelay(True) stream.max_write_buffer_size = self.MAX_WRITE_BUFFER_SIZE # Abuse IOStream object slightly by adding 'address' and 'closing' # attributes. Use nasty prefix to prevent naming collisions. stream.KATCPServer_address = address # Flag to indicate that no more write should be accepted so that # we can flush the write buffer when closing a connection stream.KATCPServer_closing = False client_conn = self.client_connection_factory(self, stream) self._connections[stream] = client_conn try: yield gen.maybe_future(self._device.on_client_connect(client_conn)) except Exception: # If on_client_connect fails there is no reason to continue # trying to handle this connection. Try and send exception info # to the client and disconnect e_type, e_value, trace = sys.exc_info() reason = "\n".join(traceback.format_exception( e_type, e_value, trace, self._tb_limit)) log_msg = 'Device error initialising connection {0}'.format(reason) self._logger.error(log_msg) stream.write(str(Message.inform('log', log_msg))) stream.close(exc_info=True) else: self._line_read_loop(stream, client_conn) except Exception: self._logger.error('Unhandled exception trying ' 'to handle new connection', exc_info=True)
python
def _handle_stream(self, stream, address): try: assert get_thread_ident() == self.ioloop_thread_id stream.set_close_callback(partial(self._stream_closed_callback, stream)) # Our message packets are small, don't delay sending them. stream.set_nodelay(True) stream.max_write_buffer_size = self.MAX_WRITE_BUFFER_SIZE # Abuse IOStream object slightly by adding 'address' and 'closing' # attributes. Use nasty prefix to prevent naming collisions. stream.KATCPServer_address = address # Flag to indicate that no more write should be accepted so that # we can flush the write buffer when closing a connection stream.KATCPServer_closing = False client_conn = self.client_connection_factory(self, stream) self._connections[stream] = client_conn try: yield gen.maybe_future(self._device.on_client_connect(client_conn)) except Exception: # If on_client_connect fails there is no reason to continue # trying to handle this connection. Try and send exception info # to the client and disconnect e_type, e_value, trace = sys.exc_info() reason = "\n".join(traceback.format_exception( e_type, e_value, trace, self._tb_limit)) log_msg = 'Device error initialising connection {0}'.format(reason) self._logger.error(log_msg) stream.write(str(Message.inform('log', log_msg))) stream.close(exc_info=True) else: self._line_read_loop(stream, client_conn) except Exception: self._logger.error('Unhandled exception trying ' 'to handle new connection', exc_info=True)
[ "def", "_handle_stream", "(", "self", ",", "stream", ",", "address", ")", ":", "try", ":", "assert", "get_thread_ident", "(", ")", "==", "self", ".", "ioloop_thread_id", "stream", ".", "set_close_callback", "(", "partial", "(", "self", ".", "_stream_closed_cal...
Handle a new connection as a tornado.iostream.IOStream instance.
[ "Handle", "a", "new", "connection", "as", "a", "tornado", ".", "iostream", ".", "IOStream", "instance", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L475-L511
16,379
ska-sa/katcp-python
katcp/server.py
KATCPServer.get_address
def get_address(self, stream): """Text representation of the network address of a connection stream. Notes ----- This method is thread-safe """ try: addr = ":".join(str(part) for part in stream.KATCPServer_address) except AttributeError: # Something weird happened, but keep trucking addr = '<error>' self._logger.warn('Could not determine address of stream', exc_info=True) return addr
python
def get_address(self, stream): try: addr = ":".join(str(part) for part in stream.KATCPServer_address) except AttributeError: # Something weird happened, but keep trucking addr = '<error>' self._logger.warn('Could not determine address of stream', exc_info=True) return addr
[ "def", "get_address", "(", "self", ",", "stream", ")", ":", "try", ":", "addr", "=", "\":\"", ".", "join", "(", "str", "(", "part", ")", "for", "part", "in", "stream", ".", "KATCPServer_address", ")", "except", "AttributeError", ":", "# Something weird hap...
Text representation of the network address of a connection stream. Notes ----- This method is thread-safe
[ "Text", "representation", "of", "the", "network", "address", "of", "a", "connection", "stream", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L599-L614
16,380
ska-sa/katcp-python
katcp/server.py
KATCPServer.send_message
def send_message(self, stream, msg): """Send an arbitrary message to a particular client. Parameters ---------- stream : :class:`tornado.iostream.IOStream` object The stream to send the message to. msg : Message object The message to send. Notes ----- This method can only be called in the IOLoop thread. Failed sends disconnect the client connection and calls the device on_client_disconnect() method. They do not raise exceptions, but they are logged. Sends also fail if more than self.MAX_WRITE_BUFFER_SIZE bytes are queued for sending, implying that client is falling behind. """ assert get_thread_ident() == self.ioloop_thread_id try: if stream.KATCPServer_closing: raise RuntimeError('Stream is closing so we cannot ' 'accept any more writes') return stream.write(str(msg) + '\n') except Exception: addr = self.get_address(stream) self._logger.warn('Could not send message {0!r} to {1}' .format(str(msg), addr), exc_info=True) stream.close(exc_info=True)
python
def send_message(self, stream, msg): assert get_thread_ident() == self.ioloop_thread_id try: if stream.KATCPServer_closing: raise RuntimeError('Stream is closing so we cannot ' 'accept any more writes') return stream.write(str(msg) + '\n') except Exception: addr = self.get_address(stream) self._logger.warn('Could not send message {0!r} to {1}' .format(str(msg), addr), exc_info=True) stream.close(exc_info=True)
[ "def", "send_message", "(", "self", ",", "stream", ",", "msg", ")", ":", "assert", "get_thread_ident", "(", ")", "==", "self", ".", "ioloop_thread_id", "try", ":", "if", "stream", ".", "KATCPServer_closing", ":", "raise", "RuntimeError", "(", "'Stream is closi...
Send an arbitrary message to a particular client. Parameters ---------- stream : :class:`tornado.iostream.IOStream` object The stream to send the message to. msg : Message object The message to send. Notes ----- This method can only be called in the IOLoop thread. Failed sends disconnect the client connection and calls the device on_client_disconnect() method. They do not raise exceptions, but they are logged. Sends also fail if more than self.MAX_WRITE_BUFFER_SIZE bytes are queued for sending, implying that client is falling behind.
[ "Send", "an", "arbitrary", "message", "to", "a", "particular", "client", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L616-L646
16,381
ska-sa/katcp-python
katcp/server.py
KATCPServer.flush_on_close
def flush_on_close(self, stream): """Flush tornado iostream write buffer and prevent further writes. Returns a future that resolves when the stream is flushed. """ assert get_thread_ident() == self.ioloop_thread_id # Prevent futher writes stream.KATCPServer_closing = True # Write empty message to get future that resolves when buffer is flushed return stream.write('\n')
python
def flush_on_close(self, stream): assert get_thread_ident() == self.ioloop_thread_id # Prevent futher writes stream.KATCPServer_closing = True # Write empty message to get future that resolves when buffer is flushed return stream.write('\n')
[ "def", "flush_on_close", "(", "self", ",", "stream", ")", ":", "assert", "get_thread_ident", "(", ")", "==", "self", ".", "ioloop_thread_id", "# Prevent futher writes", "stream", ".", "KATCPServer_closing", "=", "True", "# Write empty message to get future that resolves w...
Flush tornado iostream write buffer and prevent further writes. Returns a future that resolves when the stream is flushed.
[ "Flush", "tornado", "iostream", "write", "buffer", "and", "prevent", "further", "writes", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L648-L658
16,382
ska-sa/katcp-python
katcp/server.py
KATCPServer.call_from_thread
def call_from_thread(self, fn): """Allow thread-safe calls to ioloop functions. Uses add_callback if not in the IOLoop thread, otherwise calls directly. Returns an already resolved `tornado.concurrent.Future` if in ioloop, otherwise a `concurrent.Future`. Logs unhandled exceptions. Resolves with an exception if one occurred. """ if self.in_ioloop_thread(): f = tornado_Future() try: f.set_result(fn()) except Exception, e: f.set_exception(e) self._logger.exception('Error executing callback ' 'in ioloop thread') finally: return f else: f = Future() try: f.set_running_or_notify_cancel() def send_message_callback(): try: f.set_result(fn()) except Exception, e: f.set_exception(e) self._logger.exception( 'Error executing wrapped async callback') self.ioloop.add_callback(send_message_callback) finally: return f
python
def call_from_thread(self, fn): if self.in_ioloop_thread(): f = tornado_Future() try: f.set_result(fn()) except Exception, e: f.set_exception(e) self._logger.exception('Error executing callback ' 'in ioloop thread') finally: return f else: f = Future() try: f.set_running_or_notify_cancel() def send_message_callback(): try: f.set_result(fn()) except Exception, e: f.set_exception(e) self._logger.exception( 'Error executing wrapped async callback') self.ioloop.add_callback(send_message_callback) finally: return f
[ "def", "call_from_thread", "(", "self", ",", "fn", ")", ":", "if", "self", ".", "in_ioloop_thread", "(", ")", ":", "f", "=", "tornado_Future", "(", ")", "try", ":", "f", ".", "set_result", "(", "fn", "(", ")", ")", "except", "Exception", ",", "e", ...
Allow thread-safe calls to ioloop functions. Uses add_callback if not in the IOLoop thread, otherwise calls directly. Returns an already resolved `tornado.concurrent.Future` if in ioloop, otherwise a `concurrent.Future`. Logs unhandled exceptions. Resolves with an exception if one occurred.
[ "Allow", "thread", "-", "safe", "calls", "to", "ioloop", "functions", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L660-L694
16,383
ska-sa/katcp-python
katcp/server.py
KATCPServer.mass_send_message
def mass_send_message(self, msg): """Send a message to all connected clients. Notes ----- This method can only be called in the IOLoop thread. """ for stream in self._connections.keys(): if not stream.closed(): # Don't cause noise by trying to write to already closed streams self.send_message(stream, msg)
python
def mass_send_message(self, msg): for stream in self._connections.keys(): if not stream.closed(): # Don't cause noise by trying to write to already closed streams self.send_message(stream, msg)
[ "def", "mass_send_message", "(", "self", ",", "msg", ")", ":", "for", "stream", "in", "self", ".", "_connections", ".", "keys", "(", ")", ":", "if", "not", "stream", ".", "closed", "(", ")", ":", "# Don't cause noise by trying to write to already closed streams"...
Send a message to all connected clients. Notes ----- This method can only be called in the IOLoop thread.
[ "Send", "a", "message", "to", "all", "connected", "clients", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L719-L730
16,384
ska-sa/katcp-python
katcp/server.py
ClientRequestConnection.reply_with_message
def reply_with_message(self, rep_msg): """Send a pre-created reply message to the client connection. Will check that rep_msg.name matches the bound request. """ self._post_reply() return self.client_connection.reply(rep_msg, self.msg)
python
def reply_with_message(self, rep_msg): self._post_reply() return self.client_connection.reply(rep_msg, self.msg)
[ "def", "reply_with_message", "(", "self", ",", "rep_msg", ")", ":", "self", ".", "_post_reply", "(", ")", "return", "self", ".", "client_connection", ".", "reply", "(", "rep_msg", ",", "self", ".", "msg", ")" ]
Send a pre-created reply message to the client connection. Will check that rep_msg.name matches the bound request.
[ "Send", "a", "pre", "-", "created", "reply", "message", "to", "the", "client", "connection", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L763-L770
16,385
ska-sa/katcp-python
katcp/server.py
MessageHandlerThread.on_message
def on_message(self, client_conn, msg): """Handle message. Returns ------- ready : Future A future that will resolve once we're ready, else None. Notes ----- *on_message* should not be called again until *ready* has resolved. """ MAX_QUEUE_SIZE = 30 if len(self._msg_queue) >= MAX_QUEUE_SIZE: # This should never happen if callers to handle_message wait # for its futures to resolve before sending another message. # NM 2014-10-06: Except when there are multiple clients. Oops. raise RuntimeError('MessageHandlerThread unhandled ' 'message queue full, not handling message') ready_future = Future() self._msg_queue.append((ready_future, client_conn, msg)) self._wake.set() return ready_future
python
def on_message(self, client_conn, msg): MAX_QUEUE_SIZE = 30 if len(self._msg_queue) >= MAX_QUEUE_SIZE: # This should never happen if callers to handle_message wait # for its futures to resolve before sending another message. # NM 2014-10-06: Except when there are multiple clients. Oops. raise RuntimeError('MessageHandlerThread unhandled ' 'message queue full, not handling message') ready_future = Future() self._msg_queue.append((ready_future, client_conn, msg)) self._wake.set() return ready_future
[ "def", "on_message", "(", "self", ",", "client_conn", ",", "msg", ")", ":", "MAX_QUEUE_SIZE", "=", "30", "if", "len", "(", "self", ".", "_msg_queue", ")", ">=", "MAX_QUEUE_SIZE", ":", "# This should never happen if callers to handle_message wait", "# for its futures t...
Handle message. Returns ------- ready : Future A future that will resolve once we're ready, else None. Notes ----- *on_message* should not be called again until *ready* has resolved.
[ "Handle", "message", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L810-L833
16,386
ska-sa/katcp-python
katcp/server.py
DeviceServerBase.create_log_inform
def create_log_inform(self, level_name, msg, name, timestamp=None): """Create a katcp logging inform message. Usually this will be called from inside a DeviceLogger object, but it is also used by the methods in this class when errors need to be reported to the client. """ if timestamp is None: timestamp = time.time() katcp_version = self.PROTOCOL_INFO.major timestamp_msg = ('%.6f' % timestamp if katcp_version >= SEC_TS_KATCP_MAJOR else str(int(timestamp*1000))) return Message.inform("log", level_name, timestamp_msg, name, msg)
python
def create_log_inform(self, level_name, msg, name, timestamp=None): if timestamp is None: timestamp = time.time() katcp_version = self.PROTOCOL_INFO.major timestamp_msg = ('%.6f' % timestamp if katcp_version >= SEC_TS_KATCP_MAJOR else str(int(timestamp*1000))) return Message.inform("log", level_name, timestamp_msg, name, msg)
[ "def", "create_log_inform", "(", "self", ",", "level_name", ",", "msg", ",", "name", ",", "timestamp", "=", "None", ")", ":", "if", "timestamp", "is", "None", ":", "timestamp", "=", "time", ".", "time", "(", ")", "katcp_version", "=", "self", ".", "PRO...
Create a katcp logging inform message. Usually this will be called from inside a DeviceLogger object, but it is also used by the methods in this class when errors need to be reported to the client.
[ "Create", "a", "katcp", "logging", "inform", "message", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L977-L992
16,387
ska-sa/katcp-python
katcp/server.py
DeviceServerBase.handle_message
def handle_message(self, client_conn, msg): """Handle messages of all types from clients. Parameters ---------- client_conn : ClientConnection object The client connection the message was from. msg : Message object The message to process. """ # log messages received so that no one else has to self._logger.debug('received: {0!s}'.format(msg)) if msg.mtype == msg.REQUEST: return self.handle_request(client_conn, msg) elif msg.mtype == msg.INFORM: return self.handle_inform(client_conn, msg) elif msg.mtype == msg.REPLY: return self.handle_reply(client_conn, msg) else: reason = "Unexpected message type received by server ['%s']." \ % (msg,) client_conn.inform(self.create_log_inform("error", reason, "root"))
python
def handle_message(self, client_conn, msg): # log messages received so that no one else has to self._logger.debug('received: {0!s}'.format(msg)) if msg.mtype == msg.REQUEST: return self.handle_request(client_conn, msg) elif msg.mtype == msg.INFORM: return self.handle_inform(client_conn, msg) elif msg.mtype == msg.REPLY: return self.handle_reply(client_conn, msg) else: reason = "Unexpected message type received by server ['%s']." \ % (msg,) client_conn.inform(self.create_log_inform("error", reason, "root"))
[ "def", "handle_message", "(", "self", ",", "client_conn", ",", "msg", ")", ":", "# log messages received so that no one else has to", "self", ".", "_logger", ".", "debug", "(", "'received: {0!s}'", ".", "format", "(", "msg", ")", ")", "if", "msg", ".", "mtype", ...
Handle messages of all types from clients. Parameters ---------- client_conn : ClientConnection object The client connection the message was from. msg : Message object The message to process.
[ "Handle", "messages", "of", "all", "types", "from", "clients", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L1005-L1028
16,388
ska-sa/katcp-python
katcp/server.py
DeviceServerBase.set_ioloop
def set_ioloop(self, ioloop=None): """Set the tornado IOLoop to use. Sets the tornado.ioloop.IOLoop instance to use, defaulting to IOLoop.current(). If set_ioloop() is never called the IOLoop is started in a new thread, and will be stopped if self.stop() is called. Notes ----- Must be called before start() is called. """ self._server.set_ioloop(ioloop) self.ioloop = self._server.ioloop
python
def set_ioloop(self, ioloop=None): self._server.set_ioloop(ioloop) self.ioloop = self._server.ioloop
[ "def", "set_ioloop", "(", "self", ",", "ioloop", "=", "None", ")", ":", "self", ".", "_server", ".", "set_ioloop", "(", "ioloop", ")", "self", ".", "ioloop", "=", "self", ".", "_server", ".", "ioloop" ]
Set the tornado IOLoop to use. Sets the tornado.ioloop.IOLoop instance to use, defaulting to IOLoop.current(). If set_ioloop() is never called the IOLoop is started in a new thread, and will be stopped if self.stop() is called. Notes ----- Must be called before start() is called.
[ "Set", "the", "tornado", "IOLoop", "to", "use", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L1260-L1273
16,389
ska-sa/katcp-python
katcp/server.py
DeviceServerBase.start
def start(self, timeout=None): """Start the server in a new thread. Parameters ---------- timeout : float or None, optional Time in seconds to wait for server thread to start. """ if self._handler_thread and self._handler_thread.isAlive(): raise RuntimeError('Message handler thread already started') self._server.start(timeout) self.ioloop = self._server.ioloop if self._handler_thread: self._handler_thread.set_ioloop(self.ioloop) self._handler_thread.start(timeout)
python
def start(self, timeout=None): if self._handler_thread and self._handler_thread.isAlive(): raise RuntimeError('Message handler thread already started') self._server.start(timeout) self.ioloop = self._server.ioloop if self._handler_thread: self._handler_thread.set_ioloop(self.ioloop) self._handler_thread.start(timeout)
[ "def", "start", "(", "self", ",", "timeout", "=", "None", ")", ":", "if", "self", ".", "_handler_thread", "and", "self", ".", "_handler_thread", ".", "isAlive", "(", ")", ":", "raise", "RuntimeError", "(", "'Message handler thread already started'", ")", "self...
Start the server in a new thread. Parameters ---------- timeout : float or None, optional Time in seconds to wait for server thread to start.
[ "Start", "the", "server", "in", "a", "new", "thread", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L1309-L1324
16,390
ska-sa/katcp-python
katcp/server.py
DeviceServerBase.sync_with_ioloop
def sync_with_ioloop(self, timeout=None): """Block for ioloop to complete a loop if called from another thread. Returns a future if called from inside the ioloop. Raises concurrent.futures.TimeoutError if timed out while blocking. """ in_ioloop = self._server.in_ioloop_thread() if in_ioloop: f = tornado_Future() else: f = Future() def cb(): f.set_result(None) self.ioloop.add_callback(cb) if in_ioloop: return f else: f.result(timeout)
python
def sync_with_ioloop(self, timeout=None): in_ioloop = self._server.in_ioloop_thread() if in_ioloop: f = tornado_Future() else: f = Future() def cb(): f.set_result(None) self.ioloop.add_callback(cb) if in_ioloop: return f else: f.result(timeout)
[ "def", "sync_with_ioloop", "(", "self", ",", "timeout", "=", "None", ")", ":", "in_ioloop", "=", "self", ".", "_server", ".", "in_ioloop_thread", "(", ")", "if", "in_ioloop", ":", "f", "=", "tornado_Future", "(", ")", "else", ":", "f", "=", "Future", "...
Block for ioloop to complete a loop if called from another thread. Returns a future if called from inside the ioloop. Raises concurrent.futures.TimeoutError if timed out while blocking.
[ "Block", "for", "ioloop", "to", "complete", "a", "loop", "if", "called", "from", "another", "thread", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L1413-L1435
16,391
ska-sa/katcp-python
katcp/server.py
DeviceServer.on_client_connect
def on_client_connect(self, client_conn): """Inform client of build state and version on connect. Parameters ---------- client_conn : ClientConnection object The client connection that has been successfully established. Returns ------- Future that resolves when the device is ready to accept messages. """ assert get_thread_ident() == self._server.ioloop_thread_id self._client_conns.add(client_conn) self._strategies[client_conn] = {} # map sensors -> sampling strategies katcp_version = self.PROTOCOL_INFO.major if katcp_version >= VERSION_CONNECT_KATCP_MAJOR: client_conn.inform(Message.inform( "version-connect", "katcp-protocol", self.PROTOCOL_INFO)) client_conn.inform(Message.inform( "version-connect", "katcp-library", "katcp-python-%s" % katcp.__version__)) client_conn.inform(Message.inform( "version-connect", "katcp-device", self.version(), self.build_state())) else: client_conn.inform(Message.inform("version", self.version())) client_conn.inform(Message.inform("build-state", self.build_state()))
python
def on_client_connect(self, client_conn): assert get_thread_ident() == self._server.ioloop_thread_id self._client_conns.add(client_conn) self._strategies[client_conn] = {} # map sensors -> sampling strategies katcp_version = self.PROTOCOL_INFO.major if katcp_version >= VERSION_CONNECT_KATCP_MAJOR: client_conn.inform(Message.inform( "version-connect", "katcp-protocol", self.PROTOCOL_INFO)) client_conn.inform(Message.inform( "version-connect", "katcp-library", "katcp-python-%s" % katcp.__version__)) client_conn.inform(Message.inform( "version-connect", "katcp-device", self.version(), self.build_state())) else: client_conn.inform(Message.inform("version", self.version())) client_conn.inform(Message.inform("build-state", self.build_state()))
[ "def", "on_client_connect", "(", "self", ",", "client_conn", ")", ":", "assert", "get_thread_ident", "(", ")", "==", "self", ".", "_server", ".", "ioloop_thread_id", "self", ".", "_client_conns", ".", "add", "(", "client_conn", ")", "self", ".", "_strategies",...
Inform client of build state and version on connect. Parameters ---------- client_conn : ClientConnection object The client connection that has been successfully established. Returns ------- Future that resolves when the device is ready to accept messages.
[ "Inform", "client", "of", "build", "state", "and", "version", "on", "connect", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L1536-L1565
16,392
ska-sa/katcp-python
katcp/server.py
DeviceServer.clear_strategies
def clear_strategies(self, client_conn, remove_client=False): """Clear the sensor strategies of a client connection. Parameters ---------- client_connection : ClientConnection instance The connection that should have its sampling strategies cleared remove_client : bool, optional Remove the client connection from the strategies datastructure. Useful for clients that disconnect. """ assert get_thread_ident() == self._server.ioloop_thread_id getter = (self._strategies.pop if remove_client else self._strategies.get) strategies = getter(client_conn, None) if strategies is not None: for sensor, strategy in list(strategies.items()): strategy.cancel() del strategies[sensor]
python
def clear_strategies(self, client_conn, remove_client=False): assert get_thread_ident() == self._server.ioloop_thread_id getter = (self._strategies.pop if remove_client else self._strategies.get) strategies = getter(client_conn, None) if strategies is not None: for sensor, strategy in list(strategies.items()): strategy.cancel() del strategies[sensor]
[ "def", "clear_strategies", "(", "self", ",", "client_conn", ",", "remove_client", "=", "False", ")", ":", "assert", "get_thread_ident", "(", ")", "==", "self", ".", "_server", ".", "ioloop_thread_id", "getter", "=", "(", "self", ".", "_strategies", ".", "pop...
Clear the sensor strategies of a client connection. Parameters ---------- client_connection : ClientConnection instance The connection that should have its sampling strategies cleared remove_client : bool, optional Remove the client connection from the strategies datastructure. Useful for clients that disconnect.
[ "Clear", "the", "sensor", "strategies", "of", "a", "client", "connection", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L1567-L1587
16,393
ska-sa/katcp-python
katcp/server.py
DeviceServer.on_client_disconnect
def on_client_disconnect(self, client_conn, msg, connection_valid): """Inform client it is about to be disconnected. Parameters ---------- client_conn : ClientConnection object The client connection being disconnected. msg : str Reason client is being disconnected. connection_valid : bool True if connection is still open for sending, False otherwise. Returns ------- Future that resolves when the client connection can be closed. """ f = tornado_Future() @gen.coroutine def remove_strategies(): self.clear_strategies(client_conn, remove_client=True) if connection_valid: client_conn.inform(Message.inform("disconnect", msg)) yield client_conn.flush_on_close() try: self._client_conns.remove(client_conn) self.ioloop.add_callback(lambda: chain_future(remove_strategies(), f)) except Exception: f.set_exc_info(sys.exc_info()) return f
python
def on_client_disconnect(self, client_conn, msg, connection_valid): f = tornado_Future() @gen.coroutine def remove_strategies(): self.clear_strategies(client_conn, remove_client=True) if connection_valid: client_conn.inform(Message.inform("disconnect", msg)) yield client_conn.flush_on_close() try: self._client_conns.remove(client_conn) self.ioloop.add_callback(lambda: chain_future(remove_strategies(), f)) except Exception: f.set_exc_info(sys.exc_info()) return f
[ "def", "on_client_disconnect", "(", "self", ",", "client_conn", ",", "msg", ",", "connection_valid", ")", ":", "f", "=", "tornado_Future", "(", ")", "@", "gen", ".", "coroutine", "def", "remove_strategies", "(", ")", ":", "self", ".", "clear_strategies", "("...
Inform client it is about to be disconnected. Parameters ---------- client_conn : ClientConnection object The client connection being disconnected. msg : str Reason client is being disconnected. connection_valid : bool True if connection is still open for sending, False otherwise. Returns ------- Future that resolves when the client connection can be closed.
[ "Inform", "client", "it", "is", "about", "to", "be", "disconnected", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L1589-L1620
16,394
ska-sa/katcp-python
katcp/server.py
DeviceServer.remove_sensor
def remove_sensor(self, sensor): """Remove a sensor from the device. Also deregisters all clients observing the sensor. Parameters ---------- sensor : Sensor object or name string The sensor to remove from the device server. """ if isinstance(sensor, basestring): sensor_name = sensor else: sensor_name = sensor.name sensor = self._sensors.pop(sensor_name) def cancel_sensor_strategies(): for conn_strategies in self._strategies.values(): strategy = conn_strategies.pop(sensor, None) if strategy: strategy.cancel() self.ioloop.add_callback(cancel_sensor_strategies)
python
def remove_sensor(self, sensor): if isinstance(sensor, basestring): sensor_name = sensor else: sensor_name = sensor.name sensor = self._sensors.pop(sensor_name) def cancel_sensor_strategies(): for conn_strategies in self._strategies.values(): strategy = conn_strategies.pop(sensor, None) if strategy: strategy.cancel() self.ioloop.add_callback(cancel_sensor_strategies)
[ "def", "remove_sensor", "(", "self", ",", "sensor", ")", ":", "if", "isinstance", "(", "sensor", ",", "basestring", ")", ":", "sensor_name", "=", "sensor", "else", ":", "sensor_name", "=", "sensor", ".", "name", "sensor", "=", "self", ".", "_sensors", "....
Remove a sensor from the device. Also deregisters all clients observing the sensor. Parameters ---------- sensor : Sensor object or name string The sensor to remove from the device server.
[ "Remove", "a", "sensor", "from", "the", "device", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L1648-L1670
16,395
ska-sa/katcp-python
katcp/server.py
DeviceServer.get_sensor
def get_sensor(self, sensor_name): """Fetch the sensor with the given name. Parameters ---------- sensor_name : str Name of the sensor to retrieve. Returns ------- sensor : Sensor object The sensor with the given name. """ sensor = self._sensors.get(sensor_name, None) if not sensor: raise ValueError("Unknown sensor '%s'." % (sensor_name,)) return sensor
python
def get_sensor(self, sensor_name): sensor = self._sensors.get(sensor_name, None) if not sensor: raise ValueError("Unknown sensor '%s'." % (sensor_name,)) return sensor
[ "def", "get_sensor", "(", "self", ",", "sensor_name", ")", ":", "sensor", "=", "self", ".", "_sensors", ".", "get", "(", "sensor_name", ",", "None", ")", "if", "not", "sensor", ":", "raise", "ValueError", "(", "\"Unknown sensor '%s'.\"", "%", "(", "sensor_...
Fetch the sensor with the given name. Parameters ---------- sensor_name : str Name of the sensor to retrieve. Returns ------- sensor : Sensor object The sensor with the given name.
[ "Fetch", "the", "sensor", "with", "the", "given", "name", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L1672-L1689
16,396
ska-sa/katcp-python
katcp/server.py
DeviceServer.request_halt
def request_halt(self, req, msg): """Halt the device server. Returns ------- success : {'ok', 'fail'} Whether scheduling the halt succeeded. Examples -------- :: ?halt !halt ok """ f = Future() @gen.coroutine def _halt(): req.reply("ok") yield gen.moment self.stop(timeout=None) raise AsyncReply self.ioloop.add_callback(lambda: chain_future(_halt(), f)) return f
python
def request_halt(self, req, msg): f = Future() @gen.coroutine def _halt(): req.reply("ok") yield gen.moment self.stop(timeout=None) raise AsyncReply self.ioloop.add_callback(lambda: chain_future(_halt(), f)) return f
[ "def", "request_halt", "(", "self", ",", "req", ",", "msg", ")", ":", "f", "=", "Future", "(", ")", "@", "gen", ".", "coroutine", "def", "_halt", "(", ")", ":", "req", ".", "reply", "(", "\"ok\"", ")", "yield", "gen", ".", "moment", "self", ".", ...
Halt the device server. Returns ------- success : {'ok', 'fail'} Whether scheduling the halt succeeded. Examples -------- :: ?halt !halt ok
[ "Halt", "the", "device", "server", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L1740-L1765
16,397
ska-sa/katcp-python
katcp/server.py
DeviceServer.request_help
def request_help(self, req, msg): """Return help on the available requests. Return a description of the available requests using a sequence of #help informs. Parameters ---------- request : str, optional The name of the request to return help for (the default is to return help for all requests). Informs ------- request : str The name of a request. description : str Documentation for the named request. Returns ------- success : {'ok', 'fail'} Whether sending the help succeeded. informs : int Number of #help inform messages sent. Examples -------- :: ?help #help halt ...description... #help help ...description... ... !help ok 5 ?help halt #help halt ...description... !help ok 1 """ if not msg.arguments: for name, method in sorted(self._request_handlers.items()): doc = method.__doc__ req.inform(name, doc) num_methods = len(self._request_handlers) return req.make_reply("ok", str(num_methods)) else: name = msg.arguments[0] if name in self._request_handlers: method = self._request_handlers[name] doc = method.__doc__.strip() req.inform(name, doc) return req.make_reply("ok", "1") return req.make_reply("fail", "Unknown request method.")
python
def request_help(self, req, msg): if not msg.arguments: for name, method in sorted(self._request_handlers.items()): doc = method.__doc__ req.inform(name, doc) num_methods = len(self._request_handlers) return req.make_reply("ok", str(num_methods)) else: name = msg.arguments[0] if name in self._request_handlers: method = self._request_handlers[name] doc = method.__doc__.strip() req.inform(name, doc) return req.make_reply("ok", "1") return req.make_reply("fail", "Unknown request method.")
[ "def", "request_help", "(", "self", ",", "req", ",", "msg", ")", ":", "if", "not", "msg", ".", "arguments", ":", "for", "name", ",", "method", "in", "sorted", "(", "self", ".", "_request_handlers", ".", "items", "(", ")", ")", ":", "doc", "=", "met...
Return help on the available requests. Return a description of the available requests using a sequence of #help informs. Parameters ---------- request : str, optional The name of the request to return help for (the default is to return help for all requests). Informs ------- request : str The name of a request. description : str Documentation for the named request. Returns ------- success : {'ok', 'fail'} Whether sending the help succeeded. informs : int Number of #help inform messages sent. Examples -------- :: ?help #help halt ...description... #help help ...description... ... !help ok 5 ?help halt #help halt ...description... !help ok 1
[ "Return", "help", "on", "the", "available", "requests", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L1767-L1821
16,398
ska-sa/katcp-python
katcp/server.py
DeviceServer.request_request_timeout_hint
def request_request_timeout_hint(self, req, request): """Return timeout hints for requests KATCP requests should generally take less than 5s to complete, but some requests are unavoidably slow. This results in spurious client timeout errors. This request provides timeout hints that clients can use to select suitable request timeouts. Parameters ---------- request : str, optional The name of the request to return a timeout hint for (the default is to return hints for all requests that have timeout hints). Returns one inform per request. Must be an existing request if specified. Informs ------- request : str The name of the request. suggested_timeout : float Suggested request timeout in seconds for the request. If `suggested_timeout` is zero (0), no timeout hint is available. Returns ------- success : {'ok', 'fail'} Whether sending the help succeeded. informs : int Number of #request-timeout-hint inform messages sent. Examples -------- :: ?request-timeout-hint #request-timeout-hint halt 5 #request-timeout-hint very-slow-request 500 ... !request-timeout-hint ok 5 ?request-timeout-hint moderately-slow-request #request-timeout-hint moderately-slow-request 20 !request-timeout-hint ok 1 Notes ----- ?request-timeout-hint without a parameter will only return informs for requests that have specific timeout hints, so it will most probably be a subset of all the requests, or even no informs at all. """ timeout_hints = {} if request: if request not in self._request_handlers: raise FailReply('Unknown request method') timeout_hint = getattr( self._request_handlers[request], 'request_timeout_hint', None) timeout_hint = timeout_hint or 0 timeout_hints[request] = timeout_hint else: for request_, handler in self._request_handlers.items(): timeout_hint = getattr(handler, 'request_timeout_hint', None) if timeout_hint: timeout_hints[request_] = timeout_hint cnt = len(timeout_hints) for request_name, timeout_hint in sorted(timeout_hints.items()): req.inform(request_name, float(timeout_hint)) return ('ok', cnt)
python
def request_request_timeout_hint(self, req, request): timeout_hints = {} if request: if request not in self._request_handlers: raise FailReply('Unknown request method') timeout_hint = getattr( self._request_handlers[request], 'request_timeout_hint', None) timeout_hint = timeout_hint or 0 timeout_hints[request] = timeout_hint else: for request_, handler in self._request_handlers.items(): timeout_hint = getattr(handler, 'request_timeout_hint', None) if timeout_hint: timeout_hints[request_] = timeout_hint cnt = len(timeout_hints) for request_name, timeout_hint in sorted(timeout_hints.items()): req.inform(request_name, float(timeout_hint)) return ('ok', cnt)
[ "def", "request_request_timeout_hint", "(", "self", ",", "req", ",", "request", ")", ":", "timeout_hints", "=", "{", "}", "if", "request", ":", "if", "request", "not", "in", "self", ".", "_request_handlers", ":", "raise", "FailReply", "(", "'Unknown request me...
Return timeout hints for requests KATCP requests should generally take less than 5s to complete, but some requests are unavoidably slow. This results in spurious client timeout errors. This request provides timeout hints that clients can use to select suitable request timeouts. Parameters ---------- request : str, optional The name of the request to return a timeout hint for (the default is to return hints for all requests that have timeout hints). Returns one inform per request. Must be an existing request if specified. Informs ------- request : str The name of the request. suggested_timeout : float Suggested request timeout in seconds for the request. If `suggested_timeout` is zero (0), no timeout hint is available. Returns ------- success : {'ok', 'fail'} Whether sending the help succeeded. informs : int Number of #request-timeout-hint inform messages sent. Examples -------- :: ?request-timeout-hint #request-timeout-hint halt 5 #request-timeout-hint very-slow-request 500 ... !request-timeout-hint ok 5 ?request-timeout-hint moderately-slow-request #request-timeout-hint moderately-slow-request 20 !request-timeout-hint ok 1 Notes ----- ?request-timeout-hint without a parameter will only return informs for requests that have specific timeout hints, so it will most probably be a subset of all the requests, or even no informs at all.
[ "Return", "timeout", "hints", "for", "requests" ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L1826-L1896
16,399
ska-sa/katcp-python
katcp/server.py
DeviceServer.request_log_level
def request_log_level(self, req, msg): """Query or set the current logging level. Parameters ---------- level : {'all', 'trace', 'debug', 'info', 'warn', 'error', 'fatal', \ 'off'}, optional Name of the logging level to set the device server to (the default is to leave the log level unchanged). Returns ------- success : {'ok', 'fail'} Whether the request succeeded. level : {'all', 'trace', 'debug', 'info', 'warn', 'error', 'fatal', \ 'off'} The log level after processing the request. Examples -------- :: ?log-level !log-level ok warn ?log-level info !log-level ok info """ if msg.arguments: try: self.log.set_log_level_by_name(msg.arguments[0]) except ValueError, e: raise FailReply(str(e)) return req.make_reply("ok", self.log.level_name())
python
def request_log_level(self, req, msg): if msg.arguments: try: self.log.set_log_level_by_name(msg.arguments[0]) except ValueError, e: raise FailReply(str(e)) return req.make_reply("ok", self.log.level_name())
[ "def", "request_log_level", "(", "self", ",", "req", ",", "msg", ")", ":", "if", "msg", ".", "arguments", ":", "try", ":", "self", ".", "log", ".", "set_log_level_by_name", "(", "msg", ".", "arguments", "[", "0", "]", ")", "except", "ValueError", ",", ...
Query or set the current logging level. Parameters ---------- level : {'all', 'trace', 'debug', 'info', 'warn', 'error', 'fatal', \ 'off'}, optional Name of the logging level to set the device server to (the default is to leave the log level unchanged). Returns ------- success : {'ok', 'fail'} Whether the request succeeded. level : {'all', 'trace', 'debug', 'info', 'warn', 'error', 'fatal', \ 'off'} The log level after processing the request. Examples -------- :: ?log-level !log-level ok warn ?log-level info !log-level ok info
[ "Query", "or", "set", "the", "current", "logging", "level", "." ]
9127c826a1d030c53b84d0e95743e20e5c5ea153
https://github.com/ska-sa/katcp-python/blob/9127c826a1d030c53b84d0e95743e20e5c5ea153/katcp/server.py#L1898-L1932