Kattypes

Utilities for dealing with KATCP types.

class katcp.kattypes.Address(default=None, optional=False, multiple=False)

Bases: katcp.kattypes.KatcpType

The KATCP address type.

Note

The address type was added in katcp 0.4.

Methods

Address.check(value, major) Check whether the value is valid.
Address.decode(value, major)
Address.encode(value, major)
Address.get_default() Return the default value.
Address.next()
Address.pack(value[, nocheck, major]) Return the value formatted as a KATCP parameter.
Address.unpack(packed_value[, major]) Parse a KATCP parameter into an object.
class katcp.kattypes.Bool(default=None, optional=False, multiple=False)

Bases: katcp.kattypes.KatcpType

The KATCP boolean type.

Methods

Bool.check(value, major) Check whether the value is valid.
Bool.decode(value, major)
Bool.encode(value, major)
Bool.get_default() Return the default value.
Bool.next()
Bool.pack(value[, nocheck, major]) Return the value formatted as a KATCP parameter.
Bool.unpack(packed_value[, major]) Parse a KATCP parameter into an object.
class katcp.kattypes.Discrete(values, case_insensitive=False, **kwargs)

Bases: katcp.kattypes.Str

The KATCP discrete type.

Parameters:

values : iterable of str

List of the values the discrete type may accept.

case_insensitive : bool

Whether case-insensitive value matching should be used.

Methods

Discrete.check(value, major) Check whether the value in the set of allowed values.
Discrete.decode(value, major)
Discrete.encode(value, major)
Discrete.get_default() Return the default value.
Discrete.next()
Discrete.pack(value[, nocheck, major]) Return the value formatted as a KATCP parameter.
Discrete.unpack(packed_value[, major]) Parse a KATCP parameter into an object.
check(value, major)

Check whether the value in the set of allowed values.

Raise a ValueError if it is not.

class katcp.kattypes.DiscreteMulti(values, all_keyword='all', separator=', ', **kwargs)

Bases: katcp.kattypes.Discrete

Discrete type which can accept multiple values.

Its value is always a list.

Parameters:

values : list of str

Set of allowed values.

all_keyword : str, optional

The string which represents the list of all allowed values.

separator : str, optional

The separator used in the packed value string.

Methods

DiscreteMulti.check(value, major) Check that each item in the value list is in the allowed set.
DiscreteMulti.decode(value, major)
DiscreteMulti.encode(value, major)
DiscreteMulti.get_default() Return the default value.
DiscreteMulti.next()
DiscreteMulti.pack(value[, nocheck, major]) Return the value formatted as a KATCP parameter.
DiscreteMulti.unpack(packed_value[, major]) Parse a KATCP parameter into an object.
check(value, major)

Check that each item in the value list is in the allowed set.

class katcp.kattypes.Float(min=None, max=None, **kwargs)

Bases: katcp.kattypes.KatcpType

The KATCP float type.

Parameters:

min : float

The minimum allowed value. Ignored if not given.

max : float

The maximum allowed value. Ignored if not given.

Methods

Float.check(value, major) Check whether the value is between the minimum and maximum.
Float.decode(value, major)
Float.encode(value, major)
Float.get_default() Return the default value.
Float.next()
Float.pack(value[, nocheck, major]) Return the value formatted as a KATCP parameter.
Float.unpack(packed_value[, major]) Parse a KATCP parameter into an object.
check(value, major)

Check whether the value is between the minimum and maximum.

Raise a ValueError if it is not.

class katcp.kattypes.Int(min=None, max=None, **kwargs)

Bases: katcp.kattypes.KatcpType

The KATCP integer type.

Parameters:

min : int

The minimum allowed value. Ignored if not given.

max : int

The maximum allowed value. Ignored if not given.

Methods

Int.check(value, major) Check whether the value is between the minimum and maximum.
Int.decode(value, major)
Int.encode(value, major)
Int.get_default() Return the default value.
Int.next()
Int.pack(value[, nocheck, major]) Return the value formatted as a KATCP parameter.
Int.unpack(packed_value[, major]) Parse a KATCP parameter into an object.
check(value, major)

Check whether the value is between the minimum and maximum.

Raise a ValueError if it is not.

class katcp.kattypes.KatcpType(default=None, optional=False, multiple=False)

Bases: future.types.newobject.newobject

Class representing a KATCP type.

Sub-classes should:

  • Set the name attribute.
  • Implement the encode() method.
  • Implement the decode() method.
Parameters:

default : object, optional

The default value for this type.

optional : boolean, optional

Whether the value is allowed to be None.

multiple : boolean, optional

Whether multiple values of this type are expected. Must be the last type parameter if this is True.

Methods

KatcpType.check(value, major) Check whether the value is valid.
KatcpType.get_default() Return the default value.
KatcpType.next()
KatcpType.pack(value[, nocheck, major]) Return the value formatted as a KATCP parameter.
KatcpType.unpack(packed_value[, major]) Parse a KATCP parameter into an object.
check(value, major)

Check whether the value is valid.

Do nothing if the value is valid. Raise an exception if the value is not valid. Parameter major describes the KATCP major version to use when interpreting the validity of a value.

get_default()

Return the default value.

Raise a ValueError if the value is not optional and there is no default.

Returns:

default : object

The default value.

pack(value, nocheck=False, major=5)

Return the value formatted as a KATCP parameter.

Parameters:

value : object

The value to pack.

nocheck : bool, optional

Whether to check that the value is valid before packing it.

major : int, optional

Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP version.

Returns:

packed_value : bytes

The unescaped KATCP byte string representing the value.

unpack(packed_value, major=5)

Parse a KATCP parameter into an object.

Parameters:

packed_value : bytes

The unescaped KATCP byte string to parse into a value.

major : int, optional

Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP version.

Returns:

value : object

The value the KATCP string represented.

class katcp.kattypes.Lru(default=None, optional=False, multiple=False)

Bases: katcp.kattypes.KatcpType

The KATCP lru type

Methods

Lru.check(value, major) Check whether the value is valid.
Lru.decode(value, major)
Lru.encode(value, major)
Lru.get_default() Return the default value.
Lru.next()
Lru.pack(value[, nocheck, major]) Return the value formatted as a KATCP parameter.
Lru.unpack(packed_value[, major]) Parse a KATCP parameter into an object.
class katcp.kattypes.Parameter(position, name, kattype, major)

Bases: future.types.newobject.newobject

Wrapper for kattypes which holds parameter-specific information.

Parameters:

position : int

The parameter’s position (starts at 1)

name : str

The parameter’s name (introspected)

kattype : KatcpType object

The parameter’s kattype

major : integer

Major version of KATCP to use when interpreting types

Methods

Parameter.next()
Parameter.pack(value) Pack the parameter using its kattype.
Parameter.unpack(value) Unpack the parameter using its kattype.
pack(value)

Pack the parameter using its kattype.

Parameters:

value : object

The value to pack

Returns:

packed_value : str

The unescaped KATCP string representing the value.

unpack(value)

Unpack the parameter using its kattype.

Parameters:

packed_value : str

The unescaped KATCP string to unpack.

Returns:

value : object

The unpacked value.

class katcp.kattypes.Regex(regex, **kwargs)

Bases: katcp.kattypes.Str

String type that checks values using a regular expression.

Parameters:

regex : str or regular expression object

Regular expression that values should match.

Methods

Regex.check(value, major) Check whether the value is valid.
Regex.decode(value, major)
Regex.encode(value, major)
Regex.get_default() Return the default value.
Regex.next()
Regex.pack(value[, nocheck, major]) Return the value formatted as a KATCP parameter.
Regex.unpack(packed_value[, major]) Parse a KATCP parameter into an object.
check(value, major)

Check whether the value is valid.

Do nothing if the value is valid. Raise an exception if the value is not valid. Parameter major describes the KATCP major version to use when interpreting the validity of a value.

class katcp.kattypes.Str(default=None, optional=False, multiple=False)

Bases: katcp.kattypes.KatcpType

The KATCP string type.

Notes

The behaviour of this type is subtly different between Python versions in order to ease the porting effort for users of this library. - Unpacked (decoded) values are native strings (bytes in PY2, Unicode in PY3). - Packed (encoded) values are always byte strings (in both PY2 and PY3), as this is what is sent on the wire.

UTF-8 encoding is used when converting between Unicode and byte strings. Thus ASCII values are fine, but arbitrary strings of bytes are not safe to use, and may raise an exception.

For convenience, non-text types can be encoded. The object is converted to a string, and then to bytes. This is a one-way operation - when that byte string is decoded the original type will not be recovered.

Methods

Str.check(value, major) Check whether the value is valid.
Str.decode(value, major)
Str.encode(value, major)
Str.get_default() Return the default value.
Str.next()
Str.pack(value[, nocheck, major]) Return the value formatted as a KATCP parameter.
Str.unpack(packed_value[, major]) Parse a KATCP parameter into an object.
class katcp.kattypes.StrictTimestamp(default=None, optional=False, multiple=False)

Bases: katcp.kattypes.KatcpType

A timestamp that enforces the XXXX.YYY format for timestamps.

Methods

StrictTimestamp.check(value, major) Check whether the value is positive.
StrictTimestamp.decode(value, major)
StrictTimestamp.encode(value, major)
StrictTimestamp.get_default() Return the default value.
StrictTimestamp.next()
StrictTimestamp.pack(value[, nocheck, major]) Return the value formatted as a KATCP parameter.
StrictTimestamp.unpack(packed_value[, major]) Parse a KATCP parameter into an object.
check(value, major)

Check whether the value is positive.

Raise a ValueError if it is not.

class katcp.kattypes.Struct(fmt, **kwargs)

Bases: katcp.kattypes.KatcpType

KatcpType for parsing and packing values using the struct module.

Parameters:

fmt : str

Format to use for packing and unpacking values. It is passed directly into struct.pack() and struct.unpack().

Methods

Struct.check(value, major) Check whether the value is valid.
Struct.decode(value, major)
Struct.encode(value, major)
Struct.get_default() Return the default value.
Struct.next()
Struct.pack(value[, nocheck, major]) Return the value formatted as a KATCP parameter.
Struct.unpack(packed_value[, major]) Parse a KATCP parameter into an object.
class katcp.kattypes.Timestamp(default=None, optional=False, multiple=False)

Bases: katcp.kattypes.KatcpType

The KATCP timestamp type.

Methods

Timestamp.check(value, major) Check whether the value is valid.
Timestamp.decode(value, major)
Timestamp.encode(value, major)
Timestamp.get_default() Return the default value.
Timestamp.next()
Timestamp.pack(value[, nocheck, major]) Return the value formatted as a KATCP parameter.
Timestamp.unpack(packed_value[, major]) Parse a KATCP parameter into an object.
class katcp.kattypes.TimestampOrNow(default=None, optional=False, multiple=False)

Bases: katcp.kattypes.Timestamp

KatcpType representing either a Timestamp or the special value for now.

Floats are encoded as for katcp.kattypes.Timestamp. The special value for now, katcp.kattypes.TimestampOrNow.NOW, is encoded as the string “now”.

Methods

TimestampOrNow.check(value, major) Check whether the value is valid.
TimestampOrNow.decode(value, major)
TimestampOrNow.encode(value, major)
TimestampOrNow.get_default() Return the default value.
TimestampOrNow.next()
TimestampOrNow.pack(value[, nocheck, major]) Return the value formatted as a KATCP parameter.
TimestampOrNow.unpack(packed_value[, major]) Parse a KATCP parameter into an object.
katcp.kattypes.async_make_reply(*args, **kwargs)

Wrap future that will resolve with arguments needed by make_reply().

katcp.kattypes.concurrent_reply(handler)

Decorator for concurrent async request handlers

By default async request handlers that return a Future are serialised per-connection, i.e. until the most recent handler resolves its future, the next message will not be read from the client stream. A handler decorated with this decorator allows the next message to be read before it has resolved its future, allowing multiple requests from a single client to be handled concurrently. This is similar to raising AsyncReply.

Examples

>>> class MyDevice(DeviceServer):
...     @return_reply(Int())
...     @concurrent_reply
...     @tornado.gen.coroutine
...     def request_myreq(self, req):
...         '''A slow request'''
...         result = yield self.slow_operation()
...         raise tornado.gen.Return((req, result))
...
katcp.kattypes.has_katcp_protocol_flags(protocol_flags)

Decorator; only include handler if server has these protocol flags

Useful for including default handler implementations for KATCP features that are only present when certain server protocol flags are set.

Examples

>>> class MyDevice(DeviceServer):
...     '''This device server will expose ?myreq'''
...     PROTOCOL_INFO = katcp.core.ProtocolFlags(5, 0, [
                    katcp.core.ProtocolFlags.MULTI_CLIENT])
...
...     @has_katcp_protocol_flags([katcp.core.ProtocolFlags.MULTI_CLIENT])
...     def request_myreq(self, req, msg):
...         '''A request that requires multi-client support'''
...         # Request handler implementation here.
...
>>> class MySingleClientDevice(MyDevice):
...     '''This device server will not expose ?myreq'''
...
...     PROTOCOL_INFO = katcp.core.ProtocolFlags(5, 0, [])
...
katcp.kattypes.inform()

Decorator for inform handler methods.

The method being decorated should take arguments matching the list of types. The decorator will unpack the request message into the arguments.

Parameters:

types : list of kattypes

The types of the request message parameters (in order). A type with multiple=True has to be the last type.

Keyword Arguments:
 

include_msg : bool, optional

Pass the request message as the third parameter to the decorated request handler function (default is False).

major : int, optional

Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP version.

Examples

>>> class MyDeviceClient(katcp.client.AsyncClient):
...     @inform(Int(), Float())
...     def inform_myinf(self, my_int, my_float):
...         '''Handle #myinf <my_int> <my_float> inform received from server'''
...         # Call some code here that reacts to my_inf and my_float
katcp.kattypes.make_reply(msgname, types, arguments, major)

Helper method for constructing a reply message from a list or tuple.

Parameters:

msgname : str

Name of the reply message.

types : list of kattypes

The types of the reply message parameters (in order).

arguments : list of objects

The (unpacked) reply message parameters.

major : integer

Major version of KATCP to use when packing types

katcp.kattypes.minimum_katcp_version(major, minor=0)

Decorator; exclude handler if server’s protocol version is too low

Useful for including default handler implementations for KATCP features that are only present in certain KATCP protocol versions

Examples

>>> class MyDevice(DeviceServer):
...     '''This device server will expose ?myreq'''
...     PROTOCOL_INFO = katcp.core.ProtocolFlags(5, 1)
...
...     @minimum_katcp_version(5, 1)
...     def request_myreq(self, req, msg):
...         '''A request that should only be present for KATCP >v5.1'''
...         # Request handler implementation here.
...
>>> class MyOldDevice(MyDevice):
...     '''This device server will not expose ?myreq'''
...
...     PROTOCOL_INFO = katcp.core.ProtocolFlags(5, 0)
...
katcp.kattypes.pack_types(types, args, major)

Pack arguments according the the types list.

Parameters:

types : sequence of kattypes

The types of the arguments (in order).

args : sequence of objects

The arguments to format.

major : integer

Major version of KATCP to use when packing types

Returns:

packed_args : list

List of args after packing to byte strings

katcp.kattypes.request(*types, **options)

Decorator for request handler methods.

The method being decorated should take a req argument followed by arguments matching the list of types. The decorator will unpack the request message into the arguments.

Parameters:

types : list of kattypes

The types of the request message parameters (in order). A type with multiple=True has to be the last type.

Keyword Arguments:
 

include_msg : bool, optional

Pass the request message as the third parameter to the decorated request handler function (default is False).

major : int, optional

Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP version.

Examples

>>> class MyDevice(DeviceServer):
...     @request(Int(), Float(), Bool())
...     @return_reply(Int(), Float())
...     def request_myreq(self, req, my_int, my_float, my_bool):
...         '''?myreq my_int my_float my_bool'''
...         return ("ok", my_int + 1, my_float / 2.0)
...
...     @request(Int(), include_msg=True)
...     @return_reply(Bool())
...     def request_is_odd(self, req, msg, my_int):
            '''?is-odd <my_int>, reply '1' if <my_int> is odd, else 0'''
...         req.inform('Checking oddity of %d' % my_int)
...         return ("ok", my_int % 2)
...
katcp.kattypes.request_timeout_hint(timeout_hint)

Decorator; add recommended client timeout hint to a request for request

Useful for requests that take longer than average to reply. Hint is provided to clients via ?request-timeout-hint. Note this is only exposed if the device server sets the protocol version to KATCP v5.1 or higher and enables the REQUEST_TIMEOUT_HINTS flag in its PROTOCOL_INFO class attribute

Parameters:

timeout_hint : float (seconds) or None

How long the decorated request should reasonably take to reply. No timeout hint if None, similar to never using the decorator, provided for consistency.

Examples

>>> class MyDevice(DeviceServer):
...     @return_reply(Int())
...     @request_timeout_hint(15) # Set request timeout hint to 15 seconds
...     @tornado.gen.coroutine
...     def request_myreq(self, req):
...         '''A slow request'''
...         result = yield self.slow_operation()
...         raise tornado.gen.Return((req, result))
...
katcp.kattypes.return_reply(*types, **options)

Decorator for returning replies from request handler methods.

The method being decorated should return an iterable of result values. If the first value is ‘ok’, the decorator will check the remaining values against the specified list of types (if any). If the first value is ‘fail’ or ‘error’, there must be only one remaining parameter, and it must be a string describing the failure or error In both cases, the decorator will pack the values into a reply message.

Parameters:

types : list of kattypes

The types of the reply message parameters (in order).

Keyword Arguments:
 

major : int, optional

Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP version.

Examples

>>> class MyDevice(DeviceServer):
...     @request(Int())
...     @return_reply(Int(), Float())
...     def request_myreq(self, req, my_int):
...         return ("ok", my_int + 1, my_int * 2.0)
...
katcp.kattypes.send_reply(*types, **options)

Decorator for sending replies from request callback methods.

This decorator constructs a reply from a list or tuple returned from a callback method, but unlike the return_reply decorator it also sends the reply rather than returning it.

The list/tuple returned from the callback method must have req (a ClientRequestConnection instance) as its first parameter and the original message as the second. The original message is needed to determine the message name and ID.

The device with the callback method must have a reply method.

Parameters:

types : list of kattypes

The types of the reply message parameters (in order).

Keyword Arguments:
 

major : int, optional

Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP version.

Examples

>>> class MyDevice(DeviceServer):
...     @send_reply(Int(), Float())
...     def my_callback(self, req):
...         return (req, "ok", 5, 2.0)
...
katcp.kattypes.unpack_message()

Decorator that unpacks katcp.Messages to function arguments.

The method being decorated should take arguments matching the list of types. The decorator will unpack the request message into the arguments.

Parameters:

types : list of kattypes

The types of the request message parameters (in order). A type with multiple=True has to be the last type.

Keyword Arguments:
 

include_msg : bool, optional

Pass the request message as the third parameter to the decorated request handler function (default is False).

major : int, optional

Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP version.

Examples

>>> class MyClient(DeviceClient):
...     @unpack_message(Str(), Int(), Float(), Bool())
...     def reply_myreq(self, status, my_int, my_float, my_bool):
...         print 'myreq replied with ', (status, my_int, my_float, my_bool)
...
...     @unpack_message(Str(), Int(), include_msg=True)
...     def inform_fruit_picked(self, msg, fruit, no_picked):
...         print no_picked, 'of fruit ', fruit, ' picked.'
...         print 'Raw inform message: ', str(msg)
katcp.kattypes.unpack_types(types, args, argnames, major)

Parse arguments according to types list.

Parameters:

types : sequence of kattypes

The types of the arguments (in order).

args : sequence of strings

The arguments to parse.

argnames : sequence of strings

The names of the arguments.

major : integer

Major version of KATCP to use when packing types

Returns:

unpacked_args : list

List of args after unpacking to kattype objects

katcp.kattypes.unpack_message()

Decorator that unpacks katcp.Messages to function arguments.

The method being decorated should take arguments matching the list of types. The decorator will unpack the request message into the arguments.

Parameters:

types : list of kattypes

The types of the request message parameters (in order). A type with multiple=True has to be the last type.

Keyword Arguments:
 

include_msg : bool, optional

Pass the request message as the third parameter to the decorated request handler function (default is False).

major : int, optional

Major version of KATCP to use when interpreting types. Defaults to latest implemented KATCP version.

Examples

>>> class MyClient(DeviceClient):
...     @unpack_message(Str(), Int(), Float(), Bool())
...     def reply_myreq(self, status, my_int, my_float, my_bool):
...         print 'myreq replied with ', (status, my_int, my_float, my_bool)
...
...     @unpack_message(Str(), Int(), include_msg=True)
...     def inform_fruit_picked(self, msg, fruit, no_picked):
...         print no_picked, 'of fruit ', fruit, ' picked.'
...         print 'Raw inform message: ', str(msg)