code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
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 ...
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.
4.004569
3.938884
1.016676
if timeout: self._running.wait(timeout) return self._ioloop_manager.stop(callback=self._uninstall)
def stop(self, timeout=1.0)
Stop a running server (from another thread). Parameters ---------- timeout : float or None, optional Seconds to wait for server to have *started*. Returns ------- stopped : thread-safe Future Resolves when the server is stopped
13.940943
19.264957
0.723643
t0 = time.time() self._ioloop_manager.join(timeout=timeout) if timeout: self._stopped.wait(timeout - (time.time() - t0))
def join(self, timeout=None)
Rejoin the server thread. Parameters ---------- timeout : float or None, optional Time in seconds to wait for the thread to finish. Notes ----- If the ioloop is not managed, this function will block until the server port is closed, meaning a new serv...
4.808753
4.343122
1.107211
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)) ...
def _bind_socket(self, bindaddr)
Create a listening server socket.
1.839201
1.777684
1.034605
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(Tr...
def _handle_stream(self, stream, address)
Handle a new connection as a tornado.iostream.IOStream instance.
5.46162
5.18365
1.053624
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', e...
def get_address(self, stream)
Text representation of the network address of a connection stream. Notes ----- This method is thread-safe
7.804595
8.702982
0.896773
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 Ex...
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 ca...
5.173233
4.968102
1.04129
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)
Flush tornado iostream write buffer and prevent further writes. Returns a future that resolves when the stream is flushed.
17.895041
14.171791
1.262723
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 threa...
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 occur...
2.977577
2.752476
1.081781
return self.call_from_thread(partial(self.send_message, stream, msg))
def send_message_from_thread(self, stream, msg)
Thread-safe version of send_message() returning a Future instance. Returns ------- A Future that will resolve without raising an exception as soon as the call to send_message() completes. This does not guarantee that the message has been delivered yet. If the call to send_messag...
6.147115
6.356363
0.967081
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)
Send a message to all connected clients. Notes ----- This method can only be called in the IOLoop thread.
10.004985
11.041759
0.906104
self._post_reply() return self.client_connection.reply(rep_msg, self.msg)
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.
10.697809
11.006649
0.971941
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. ...
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.
7.743297
6.85083
1.130271
if timeout: self._running.wait(timeout) self._running.clear() # Make sure to wake the run thread. self._wake.set()
def stop(self, timeout=1.0)
Stop the handler thread (from another thread). Parameters ---------- timeout : float, optional Seconds to wait for server to have *started*.
6.947333
8.494022
0.817908
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("...
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.
6.000714
5.134584
1.168685
# 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) ...
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.
4.33124
4.481918
0.966381
send_reply = True # TODO Should check presence of Message-ids against protocol flags and # raise an error as needed. if msg.name in self._request_handlers: req_conn = ClientRequestConnection(connection, msg) handler = self._request_handlers[msg.name] ...
def handle_request(self, connection, msg)
Dispatch a request message to the appropriate method. Parameters ---------- connection : ClientConnection object The client connection the message was from. msg : Message object The request message to process. Returns ------- done_future ...
3.824829
3.819279
1.001453
if msg.name in self._inform_handlers: try: self._inform_handlers[msg.name](self, connection, msg) except Exception: e_type, e_value, trace = sys.exc_info() reason = "\n".join(traceback.format_exception( e_type, ...
def handle_inform(self, connection, msg)
Dispatch an inform message to the appropriate method. Parameters ---------- connection : ClientConnection object The client connection the message was from. msg : Message object The inform message to process.
3.004303
3.157322
0.951535
if isinstance(connection, ClientRequestConnection): self._logger.warn( 'Deprecation warning: do not use self.inform() ' 'within a reply handler context -- use req.inform()\n' 'Traceback:\n %s', "".join(traceback.format_stack())) # ...
def inform(self, connection, msg)
Send an inform message to a particular client. Should only be used for asynchronous informs. Informs that are part of the response to a request should use :meth:`reply_inform` so that the message identifier from the original request can be attached to the inform. Parame...
9.044866
10.469774
0.863903
assert (msg.mtype == Message.INFORM) self._server.mass_send_message_from_thread(msg)
def mass_inform(self, msg)
Send an inform message to all clients. Parameters ---------- msg : Message object The inform message to send.
12.171134
11.50798
1.057626
if isinstance(connection, ClientRequestConnection): self._logger.warn( 'Deprecation warning: do not use self.reply() ' 'within a reply handler context -- use req.reply(*msg_args)\n' 'or req.reply_with_message(msg) Traceback:\n %s', ...
def reply(self, connection, reply, orig_req)
Send an asynchronous reply to an earlier request. Parameters ---------- connection : ClientConnection object The client to send the reply to. reply : Message object The reply message to send. orig_req : Message object The request message being...
8.896186
9.318684
0.954661
if isinstance(connection, ClientRequestConnection): self._logger.warn( 'Deprecation warning: do not use self.reply_inform() ' 'within a reply handler context -- ' 'use req.inform(*inform_arguments)\n' 'Traceback:\n %s', "".join...
def reply_inform(self, connection, inform, orig_req)
Send an inform as part of the reply to an earlier request. Parameters ---------- connection : ClientConnection object The client to send the inform to. inform : Message object The inform message to send. orig_req : Message object The request m...
7.922741
8.879687
0.892232
self._server.set_ioloop(ioloop) self.ioloop = self._server.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() ...
3.669021
5.464564
0.671421
if handler_thread: assert thread_safe, "handler_thread=True requires thread_safe=True" self._server.client_connection_factory = ( ThreadsafeClientConnection if thread_safe else ClientConnection) if handler_thread: self._handler_thread = MessageHandler...
def set_concurrency_options(self, thread_safe=True, handler_thread=True)
Set concurrency options for this device server. Must be called before :meth:`start`. Parameters ========== thread_safe : bool If True, make the server public methods thread safe. Incurs performance overhead. handler_thread : bool Can only be ...
3.829481
3.843066
0.996465
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) ...
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.
3.427036
3.619171
0.946912
self._server.join(timeout) if self._handler_thread: self._handler_thread.join(timeout)
def join(self, timeout=None)
Rejoin the server thread. Parameters ---------- timeout : float or None, optional Time in seconds to wait for the thread to finish.
4.28218
5.527572
0.774695
stopped = self._server.stop(timeout) if self._handler_thread: self._handler_thread.stop(timeout) return stopped
def stop(self, timeout=1.0)
Stop a running server (from another thread). Parameters ---------- timeout : float, optional Seconds to wait for server to have *started*. Returns ------- stopped : thread-safe Future Resolves when the server is stopped
5.397964
8.034067
0.671884
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.resul...
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.
3.495775
3.160616
1.106042
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: ...
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.
4.137208
4.056453
1.019908
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())...
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...
4.778389
5.288047
0.903621
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() ...
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 st...
5.106388
5.387456
0.947829
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_...
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.
3.191213
3.204421
0.995878
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)
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.
2.873545
3.568744
0.805198
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)
Halt the device server. Returns ------- success : {'ok', 'fail'} Whether scheduling the halt succeeded. Examples -------- :: ?halt !halt ok
6.434451
10.1601
0.633306
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: ...
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 reque...
2.786138
2.934538
0.94943
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_hi...
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. ...
2.94232
2.779836
1.058451
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)
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). ...
4.178781
6.536681
0.639282
if self._restart_queue is None: raise FailReply("No restart queue registered -- cannot restart.") f = tornado_Future() @gen.coroutine def _restart(): # .put should never block because queue should have no size limit self._restart_queue.put_n...
def request_restart(self, req, msg)
Restart the device server. Returns ------- success : {'ok', 'fail'} Whether scheduling the restart succeeded. Examples -------- :: ?restart !restart ok
8.193758
9.433309
0.868599
# TODO Get list of ClientConnection* instances and implement a standard # 'address-print' method in the ClientConnection class clients = self._client_conns num_clients = len(clients) for conn in clients: addr = conn.address req.inform(addr) ...
def request_client_list(self, req, msg)
Request the list of connected clients. The list of clients is sent as a sequence of #client-list informs. Informs ------- addr : str The address of the client as host:port with host in dotted quad notation. If the address of the client could not be determined ...
11.138019
11.032243
1.009588
versions = [ ("katcp-protocol", (self.PROTOCOL_INFO, None)), ("katcp-library", ("katcp-python-%s" % katcp.__version__, katcp.__version__)), ("katcp-device", (self.version(), self.build_state())), ] extra_versions = sorted(self.extra_versions.items()) ...
def request_version_list(self, req, msg)
Request the list of versions of roles and subcomponents. Informs ------- name : str Name of the role or component. version : str A string identifying the version of the component. Individual components may define the structure of this argument as they...
3.77189
3.244578
1.162521
exact, name_filter = construct_name_filter(msg.arguments[0] if msg.arguments else None) sensors = [(name, sensor) for name, sensor in sorted(self._sensors.iteritems()) if name_filter(name)] if exact and not sensors: ...
def request_sensor_list(self, req, msg)
Request the list of sensors. The list of sensors is sent as a sequence of #sensor-list informs. Parameters ---------- name : str, optional Name of the sensor to list (the default is to list all sensors). If name starts and ends with '/' it is treated as a regula...
5.142578
5.981907
0.859689
exact, name_filter = construct_name_filter(msg.arguments[0] if msg.arguments else None) sensors = [(name, sensor) for name, sensor in sorted(self._sensors.iteritems()) if name_filter(name)] if exact and not sensors: ...
def request_sensor_value(self, req, msg)
Request the value of a sensor or sensors. A list of sensor values as a sequence of #sensor-value informs. Parameters ---------- name : str, optional Name of the sensor to poll (the default is to send values for all sensors). If name starts and ends with '/' it i...
5.796928
5.443717
1.064884
f = Future() self.ioloop.add_callback(lambda: chain_future( self._handle_sensor_sampling(req, msg), f)) return f
def request_sensor_sampling(self, req, msg)
Configure or query the way a sensor is sampled. Sampled values are reported asynchronously using the #sensor-status message. Parameters ---------- name : str Name of the sensor whose sampling strategy to query or configure. strategy : {'none', 'auto', 'event...
5.960324
9.098228
0.655108
f = Future() @gen.coroutine def _clear_strategies(): self.clear_strategies(req.client_connection) raise gen.Return(('ok',)) self.ioloop.add_callback(lambda: chain_future(_clear_strategies(), f)) return f
def request_sensor_sampling_clear(self, req)
Set all sampling strategies for this client to none. Returns ------- success : {'ok', 'fail'} Whether sending the list of devices succeeded. Examples -------- ?sensor-sampling-clear !sensor-sampling-clear ok
6.427301
6.943955
0.925597
if level is None: level = self._log_level return self.LEVELS[level]
def level_name(self, level=None)
Return the name of the given level value. If level is None, return the name of the current level. Parameters ---------- level : logging level constant The logging level constant whose name to retrieve. Returns ------- level_name : str Th...
4.987421
7.12368
0.700119
try: return self.LEVELS.index(level_name) except ValueError: raise ValueError("Unknown logging level name '%s'" % (level_name,))
def level_from_name(self, level_name)
Return the level constant for a given name. If the *level_name* is not known, raise a ValueError. Parameters ---------- level_name : str The logging level name whose logging level constant to retrieve. Returns ------- level : logging lev...
3.259042
3.264159
0.998432
self._log_level = level if self._python_logger: try: level = self.PYTHON_LEVEL.get(level) except ValueError as err: raise FailReply("Unknown logging level '%s'" % (level)) self._python_logger.setLevel(level)
def set_log_level(self, level)
Set the logging level. Parameters ---------- level : logging level constant The value to set the logging level to.
4.312311
5.045228
0.854731
timestamp = kwargs.get("timestamp") python_msg = msg if self._python_logger is not None: if timestamp is not None: python_msg = ' '.join(( 'katcp timestamp: %r' % timestamp, python_msg)) self._python_logger....
def log(self, level, msg, *args, **kwargs)
Log a message and inform all clients. Parameters ---------- level : logging level constant The level to log the message at. msg : str The text format for the log message. args : list of objects Arguments to pass to log format string. Final mes...
4.394011
4.318128
1.017573
self.log(self.WARN, msg, *args, **kwargs)
def warn(self, msg, *args, **kwargs)
Log an warning message.
4.275635
3.425704
1.248104
(level, timestamp, name, message) = tuple(msg.arguments) log_string = "%s %s: %s" % (timestamp, name, message) logger.log({"trace": 0, "debug": logging.DEBUG, "info": logging.INFO, "warn": logging.WARN, "err...
def log_to_python(cls, logger, msg)
Log a KATCP logging message to a Python logger. Parameters ---------- logger : logging.Logger object The Python logger to log the given message to. msg : Message object The #log message to create a log entry from.
3.263774
3.405979
0.958248
return katcp.Message.reply(msg.name, "ok", *msg.arguments)
def request_echo(self, sock, msg)
Echo the arguments of the message sent.
13.254381
11.35734
1.167032
def log_cb(self, f): try: f.result() except Exception: self._logger.exception('Unhandled exception calling coroutine {0!r}' .format(coro)) @wraps(coro) def wrapped_coro(self, *args, **kwargs): try: f = coro(...
def log_coroutine_exceptions(coro)
Coroutine (or any method that returns a future) decorator to log exceptions Example ------- :: import logging class A(object): _logger = logging.getLogger(__name__) @log_coroutine_exceptions @tornado.gen.coroutine def raiser(self, arg): yield tornado....
2.520434
2.774678
0.90837
def log_cb(f): try: f.result() except ignore: pass except Exception: logger.exception('Unhandled exception returned by future') f.add_done_callback(log_cb)
def log_future_exceptions(logger, f, ignore=())
Log any exceptions set to a future Parameters ---------- logger : logging.Logger instance logger.exception(...) is called if the future resolves with an exception f : Future object Future to be monitored for exceptions ignore : Exception or tuple of Exception Exptected excep...
3.480247
4.622572
0.752881
def deco(fn): docs = [obj.__doc__] if fn.__doc__: docs.append(fn.__doc__) fn.__doc__ = '\n\n'.join(docs) return fn return deco
def steal_docstring_from(obj)
Decorator that lets you steal a docstring from another object Example ------- :: @steal_docstring_from(superclass.meth) def meth(self, arg): "Extra subclass documentation" pass In this case the docstring of the new 'meth' will be copied from superclass.meth, and if an add...
3.068873
3.981827
0.77072
if hasattr(obj, '__func__'): return (id(obj.__func__), id(obj.__self__)) elif hasattr(obj, 'im_func'): return (id(obj.im_func), id(obj.im_self)) elif isinstance(obj, (basestring, unicode)): return obj else: return id(obj)
def hashable_identity(obj)
Generate a hashable ID that is stable for methods etc Approach borrowed from blinker. Why it matters: see e.g. http://stackoverflow.com/questions/13348031/python-bound-and-unbound-method-object
2.107383
1.919684
1.097776
timeout = kwargs.get('timeout', None) ioloop = kwargs.get('ioloop', None) or tornado.ioloop.IOLoop.current() any_future = tornado_Future() def handle_done(done_future): if not any_future.done(): try: any_future.set_result(done_future.result()) except...
def until_any(*futures, **kwargs)
Return a future that resolves when any of the passed futures resolves. Resolves with the value yielded by the first future to resolve. Note, this will only work with tornado futures.
4.196856
4.203612
0.998393
ioloop = ioloop or tornado.ioloop.IOLoop.current() t0 = ioloop.time() def _remaining(): return timeout - (ioloop.time() - t0) if timeout else None def maybe_timeout(f): if not timeout: return f else: remaining = _remaining() dea...
def future_timeout_manager(timeout=None, ioloop=None)
Create Helper function for yielding with a cumulative timeout if required Keeps track of time over multiple timeout calls so that a single timeout can be placed over multiple operations. Parameters ---------- timeout : int or None Timeout, or None for no timeout ioloop : IOLoop instanc...
3.148532
3.718982
0.846611
done_at_least = kwargs.pop('done_at_least', None) timeout = kwargs.pop('timeout', None) # At this point args and kwargs are either empty or contain futures only if done_at_least is None: done_at_least = len(args) + len(kwargs) wait_iterator = tornado.gen.WaitIterator(*args, **kwargs) ...
def until_some(*args, **kwargs)
Return a future that resolves when some of the passed futures resolve. The futures can be passed as either a sequence of *args* or a dict of *kwargs* (but not both). Some additional keyword arguments are supported, as described below. Once a specified number of underlying futures have resolved, the ret...
3.157699
2.817256
1.120842
if isinstance(arg, float): return repr(arg) elif isinstance(arg, bool): return str(int(arg)) else: try: return str(arg) except UnicodeEncodeError: # unicode characters will break the str cast, so ...
def format_argument(self, arg)
Format a Message argument to a string
4.398006
4.244457
1.036176
return (self.mtype == self.REPLY and self.arguments and self.arguments[0] == self.OK)
def reply_ok(self)
Return True if this is a reply and its first argument is 'ok'.
7.232831
4.194318
1.724435
mid = kwargs.pop('mid', None) if len(kwargs) > 0: raise TypeError('Invalid keyword argument(s): %r' % kwargs) return cls(cls.REQUEST, name, args, mid)
def request(cls, name, *args, **kwargs)
Helper method for creating request messages. Parameters ---------- name : str The name of the message. args : list of strings The message arguments. Keyword arguments ----------------- mid : str or None Message ID to use or No...
4.30457
3.902897
1.102917
mid = kwargs.pop('mid', None) if len(kwargs) > 0: raise TypeError('Invalid keyword argument(s): %r' % kwargs) return cls(cls.REPLY, name, args, mid)
def reply(cls, name, *args, **kwargs)
Helper method for creating reply messages. Parameters ---------- name : str The name of the message. args : list of strings The message arguments. Keyword Arguments ----------------- mid : str or None Message ID to use or None...
4.103299
4.19136
0.97899
return cls(cls.REPLY, req_msg.name, args, req_msg.mid)
def reply_to_request(cls, req_msg, *args)
Helper method for creating reply messages to a specific request. Copies the message name and message identifier from request message. Parameters ---------- req_msg : katcp.core.Message instance The request message that this inform if in reply to args : list of strin...
9.140654
9.994531
0.914566
mid = kwargs.pop('mid', None) if len(kwargs) > 0: raise TypeError('Invalid keyword argument(s): %r' % kwargs) return cls(cls.INFORM, name, args, mid)
def inform(cls, name, *args, **kwargs)
Helper method for creating inform messages. Parameters ---------- name : str The name of the message. args : list of strings The message arguments.
4.18005
4.549521
0.918789
return cls(cls.INFORM, req_msg.name, args, req_msg.mid)
def reply_inform(cls, req_msg, *args)
Helper method for creating inform messages in reply to a request. Copies the message name and message identifier from request message. Parameters ---------- req_msg : katcp.core.Message instance The request message that this inform if in reply to args : list of stri...
8.107583
8.727034
0.929019
char = match.group(1) if char in self.ESCAPE_LOOKUP: return self.ESCAPE_LOOKUP[char] elif not char: raise KatcpSyntaxError("Escape slash at end of argument.") else: raise KatcpSyntaxError("Invalid escape character %r." % (char,))
def _unescape_match(self, match)
Given an re.Match, unescape the escape code it represents.
4.642481
4.263947
1.088775
match = self.SPECIAL_RE.search(arg) if match: raise KatcpSyntaxError("Unescaped special %r." % (match.group(),)) return self.UNESCAPE_RE.sub(self._unescape_match, arg)
def _parse_arg(self, arg)
Parse an argument.
6.331923
6.123485
1.034039
# find command type and check validity if not line: raise KatcpSyntaxError("Empty message received.") type_char = line[0] if type_char not in self.TYPE_SYMBOL_LOOKUP: raise KatcpSyntaxError("Bad type character %r." % (type_char,)) mtype = self.T...
def parse(self, line)
Parse a line, return a Message. Parameters ---------- line : str The line to parse (should not contain the terminating newline or carriage return). Returns ------- msg : Message object The resulting Message.
4.029642
4.126479
0.976533
match = cls.VERSION_RE.match(version_str) if match: major = int(match.group('major')) minor = int(match.group('minor')) flags = set(match.group('flags') or '') else: major, minor, flags = None, None, set() return cls(major, minor, ...
def parse_version(cls, version_str)
Create a :class:`ProtocolFlags` object from a version string. Parameters ---------- version_str : str The version string from a #version-connect katcp-protocol message.
2.143335
2.31047
0.927662
protocol_info = mcs.PROTOCOL_INFO protocol_version = (protocol_info.major, protocol_info.minor) protocol_flags = protocol_info.flags # Check if minimum protocol version requirement is met min_protocol_version = getattr(handler, '_minimum_katcp_version', None) pr...
def check_protocol(mcs, handler)
True if the current server's protocol flags satisfy handler requirements
2.763416
2.676646
1.032417
return cls(cls.INTEGER, name, description, unit, params, default, initial_status)
def integer(cls, name, description=None, unit='', params=None, default=None, initial_status=None)
Instantiate a new integer sensor object. Parameters ---------- name : str The name of the sensor. description : str A short description of the sensor. units : str The units of the sensor value. May be the empty string if there are ...
3.348635
6.369812
0.525704
return cls(cls.FLOAT, name, description, unit, params, default, initial_status)
def float(cls, name, description=None, unit='', params=None, default=None, initial_status=None)
Instantiate a new float sensor object. Parameters ---------- name : str The name of the sensor. description : str A short description of the sensor. units : str The units of the sensor value. May be the empty string if there are no...
3.368768
6.334713
0.531795
return cls(cls.BOOLEAN, name, description, unit, None, default, initial_status)
def boolean(cls, name, description=None, unit='', default=None, initial_status=None)
Instantiate a new boolean sensor object. Parameters ---------- name : str The name of the sensor. description : str A short description of the sensor. units : str The units of the sensor value. May be the empty string if there are ...
4.544687
8.847078
0.513694
return cls(cls.LRU, name, description, unit, None, default, initial_status)
def lru(cls, name, description=None, unit='', default=None, initial_status=None)
Instantiate a new lru sensor object. Parameters ---------- name : str The name of the sensor. description : str A short description of the sensor. units : str The units of the sensor value. May be the empty string if there are no a...
4.621086
7.085918
0.652151
return cls(cls.STRING, name, description, unit, None, default, initial_status)
def string(cls, name, description=None, unit='', default=None, initial_status=None)
Instantiate a new string sensor object. Parameters ---------- name : str The name of the sensor. description : str A short description of the sensor. units : str The units of the sensor value. May be the empty string if there are n...
4.542243
8.513287
0.533547
return cls(cls.DISCRETE, name, description, unit, params, default, initial_status)
def discrete(cls, name, description=None, unit='', params=None, default=None, initial_status=None)
Instantiate a new discrete sensor object. Parameters ---------- name : str The name of the sensor. description : str A short description of the sensor. units : str The units of the sensor value. May be the empty string if there are...
3.190287
5.413779
0.58929
return cls(cls.TIMESTAMP, name, description, unit, None, default, initial_status)
def timestamp(cls, name, description=None, unit='', default=None, initial_status=None)
Instantiate a new timestamp sensor object. Parameters ---------- name : str The name of the sensor. description : str A short description of the sensor. units : str The units of the sensor value. For timestamp sensor may only be the ...
4.377312
8.333978
0.525237
return cls(cls.ADDRESS, name, description, unit, None, default, initial_status)
def address(cls, name, description=None, unit='', default=None, initial_status=None)
Instantiate a new IP address sensor object. Parameters ---------- name : str The name of the sensor. description : str A short description of the sensor. units : str The units of the sensor value. May be the empty string if there a...
4.485355
9.084799
0.493721
# copy list before iterating in case new observers arrive for o in list(self._observers): o.update(self, reading)
def notify(self, reading)
Notify all observers of changes to this sensor.
9.82318
7.932592
1.238332
reading = self._current_reading = Reading(timestamp, status, value) self.notify(reading)
def set(self, timestamp, status, value)
Set the current value of the sensor. Parameters ---------- timestamp : float in seconds The time at which the sensor value was determined. status : Sensor status constant Whether the value represents an error condition or not. value : object Th...
7.32711
11.093998
0.660457
timestamp = self.TIMESTAMP_TYPE.decode(raw_timestamp, major) status = self.STATUS_NAMES[raw_status] value = self.parse_value(raw_value, major) self.set(timestamp, status, value)
def set_formatted(self, raw_timestamp, raw_status, raw_value, major=DEFAULT_KATCP_MAJOR)
Set the current value of the sensor. Parameters ---------- timestamp : str KATCP formatted timestamp string status : str KATCP formatted sensor status string value : str KATCP formatted sensor value major : int, default = 5 ...
3.288848
4.514065
0.728578
timestamp, status, value = reading return (self.TIMESTAMP_TYPE.encode(timestamp, major), self.STATUSES[status], self._formatter(value, True, major))
def format_reading(self, reading, major=DEFAULT_KATCP_MAJOR)
Format sensor reading as (timestamp, status, value) tuple of strings. All values are strings formatted as specified in the Sensor Type Formats in the katcp specification. Parameters ---------- reading : :class:`Reading` object Sensor reading as returned by :meth:`re...
9.621573
9.613754
1.000813
self._kattype.check(value, major) if timestamp is None: timestamp = time.time() self.set(timestamp, status, value)
def set_value(self, value, status=NOMINAL, timestamp=None, major=DEFAULT_KATCP_MAJOR)
Check and then set the value of the sensor. Parameters ---------- value : object Value of the appropriate type for the sensor. status : Sensor status constant Whether the value represents an error condition or not. timestamp : float in seconds or None ...
6.041063
5.48213
1.101955
if type_string in cls.SENSOR_TYPE_LOOKUP: return cls.SENSOR_TYPE_LOOKUP[type_string] else: raise KatcpSyntaxError("Invalid sensor type string %s" % type_string)
def parse_type(cls, type_string)
Parse KATCP formatted type code into Sensor type constant. Parameters ---------- type_string : str KATCP formatted type code. Returns ------- sensor_type : Sensor type constant The corresponding Sensor type constant.
3.833783
3.28629
1.166599
typeclass, _value = cls.SENSOR_TYPES[sensor_type] if sensor_type == cls.DISCRETE: kattype = typeclass([]) else: kattype = typeclass() return [kattype.decode(x, major) for x in formatted_params]
def parse_params(cls, sensor_type, formatted_params, major=DEFAULT_KATCP_MAJOR)
Parse KATCP formatted parameters into Python values. Parameters ---------- sensor_type : Sensor type constant The type of sensor the parameters are for. formatted_params : list of strings The formatted parameters that should be parsed. major : int ...
6.098396
6.585481
0.926037
self._flag = True old_future = self._waiting_future # Replace _waiting_future with a fresh one incase someone woken up by set_result() # sets this AsyncEvent to False before waiting on it to be set again. self._waiting_future = tornado_Future() old_future.set_res...
def set(self)
Set event flag to true and resolve future(s) returned by until_set() Notes ----- A call to set() may result in control being transferred to done_callbacks attached to the future returned by until_set().
12.476902
10.966577
1.137721
f = Future() def cb(): return gen.chain_future(self.until_set(), f) ioloop.add_callback(cb) try: f.result(timeout) return True except TimeoutError: return self._flag
def wait_with_ioloop(self, ioloop, timeout=None)
Do blocking wait until condition is event is set. Parameters ---------- ioloop : tornadio.ioloop.IOLoop instance MUST be the same ioloop that set() / clear() is called from timeout : float, int or None If not None, only wait up to `timeout` seconds for event to b...
5.764138
6.932121
0.831511
if state not in self._valid_states: raise ValueError('State must be one of {0}, not {1}' .format(self._valid_states, state)) if state != self._state: if timeout: return with_timeout(self._ioloop.time() + timeout, ...
def until_state(self, state, timeout=None)
Return a tornado Future that will resolve when the requested state is set
3.317687
2.843195
1.166887
timeout = kwargs.get('timeout', None) state_futures = (self.until_state(s, timeout=timeout) for s in states) return until_any(*state_futures)
def until_state_in(self, *states, **kwargs)
Return a tornado Future, resolves when any of the requested states is set
4.623773
3.781077
1.222872
done = self.done = fut.done() if done and not self.prev_done: self.done_since = self.ioloop.time() self.prev_done = done
def check_future(self, fut)
Call with each future that is to be yielded on
5.362131
5.857724
0.915395
delta = self.ioloop.time() - self.done_since if self.done and delta > self.max_loop_latency: return True return False
def time_to_yield(self)
Call after check_future(). If True, it is time to yield tornado.gen.moment
8.824964
7.121769
1.239153
timeout = kwargs.get('timeout', None) req_msg = Message.request(*msg_parms) if timeout is not None: reply, informs = client.blocking_request(req_msg, timeout=timeout) else: reply, informs = client.blocking_request(req_msg) if not reply.reply_ok(): raise exception('Unexp...
def request_check(client, exception, *msg_parms, **kwargs)
Make blocking request to client and raise exception if reply is not ok. Parameters ---------- client : DeviceClient instance exception: Exception class to raise *msg_parms : Message parameters sent to the Message.request() call **kwargs : Keyword arguments Forwards kwargs['timeout'] to ...
4.597778
3.535013
1.30064
if self.protocol_flags.major >= SEC_TS_KATCP_MAJOR: return time_seconds else: device_time = time_seconds * SEC_TO_MS_FAC if self.protocol_flags.major < FLOAT_TS_KATCP_MAJOR: device_time = int(device_time) return device_time
def convert_seconds(self, time_seconds)
Convert a time in seconds to the device timestamp units. KATCP v4 and earlier, specified all timestamps in milliseconds. Since KATCP v5, all timestamps are in seconds. If the device KATCP version has been detected, this method converts a value in seconds to the appropriate (seconds or m...
5.672462
4.205548
1.348804
assert get_thread_ident() == self.ioloop_thread_id self._last_msg_id += 1 return str(self._last_msg_id)
def _next_id(self)
Return the next available message id.
6.007663
4.884875
1.22985
if len(msg.arguments) < 2: return # Store version information. name = msg.arguments[0] self.versions[name] = tuple(msg.arguments[1:]) if msg.arguments[0] == "katcp-protocol": protocol_flags = ProtocolFlags.parse_version(msg.arguments[1]) ...
def inform_version_connect(self, msg)
Process a #version-connect message.
4.855143
4.581652
1.059693
if use_mid is None: use_mid = self._server_supports_ids if msg.mid is None: mid = self._next_id() if use_mid: msg.mid = mid # An internal mid may be needed for the request/inform/response # machinery to work, so we ret...
def _get_mid_and_update_msg(self, msg, use_mid)
Get message ID for current request and assign to msg.mid if needed. Parameters ---------- msg : katcp.Message ?request message use_mid : bool or None If msg.mid is None, a new message ID will be created. msg.mid will be filled with this ID if use_mid is True or if use_m...
5.838087
5.681411
1.027577
mid = self._get_mid_and_update_msg(msg, use_mid) self.send_request(msg) return mid
def request(self, msg, use_mid=None)
Send a request message, with automatic message ID assignment. Parameters ---------- msg : katcp.Message request message use_mid : bool or None, default=None Returns ------- mid : string or None The message id, or None if no msg id is used If...
5.055585
5.382317
0.939295
assert(msg.mtype == Message.REQUEST) if msg.mid and not self._server_supports_ids: raise KatcpVersionError('Message IDs not supported by server') self.send_message(msg)
def send_request(self, msg)
Send a request messsage. Parameters ---------- msg : Message object The request Message to send.
8.214293
8.458208
0.971162
assert get_thread_ident() == self.ioloop_thread_id data = str(msg) + "\n" # Log all sent messages here so no one else has to. if self._logger.isEnabledFor(logging.DEBUG): self._logger.debug("Sending to {}: {}" .format(self.bind_address_...
def send_message(self, msg)
Send any kind of message. Parameters ---------- msg : Message object The message to send.
4.442645
4.764866
0.932376
assert get_thread_ident() == self.ioloop_thread_id if self._stream: self._logger.warn('Disconnecting existing connection to {0!r} ' 'to create a new connection') self._disconnect() yield self._disconnected.until_set() st...
def _connect(self)
Connect to the server.
5.01789
4.94896
1.013928