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 at 0x7f7cc3f60c50>, auto_reconnect=True)

Implement blocking 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

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.

timeout : float in seconds

Default number of seconds to wait before a blocking send_request times out. Can be overriden in individual calls to blocking_request.

Examples

>>> c = BlockingClient('localhost', 10000)
>>> c.start()
>>> reply, informs = c.blocking_request(katcp.Message.request('myreq'))
>>> print reply
>>> print [str(msg) for msg in informs]
>>> c.stop()
>>> c.join()

Methods

BlockingClient.blocking_request(msg[, ...]) Send a request messsage.
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, timeout]) Send a request message, automatically assign a message ID if requested
BlockingClient.run() Process reply and inform messages from the server.
BlockingClient.running() Whether the client is running.
BlockingClient.send_message(msg[, timeout]) Send any kind of message.
BlockingClient.send_request(msg[, timeout]) Send a request messsage.
BlockingClient.start([timeout, daemon, ...]) Start the client in a new thread.
BlockingClient.stop([timeout]) Stop a running client (from another thread).
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.wait_connected([timeout]) Wait until the client is connected.
BlockingClient.wait_protocol([timeout]) Wait until katcp protocol information has been received from the client.
blocking_request(msg, timeout=None, keepalive=False, use_mid=None)

Send a request messsage.

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 BlockingClient.

keepalive : boolean, optional

Whether the arrival of an inform should cause the timeout to be reset.

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.

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 handle.

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 handle.

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.

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, timeout=None)

Send a request message, automatically assign a message ID if requested

Parameters :

msg : katcp.Message request message

use_mid : bool or None, default=None

timeout : float or None, default=None

Set timeout for sending request message, or None for no timeout

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 :

run()

Process reply and inform messages from the server.

running()

Whether the client is running.

Returns :

running : bool

Whether the client is running.

send_message(msg, timeout=None)

Send any kind of message.

Parameters :

msg : Message object

The message to send.

timeout : float or None, default=None

Set timeout for sending request message, or None for no timeout.

send_request(msg, timeout=None)

Send a request messsage.

Parameters :

msg : Message object

The request Message to send.

timeout : float or None, default=None

Set timeout for sending request message, or None for no timeout

start(timeout=None, daemon=None, excepthook=None)

Start the client in a new thread.

Parameters :

timeout : float in seconds

Seconds to wait for client thread to start.

daemon : boolean

If not None, the thread’s setDaemon method is called with this parameter before the thread is started.

excepthook : function

Function to call if the client throws an exception. Signature is as for sys.excepthook.

stop(timeout=1.0)

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.

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.

wait_protocol(timeout=None)

Wait until katcp protocol information has been received from the client.

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. :

CallbackClient

class katcp.CallbackClient(host, port, tb_limit=20, timeout=5.0, logger=<logging.Logger object at 0x7f7cc3f60c50>, auto_reconnect=True)

Implement 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. Default is 20.

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. Default is True.

timeout : float in seconds, optional

Default number of seconds to wait before a callback callback_request times out. Can be overriden in individual calls to callback_request. Default is 5s.

Examples

>>> def reply_cb(msg):
...     print "Reply:", msg
...
>>> def inform_cb(msg):
...     print "Inform:", msg
...
>>> c = CallbackClient('localhost', 10000)
>>> c.start()
>>> 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

CallbackClient.blocking_request(msg[, ...]) Send a request messsage.
CallbackClient.callback_request(msg[, ...]) Send a request messsage.
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])
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, timeout]) Send a request message, automatically assign a message ID if requested
CallbackClient.run() Process reply and inform messages from the server.
CallbackClient.running() Whether the client is running.
CallbackClient.send_message(msg[, timeout]) Send any kind of message.
CallbackClient.send_request(msg[, timeout]) Send a request messsage.
CallbackClient.start([timeout, daemon, ...]) 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.wait_connected([timeout]) Wait until the client is connected.
CallbackClient.wait_protocol([timeout]) Wait until katcp protocol information has been received from the client.
blocking_request(msg, timeout=None, use_mid=None)

Send a request messsage.

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 CallbackClient.

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 CallbackClient.

use_mid : boolean, optional

Whether to use message IDs. Default is to use message IDs if the server supports them.

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.

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, timeout=None)

Send a request message, automatically assign a message ID if requested

Parameters :

msg : katcp.Message request message

use_mid : bool or None, default=None

timeout : float or None, default=None

Set timeout for sending request message, or None for no timeout

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 :

run()

Process reply and inform messages from the server.

running()

Whether the client is running.

Returns :

running : bool

Whether the client is running.

send_message(msg, timeout=None)

Send any kind of message.

Parameters :

msg : Message object

The message to send.

timeout : float or None, default=None

Set timeout for sending request message, or None for no timeout.

send_request(msg, timeout=None)

Send a request messsage.

Parameters :

msg : Message object

The request Message to send.

timeout : float or None, default=None

Set timeout for sending request message, or None for no timeout

start(timeout=None, daemon=None, excepthook=None)

Start the client in a new thread.

Parameters :

timeout : float in seconds

Seconds to wait for client thread to start.

daemon : boolean

If not None, the thread’s setDaemon method is called with this parameter before the thread is started.

excepthook : function

Function to call if the client throws an exception. Signature is as for sys.excepthook.

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.

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.

wait_protocol(timeout=None)

Wait until katcp protocol information has been received from the client.

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. :

Base Classes

class katcp.DeviceClient(host, port, tb_limit=20, logger=<logging.Logger object at 0x7f7cc3f60c50>, 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.

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.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, timeout]) Send a request message, automatically assign a message ID if requested
DeviceClient.run() Process reply and inform messages from the server.
DeviceClient.running() Whether the client is running.
DeviceClient.send_message(msg[, timeout]) Send any kind of message.
DeviceClient.send_request(msg[, timeout]) Send a request messsage.
DeviceClient.start([timeout, daemon, excepthook]) 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.wait_connected([timeout]) Wait until the client is connected.
DeviceClient.wait_protocol([timeout]) Wait until katcp protocol information has been received from the client.
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.

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.

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, timeout=None)

Send a request message, automatically assign a message ID if requested

Parameters :

msg : katcp.Message request message

use_mid : bool or None, default=None

timeout : float or None, default=None

Set timeout for sending request message, or None for no timeout

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 :

run()

Process reply and inform messages from the server.

running()

Whether the client is running.

Returns :

running : bool

Whether the client is running.

send_message(msg, timeout=None)

Send any kind of message.

Parameters :

msg : Message object

The message to send.

timeout : float or None, default=None

Set timeout for sending request message, or None for no timeout.

send_request(msg, timeout=None)

Send a request messsage.

Parameters :

msg : Message object

The request Message to send.

timeout : float or None, default=None

Set timeout for sending request message, or None for no timeout

start(timeout=None, daemon=None, excepthook=None)

Start the client in a new thread.

Parameters :

timeout : float in seconds

Seconds to wait for client thread to start.

daemon : boolean

If not None, the thread’s setDaemon method is called with this parameter before the thread is started.

excepthook : function

Function to call if the client throws an exception. Signature is as for sys.excepthook.

stop(timeout=1.0)

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.

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.

wait_protocol(timeout=None)

Wait until katcp protocol information has been received from the client.

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. :

Exceptions

class katcp.KatcpClientError

Raised by KATCP clients when errors occur.

Server

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 a build state string in the form
DeviceServer.clear_strategies(client_conn[, ...]) Clear the sensor strategies of a client connection
DeviceServer.get_sensor(sensor_name) Fetch the sensor with the given name.
DeviceServer.get_sensors() Fetch a list of all sensors
DeviceServer.get_sockets() Return the complete list of current client socket.
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 a sensor_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(client_conn) Inform client of build state and version on connect.
DeviceServer.on_client_disconnect(...) Inform client it is about to be disconnected.
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(*args) 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.run() Override DeviceServerBase.run() to ensure that the reactor thread is
DeviceServer.running() Whether the server is running.
DeviceServer.set_restart_queue(restart_queue) Set the restart queue.
DeviceServer.setup_sensors() Populate the dictionary of sensors.
DeviceServer.start([timeout, daemon, excepthook]) Start the server in a new thread.
DeviceServer.stop([timeout]) Stop a running server (from another thread).
DeviceServer.tcp_inform(sock, msg) Send an inform message to a particular TCP client.
DeviceServer.tcp_reply(sock, reply, orig_req) Send an asynchronous reply to an earlier request for a tcp socket.
DeviceServer.tcp_reply_inform(sock, inform, ...) Send an inform as part of the reply to an earlier request.
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 a build state string in 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 : ClientConnectionTCP instance

The connection that should have its sampling strategies cleared

remove_client : bool, default=False

Remove the client connection from the strategies datastructure. Usefull for clients that disconnect.

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.

get_sockets()

Return the complete list of current client socket.

Returns :

sockets : list of socket.socket objects

A list of connected client sockets.

handle_inform(connection, msg)

Dispatch an inform message to the appropriate method.

Parameters :

connection : ClientConnectionTCP 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 : ClientConnectionTCP 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 : ClientConnectionTCP 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 : ClientConnectionTCP object

The client connection the message was from.

msg : Message object

The request message to process.

has_sensor(sensor_name)

Whether a sensor_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 : ClientConnectionTCP 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 in seconds

Time 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(client_conn)

Inform client of build state and version on connect.

Parameters :

client_conn : ClientConnectionTCP object

The client connection that has been successfully established.

on_client_disconnect(client_conn, msg, connection_valid)

Inform client it is about to be disconnected.

Parameters :

client_conn : ClientConnectionTCP object

The client connection being disconnected.

msg : str

Reason client is being disconnected.

connection_valid : boolean

True if connection is still open for sending, False otherwise.

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 object (or name of sensor) to remove from the device server.

reply(connection, reply, orig_req)

Send an asynchronous reply to an earlier request.

Parameters :

connection : ClientConnectionTCP 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 : ClientConnectionTCP 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 seqeunce 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’}, optional

Type of strategy to use to report the sensor value. The differential strategy type may only be used with integer or float sensors.

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 period to sample at in milliseconds. For the event strategy, an optional minimum time between updates in milliseconds may be given.

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(*args)

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
run()

Override DeviceServerBase.run() to ensure that the reactor thread is running at the same time.

running()

Whether the server is running.

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, daemon=None, excepthook=None)

Start the server in a new thread.

Parameters :

timeout : float in seconds

Time to wait for server thread to start.

daemon : boolean

If not None, the thread’s setDaemon method is called with this parameter before the thread is started.

excepthook : function

Function to call if the client throws an exception. Signature is as for sys.excepthook.

stop(timeout=1.0)

Stop a running server (from another thread).

Parameters :

timeout : float in seconds

Seconds to wait for server to have started.

tcp_inform(sock, msg)

Send an inform message to a particular TCP 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 :

sock : socket.socket object

The client to send the message to.

msg : Message object

The inform message to send.

tcp_reply(sock, reply, orig_req)

Send an asynchronous reply to an earlier request for a tcp socket.

Parameters :

sock : socket.socket 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.

tcp_reply_inform(sock, inform, orig_req)

Send an inform as part of the reply to an earlier request.

Parameters :

sock : socket.socket 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.

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 at 0x7f7cc3f60c50>)

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

Maximum number of stack frames to send in error tracebacks.

logger : logging.Logger object

Logger to log messages to.

Methods

DeviceServerBase.get_sockets() Return the complete list of current client socket.
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(conn) Called after client connection is established.
DeviceServerBase.on_client_disconnect(conn, ...) Called before a client connection is closed.
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.run() Listen for clients and process their requests.
DeviceServerBase.running() Whether the server is running.
DeviceServerBase.start([timeout, daemon, ...]) Start the server in a new thread.
DeviceServerBase.stop([timeout]) Stop a running server (from another thread).
DeviceServerBase.tcp_inform(sock, msg) Send an inform message to a particular TCP client.
DeviceServerBase.tcp_reply(sock, reply, orig_req) Send an asynchronous reply to an earlier request for a tcp socket.
DeviceServerBase.tcp_reply_inform(sock, ...) Send an inform as part of the reply to an earlier request.
DeviceServerBase.wait_running([timeout]) Wait until the server is running
get_sockets()

Return the complete list of current client socket.

Returns :

sockets : list of socket.socket objects

A list of connected client sockets.

handle_inform(connection, msg)

Dispatch an inform message to the appropriate method.

Parameters :

connection : ClientConnectionTCP 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 : ClientConnectionTCP 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 : ClientConnectionTCP 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 : ClientConnectionTCP object

The client connection the message was from.

msg : Message object

The request message to process.

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 : ClientConnectionTCP 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 in seconds

Time 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(conn)

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 : ClientConnectionTCP object

The client connection that has been successfully established.

on_client_disconnect(conn, msg, connection_valid)

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 : ClientConnectionTCP 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.

reply(connection, reply, orig_req)

Send an asynchronous reply to an earlier request.

Parameters :

connection : ClientConnectionTCP 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 : ClientConnectionTCP 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.

run()

Listen for clients and process their requests.

running()

Whether the server is running.

start(timeout=None, daemon=None, excepthook=None)

Start the server in a new thread.

Parameters :

timeout : float in seconds

Time to wait for server thread to start.

daemon : boolean

If not None, the thread’s setDaemon method is called with this parameter before the thread is started.

excepthook : function

Function to call if the client throws an exception. Signature is as for sys.excepthook.

stop(timeout=1.0)

Stop a running server (from another thread).

Parameters :

timeout : float in seconds

Seconds to wait for server to have started.

tcp_inform(sock, msg)

Send an inform message to a particular TCP 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 :

sock : socket.socket object

The client to send the message to.

msg : Message object

The inform message to send.

tcp_reply(sock, reply, orig_req)

Send an asynchronous reply to an earlier request for a tcp socket.

Parameters :

sock : socket.socket 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.

tcp_reply_inform(sock, inform, orig_req)

Send an inform as part of the reply to an earlier request.

Parameters :

sock : socket.socket 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.

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)

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 and FLOAT 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.

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.integer(name[, description, unit, ...]) Instantiate a new integer sensor object.
Sensor.lru(name[, description, unit, default]) Instantiate a new lru sensor object.
Sensor.notify() 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.string(name[, description, unit, default]) 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)

Instantiate a new IP address sensor object.

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)
attach(observer)

Attach an observer to this sensor.

The observer must support a call to observer.update(sensor).

Parameters :

observer : object

Object with an .update(sensor) method that will be called when the sensor value is set.

classmethod boolean(name, description=None, unit='', default=None)

Instantiate a new boolean sensor object.

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.
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)

Instantiate a new discrete sensor object.

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
classmethod float(name, description=None, unit='', params=None, default=None)

Instantiate a new float sensor object.

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.
classmethod integer(name, description=None, unit='', params=None, default=None)

Instantiate a new integer sensor object.

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.
classmethod lru(name, description=None, unit='', default=None)

Instantiate a new lru sensor object.

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
notify()

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. Defaults to latest implemented KATCP version (5)

Major version of KATCP to use when interpreting types

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 :

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 will be appropriate to the sensor’s type).

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. Defaults to latest implemented KATCP version (5)

Major version of KATCP to use when interpreting types

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. Defaults to latest implemented KATCP version (5)

Major version of KATCP to use when interpreting types

classmethod string(name, description=None, unit='', default=None)

Instantiate a new string sensor object.

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.
classmethod timestamp(name, description=None, unit='', default=None)

Instantiate a new timestamp sensor object.

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.
value()

Read the current sensor value.

Returns :

value : object

The value of the sensor (the type will be appropriate to the sensor’s type).

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.

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.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.

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.

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 the 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 the 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.

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.

Exceptions

class katcp.KatcpSyntaxError

Exception raised by parsers on encountering syntax errors.

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

ExcepthookThread

class katcp.ExcepthookThread(excepthook=None, *args, **kwargs)

A custom Thread class that provides an exception hook.

Exceptions are passed up to an excepthook callable that functions like sys.excepthook.

Parameters :

excepthook : callable

Function to call when the thread raises an unhandled exception. The signature is the same as for sys.excepthook.

args : additional arguments

Passed to the threading.Thread constructor.

kwargs: additional keyword arguments :

Passed to the threading.Thread constructor.

Methods

ExcepthookThread.getName()
ExcepthookThread.isAlive()
ExcepthookThread.isDaemon()
ExcepthookThread.is_alive()
ExcepthookThread.join([timeout])
ExcepthookThread.run()
ExcepthookThread.setDaemon(daemonic)
ExcepthookThread.setName(name)
ExcepthookThread.start()

Version Information

katcp.VERSION

Five-element tuple containing the version number.

katcp.VERSION_STR

String representing the version number.