Core API¶
Client¶
Two different clients are provided: the BlockingClient
for synchronous communication with a server and the CallbackClient
for asynchronous communication. Both clients raise KatcpClientError
when exceptions occur.
The DeviceClient
base class is provided as a foundation for
those wishing to implement their own clients.
BlockingClient¶
-
class
katcp.
BlockingClient
(host, port, tb_limit=20, timeout=5.0, logger=<logging.Logger object>, auto_reconnect=True)¶ Methods
BlockingClient.blocking_request
(msg[, ...])Send a request messsage and wait for its reply. BlockingClient.callback_request
(msg[, ...])Send a request messsage. BlockingClient.convert_seconds
(time_seconds)Convert a time in seconds to the device timestamp units. BlockingClient.disconnect
()Force client connection to close, reconnect if auto-connect set. BlockingClient.enable_thread_safety
()Enable thread-safety features. BlockingClient.future_request
(msg[, ...])Send a request messsage, with future replies. BlockingClient.handle_inform
(msg)Handle inform messages related to any current requests. BlockingClient.handle_message
(msg)Handle a message from the server. BlockingClient.handle_reply
(msg)Handle a reply message related to the current request. BlockingClient.handle_request
(msg)Dispatch a request message to the appropriate method. BlockingClient.inform_build_state
(msg)Handle katcp v4 and below build-state inform. BlockingClient.inform_version
(msg)Handle katcp v4 and below version inform. BlockingClient.inform_version_connect
(msg)Process a #version-connect message. BlockingClient.is_connected
()Check if the socket is currently connected. BlockingClient.join
([timeout])Rejoin the client thread. BlockingClient.notify_connected
(connected)Event handler that is called whenever the connection status changes. BlockingClient.preset_protocol_flags
(...)Preset server protocol flags. BlockingClient.request
(msg[, use_mid])Send a request message, with automatic message ID assignment. BlockingClient.running
()Whether the client is running. BlockingClient.send_message
(msg)Send any kind of message. BlockingClient.send_request
(msg)Send a request messsage. BlockingClient.setDaemon
(daemonic)Set daemonic state of the managed ioloop thread to True / False BlockingClient.set_ioloop
([ioloop])Set the tornado.ioloop.IOLoop instance to use. BlockingClient.start
([timeout])Start the client in a new thread. BlockingClient.stop
(*args, **kwargs)BlockingClient.unhandled_inform
(msg)Fallback method for inform messages without a registered handler. BlockingClient.unhandled_reply
(msg)Fallback method for reply messages without a registered handler. BlockingClient.unhandled_request
(msg)Fallback method for requests without a registered handler. BlockingClient.until_connected
(*args, **kwargs)Return future that resolves when the client is connected. BlockingClient.until_protocol
(*args, **kwargs)Return future that resolves after receipt of katcp protocol info. BlockingClient.until_running
([timeout])Return future that resolves when the client is running. BlockingClient.wait_connected
([timeout])Wait until the client is connected. BlockingClient.wait_protocol
([timeout])Wait until katcp protocol information has been received from server. BlockingClient.wait_running
([timeout])Wait until the client is running. -
bind_address
¶ (host, port) where the client is connecting
-
blocking_request
(msg, timeout=None, use_mid=None)¶ Send a request messsage and wait for its reply.
Parameters: msg : Message object
The request Message to send.
timeout : float in seconds
How long to wait for a reply. The default is the the timeout set when creating the AsyncClient.
use_mid : boolean, optional
Whether to use message IDs. Default is to use message IDs if the server supports them.
Returns: reply : Message object
The reply message received.
informs : list of Message objects
A list of the inform messages received.
-
callback_request
(msg, reply_cb=None, inform_cb=None, user_data=None, timeout=None, use_mid=None)¶ Send a request messsage.
Parameters: msg : Message object
The request message to send.
reply_cb : function
The reply callback with signature reply_cb(msg) or reply_cb(msg, *user_data)
inform_cb : function
The inform callback with signature inform_cb(msg) or inform_cb(msg, *user_data)
user_data : tuple
Optional user data to send to the reply and inform callbacks.
timeout : float in seconds
How long to wait for a reply. The default is the the timeout set when creating the AsyncClient.
use_mid : boolean, optional
Whether to use message IDs. Default is to use message IDs if the server supports them.
-
convert_seconds
(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 milliseconds) quantity. For version smaller than V4, the time value will be truncated to the nearest millisecond.
-
disconnect
()¶ Force client connection to close, reconnect if auto-connect set.
-
enable_thread_safety
()¶ Enable thread-safety features.
Must be called before start().
-
future_request
(msg, timeout=None, use_mid=None)¶ Send a request messsage, with future replies.
Parameters: msg : Message object
The request Message to send.
timeout : float in seconds
How long to wait for a reply. The default is the the timeout set when creating the AsyncClient.
use_mid : boolean, optional
Whether to use message IDs. Default is to use message IDs if the server supports them.
Returns: A tornado.concurrent.Future that resolves with: :
reply : Message object
The reply message received.
informs : list of Message objects
A list of the inform messages received.
-
handle_inform
(msg)¶ Handle inform messages related to any current requests.
Inform messages not related to the current request go up to the base class method.
Parameters: msg : Message object
The inform message to dispatch.
-
handle_message
(msg)¶ Handle a message from the server.
Parameters: msg : Message object
The Message to dispatch to the handler methods.
-
handle_reply
(msg)¶ Handle a reply message related to the current request.
Reply messages not related to the current request go up to the base class method.
Parameters: msg : Message object
The reply message to dispatch.
-
handle_request
(msg)¶ Dispatch a request message to the appropriate method.
Parameters: msg : Message object
The request message to dispatch.
-
inform_build_state
(msg)¶ Handle katcp v4 and below build-state inform.
-
inform_version
(msg)¶ Handle katcp v4 and below version inform.
-
inform_version_connect
(msg)¶ Process a #version-connect message.
-
is_connected
()¶ Check if the socket is currently connected.
Returns: connected : bool
Whether the client is connected.
-
join
(timeout=None)¶ Rejoin the client thread.
Parameters: timeout : float in seconds
Seconds to wait for thread to finish.
Notes
Does nothing if the ioloop is not managed.
-
notify_connected
(connected)¶ Event handler that is called whenever the connection status changes.
Override in derived class for desired behaviour.
Note
This function should never block. Doing so will cause the client to cease processing data from the server until notify_connected completes.
Parameters: connected : bool
Whether the client has just connected (True) or just disconnected (False).
-
preset_protocol_flags
(protocol_flags)¶ Preset server protocol flags.
Sets the assumed server protocol flags and disables automatic server version detection.
Parameters: protocol_flags : katcp.core.ProtocolFlags instance
-
request
(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 use_mid is None and the server supports msg ids, or if use_mid is :
True a message ID will automatically be assigned msg.mid is None. :
if msg.mid has a value, and the server supports msg ids, that value :
will be used. If the server does not support msg ids, KatcpVersionError :
will be raised. :
-
running
()¶ Whether the client is running.
Returns: running : bool
Whether the client is running.
-
send_message
(msg)¶ Send any kind of message.
Parameters: msg : Message object
The message to send.
-
send_request
(msg)¶ Send a request messsage.
Parameters: msg : Message object
The request Message to send.
-
setDaemon
(daemonic)¶ Set daemonic state of the managed ioloop thread to True / False
Calling this method for a non-managed ioloop has no effect. Must be called before start(), or it will also have no effect
-
set_ioloop
(ioloop=None)¶ Set the tornado.ioloop.IOLoop instance to use.
This defaults to IOLoop.current(). If set_ioloop() is never called the IOLoop is managed: started in a new thread, and will be stopped if self.stop() is called.
Notes
Must be called before start() is called
-
start
(timeout=None)¶ Start the client in a new thread.
Parameters: timeout : float in seconds
Seconds to wait for client thread to start. Do not specify a timeout if start() is being called from the same ioloop that this client will be installed on, since it will block the ioloop without progressing.
-
unhandled_inform
(msg)¶ Fallback method for inform messages without a registered handler.
Parameters: msg : Message object
The inform message that wasn’t processed by any handlers.
-
unhandled_reply
(msg)¶ Fallback method for reply messages without a registered handler.
Parameters: msg : Message object
The reply message that wasn’t processed by any handlers.
-
unhandled_request
(msg)¶ Fallback method for requests without a registered handler.
Parameters: msg : Message object
The request message that wasn’t processed by any handlers.
-
until_connected
(*args, **kwargs)¶ Return future that resolves when the client is connected.
-
until_protocol
(*args, **kwargs)¶ Return future that resolves after receipt of katcp protocol info.
If the returned future resolves, the server’s protocol information is available in the ProtocolFlags instance self.protocol_flags.
-
until_running
(timeout=None)¶ Return future that resolves when the client is running.
Notes
Must be called from the same ioloop as the client.
-
wait_connected
(timeout=None)¶ Wait until the client is connected.
Parameters: timeout : float in seconds
Seconds to wait for the client to connect.
Returns: connected : bool
Whether the client is connected.
Notes
Do not call this from the ioloop, use until_connected().
-
wait_protocol
(timeout=None)¶ Wait until katcp protocol information has been received from server.
Parameters: timeout : float in seconds
Seconds to wait for the client to connect.
Returns: received : bool
Whether protocol information was received
If this method returns True, the server’s protocol information is :
available in the ProtocolFlags instance self.protocol_flags. :
Notes
Do not call this from the ioloop, use until_protocol().
-
wait_running
(timeout=None)¶ Wait until the client is running.
Parameters: timeout : float in seconds
Seconds to wait for the client to start running.
Returns: running : bool
Whether the client is running
Notes
Do not call this from the ioloop, use until_running().
-
CallbackClient¶
-
class
katcp.
CallbackClient
(host, port, tb_limit=20, timeout=5.0, logger=<logging.Logger object>, auto_reconnect=True)¶ Methods
CallbackClient.blocking_request
(msg[, ...])Send a request messsage and wait for its reply. CallbackClient.callback_request
(msg[, ...])Send a request messsage. CallbackClient.convert_seconds
(time_seconds)Convert a time in seconds to the device timestamp units. CallbackClient.disconnect
()Force client connection to close, reconnect if auto-connect set. CallbackClient.enable_thread_safety
()Enable thread-safety features. CallbackClient.future_request
(msg[, ...])Send a request messsage, with future replies. CallbackClient.handle_inform
(msg)Handle inform messages related to any current requests. CallbackClient.handle_message
(msg)Handle a message from the server. CallbackClient.handle_reply
(msg)Handle a reply message related to the current request. CallbackClient.handle_request
(msg)Dispatch a request message to the appropriate method. CallbackClient.inform_build_state
(msg)Handle katcp v4 and below build-state inform. CallbackClient.inform_version
(msg)Handle katcp v4 and below version inform. CallbackClient.inform_version_connect
(msg)Process a #version-connect message. CallbackClient.is_connected
()Check if the socket is currently connected. CallbackClient.join
([timeout])Rejoin the client thread. CallbackClient.notify_connected
(connected)Event handler that is called whenever the connection status changes. CallbackClient.preset_protocol_flags
(...)Preset server protocol flags. CallbackClient.request
(msg[, use_mid])Send a request message, with automatic message ID assignment. CallbackClient.running
()Whether the client is running. CallbackClient.send_message
(msg)Send any kind of message. CallbackClient.send_request
(msg)Send a request messsage. CallbackClient.setDaemon
(daemonic)Set daemonic state of the managed ioloop thread to True / False CallbackClient.set_ioloop
([ioloop])Set the tornado.ioloop.IOLoop instance to use. CallbackClient.start
([timeout])Start the client in a new thread. CallbackClient.stop
(*args, **kwargs)CallbackClient.unhandled_inform
(msg)Fallback method for inform messages without a registered handler. CallbackClient.unhandled_reply
(msg)Fallback method for reply messages without a registered handler. CallbackClient.unhandled_request
(msg)Fallback method for requests without a registered handler. CallbackClient.until_connected
(*args, **kwargs)Return future that resolves when the client is connected. CallbackClient.until_protocol
(*args, **kwargs)Return future that resolves after receipt of katcp protocol info. CallbackClient.until_running
([timeout])Return future that resolves when the client is running. CallbackClient.wait_connected
([timeout])Wait until the client is connected. CallbackClient.wait_protocol
([timeout])Wait until katcp protocol information has been received from server. CallbackClient.wait_running
([timeout])Wait until the client is running. -
bind_address
¶ (host, port) where the client is connecting
-
blocking_request
(msg, timeout=None, use_mid=None)¶ Send a request messsage and wait for its reply.
Parameters: msg : Message object
The request Message to send.
timeout : float in seconds
How long to wait for a reply. The default is the the timeout set when creating the AsyncClient.
use_mid : boolean, optional
Whether to use message IDs. Default is to use message IDs if the server supports them.
Returns: reply : Message object
The reply message received.
informs : list of Message objects
A list of the inform messages received.
-
callback_request
(msg, reply_cb=None, inform_cb=None, user_data=None, timeout=None, use_mid=None)¶ Send a request messsage.
Parameters: msg : Message object
The request message to send.
reply_cb : function
The reply callback with signature reply_cb(msg) or reply_cb(msg, *user_data)
inform_cb : function
The inform callback with signature inform_cb(msg) or inform_cb(msg, *user_data)
user_data : tuple
Optional user data to send to the reply and inform callbacks.
timeout : float in seconds
How long to wait for a reply. The default is the the timeout set when creating the AsyncClient.
use_mid : boolean, optional
Whether to use message IDs. Default is to use message IDs if the server supports them.
-
convert_seconds
(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 milliseconds) quantity. For version smaller than V4, the time value will be truncated to the nearest millisecond.
-
disconnect
()¶ Force client connection to close, reconnect if auto-connect set.
-
enable_thread_safety
()¶ Enable thread-safety features.
Must be called before start().
-
future_request
(msg, timeout=None, use_mid=None)¶ Send a request messsage, with future replies.
Parameters: msg : Message object
The request Message to send.
timeout : float in seconds
How long to wait for a reply. The default is the the timeout set when creating the AsyncClient.
use_mid : boolean, optional
Whether to use message IDs. Default is to use message IDs if the server supports them.
Returns: A tornado.concurrent.Future that resolves with: :
reply : Message object
The reply message received.
informs : list of Message objects
A list of the inform messages received.
-
handle_inform
(msg)¶ Handle inform messages related to any current requests.
Inform messages not related to the current request go up to the base class method.
Parameters: msg : Message object
The inform message to dispatch.
-
handle_message
(msg)¶ Handle a message from the server.
Parameters: msg : Message object
The Message to dispatch to the handler methods.
-
handle_reply
(msg)¶ Handle a reply message related to the current request.
Reply messages not related to the current request go up to the base class method.
Parameters: msg : Message object
The reply message to dispatch.
-
handle_request
(msg)¶ Dispatch a request message to the appropriate method.
Parameters: msg : Message object
The request message to dispatch.
-
inform_build_state
(msg)¶ Handle katcp v4 and below build-state inform.
-
inform_version
(msg)¶ Handle katcp v4 and below version inform.
-
inform_version_connect
(msg)¶ Process a #version-connect message.
-
is_connected
()¶ Check if the socket is currently connected.
Returns: connected : bool
Whether the client is connected.
-
join
(timeout=None)¶ Rejoin the client thread.
Parameters: timeout : float in seconds
Seconds to wait for thread to finish.
Notes
Does nothing if the ioloop is not managed.
-
notify_connected
(connected)¶ Event handler that is called whenever the connection status changes.
Override in derived class for desired behaviour.
Note
This function should never block. Doing so will cause the client to cease processing data from the server until notify_connected completes.
Parameters: connected : bool
Whether the client has just connected (True) or just disconnected (False).
-
preset_protocol_flags
(protocol_flags)¶ Preset server protocol flags.
Sets the assumed server protocol flags and disables automatic server version detection.
Parameters: protocol_flags : katcp.core.ProtocolFlags instance
-
request
(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 use_mid is None and the server supports msg ids, or if use_mid is :
True a message ID will automatically be assigned msg.mid is None. :
if msg.mid has a value, and the server supports msg ids, that value :
will be used. If the server does not support msg ids, KatcpVersionError :
will be raised. :
-
running
()¶ Whether the client is running.
Returns: running : bool
Whether the client is running.
-
send_message
(msg)¶ Send any kind of message.
Parameters: msg : Message object
The message to send.
-
send_request
(msg)¶ Send a request messsage.
Parameters: msg : Message object
The request Message to send.
-
setDaemon
(daemonic)¶ Set daemonic state of the managed ioloop thread to True / False
Calling this method for a non-managed ioloop has no effect. Must be called before start(), or it will also have no effect
-
set_ioloop
(ioloop=None)¶ Set the tornado.ioloop.IOLoop instance to use.
This defaults to IOLoop.current(). If set_ioloop() is never called the IOLoop is managed: started in a new thread, and will be stopped if self.stop() is called.
Notes
Must be called before start() is called
-
start
(timeout=None)¶ Start the client in a new thread.
Parameters: timeout : float in seconds
Seconds to wait for client thread to start. Do not specify a timeout if start() is being called from the same ioloop that this client will be installed on, since it will block the ioloop without progressing.
-
unhandled_inform
(msg)¶ Fallback method for inform messages without a registered handler.
Parameters: msg : Message object
The inform message that wasn’t processed by any handlers.
-
unhandled_reply
(msg)¶ Fallback method for reply messages without a registered handler.
Parameters: msg : Message object
The reply message that wasn’t processed by any handlers.
-
unhandled_request
(msg)¶ Fallback method for requests without a registered handler.
Parameters: msg : Message object
The request message that wasn’t processed by any handlers.
-
until_connected
(*args, **kwargs)¶ Return future that resolves when the client is connected.
-
until_protocol
(*args, **kwargs)¶ Return future that resolves after receipt of katcp protocol info.
If the returned future resolves, the server’s protocol information is available in the ProtocolFlags instance self.protocol_flags.
-
until_running
(timeout=None)¶ Return future that resolves when the client is running.
Notes
Must be called from the same ioloop as the client.
-
wait_connected
(timeout=None)¶ Wait until the client is connected.
Parameters: timeout : float in seconds
Seconds to wait for the client to connect.
Returns: connected : bool
Whether the client is connected.
Notes
Do not call this from the ioloop, use until_connected().
-
wait_protocol
(timeout=None)¶ Wait until katcp protocol information has been received from server.
Parameters: timeout : float in seconds
Seconds to wait for the client to connect.
Returns: received : bool
Whether protocol information was received
If this method returns True, the server’s protocol information is :
available in the ProtocolFlags instance self.protocol_flags. :
Notes
Do not call this from the ioloop, use until_protocol().
-
wait_running
(timeout=None)¶ Wait until the client is running.
Parameters: timeout : float in seconds
Seconds to wait for the client to start running.
Returns: running : bool
Whether the client is running
Notes
Do not call this from the ioloop, use until_running().
-
AsyncClient¶
-
class
katcp.
AsyncClient
(host, port, tb_limit=20, timeout=5.0, logger=<logging.Logger object>, auto_reconnect=True)¶ Implement async and callback-based requests on top of DeviceClient.
This client will use message IDs if the server supports them.
Parameters: host : string
Host to connect to.
port : int
Port to connect to.
tb_limit : int, optional
Maximum number of stack frames to send in error traceback.
logger : object, optional
Python Logger object to log to. Default is a logger named ‘katcp’.
auto_reconnect : bool, optional
Whether to automatically reconnect if the connection dies.
timeout : float in seconds, optional
Default number of seconds to wait before a callback callback_request times out. Can be overridden in individual calls to callback_request.
Examples
>>> def reply_cb(msg): ... print "Reply:", msg ... >>> def inform_cb(msg): ... print "Inform:", msg ... >>> c = AsyncClient('localhost', 10000) >>> c.start() >>> c.ioloop.add_callback( ... c.callback_request, ... katcp.Message.request('myreq'), ... reply_cb=reply_cb, ... inform_cb=inform_cb, ... ) ... >>> # expect reply to be printed here >>> # stop the client once we're finished with it >>> c.stop() >>> c.join()
Methods
AsyncClient.blocking_request
(msg[, timeout, ...])Send a request messsage and wait for its reply. AsyncClient.callback_request
(msg[, ...])Send a request messsage. AsyncClient.convert_seconds
(time_seconds)Convert a time in seconds to the device timestamp units. AsyncClient.disconnect
()Force client connection to close, reconnect if auto-connect set. AsyncClient.enable_thread_safety
()Enable thread-safety features. AsyncClient.future_request
(msg[, timeout, ...])Send a request messsage, with future replies. AsyncClient.handle_inform
(msg)Handle inform messages related to any current requests. AsyncClient.handle_message
(msg)Handle a message from the server. AsyncClient.handle_reply
(msg)Handle a reply message related to the current request. AsyncClient.handle_request
(msg)Dispatch a request message to the appropriate method. AsyncClient.inform_build_state
(msg)Handle katcp v4 and below build-state inform. AsyncClient.inform_version
(msg)Handle katcp v4 and below version inform. AsyncClient.inform_version_connect
(msg)Process a #version-connect message. AsyncClient.is_connected
()Check if the socket is currently connected. AsyncClient.join
([timeout])Rejoin the client thread. AsyncClient.notify_connected
(connected)Event handler that is called whenever the connection status changes. AsyncClient.preset_protocol_flags
(protocol_flags)Preset server protocol flags. AsyncClient.request
(msg[, use_mid])Send a request message, with automatic message ID assignment. AsyncClient.running
()Whether the client is running. AsyncClient.send_message
(msg)Send any kind of message. AsyncClient.send_request
(msg)Send a request messsage. AsyncClient.set_ioloop
([ioloop])Set the tornado.ioloop.IOLoop instance to use. AsyncClient.start
([timeout])Start the client in a new thread. AsyncClient.stop
(*args, **kwargs)AsyncClient.unhandled_inform
(msg)Fallback method for inform messages without a registered handler. AsyncClient.unhandled_reply
(msg)Fallback method for reply messages without a registered handler. AsyncClient.unhandled_request
(msg)Fallback method for requests without a registered handler. AsyncClient.until_connected
(*args, **kwargs)Return future that resolves when the client is connected. AsyncClient.until_protocol
(*args, **kwargs)Return future that resolves after receipt of katcp protocol info. AsyncClient.until_running
([timeout])Return future that resolves when the client is running. AsyncClient.wait_connected
([timeout])Wait until the client is connected. AsyncClient.wait_protocol
([timeout])Wait until katcp protocol information has been received from server. AsyncClient.wait_running
([timeout])Wait until the client is running. -
bind_address
¶ (host, port) where the client is connecting
-
blocking_request
(msg, timeout=None, use_mid=None)¶ Send a request messsage and wait for its reply.
Parameters: msg : Message object
The request Message to send.
timeout : float in seconds
How long to wait for a reply. The default is the the timeout set when creating the AsyncClient.
use_mid : boolean, optional
Whether to use message IDs. Default is to use message IDs if the server supports them.
Returns: reply : Message object
The reply message received.
informs : list of Message objects
A list of the inform messages received.
-
callback_request
(msg, reply_cb=None, inform_cb=None, user_data=None, timeout=None, use_mid=None)¶ Send a request messsage.
Parameters: msg : Message object
The request message to send.
reply_cb : function
The reply callback with signature reply_cb(msg) or reply_cb(msg, *user_data)
inform_cb : function
The inform callback with signature inform_cb(msg) or inform_cb(msg, *user_data)
user_data : tuple
Optional user data to send to the reply and inform callbacks.
timeout : float in seconds
How long to wait for a reply. The default is the the timeout set when creating the AsyncClient.
use_mid : boolean, optional
Whether to use message IDs. Default is to use message IDs if the server supports them.
-
convert_seconds
(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 milliseconds) quantity. For version smaller than V4, the time value will be truncated to the nearest millisecond.
-
disconnect
()¶ Force client connection to close, reconnect if auto-connect set.
-
enable_thread_safety
()¶ Enable thread-safety features.
Must be called before start().
-
future_request
(msg, timeout=None, use_mid=None)¶ Send a request messsage, with future replies.
Parameters: msg : Message object
The request Message to send.
timeout : float in seconds
How long to wait for a reply. The default is the the timeout set when creating the AsyncClient.
use_mid : boolean, optional
Whether to use message IDs. Default is to use message IDs if the server supports them.
Returns: A tornado.concurrent.Future that resolves with: :
reply : Message object
The reply message received.
informs : list of Message objects
A list of the inform messages received.
-
handle_inform
(msg)¶ Handle inform messages related to any current requests.
Inform messages not related to the current request go up to the base class method.
Parameters: msg : Message object
The inform message to dispatch.
-
handle_message
(msg)¶ Handle a message from the server.
Parameters: msg : Message object
The Message to dispatch to the handler methods.
-
handle_reply
(msg)¶ Handle a reply message related to the current request.
Reply messages not related to the current request go up to the base class method.
Parameters: msg : Message object
The reply message to dispatch.
-
handle_request
(msg)¶ Dispatch a request message to the appropriate method.
Parameters: msg : Message object
The request message to dispatch.
-
inform_build_state
(msg)¶ Handle katcp v4 and below build-state inform.
-
inform_version
(msg)¶ Handle katcp v4 and below version inform.
-
inform_version_connect
(msg)¶ Process a #version-connect message.
-
is_connected
()¶ Check if the socket is currently connected.
Returns: connected : bool
Whether the client is connected.
-
join
(timeout=None)¶ Rejoin the client thread.
Parameters: timeout : float in seconds
Seconds to wait for thread to finish.
Notes
Does nothing if the ioloop is not managed.
-
notify_connected
(connected)¶ Event handler that is called whenever the connection status changes.
Override in derived class for desired behaviour.
Note
This function should never block. Doing so will cause the client to cease processing data from the server until notify_connected completes.
Parameters: connected : bool
Whether the client has just connected (True) or just disconnected (False).
-
preset_protocol_flags
(protocol_flags)¶ Preset server protocol flags.
Sets the assumed server protocol flags and disables automatic server version detection.
Parameters: protocol_flags : katcp.core.ProtocolFlags instance
-
request
(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 use_mid is None and the server supports msg ids, or if use_mid is :
True a message ID will automatically be assigned msg.mid is None. :
if msg.mid has a value, and the server supports msg ids, that value :
will be used. If the server does not support msg ids, KatcpVersionError :
will be raised. :
-
running
()¶ Whether the client is running.
Returns: running : bool
Whether the client is running.
-
send_message
(msg)¶ Send any kind of message.
Parameters: msg : Message object
The message to send.
-
send_request
(msg)¶ Send a request messsage.
Parameters: msg : Message object
The request Message to send.
-
set_ioloop
(ioloop=None)¶ Set the tornado.ioloop.IOLoop instance to use.
This defaults to IOLoop.current(). If set_ioloop() is never called the IOLoop is managed: started in a new thread, and will be stopped if self.stop() is called.
Notes
Must be called before start() is called
-
start
(timeout=None)¶ Start the client in a new thread.
Parameters: timeout : float in seconds
Seconds to wait for client thread to start. Do not specify a timeout if start() is being called from the same ioloop that this client will be installed on, since it will block the ioloop without progressing.
-
unhandled_inform
(msg)¶ Fallback method for inform messages without a registered handler.
Parameters: msg : Message object
The inform message that wasn’t processed by any handlers.
-
unhandled_reply
(msg)¶ Fallback method for reply messages without a registered handler.
Parameters: msg : Message object
The reply message that wasn’t processed by any handlers.
-
unhandled_request
(msg)¶ Fallback method for requests without a registered handler.
Parameters: msg : Message object
The request message that wasn’t processed by any handlers.
-
until_connected
(*args, **kwargs)¶ Return future that resolves when the client is connected.
-
until_protocol
(*args, **kwargs)¶ Return future that resolves after receipt of katcp protocol info.
If the returned future resolves, the server’s protocol information is available in the ProtocolFlags instance self.protocol_flags.
-
until_running
(timeout=None)¶ Return future that resolves when the client is running.
Notes
Must be called from the same ioloop as the client.
-
wait_connected
(timeout=None)¶ Wait until the client is connected.
Parameters: timeout : float in seconds
Seconds to wait for the client to connect.
Returns: connected : bool
Whether the client is connected.
Notes
Do not call this from the ioloop, use until_connected().
-
wait_protocol
(timeout=None)¶ Wait until katcp protocol information has been received from server.
Parameters: timeout : float in seconds
Seconds to wait for the client to connect.
Returns: received : bool
Whether protocol information was received
If this method returns True, the server’s protocol information is :
available in the ProtocolFlags instance self.protocol_flags. :
Notes
Do not call this from the ioloop, use until_protocol().
-
wait_running
(timeout=None)¶ Wait until the client is running.
Parameters: timeout : float in seconds
Seconds to wait for the client to start running.
Returns: running : bool
Whether the client is running
Notes
Do not call this from the ioloop, use until_running().
-
Base Classes¶
-
class
katcp.
DeviceClient
(host, port, tb_limit=20, logger=<logging.Logger object>, auto_reconnect=True)¶ Device client proxy.
Subclasses should implement .reply_*, .inform_* and send_request_* methods to take actions when messages arrive, and implement unhandled_inform, unhandled_reply and unhandled_request to provide fallbacks for messages for which there is no handler.
Request messages can be sent by calling .send_request().
Parameters: host : string
Host to connect to.
port : int
Port to connect to.
tb_limit : int
Maximum number of stack frames to send in error traceback.
logger : object
Python Logger object to log to.
auto_reconnect : bool
Whether to automatically reconnect if the connection dies.
Notes
The client may block its ioloop if the default blocking tornado DNS resolver is used. When an ioloop is shared, it would make sens to configure one of the non-blocking resolver classes, see http://tornado.readthedocs.org/en/latest/netutil.html
Examples
>>> MyClient(DeviceClient): ... def reply_myreq(self, msg): ... print str(msg) ... >>> c = MyClient('localhost', 10000) >>> c.start() >>> c.send_request(katcp.Message.request('myreq')) >>> # expect reply to be printed here >>> # stop the client once we're finished with it >>> c.stop() >>> c.join()
Methods
DeviceClient.convert_seconds
(time_seconds)Convert a time in seconds to the device timestamp units. DeviceClient.disconnect
()Force client connection to close, reconnect if auto-connect set. DeviceClient.enable_thread_safety
()Enable thread-safety features. DeviceClient.handle_inform
(msg)Dispatch an inform message to the appropriate method. DeviceClient.handle_message
(msg)Handle a message from the server. DeviceClient.handle_reply
(msg)Dispatch a reply message to the appropriate method. DeviceClient.handle_request
(msg)Dispatch a request message to the appropriate method. DeviceClient.inform_build_state
(msg)Handle katcp v4 and below build-state inform. DeviceClient.inform_version
(msg)Handle katcp v4 and below version inform. DeviceClient.inform_version_connect
(msg)Process a #version-connect message. DeviceClient.is_connected
()Check if the socket is currently connected. DeviceClient.join
([timeout])Rejoin the client thread. DeviceClient.notify_connected
(connected)Event handler that is called whenever the connection status changes. DeviceClient.preset_protocol_flags
(...)Preset server protocol flags. DeviceClient.request
(msg[, use_mid])Send a request message, with automatic message ID assignment. DeviceClient.running
()Whether the client is running. DeviceClient.send_message
(msg)Send any kind of message. DeviceClient.send_request
(msg)Send a request messsage. DeviceClient.set_ioloop
([ioloop])Set the tornado.ioloop.IOLoop instance to use. DeviceClient.start
([timeout])Start the client in a new thread. DeviceClient.stop
([timeout])Stop a running client (from another thread). DeviceClient.unhandled_inform
(msg)Fallback method for inform messages without a registered handler. DeviceClient.unhandled_reply
(msg)Fallback method for reply messages without a registered handler. DeviceClient.unhandled_request
(msg)Fallback method for requests without a registered handler. DeviceClient.until_connected
(*args, **kwargs)Return future that resolves when the client is connected. DeviceClient.until_protocol
(*args, **kwargs)Return future that resolves after receipt of katcp protocol info. DeviceClient.until_running
([timeout])Return future that resolves when the client is running. DeviceClient.wait_connected
([timeout])Wait until the client is connected. DeviceClient.wait_protocol
([timeout])Wait until katcp protocol information has been received from server. DeviceClient.wait_running
([timeout])Wait until the client is running. -
MAX_LOOP_LATENCY
= 0.03¶ Do not spend more than this many seconds reading pipelined socket data
IOStream inline-reading can result in ioloop starvation (see https://groups.google.com/forum/#!topic/python-tornado/yJrDAwDR_kA).
-
MAX_MSG_SIZE
= 2097152¶ Maximum message size that can be received in bytes.
If more than MAX_MSG_SIZE bytes are read from the socket without encountering a message terminator (i.e. newline), the connection is closed.
-
MAX_WRITE_BUFFER_SIZE
= 4194304¶ Maximum outstanding bytes to be buffered by the server process.
If more than MAX_WRITE_BUFFER_SIZE bytes are outstanding, the connection is closed. Note that the OS also buffers socket writes, so more than MAX_WRITE_BUFFER_SIZE bytes may be untransmitted in total.
-
bind_address
¶ (host, port) where the client is connecting
-
convert_seconds
(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 milliseconds) quantity. For version smaller than V4, the time value will be truncated to the nearest millisecond.
-
disconnect
()¶ Force client connection to close, reconnect if auto-connect set.
-
enable_thread_safety
()¶ Enable thread-safety features.
Must be called before start().
-
handle_inform
(msg)¶ Dispatch an inform message to the appropriate method.
Parameters: msg : Message object
The inform message to dispatch.
-
handle_message
(msg)¶ Handle a message from the server.
Parameters: msg : Message object
The Message to dispatch to the handler methods.
-
handle_reply
(msg)¶ Dispatch a reply message to the appropriate method.
Parameters: msg : Message object
The reply message to dispatch.
-
handle_request
(msg)¶ Dispatch a request message to the appropriate method.
Parameters: msg : Message object
The request message to dispatch.
-
inform_build_state
(msg)¶ Handle katcp v4 and below build-state inform.
-
inform_version
(msg)¶ Handle katcp v4 and below version inform.
-
inform_version_connect
(msg)¶ Process a #version-connect message.
-
ioloop
= None¶ The Tornado IOloop to use, set by self.set_ioloop()
-
is_connected
()¶ Check if the socket is currently connected.
Returns: connected : bool
Whether the client is connected.
-
join
(timeout=None)¶ Rejoin the client thread.
Parameters: timeout : float in seconds
Seconds to wait for thread to finish.
Notes
Does nothing if the ioloop is not managed.
-
notify_connected
(connected)¶ Event handler that is called whenever the connection status changes.
Override in derived class for desired behaviour.
Note
This function should never block. Doing so will cause the client to cease processing data from the server until notify_connected completes.
Parameters: connected : bool
Whether the client has just connected (True) or just disconnected (False).
-
preset_protocol_flags
(protocol_flags)¶ Preset server protocol flags.
Sets the assumed server protocol flags and disables automatic server version detection.
Parameters: protocol_flags : katcp.core.ProtocolFlags instance
-
request
(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 use_mid is None and the server supports msg ids, or if use_mid is :
True a message ID will automatically be assigned msg.mid is None. :
if msg.mid has a value, and the server supports msg ids, that value :
will be used. If the server does not support msg ids, KatcpVersionError :
will be raised. :
-
running
()¶ Whether the client is running.
Returns: running : bool
Whether the client is running.
-
send_message
(msg)¶ Send any kind of message.
Parameters: msg : Message object
The message to send.
-
send_request
(msg)¶ Send a request messsage.
Parameters: msg : Message object
The request Message to send.
-
set_ioloop
(ioloop=None)¶ Set the tornado.ioloop.IOLoop instance to use.
This defaults to IOLoop.current(). If set_ioloop() is never called the IOLoop is managed: started in a new thread, and will be stopped if self.stop() is called.
Notes
Must be called before start() is called
-
start
(timeout=None)¶ Start the client in a new thread.
Parameters: timeout : float in seconds
Seconds to wait for client thread to start. Do not specify a timeout if start() is being called from the same ioloop that this client will be installed on, since it will block the ioloop without progressing.
-
stop
(timeout=None)¶ Stop a running client (from another thread).
Parameters: timeout : float in seconds
Seconds to wait for client thread to have started.
-
unhandled_inform
(msg)¶ Fallback method for inform messages without a registered handler.
Parameters: msg : Message object
The inform message that wasn’t processed by any handlers.
-
unhandled_reply
(msg)¶ Fallback method for reply messages without a registered handler.
Parameters: msg : Message object
The reply message that wasn’t processed by any handlers.
-
unhandled_request
(msg)¶ Fallback method for requests without a registered handler.
Parameters: msg : Message object
The request message that wasn’t processed by any handlers.
-
until_connected
(*args, **kwargs)¶ Return future that resolves when the client is connected.
-
until_protocol
(*args, **kwargs)¶ Return future that resolves after receipt of katcp protocol info.
If the returned future resolves, the server’s protocol information is available in the ProtocolFlags instance self.protocol_flags.
-
until_running
(timeout=None)¶ Return future that resolves when the client is running.
Notes
Must be called from the same ioloop as the client.
-
wait_connected
(timeout=None)¶ Wait until the client is connected.
Parameters: timeout : float in seconds
Seconds to wait for the client to connect.
Returns: connected : bool
Whether the client is connected.
Notes
Do not call this from the ioloop, use until_connected().
-
wait_protocol
(timeout=None)¶ Wait until katcp protocol information has been received from server.
Parameters: timeout : float in seconds
Seconds to wait for the client to connect.
Returns: received : bool
Whether protocol information was received
If this method returns True, the server’s protocol information is :
available in the ProtocolFlags instance self.protocol_flags. :
Notes
Do not call this from the ioloop, use until_protocol().
-
wait_running
(timeout=None)¶ Wait until the client is running.
Parameters: timeout : float in seconds
Seconds to wait for the client to start running.
Returns: running : bool
Whether the client is running
Notes
Do not call this from the ioloop, use until_running().
-
Server¶
AsyncDeviceServer¶
-
class
katcp.
AsyncDeviceServer
(*args, **kwargs)¶ DeviceServer that is automatically configured for async use.
Same as instantiating a
DeviceServer
instance and calling methods set_concurrency_options(thread_safe=False, handler_thread=False) and set_ioloop(tornado.ioloop.IOLoop.current()) before starting.Methods
AsyncDeviceServer.add_sensor
(sensor)Add a sensor to the device. AsyncDeviceServer.build_state
()Return build state string of the form name-major.minor[(a|b|rc)n]. AsyncDeviceServer.clear_strategies
(client_conn)Clear the sensor strategies of a client connection. AsyncDeviceServer.create_exception_reply_and_log
(...)AsyncDeviceServer.create_log_inform
(...[, ...])Create a katcp logging inform message. AsyncDeviceServer.get_sensor
(sensor_name)Fetch the sensor with the given name. AsyncDeviceServer.get_sensors
()Fetch a list of all sensors. AsyncDeviceServer.handle_inform
(connection, msg)Dispatch an inform message to the appropriate method. AsyncDeviceServer.handle_message
(...)Handle messages of all types from clients. AsyncDeviceServer.handle_reply
(connection, msg)Dispatch a reply message to the appropriate method. AsyncDeviceServer.handle_request
(connection, msg)Dispatch a request message to the appropriate method. AsyncDeviceServer.has_sensor
(sensor_name)Whether the sensor with specified name is known. AsyncDeviceServer.inform
(connection, msg)Send an inform message to a particular client. AsyncDeviceServer.join
([timeout])Rejoin the server thread. AsyncDeviceServer.mass_inform
(msg)Send an inform message to all clients. AsyncDeviceServer.on_client_connect
(*args, ...)Inform client of build state and version on connect. AsyncDeviceServer.on_client_disconnect
(...)Inform client it is about to be disconnected. AsyncDeviceServer.on_message
(client_conn, msg)Dummy implementation of on_message required by KATCPServer. AsyncDeviceServer.remove_sensor
(sensor)Remove a sensor from the device. AsyncDeviceServer.reply
(connection, reply, ...)Send an asynchronous reply to an earlier request. AsyncDeviceServer.reply_inform
(connection, ...)Send an inform as part of the reply to an earlier request. AsyncDeviceServer.request_client_list
(req, msg)Request the list of connected clients. AsyncDeviceServer.request_halt
(req, msg)Halt the device server. AsyncDeviceServer.request_help
(req, msg)Return help on the available requests. AsyncDeviceServer.request_log_level
(req, msg)Query or set the current logging level. AsyncDeviceServer.request_restart
(req, msg)Restart the device server. AsyncDeviceServer.request_sensor_list
(req, msg)Request the list of sensors. AsyncDeviceServer.request_sensor_sampling
(...)Configure or query the way a sensor is sampled. AsyncDeviceServer.request_sensor_sampling_clear
(...)Set all sampling strategies for this client to none. AsyncDeviceServer.request_sensor_value
(req, msg)Request the value of a sensor or sensors. AsyncDeviceServer.request_version_list
(req, msg)Request the list of versions of roles and subcomponents. AsyncDeviceServer.request_watchdog
(req, msg)Check that the server is still alive. AsyncDeviceServer.running
()Whether the server is running. AsyncDeviceServer.setDaemon
(daemonic)Set daemonic state of the managed ioloop thread to True / False AsyncDeviceServer.set_concurrency_options
([...])Set concurrency options for this device server. AsyncDeviceServer.set_ioloop
([ioloop])Set the tornado IOLoop to use. AsyncDeviceServer.set_restart_queue
(...)Set the restart queue. AsyncDeviceServer.setup_sensors
()Populate the dictionary of sensors. AsyncDeviceServer.start
([timeout])Start the server in a new thread. AsyncDeviceServer.stop
([timeout])Stop a running server (from another thread). AsyncDeviceServer.sync_with_ioloop
([timeout])Block for ioloop to complete a loop if called from another thread. AsyncDeviceServer.version
()Return a version string of the form type-major.minor. AsyncDeviceServer.wait_running
([timeout])Wait until the server is running -
add_sensor
(sensor)¶ Add a sensor to the device.
Usually called inside .setup_sensors() but may be called from elsewhere.
Parameters: sensor : Sensor object
The sensor object to register with the device server.
-
build_state
()¶ Return build state string of the form name-major.minor[(a|b|rc)n].
-
clear_strategies
(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.
-
create_log_inform
(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.
-
get_sensor
(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.
-
get_sensors
()¶ Fetch a list of all sensors.
Returns: sensors : list of Sensor objects
The list of sensors registered with the device server.
-
handle_inform
(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.
-
handle_message
(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.
-
handle_reply
(connection, msg)¶ Dispatch a reply message to the appropriate method.
Parameters: connection : ClientConnection object
The client connection the message was from.
msg : Message object
The reply message to process.
-
handle_request
(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 : Future or None
Returns Future for async request handlers that will resolve when done, or None for sync request handlers once they have completed.
-
has_sensor
(sensor_name)¶ Whether the sensor with specified name is known.
-
inform
(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
reply_inform()
so that the message identifier from the original request can be attached to the inform.Parameters: connection : ClientConnection object
The client to send the message to.
msg : Message object
The inform message to send.
-
join
(timeout=None)¶ Rejoin the server thread.
Parameters: timeout : float or None, optional
Time in seconds to wait for the thread to finish.
-
mass_inform
(msg)¶ Send an inform message to all clients.
Parameters: msg : Message object
The inform message to send.
-
on_client_connect
(*args, **kwargs)¶ 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. :
-
on_client_disconnect
(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. :
-
on_message
(client_conn, msg)¶ Dummy implementation of on_message required by KATCPServer.
Will be replaced by a handler with the appropriate concurrency semantics when set_concurrency_options is called (defaults are set in __init__()).
-
remove_sensor
(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.
-
reply
(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 replied to. The reply message’s id is overridden with the id from orig_req before the reply is sent.
-
reply_inform
(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 message being replied to. The inform message’s id is overridden with the id from orig_req before the inform is sent.
-
request_client_list
(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 (because, for example, the client disconnected suddenly) then a unique string representing the client is sent instead.
Returns: success : {‘ok’, ‘fail’}
Whether sending the client list succeeded.
informs : int
Number of #client-list inform messages sent.
Examples
?client-list #client-list 127.0.0.1:53600 !client-list ok 1
-
request_halt
(req, msg)¶ Halt the device server.
Returns: success : {‘ok’, ‘fail’}
Whether scheduling the halt succeeded.
Examples
?halt !halt ok
-
request_help
(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
-
request_log_level
(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
-
request_restart
(req, msg)¶ Restart the device server.
Returns: success : {‘ok’, ‘fail’}
Whether scheduling the restart succeeded.
Examples
?restart !restart ok
-
request_sensor_list
(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 regular expression and all sensors whose names contain the regular expression are returned.
Informs: name : str
The name of the sensor being described.
description : str
Description of the named sensor.
units : str
Units for the value of the named sensor.
type : str
Type of the named sensor.
params : list of str, optional
Additional sensor parameters (type dependent). For integer and float sensors the additional parameters are the minimum and maximum sensor value. For discrete sensors the additional parameters are the allowed values. For all other types no additional parameters are sent.
Returns: success : {‘ok’, ‘fail’}
Whether sending the sensor list succeeded.
informs : int
Number of #sensor-list inform messages sent.
Examples
?sensor-list #sensor-list psu.voltage PSU\_voltage. V float 0.0 5.0 #sensor-list cpu.status CPU\_status. \@ discrete on off error ... !sensor-list ok 5 ?sensor-list cpu.power.on #sensor-list cpu.power.on Whether\_CPU\_hase\_power. \@ boolean !sensor-list ok 1 ?sensor-list /voltage/ #sensor-list psu.voltage PSU\_voltage. V float 0.0 5.0 #sensor-list cpu.voltage CPU\_voltage. V float 0.0 3.0 !sensor-list ok 2
-
request_sensor_sampling
(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’, ‘differential’, ‘period’, ‘event-rate’}, optional
Type of strategy to use to report the sensor value. The differential strategy type may only be used with integer or float sensors. If this parameter is supplied, it sets the new strategy.
params : list of str, optional
Additional strategy parameters (dependent on the strategy type). For the differential strategy, the parameter is an integer or float giving the amount by which the sensor value may change before an updated value is sent. For the period strategy, the parameter is the sampling period in float seconds. The event strategy has no parameters. Note that this has changed from KATCPv4. For the event-rate strategy, a minimum period between updates and a maximum period between updates (both in float seconds) must be given. If the event occurs more than once within the minimum period, only one update will occur. Whether or not the event occurs, the sensor value will be updated at least once per maximum period. The differential-rate strategy is not supported in this release.
Returns: success : {‘ok’, ‘fail’}
Whether the sensor-sampling request succeeded.
name : str
Name of the sensor queried or configured.
strategy : {‘none’, ‘auto’, ‘event’, ‘differential’, ‘period’}
Name of the new or current sampling strategy for the sensor.
params : list of str
Additional strategy parameters (see description under Parameters).
Examples
?sensor-sampling cpu.power.on !sensor-sampling ok cpu.power.on none ?sensor-sampling cpu.power.on period 500 !sensor-sampling ok cpu.power.on period 500
-
request_sensor_sampling_clear
(req, msg)¶ 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
-
request_sensor_value
(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 is treated as a regular expression and all sensors whose names contain the regular expression are returned.
Informs: timestamp : float
Timestamp of the sensor reading in seconds since the Unix epoch, or milliseconds for katcp versions <= 4.
count : {1}
Number of sensors described in this #sensor-value inform. Will always be one. It exists to keep this inform compatible with #sensor-status.
name : str
Name of the sensor whose value is being reported.
value : object
Value of the named sensor. Type depends on the type of the sensor.
Returns: success : {‘ok’, ‘fail’}
Whether sending the list of values succeeded.
informs : int
Number of #sensor-value inform messages sent.
Examples
?sensor-value #sensor-value 1244631611.415231 1 psu.voltage 4.5 #sensor-value 1244631611.415200 1 cpu.status off ... !sensor-value ok 5 ?sensor-value cpu.power.on #sensor-value 1244631611.415231 1 cpu.power.on 0 !sensor-value ok 1
-
request_version_list
(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 choose. In the absence of other information clients should treat it as an opaque string.
build_state_or_serial_number : str
A unique identifier for a particular instance of a component. This should change whenever the component is replaced or updated.
Returns: success : {‘ok’, ‘fail’}
Whether sending the version list succeeded.
informs : int
Number of #version-list inform messages sent.
Examples
?version-list #version-list katcp-protocol 5.0-MI #version-list katcp-library katcp-python-0.4 katcp-python-0.4.1-py2 #version-list katcp-device foodevice-1.0 foodevice-1.0.0rc1 !version-list ok 3
-
request_watchdog
(req, msg)¶ Check that the server is still alive.
Returns: success : {‘ok’} Examples
?watchdog !watchdog ok
-
running
()¶ Whether the server is running.
-
setDaemon
(daemonic)¶ Set daemonic state of the managed ioloop thread to True / False
Calling this method for a non-managed ioloop has no effect. Must be called before start(), or it will also have no effect
-
set_concurrency_options
(thread_safe=True, handler_thread=True)¶ Set concurrency options for this device server. Must be called before
start()
.Parameters: thread_safe : bool
If True, make the server public methods thread safe. Incurs performance overhead.
handler_thread : bool
Can only be set if thread_safe is True. Handle all requests (even from different clients) in a separate, single, request-handling thread. Blocking request handlers will prevent the server from handling new requests from any client, but sensor strategies should still function. This more or less mimics the behaviour of a server in library versions before 0.6.0.
-
set_ioloop
(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.
-
set_restart_queue
(restart_queue)¶ Set the restart queue.
When the device server should be restarted, it will be added to the queue.
Parameters: restart_queue : Queue.Queue object
The queue to add the device server to when it should be restarted.
-
setup_sensors
()¶ Populate the dictionary of sensors.
Unimplemented by default – subclasses should add their sensors here or pass if there are no sensors.
Examples
>>> class MyDevice(DeviceServer): ... def setup_sensors(self): ... self.add_sensor(Sensor(...)) ... self.add_sensor(Sensor(...)) ...
-
start
(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.
-
stop
(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
-
sync_with_ioloop
(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.
-
version
()¶ Return a version string of the form type-major.minor.
-
wait_running
(timeout=None)¶ Wait until the server is running
-
DeviceServer¶
-
class
katcp.
DeviceServer
(*args, **kwargs)¶ Implements some standard messages on top of DeviceServerBase.
Inform messages handled are:
- version (sent on connect)
- build-state (sent on connect)
- log (via self.log.warn(...), etc)
- disconnect
- client-connected
Requests handled are:
- halt
- help
- log-level
- restart [1]
- client-list
- sensor-list
- sensor-sampling
- sensor-value
- watchdog
- version-list (only standard in KATCP v5 or later)
- sensor-sampling-clear (non-standard)
[1] Restart relies on .set_restart_queue() being used to register a restart queue with the device. When the device needs to be restarted, it will be added to the restart queue. The queue should be a Python Queue.Queue object without a maximum size. Unhandled standard requests are:
- configure
- mode
Subclasses can define the tuple VERSION_INFO to set the interface name, major and minor version numbers. The BUILD_INFO tuple can be defined to give a string describing a particular interface instance and may have a fourth element containing additional version information (e.g. rc1).
Subclasses may manipulate the versions returned by the ?version-list command by editing .extra_versions which is a dictionary mapping role or component names to (version, build_state_or_serial_no) tuples. The build_state_or_serial_no may be None.
Subclasses must override the .setup_sensors() method. If they have no sensors to register, the method should just be a pass.
Methods
DeviceServer.add_sensor
(sensor)Add a sensor to the device. DeviceServer.build_state
()Return build state string of the form name-major.minor[(a|b|rc)n]. DeviceServer.clear_strategies
(client_conn[, ...])Clear the sensor strategies of a client connection. DeviceServer.create_exception_reply_and_log
(...)DeviceServer.create_log_inform
(level_name, ...)Create a katcp logging inform message. DeviceServer.get_sensor
(sensor_name)Fetch the sensor with the given name. DeviceServer.get_sensors
()Fetch a list of all sensors. DeviceServer.handle_inform
(connection, msg)Dispatch an inform message to the appropriate method. DeviceServer.handle_message
(client_conn, msg)Handle messages of all types from clients. DeviceServer.handle_reply
(connection, msg)Dispatch a reply message to the appropriate method. DeviceServer.handle_request
(connection, msg)Dispatch a request message to the appropriate method. DeviceServer.has_sensor
(sensor_name)Whether the sensor with specified name is known. DeviceServer.inform
(connection, msg)Send an inform message to a particular client. DeviceServer.join
([timeout])Rejoin the server thread. DeviceServer.mass_inform
(msg)Send an inform message to all clients. DeviceServer.on_client_connect
(*args, **kwargs)Inform client of build state and version on connect. DeviceServer.on_client_disconnect
(...)Inform client it is about to be disconnected. DeviceServer.on_message
(client_conn, msg)Dummy implementation of on_message required by KATCPServer. DeviceServer.remove_sensor
(sensor)Remove a sensor from the device. DeviceServer.reply
(connection, reply, orig_req)Send an asynchronous reply to an earlier request. DeviceServer.reply_inform
(connection, ...)Send an inform as part of the reply to an earlier request. DeviceServer.request_client_list
(req, msg)Request the list of connected clients. DeviceServer.request_halt
(req, msg)Halt the device server. DeviceServer.request_help
(req, msg)Return help on the available requests. DeviceServer.request_log_level
(req, msg)Query or set the current logging level. DeviceServer.request_restart
(req, msg)Restart the device server. DeviceServer.request_sensor_list
(req, msg)Request the list of sensors. DeviceServer.request_sensor_sampling
(req, msg)Configure or query the way a sensor is sampled. DeviceServer.request_sensor_sampling_clear
(...)Set all sampling strategies for this client to none. DeviceServer.request_sensor_value
(req, msg)Request the value of a sensor or sensors. DeviceServer.request_version_list
(req, msg)Request the list of versions of roles and subcomponents. DeviceServer.request_watchdog
(req, msg)Check that the server is still alive. DeviceServer.running
()Whether the server is running. DeviceServer.setDaemon
(daemonic)Set daemonic state of the managed ioloop thread to True / False DeviceServer.set_concurrency_options
([...])Set concurrency options for this device server. DeviceServer.set_ioloop
([ioloop])Set the tornado IOLoop to use. DeviceServer.set_restart_queue
(restart_queue)Set the restart queue. DeviceServer.setup_sensors
()Populate the dictionary of sensors. DeviceServer.start
([timeout])Start the server in a new thread. DeviceServer.stop
([timeout])Stop a running server (from another thread). DeviceServer.sync_with_ioloop
([timeout])Block for ioloop to complete a loop if called from another thread. DeviceServer.version
()Return a version string of the form type-major.minor. DeviceServer.wait_running
([timeout])Wait until the server is running -
add_sensor
(sensor)¶ Add a sensor to the device.
Usually called inside .setup_sensors() but may be called from elsewhere.
Parameters: sensor : Sensor object
The sensor object to register with the device server.
-
build_state
()¶ Return build state string of the form name-major.minor[(a|b|rc)n].
-
clear_strategies
(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.
-
create_log_inform
(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.
-
get_sensor
(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.
-
get_sensors
()¶ Fetch a list of all sensors.
Returns: sensors : list of Sensor objects
The list of sensors registered with the device server.
-
handle_inform
(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.
-
handle_message
(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.
-
handle_reply
(connection, msg)¶ Dispatch a reply message to the appropriate method.
Parameters: connection : ClientConnection object
The client connection the message was from.
msg : Message object
The reply message to process.
-
handle_request
(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 : Future or None
Returns Future for async request handlers that will resolve when done, or None for sync request handlers once they have completed.
-
has_sensor
(sensor_name)¶ Whether the sensor with specified name is known.
-
inform
(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
reply_inform()
so that the message identifier from the original request can be attached to the inform.Parameters: connection : ClientConnection object
The client to send the message to.
msg : Message object
The inform message to send.
-
join
(timeout=None)¶ Rejoin the server thread.
Parameters: timeout : float or None, optional
Time in seconds to wait for the thread to finish.
-
mass_inform
(msg)¶ Send an inform message to all clients.
Parameters: msg : Message object
The inform message to send.
-
on_client_connect
(*args, **kwargs)¶ 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. :
-
on_client_disconnect
(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. :
-
on_message
(client_conn, msg)¶ Dummy implementation of on_message required by KATCPServer.
Will be replaced by a handler with the appropriate concurrency semantics when set_concurrency_options is called (defaults are set in __init__()).
-
remove_sensor
(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.
-
reply
(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 replied to. The reply message’s id is overridden with the id from orig_req before the reply is sent.
-
reply_inform
(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 message being replied to. The inform message’s id is overridden with the id from orig_req before the inform is sent.
-
request_client_list
(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 (because, for example, the client disconnected suddenly) then a unique string representing the client is sent instead.
Returns: success : {‘ok’, ‘fail’}
Whether sending the client list succeeded.
informs : int
Number of #client-list inform messages sent.
Examples
?client-list #client-list 127.0.0.1:53600 !client-list ok 1
-
request_halt
(req, msg)¶ Halt the device server.
Returns: success : {‘ok’, ‘fail’}
Whether scheduling the halt succeeded.
Examples
?halt !halt ok
-
request_help
(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
-
request_log_level
(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
-
request_restart
(req, msg)¶ Restart the device server.
Returns: success : {‘ok’, ‘fail’}
Whether scheduling the restart succeeded.
Examples
?restart !restart ok
-
request_sensor_list
(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 regular expression and all sensors whose names contain the regular expression are returned.
Informs: name : str
The name of the sensor being described.
description : str
Description of the named sensor.
units : str
Units for the value of the named sensor.
type : str
Type of the named sensor.
params : list of str, optional
Additional sensor parameters (type dependent). For integer and float sensors the additional parameters are the minimum and maximum sensor value. For discrete sensors the additional parameters are the allowed values. For all other types no additional parameters are sent.
Returns: success : {‘ok’, ‘fail’}
Whether sending the sensor list succeeded.
informs : int
Number of #sensor-list inform messages sent.
Examples
?sensor-list #sensor-list psu.voltage PSU\_voltage. V float 0.0 5.0 #sensor-list cpu.status CPU\_status. \@ discrete on off error ... !sensor-list ok 5 ?sensor-list cpu.power.on #sensor-list cpu.power.on Whether\_CPU\_hase\_power. \@ boolean !sensor-list ok 1 ?sensor-list /voltage/ #sensor-list psu.voltage PSU\_voltage. V float 0.0 5.0 #sensor-list cpu.voltage CPU\_voltage. V float 0.0 3.0 !sensor-list ok 2
-
request_sensor_sampling
(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’, ‘differential’, ‘period’, ‘event-rate’}, optional
Type of strategy to use to report the sensor value. The differential strategy type may only be used with integer or float sensors. If this parameter is supplied, it sets the new strategy.
params : list of str, optional
Additional strategy parameters (dependent on the strategy type). For the differential strategy, the parameter is an integer or float giving the amount by which the sensor value may change before an updated value is sent. For the period strategy, the parameter is the sampling period in float seconds. The event strategy has no parameters. Note that this has changed from KATCPv4. For the event-rate strategy, a minimum period between updates and a maximum period between updates (both in float seconds) must be given. If the event occurs more than once within the minimum period, only one update will occur. Whether or not the event occurs, the sensor value will be updated at least once per maximum period. The differential-rate strategy is not supported in this release.
Returns: success : {‘ok’, ‘fail’}
Whether the sensor-sampling request succeeded.
name : str
Name of the sensor queried or configured.
strategy : {‘none’, ‘auto’, ‘event’, ‘differential’, ‘period’}
Name of the new or current sampling strategy for the sensor.
params : list of str
Additional strategy parameters (see description under Parameters).
Examples
?sensor-sampling cpu.power.on !sensor-sampling ok cpu.power.on none ?sensor-sampling cpu.power.on period 500 !sensor-sampling ok cpu.power.on period 500
-
request_sensor_sampling_clear
(req, msg)¶ 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
-
request_sensor_value
(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 is treated as a regular expression and all sensors whose names contain the regular expression are returned.
Informs: timestamp : float
Timestamp of the sensor reading in seconds since the Unix epoch, or milliseconds for katcp versions <= 4.
count : {1}
Number of sensors described in this #sensor-value inform. Will always be one. It exists to keep this inform compatible with #sensor-status.
name : str
Name of the sensor whose value is being reported.
value : object
Value of the named sensor. Type depends on the type of the sensor.
Returns: success : {‘ok’, ‘fail’}
Whether sending the list of values succeeded.
informs : int
Number of #sensor-value inform messages sent.
Examples
?sensor-value #sensor-value 1244631611.415231 1 psu.voltage 4.5 #sensor-value 1244631611.415200 1 cpu.status off ... !sensor-value ok 5 ?sensor-value cpu.power.on #sensor-value 1244631611.415231 1 cpu.power.on 0 !sensor-value ok 1
-
request_version_list
(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 choose. In the absence of other information clients should treat it as an opaque string.
build_state_or_serial_number : str
A unique identifier for a particular instance of a component. This should change whenever the component is replaced or updated.
Returns: success : {‘ok’, ‘fail’}
Whether sending the version list succeeded.
informs : int
Number of #version-list inform messages sent.
Examples
?version-list #version-list katcp-protocol 5.0-MI #version-list katcp-library katcp-python-0.4 katcp-python-0.4.1-py2 #version-list katcp-device foodevice-1.0 foodevice-1.0.0rc1 !version-list ok 3
-
request_watchdog
(req, msg)¶ Check that the server is still alive.
Returns: success : {‘ok’} Examples
?watchdog !watchdog ok
-
running
()¶ Whether the server is running.
-
setDaemon
(daemonic)¶ Set daemonic state of the managed ioloop thread to True / False
Calling this method for a non-managed ioloop has no effect. Must be called before start(), or it will also have no effect
-
set_concurrency_options
(thread_safe=True, handler_thread=True)¶ Set concurrency options for this device server. Must be called before
start()
.Parameters: thread_safe : bool
If True, make the server public methods thread safe. Incurs performance overhead.
handler_thread : bool
Can only be set if thread_safe is True. Handle all requests (even from different clients) in a separate, single, request-handling thread. Blocking request handlers will prevent the server from handling new requests from any client, but sensor strategies should still function. This more or less mimics the behaviour of a server in library versions before 0.6.0.
-
set_ioloop
(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.
-
set_restart_queue
(restart_queue)¶ Set the restart queue.
When the device server should be restarted, it will be added to the queue.
Parameters: restart_queue : Queue.Queue object
The queue to add the device server to when it should be restarted.
-
setup_sensors
()¶ Populate the dictionary of sensors.
Unimplemented by default – subclasses should add their sensors here or pass if there are no sensors.
Examples
>>> class MyDevice(DeviceServer): ... def setup_sensors(self): ... self.add_sensor(Sensor(...)) ... self.add_sensor(Sensor(...)) ...
-
start
(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.
-
stop
(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
-
sync_with_ioloop
(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.
-
version
()¶ Return a version string of the form type-major.minor.
-
wait_running
(timeout=None)¶ Wait until the server is running
DeviceServerBase¶
-
class
katcp.
DeviceServerBase
(host, port, tb_limit=20, logger=<logging.Logger object>)¶ Base class for device servers.
Subclasses should add .request_* methods for dealing with request messages. These methods each take the client request connection and msg objects as arguments and should return the reply message or raise an exception as a result.
Subclasses can also add .inform_* and reply_* methods to handle those types of messages.
Should a subclass need to generate inform messages it should do so using either the .inform() or .mass_inform() methods.
Finally, this class should probably not be subclassed directly but rather via subclassing DeviceServer itself which implements common .request_* methods.
Parameters: host : str
Host to listen on.
port : int
Port to listen on.
tb_limit : int, optional
Maximum number of stack frames to send in error tracebacks.
logger : logging.Logger object, optional
Logger to log messages to.
Methods
DeviceServerBase.create_exception_reply_and_log
(...)DeviceServerBase.create_log_inform
(...[, ...])Create a katcp logging inform message. DeviceServerBase.handle_inform
(connection, msg)Dispatch an inform message to the appropriate method. DeviceServerBase.handle_message
(client_conn, msg)Handle messages of all types from clients. DeviceServerBase.handle_reply
(connection, msg)Dispatch a reply message to the appropriate method. DeviceServerBase.handle_request
(connection, msg)Dispatch a request message to the appropriate method. DeviceServerBase.inform
(connection, msg)Send an inform message to a particular client. DeviceServerBase.join
([timeout])Rejoin the server thread. DeviceServerBase.mass_inform
(msg)Send an inform message to all clients. DeviceServerBase.on_client_connect
(*args, ...)Called after client connection is established. DeviceServerBase.on_client_disconnect
(*args, ...)Called before a client connection is closed. DeviceServerBase.on_message
(client_conn, msg)Dummy implementation of on_message required by KATCPServer. DeviceServerBase.reply
(connection, reply, ...)Send an asynchronous reply to an earlier request. DeviceServerBase.reply_inform
(connection, ...)Send an inform as part of the reply to an earlier request. DeviceServerBase.running
()Whether the server is running. DeviceServerBase.setDaemon
(daemonic)Set daemonic state of the managed ioloop thread to True / False DeviceServerBase.set_concurrency_options
([...])Set concurrency options for this device server. DeviceServerBase.set_ioloop
([ioloop])Set the tornado IOLoop to use. DeviceServerBase.start
([timeout])Start the server in a new thread. DeviceServerBase.stop
([timeout])Stop a running server (from another thread). DeviceServerBase.sync_with_ioloop
([timeout])Block for ioloop to complete a loop if called from another thread. DeviceServerBase.wait_running
([timeout])Wait until the server is running -
create_log_inform
(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.
-
handle_inform
(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.
-
handle_message
(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.
-
handle_reply
(connection, msg)¶ Dispatch a reply message to the appropriate method.
Parameters: connection : ClientConnection object
The client connection the message was from.
msg : Message object
The reply message to process.
-
handle_request
(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 : Future or None
Returns Future for async request handlers that will resolve when done, or None for sync request handlers once they have completed.
-
inform
(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
reply_inform()
so that the message identifier from the original request can be attached to the inform.Parameters: connection : ClientConnection object
The client to send the message to.
msg : Message object
The inform message to send.
-
join
(timeout=None)¶ Rejoin the server thread.
Parameters: timeout : float or None, optional
Time in seconds to wait for the thread to finish.
-
mass_inform
(msg)¶ Send an inform message to all clients.
Parameters: msg : Message object
The inform message to send.
-
on_client_connect
(*args, **kwargs)¶ Called after client connection is established.
Subclasses should override if they wish to send clients message or perform house-keeping at this point.
Parameters: conn : ClientConnection object
The client connection that has been successfully established.
Returns: Future that resolves when the device is ready to accept messages. :
-
on_client_disconnect
(*args, **kwargs)¶ Called before a client connection is closed.
Subclasses should override if they wish to send clients message or perform house-keeping at this point. The server cannot guarantee this will be called (for example, the client might drop the connection). The message parameter contains the reason for the disconnection.
Parameters: conn : ClientConnection object
Client connection being disconnected.
msg : str
Reason client is being disconnected.
connection_valid : boolean
True if connection is still open for sending, False otherwise.
Returns: Future that resolves when the client connection can be closed. :
-
on_message
(client_conn, msg)¶ Dummy implementation of on_message required by KATCPServer.
Will be replaced by a handler with the appropriate concurrency semantics when set_concurrency_options is called (defaults are set in __init__()).
-
reply
(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 replied to. The reply message’s id is overridden with the id from orig_req before the reply is sent.
-
reply_inform
(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 message being replied to. The inform message’s id is overridden with the id from orig_req before the inform is sent.
-
running
()¶ Whether the server is running.
-
setDaemon
(daemonic)¶ Set daemonic state of the managed ioloop thread to True / False
Calling this method for a non-managed ioloop has no effect. Must be called before start(), or it will also have no effect
-
set_concurrency_options
(thread_safe=True, handler_thread=True)¶ Set concurrency options for this device server. Must be called before
start()
.Parameters: thread_safe : bool
If True, make the server public methods thread safe. Incurs performance overhead.
handler_thread : bool
Can only be set if thread_safe is True. Handle all requests (even from different clients) in a separate, single, request-handling thread. Blocking request handlers will prevent the server from handling new requests from any client, but sensor strategies should still function. This more or less mimics the behaviour of a server in library versions before 0.6.0.
-
set_ioloop
(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.
-
start
(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.
-
stop
(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
-
sync_with_ioloop
(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.
-
wait_running
(timeout=None)¶ Wait until the server is running
-
DeviceLogger¶
-
class
katcp.
DeviceLogger
(device_server, root_logger='root', python_logger=None)¶ Object for logging messages from a DeviceServer.
Log messages are logged at a particular level and under a particular name. Names use dotted notation to form a virtual hierarchy of loggers with the device.
Parameters: device_server : DeviceServerBase object
The device server this logger should use for sending out logs.
root_logger : str
The name of the root logger.
Methods
DeviceLogger.debug
(msg, *args, **kwargs)Log a debug message. DeviceLogger.error
(msg, *args, **kwargs)Log an error message. DeviceLogger.fatal
(msg, *args, **kwargs)Log a fatal error message. DeviceLogger.info
(msg, *args, **kwargs)Log an info message. DeviceLogger.level_from_name
(level_name)Return the level constant for a given name. DeviceLogger.level_name
([level])Return the name of the given level value. DeviceLogger.log
(level, msg, *args, **kwargs)Log a message and inform all clients. DeviceLogger.log_to_python
(logger, msg)Log a KATCP logging message to a Python logger. DeviceLogger.set_log_level
(level)Set the logging level. DeviceLogger.set_log_level_by_name
(level_name)Set the logging level using a level name. DeviceLogger.trace
(msg, *args, **kwargs)Log a trace message. DeviceLogger.warn
(msg, *args, **kwargs)Log an warning message. -
debug
(msg, *args, **kwargs)¶ Log a debug message.
-
error
(msg, *args, **kwargs)¶ Log an error message.
-
fatal
(msg, *args, **kwargs)¶ Log a fatal error message.
-
info
(msg, *args, **kwargs)¶ Log an info message.
-
level_from_name
(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 level constant
The logging level constant associated with the name.
-
level_name
(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
The name of the logging level.
-
log
(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 message text is created using: msg % args.
kwargs : additional keyword parameters
Allowed keywords are ‘name’ and ‘timestamp’. The name is the name of the logger to log the message to. If not given the name defaults to the root logger. The timestamp is a float in seconds. If not given the timestamp defaults to the current time.
-
classmethod
log_to_python
(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.
-
set_log_level
(level)¶ Set the logging level.
Parameters: level : logging level constant
The value to set the logging level to.
-
set_log_level_by_name
(level_name)¶ Set the logging level using a level name.
Parameters: level_name : str
The name of the logging level.
-
trace
(msg, *args, **kwargs)¶ Log a trace message.
-
warn
(msg, *args, **kwargs)¶ Log an warning message.
-
Sensor¶
-
class
katcp.
Sensor
(sensor_type, name, description=None, units='', params=None, default=None, initial_status=None)¶ Instantiate a new sensor object.
Subclasses will usually pass in a fixed sensor_type which should be one of the sensor type constants. The list params if set will have its values formatter by the type formatter for the given sensor type.
Note
The LRU sensor type was deprecated in katcp 0.4.
Note
The ADDRESS sensor type was added in katcp 0.4.
Parameters: sensor_type : Sensor type constant
The type of sensor.
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 applicable units.
params : list
Additional parameters, dependent on the type of sensor:
- For
INTEGER
andFLOAT
the list should give the minimum and maximum that define the range of the sensor value. - For
DISCRETE
the list should contain all possible values the sensor may take. - For all other types, params should be omitted.
default : object
An initial value for the sensor. By default this is determined by the sensor type.
initial_status : int enum or None
An initial status for the sensor. If None, defaults to Sensor.UNKNOWN. initial_status must be one of the keys in Sensor.STATUSES
Methods
Sensor.address
(name[, description, unit, ...])Instantiate a new IP address sensor object. Sensor.attach
(observer)Attach an observer to this sensor. Sensor.boolean
(name[, description, unit, ...])Instantiate a new boolean sensor object. Sensor.detach
(observer)Detach an observer from this sensor. Sensor.discrete
(name[, description, unit, ...])Instantiate a new discrete sensor object. Sensor.float
(name[, description, unit, ...])Instantiate a new float sensor object. Sensor.format_reading
(reading[, major])Format sensor reading as (timestamp, status, value) tuple of strings. Sensor.integer
(name[, description, unit, ...])Instantiate a new integer sensor object. Sensor.lru
(name[, description, unit, ...])Instantiate a new lru sensor object. Sensor.notify
(reading)Notify all observers of changes to this sensor. Sensor.parse_params
(sensor_type, ...[, major])Parse KATCP formatted parameters into Python values. Sensor.parse_type
(type_string)Parse KATCP formatted type code into Sensor type constant. Sensor.parse_value
(s_value[, katcp_major])Parse a value from a string. Sensor.read
()Read the sensor and return a (timestamp, status, value) tuple. Sensor.read_formatted
([major])Read the sensor and return a (timestamp, status, value) tuple. Sensor.set
(timestamp, status, value)Set the current value of the sensor. Sensor.set_formatted
(raw_timestamp, ...[, major])Set the current value of the sensor. Sensor.set_value
(value[, status, timestamp, ...])Check and then set the value of the sensor. Sensor.status
()Read the current sensor status. Sensor.string
(name[, description, unit, ...])Instantiate a new string sensor object. Sensor.timestamp
(name[, description, unit, ...])Instantiate a new timestamp sensor object. Sensor.value
()Read the current sensor value. -
classmethod
address
(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 are no applicable units.
default : (string, int)
An initial value for the sensor. Tuple contaning (host, port). default is (“0.0.0.0”, None)
initial_status : int enum or None
An initial status for the sensor. If None, defaults to Sensor.UNKNOWN. initial_status must be one of the keys in Sensor.STATUSES
-
attach
(observer)¶ Attach an observer to this sensor.
The observer must support a call to observer.update(sensor, reading), where sensor is the sensor object and reading is a (timestamp, status, value) tuple for this update (matching the return value of the
read()
method).Parameters: observer : object
Object with an .update(sensor, reading) method that will be called when the sensor value is set
-
classmethod
boolean
(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 no applicable units.
default : bool
An initial value for the sensor. Defaults to False.
initial_status : int enum or None
An initial status for the sensor. If None, defaults to Sensor.UNKNOWN. initial_status must be one of the keys in Sensor.STATUSES
-
detach
(observer)¶ Detach an observer from this sensor.
Parameters: observer : object
The observer to remove from the set of observers notified when the sensor value is set.
-
classmethod
discrete
(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 no applicable units.
params : [str]
Sequence of all allowable discrete sensor states
default : str
An initial value for the sensor. Defaults to the first item of params
initial_status : int enum or None
An initial status for the sensor. If None, defaults to Sensor.UNKNOWN. initial_status must be one of the keys in Sensor.STATUSES
-
classmethod
float
(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 applicable units.
params : list
[min, max] – miniumum and maximum values of the sensor
default : float
An initial value for the sensor. Defaults to 0.0.
initial_status : int enum or None
An initial status for the sensor. If None, defaults to Sensor.UNKNOWN. initial_status must be one of the keys in Sensor.STATUSES
-
format_reading
(reading, major=5)¶ 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 :
Reading
objectSensor reading as returned by
read()
major : int
Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP version.
Returns: timestamp : str
KATCP formatted timestamp string
status : str
KATCP formatted sensor status string
value : str
KATCP formatted sensor value
-
classmethod
integer
(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 no applicable units.
params : list
[min, max] – miniumum and maximum values of the sensor
default : int
An initial value for the sensor. Defaults to 0.
initial_status : int enum or None
An initial status for the sensor. If None, defaults to Sensor.UNKNOWN. initial_status must be one of the keys in Sensor.STATUSES
-
classmethod
lru
(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 applicable units.
default : enum, Sensor.LRU_*
An initial value for the sensor. Defaults to self.LRU_NOMINAL
initial_status : int enum or None
An initial status for the sensor. If None, defaults to Sensor.UNKNOWN. initial_status must be one of the keys in Sensor.STATUSES
-
notify
(reading)¶ Notify all observers of changes to this sensor.
-
classmethod
parse_params
(sensor_type, formatted_params, major=5)¶ 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
Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP version.
Returns: params : list of objects
The parsed parameters.
-
classmethod
parse_type
(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.
-
parse_value
(s_value, katcp_major=5)¶ Parse a value from a string.
Parameters: s_value : str
A string value to attempt to convert to a value for the sensor.
Returns: value : object
A value of a type appropriate to the sensor.
-
read
()¶ Read the sensor and return a (timestamp, status, value) tuple.
Returns: reading :
Reading
objectSensor reading as a (timestamp, status, value) tuple.
-
read_formatted
(major=5)¶ Read the sensor and return a (timestamp, status, value) tuple.
All values are strings formatted as specified in the Sensor Type Formats in the katcp specification.
Parameters: major : int
Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP version.
Returns: timestamp : str
KATCP formatted timestamp string
status : str
KATCP formatted sensor status string
value : str
KATCP formatted sensor value
-
set
(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
The value of the sensor (the type should be appropriate to the sensor’s type).
-
set_formatted
(raw_timestamp, raw_status, raw_value, major=5)¶ 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
KATCP major version to use for interpreting the raw values
-
set_value
(value, status=1, timestamp=None, major=5)¶ 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
The time at which the sensor value was determined. Uses current time if None.
major : int
Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP version.
-
status
()¶ Read the current sensor status.
Returns: status : enum (int)
The status of the sensor, one of the keys in Sensor.STATUSES
-
classmethod
string
(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 no applicable units.
default : string
An initial value for the sensor. Defaults to the empty string.
initial_status : int enum or None
An initial status for the sensor. If None, defaults to Sensor.UNKNOWN. initial_status must be one of the keys in Sensor.STATUSES
-
classmethod
timestamp
(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 empty string.
default : string
An initial value for the sensor in seconds since the Unix Epoch. Defaults to 0.
initial_status : int enum or None
An initial status for the sensor. If None, defaults to Sensor.UNKNOWN. initial_status must be one of the keys in Sensor.STATUSES
-
value
()¶ Read the current sensor value.
Returns: value : object
The value of the sensor (the type will be appropriate to the sensor’s type).
- For
Exceptions¶
-
class
katcp.
FailReply
¶ Raised by request handlers to indicate a failure.
A custom exception which, when thrown in a request handler, causes DeviceServerBase to send a fail reply with the specified fail message, bypassing the generic exception handling, which would send a fail reply with a full traceback.
Examples
>>> class MyDevice(DeviceServer): ... def request_myreq(self, req, msg): ... raise FailReply("This request always fails.") ...
-
class
katcp.
AsyncReply
¶ Raised by a request handlers to indicate it will reply later.
A custom exception which, when thrown in a request handler, indicates to DeviceServerBase that no reply has been returned by the handler but that the handler has arranged for a reply message to be sent at a later time.
Examples
>>> class MyDevice(DeviceServer): ... def request_myreq(self, req, msg): ... self.callback_client.request( ... Message.request("otherreq"), ... reply_cb=self._send_reply, ... ) ... raise AsyncReply() ...
-
class
katcp.
KatcpDeviceError
¶ Raised by KATCP servers when errors occur.
Changed in version 0.1: Deprecated in 0.1. Servers should not raise errors if communication with a client fails – errors are simply logged instead.
High Level Clients¶
KATCPClientResource¶
-
class
katcp.
KATCPClientResource
(resource_spec, parent=None, logger=<logging.Logger object>)¶ Class managing a client connection to a single KATCP resource
Inspects the KATCP interface of the resources, exposing sensors and requests as per the
katcp.resource.KATCPResource
API. Can also operate without exposinMethods
KATCPClientResource.inspecting_client_factory
(...)Return an instance of ReplyWrappedInspectingClientAsync
or similarKATCPClientResource.is_active
()KATCPClientResource.is_connected
()Indication of the connection state KATCPClientResource.list_sensors
([filter, ...])List sensors available on this resource matching certain criteria. KATCPClientResource.set_active
(active)KATCPClientResource.set_ioloop
([ioloop])Set the tornado ioloop to use KATCPClientResource.set_sampling_strategies
(...)Set a strategy for all sensors matching the filter, including unseen sensors The strategy should persist across sensor disconnect/reconnect. KATCPClientResource.set_sampling_strategy
(...)Set a strategy for a sensor even if it is not yet known. KATCPClientResource.set_sensor_listener
(...)Set a sensor listener for a sensor even if it is not yet known The listener registration should persist across sensor disconnect/reconnect. KATCPClientResource.start
()Start the client and connect KATCPClientResource.stop
()KATCPClientResource.until_not_synced
([timeout])Convenience method to wait (with Future) until client is not synced KATCPClientResource.until_state
(state[, timeout])Future that resolves when a certain client state is attained KATCPClientResource.until_synced
([timeout])Convenience method to wait (with Future) until client is synced KATCPClientResource.wait
(*args, **kwargs)Wait for a sensor in this resource to satisfy a condition. KATCPClientResource.wait_connected
([timeout])Future that resolves when the state is not ‘disconnected’. -
MAX_LOOP_LATENCY
= 0.03¶ When doing potentially tight loops in coroutines yield tornado.gen.moment after this much time. This is a suggestion for methods to use.
-
inspecting_client_factory
(host, port, ioloop_set_to)¶ Return an instance of
ReplyWrappedInspectingClientAsync
or similarProvided to ease testing. Dynamically overriding this method after instantiation but before start() is called allows for deep brain surgery. See
katcp.fake_clients.fake_inspecting_client_factory
-
is_connected
()¶ Indication of the connection state
Returns True if state is not “disconnected”, i.e “syncing” or “synced”
-
list_sensors
(filter='', strategy=False, status='', use_python_identifiers=True, tuple=False, refresh=False)¶ List sensors available on this resource matching certain criteria.
Parameters: filter : string, optional
Filter each returned sensor’s name against this regexp if specified. To ease the dichotomy between Python identifier names and actual sensor names, the default is to search on Python identifier names rather than KATCP sensor names, unless use_python_identifiers below is set to False. Note that the sensors of subordinate KATCPResource instances may have inconsistent names and Python identifiers, better to always search on Python identifiers in this case.
strategy : {False, True}, optional
Only list sensors with a set strategy if True
status : string, optional
Filter each returned sensor’s status against this regexp if given
use_python_identifiers : {True, False}, optional
Match on python identfiers even the the KATCP name is available.
tuple : {True, False}, optional, Default: False
Return backwards compatible tuple instead of SensorResultTuples
refresh : {True, False}, optional, Default: False
If set the sensor values will be refreshed with get_value before returning the results.
Returns: sensors : list of SensorResultTuples, or list of tuples
List of matching sensors presented as named tuples. The object field is the
KATCPSensor
object associated with the sensor. Note that the name of the object may not match name if it originates from a subordinate device.
-
set_ioloop
(ioloop=None)¶ Set the tornado ioloop to use
Defaults to tornado.ioloop.IOLoop.current() if set_ioloop() is not called or if ioloop=None. Must be called before start()
-
set_sampling_strategies
(*args, **kwargs)¶ Set a strategy for all sensors matching the filter, including unseen sensors The strategy should persist across sensor disconnect/reconnect.
- filter : str
- Filter for sensor names
- 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: done : tornado Future
Resolves when done
-
set_sampling_strategy
(*args, **kwargs)¶ Set a strategy for a sensor even if it is not yet known. The strategy should persist across sensor disconnect/reconnect.
- sensor_name : str
- Name of the 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: done : tornado Future
Resolves when done
-
set_sensor_listener
(*args, **kwargs)¶ Set a sensor listener for a sensor even if it is not yet known The listener registration should persist across sensor disconnect/reconnect.
- sensor_name : str
- Name of the sensor
- listener : callable
- Listening callable that will be registered on the named sensor when it becomes
available. Callable as for
KATCPSensor.register_listener()
-
start
()¶ Start the client and connect
-
until_not_synced
(timeout=None)¶ Convenience method to wait (with Future) until client is not synced
-
until_state
(state, timeout=None)¶ Future that resolves when a certain client state is attained
Parameters: state : str
Desired state, one of (“disconnected”, “syncing”, “synced”)
timeout: float :
Timeout for operation in seconds.
-
until_synced
(timeout=None)¶ Convenience method to wait (with Future) until client is synced
-
wait
(*args, **kwargs)¶ 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_connected
(timeout=None)¶ Future that resolves when the state is not ‘disconnected’.
-
KATCPClientResourceContainer¶
-
class
katcp.
KATCPClientResourceContainer
(resources_spec, logger=<logging.Logger object>)¶ Class for containing multiple
KATCPClientResource
instancesProvides aggregate sensor and req attributes containing the union of all the sensors in requests in the contained resources. Names are prefixed with <resname>_, where <resname> is the name of the resource to which the sensor / request belongs except for aggregate sensors that starts with ‘agg_‘.
Methods
KATCPClientResourceContainer.add_child_resource_client
(...)Add a resource client to the container and start the resource connection KATCPClientResourceContainer.add_group
(...)Add a new ClientGroup
to container groups member.KATCPClientResourceContainer.client_resource_factory
(...)Return an instance of KATCPClientResource
or similarKATCPClientResourceContainer.is_active
()KATCPClientResourceContainer.is_connected
()Indication of the connection state of all children KATCPClientResourceContainer.list_sensors
([...])List sensors available on this resource matching certain criteria. KATCPClientResourceContainer.set_active
(active)KATCPClientResourceContainer.set_ioloop
([ioloop])Set the tornado ioloop to use KATCPClientResourceContainer.set_sampling_strategies
(...)Set sampling strategies for filtered sensors - these sensors have to exsist KATCPClientResourceContainer.set_sampling_strategy
(...)Set sampling strategies for the specific sensor - this sensor has to exist KATCPClientResourceContainer.set_sensor_listener
(...)Set listener for the specific sensor - this sensor has to exsist KATCPClientResourceContainer.start
()Start and connect all the subordinate clients KATCPClientResourceContainer.stop
()Stop all child resources KATCPClientResourceContainer.until_all_children_in_state
(...)Return a tornado Future; resolves when all clients are in specified state KATCPClientResourceContainer.until_any_child_in_state
(state)Return a tornado Future; resolves when any client is in specified state KATCPClientResourceContainer.until_not_synced
(...)Return a tornado Future; resolves when any subordinate client is not synced KATCPClientResourceContainer.until_synced
(...)Return a tornado Future; resolves when all subordinate clients are synced KATCPClientResourceContainer.wait
(...[, timeout])Wait for a sensor in this resource to satisfy a condition. -
add_child_resource_client
(res_name, res_spec)¶ Add a resource client to the container and start the resource connection
-
add_group
(group_name, group_client_names)¶ Add a new
ClientGroup
to container groups member.Add the group named group_name with sequence of client names to the container groups member. From there it will be wrapped appropriately in the higher-level thread-safe container.
-
client_resource_factory
(res_spec, parent, logger)¶ Return an instance of
KATCPClientResource
or similarProvided to ease testing. Overriding this method allows deep brain surgery. See
katcp.fake_clients.fake_KATCP_client_resource_factory()
-
is_connected
()¶ Indication of the connection state of all children
-
list_sensors
(filter='', strategy=False, status='', use_python_identifiers=True, tuple=False, refresh=False)¶ List sensors available on this resource matching certain criteria.
Parameters: filter : string, optional
Filter each returned sensor’s name against this regexp if specified. To ease the dichotomy between Python identifier names and actual sensor names, the default is to search on Python identifier names rather than KATCP sensor names, unless use_python_identifiers below is set to False. Note that the sensors of subordinate KATCPResource instances may have inconsistent names and Python identifiers, better to always search on Python identifiers in this case.
strategy : {False, True}, optional
Only list sensors with a set strategy if True
status : string, optional
Filter each returned sensor’s status against this regexp if given
use_python_identifiers : {True, False}, optional
Match on python identfiers even the the KATCP name is available.
tuple : {True, False}, optional, Default: False
Return backwards compatible tuple instead of SensorResultTuples
refresh : {True, False}, optional, Default: False
If set the sensor values will be refreshed with get_value before returning the results.
Returns: sensors : list of SensorResultTuples, or list of tuples
List of matching sensors presented as named tuples. The object field is the
KATCPSensor
object associated with the sensor. Note that the name of the object may not match name if it originates from a subordinate device.
-
set_ioloop
(ioloop=None)¶ Set the tornado ioloop to use
Defaults to tornado.ioloop.IOLoop.current() if set_ioloop() is not called or if ioloop=None. Must be called before start()
-
set_sampling_strategies
(*args, **kwargs)¶ Set sampling strategies for filtered sensors - these sensors have to exsist
-
set_sampling_strategy
(*args, **kwargs)¶ Set sampling strategies for the specific sensor - this sensor has to exist
-
set_sensor_listener
(*args, **kwargs)¶ Set listener for the specific sensor - this sensor has to exsist
-
start
()¶ Start and connect all the subordinate clients
-
stop
()¶ Stop all child resources
-
until_all_children_in_state
(*args, **kwargs)¶ Return a tornado Future; resolves when all clients are in specified state
-
until_any_child_in_state
(state, timeout=None)¶ Return a tornado Future; resolves when any client is in specified state
-
until_not_synced
(*args, **kwargs)¶ Return a tornado Future; resolves when any subordinate client is not synced
-
until_synced
(*args, **kwargs)¶ Return a tornado Future; resolves when all subordinate clients are synced
-
wait
(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
-
Message Parsing¶
Message¶
-
class
katcp.
Message
(mtype, name, arguments=None, mid=None)¶ Represents a KAT device control language message.
Parameters: mtype : Message type constant
The message type (request, reply or inform).
name : str
The message name.
arguments : list of strings
The message arguments.
mid : str, digits only
The message identifier. Replies and informs that are part of the reply to a request should have the same id as the request did.
Methods
Message.copy
()Return a shallow copy of the message object and its arguments. Message.format_argument
(arg)Format a Message argument to a string Message.inform
(name, *args, **kwargs)Helper method for creating inform messages. Message.reply
(name, *args, **kwargs)Helper method for creating reply messages. Message.reply_inform
(req_msg, *args)Helper method for creating inform messages in reply to a request. Message.reply_ok
()Return True if this is a reply and its first argument is ‘ok’. Message.reply_to_request
(req_msg, *args)Helper method for creating reply messages to a specific request. Message.request
(name, *args, **kwargs)Helper method for creating request messages. -
copy
()¶ Return a shallow copy of the message object and its arguments.
Returns: msg : Message
A copy of the message object.
-
format_argument
(arg)¶ Format a Message argument to a string
-
classmethod
inform
(name, *args, **kwargs)¶ Helper method for creating inform messages.
Parameters: name : str
The name of the message.
args : list of strings
The message arguments.
-
classmethod
reply
(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 (default) for no Message ID
-
classmethod
reply_inform
(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 strings
The message arguments except name
-
reply_ok
()¶ Return True if this is a reply and its first argument is ‘ok’.
-
classmethod
reply_to_request
(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 strings
The message arguments.
-
classmethod
request
(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 None (default) for no Message ID
-
MessageParser¶
-
class
katcp.
MessageParser
¶ Parses lines into Message objects.
Methods
MessageParser.parse
(line)Parse a line, return a Message. -
parse
(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.
-
Other¶
DeviceMetaclass¶
-
class
katcp.
DeviceMetaclass
(mcs, name, bases, dct)¶ Metaclass for DeviceServer and DeviceClient classes.
Collects up methods named request_* and adds them to a dictionary of supported methods on the class. All request_* methods must have a doc string so that help can be generated. The same is done for inform_* and reply_* methods.
Methods
DeviceMetaclass.mro
(() -> list)return a type’s method resolution order