The inm module provides a complete INM messaging API. This API is primarily designed for flexibility, not ease of use (or performance). When implementing an INM client, consider using an InmHelper to simplify the exchange of messages.
CAUTION: This module is NOT inherently thread-safe. In a multi-threaded application, access to thread-shared objects from this module (including the default_msg_factory) MUST be synchronized in application code.
inm.py | The inm module provides a complete INM messaging API. |
General Utilities | |
Variables | |
ZERO_DURATION | A datetime.timedelta representing a zero duration. |
get_timestamp | Produces a datetime.datetime representing the current local time. |
Functions | |
get_timedelta | Produces a datetime.timedelta with a specified duration. |
bytes_to_hex | Produces a hexadecimal string representation of a bytes object. |
bytes_to_bin | Produces a binary string representation of a bytes object. |
map_enum | Searches an enum class for a member with a specified integer value. |
format_msg_info | Provides a standard way to represent INM communication events as strings. |
Enum Types | |
Enumerations | |
StandardTypes | Standard INM message types. |
StandardResults | Standard INM result codes. |
StandardRegisters | Standard INM register identifiers. |
ResultCode | Result codes for the INM module. |
ValueConversions | Type conversion specifiers for INM message values. |
Strictness | Multipart formatting strictness specifiers for INM message values. |
Messages and Message Processing | |
Message | Instances of subclasses of this abstract class represent INM messages. |
Variables | |
MESSAGE_TYP_SIZE | Size in bytes of the message type identifier field in an INM message. |
Functions and Properties | |
__init__ | Instance initializer. |
typ | Message type identifier. |
val | Message value/payload. |
__len__ | Message (value) length. |
__str__ | String conversion. |
__repr__ | String representation. |
check_tl | Message type and length check predicate. |
format_str | Applies string formatting to the INM message type and value. |
format | Applies formatting to the INM message type and value. |
format_type | Applies formatting to the INM message type. |
format_val_str | Applies string formatting to the INM message value. |
format_val | Applies formatting to the INM message value. |
format_mval | Applies multipart formatting to the INM message value. |
format_mval_0 | Applies multipart formatting to the INM message value, but returns only the first field. |
to_bytes | Converts the Message to a bytes object containing the message in standard binary on-wire format. |
StandardMessage | Concrete Message subclass for standard-size INM messages. |
Variables | |
MESSAGE_LEN_SIZE | Size in bytes of the message length field in a standard INM message. |
MIN_MESSAGE_SIZE | Minimum size in bytes of a standard INM message. |
MIN_TYPE_NUM | Smallest valid message type identifier for standard INM messages. |
MAX_TYPE_NUM | Largest valid message type identifier for standard INM messages. |
MAX_MESSAGE_LEN | Maximum value of the message length field in a standard INM message, and thereby also the maximum size in bytes of a standard message value field. |
PROTOCOL_TYPE_NUM | Type identifier reserved for INM protocol messages. |
LargeMessage | Concrete Message subclass for large-size INM messages. |
Variables | |
MESSAGE_LEN_SIZE | Size in bytes of the message length field in a large INM message. |
MIN_MESSAGE_SIZE | Minimum size in bytes of a large INM message. |
MIN_TYPE_NUM | Smallest valid message type identifier for large INM messages. |
MAX_TYPE_NUM | Largest valid message type identifier for large INM messages. |
MAX_MESSAGE_LEN | Maximum value of the message length field in a large INM message, and thereby also the maximum size in bytes of a large message value field. |
MessageFactory | A configurable factory class for INM messages. |
Variables | |
MAKE_VAL_ATTR_NAME | Name of attribute to use for custom conversion of objects into INM message values/payloads. |
DEFAULT_RES_ENUM_MSG_TYPES | Default message types for result code enum conversion. |
DEFAULT_REG_ENUM_MSG_TYPES | Default message types for register identifier enum conversion. |
Functions | |
__init__ | Instance initializer. |
Properties | |
make_val_hex_str | If true, strings will be interpreted as sequences of hexadecimal digits (instead of text) when making message values. |
str_encoding | Name of text encoding to use when making and formatting message values. |
int_size | Default size in bytes of integer fields in message values. |
int_byteorder | Name of default byte order of integer fields in message values. |
byte_sep | Byte group separator for message values formatted as hex or binary strings. |
bytes_per_sep | Byte group size for message values formatted as hex or binary strings. |
byte_str_big_endian | Byte order selector for message values formatted as hex or binary strings. |
default_val_conv | Default conversion for formatted message values. |
str_val_conv | Conversion for string-formatted message values. |
enum_format_val | If true, fields known to contain result codes or message type or register identifiers will be converted to the corresponding enum members (from type_enum_class or res_enum_class) when formatting message values. |
type_enum_class | Enum class to use for conversion of message type identifiers. |
res_enum_class | Enum class to use for conversion of INM result codes. |
res_enum_msg_types | Message types to perform result code enum conversion on. |
reg_enum_class | Enum class to use for conversion of logical register identifiers. |
reg_enum_msg_types | Message types to perform register identifier enum conversion on. |
default_strictness | Default strictness level for multipart message value formatting. |
Functions | |
clone | Copies the MessageFactory. |
get_make_val_int_size | Gets the value construction integer field sizes associated with a specified message type. |
set_make_val_int_size | Sets the value construction integer field sizes associated with a specified message type. |
get_format_val_conv | Gets the value formatting conversion specifier associated with a specified message type. |
set_format_val_conv | Sets the value formatting conversion specifier associated with a specified message type. |
get_format_val_size | Gets the value formatting field sizes associated with a specified message type. |
set_format_val_size | Sets the value formatting field sizes associated with a specified message type. |
make_val | Creates a bytes object containing an INM message value. |
make_mval | Creates a bytes object containing a multipart INM message value. |
format_val_str | Applies string formatting to an INM message value. |
format_val | Applies formatting to an INM message value. |
format_mval | Applies multipart formatting to an INM message value. |
make_msg | Constructs an INM Message with the specified type and value. |
make_msg_mval | Constructs an INM Message with the specified type and multipart value. |
make_large_msg | Constructs a large INM Message with the specified type and value. |
make_large_msg_mval | Constructs a large INM Message with the specified type and multipart value. |
msg_to_bytes | Converts a Message and MessageHeader to a bytes object containing the message and header in standard binary on-wire format. |
MessageHeader | Represents the header of an INM message. |
Variables | |
MESSAGE_ID_SIZE | Size in bytes of the message identifier field in an INM message header. |
DSTADR_SIZE | Size in bytes of the destination address field in an INM message header. |
SRCADR_SIZE | Size in bytes of the source address field in an INM message header. |
HEADER_SIZE | Size in bytes of a complete INM message header. |
MAX_MESSAGE_ID | Largest valid INM message identifier. |
MAX_MESSAGE_ADR | Largest valid INM node address. |
LOCAL_ADR | Reserved INM node address for the local node. |
BROADCAST_ADR | Reserved INM node address for broadcast messages. |
Functions and Properties | |
__init__ | Instance initializer. |
msg_id | INM message identifier. |
dstadr | Destination INM node address. |
srcadr | Source INM node address. |
__str__ | String conversion. |
__repr__ | String representation. |
to_bytes | Converts the MessageHeader to a bytes object containing the header in standard binary on-wire format. |
Default Objects | |
Variables | |
default_msg_factory | A default instance of MessageFactory. |
Message Channels | |
MessageChannelError | Exception class for MessageChannels. |
MessageChannel | Abstract parent class for objects that send and receive INM messages. |
Variables | |
make_default_selector | If this is true, a default selector object (from the standard library module selectors) will be created for each instance of MessageChannel that isn’t provided with a custom selector at initialization. |
Functions | |
__init__ | Instance initializer. |
Properties | |
srcadr | Default INM source address of messages sent via this MessageChannel. |
timeout | Receive timeout. |
msg_factory | The MessageFactory that the MessageChannel uses to create INM Message objects. |
selector | A selector object compatible with the ones provided by the standard library module selectors. |
ch_num | Channel number of this MessageChannel. |
Functions | |
__str__ | String conversion. |
__repr__ | String representation. |
peek_prev_msg_id | Peeks at the most recently auto-generated INM message ID. |
peek_next_msg_id | Peeks at the next INM message ID to be auto-generated. |
get_next_msg_id | Auto-generates an INM message ID. |
is_open | Checks whether the MessageChannel is open. |
open | Opens the MessageChannel. |
close | Closes the MessageChannel. |
readable | Checks whether the MessageChannel is readable. |
get_selector_keys | Gets the selector keys of encapsulated selectable objects from this MessageChannel. |
set_timeout | Updates the timeout attribute. |
send | Sends an INM message. |
recv | Attempts to receive an INM message. |
RoutingMessageChannel | A MessageChannel with message routing functionality. |
Variables | |
TIMEOUT_DIVISOR | If a receive timeout is set on a RoutingMessageChannel, the timeout set on each of the recv_channels will be the primary timeout divided by TIMEOUT_DIVISOR times the number of receive channels. |
DEFAULT_CH_TIMEOUT | If no receive timeout is set on a RoutingMessageChannel, then the timeout set on each of the recv_channels will be DEFAULT_CH_TIMEOUT. |
Functions | |
__init__ | Instance initializer. |
Properties | |
rtab | The routing table. |
recv_channels | The receive channel table. |
cc_to | List of INM node addresses of CC message destinations. |
close_recv_channels | If this is true, all channels in recv_channels are closed when this RoutingMessageChannel is closed. |
relay_messages | If this is true, routing is applied even to messages where the destination address equals the source address of the local node. |
Functions | |
add_cc_adr | Adds the INM address of a CC message destination node to cc_to. |
remove_cc_adr | Removes the INM address of a CC message destination node from cc_to. |
open | Overrides MessageChannel.open. |
close | Overrides MessageChannel.close. |
get_selector_keys | Returns all selector keys obtained by calling the get_selector_keys methods of the channels in recv_channels. |
set_timeout | Overrides MessageChannel.set_timeout. |
send | Implements MessageChannel.send. |
recv | Implements MessageChannel.recv. |
route | Attempts to receive and then route an INM message. |
BinaryMessageChannel | Abstract parent class for MessageChannels that send and receive INM messages encoded in the standard binary on-wire format. |
Functions | |
__init__ | Instance initializer. |
InetMessageChannel | A BinaryMessageChannel that sends and receives messages via a UDP socket. |
Variables | |
DEFAULT_IP_ADR | Default IP socket address. |
DEFAULT_UDP_PORT | Default port number of UDP socket. |
DEFAULT_TCP_PORT | Default port number of TCP socket. |
MAX_DATAGRAM_SIZE | Maximum size of sent UDP datagrams. |
Functions and Properties | |
__init__ | Instance initializer. |
ip_adr | IP address of sockets used by this InetMessageChannel, as a hostname or dotted-decimal string. |
udp_port | Port number of UDP socket used by this InetMessageChannel. |
tcp_port | Port number of TCP socket used by this InetMessageChannel. |
__str__ | String conversion. |
open | Overrides MessageChannel.open. |
close | Overrides MessageChannel.close. |
get_selector_keys | Returns the selector key of the UDP socket. |
set_timeout | Overrides MessageChannel.set_timeout. |
send | Implements MessageChannel.send. |
recv | Implements MessageChannel.recv. |
SerialMessageChannel | A BinaryMessageChannel that sends and receives messages via a serial port. |
Variables | |
DEFAULT_BAUDRATE | Default baud rate to set on the opened serial port. |
N_HEADER_BYTES | Total size of the header, type and length fields of an INM message. |
MAX_MESSAGE_LEN | Maximum supported INM message (value) length. |
TIMEOUT_DIVISOR | If a receive timeout is set on a SerialMessageChannel, the timeout set for each attempt to read data from the underlying serial port API will be the primary timeout divided by TIMEOUT_DIVISOR. |
Functions and Properties | |
__init__ | Instance initializer. |
port | Filesystem path of the used serial port device. |
baudrate | Baud rate to open the used serial port at. |
__str__ | String conversion. |
open | Overrides MessageChannel.open. |
close | Overrides MessageChannel.close. |
get_selector_keys | Returns the selector key of the serial port device. |
set_timeout | Overrides MessageChannel.set_timeout. |
send | Implements MessageChannel.send. |
recv | Implements MessageChannel.recv. |
Variables | |
ZERO_DURATION | A datetime.timedelta representing a zero duration. |
get_timestamp | Produces a datetime.datetime representing the current local time. |
Functions | |
get_timedelta | Produces a datetime.timedelta with a specified duration. |
bytes_to_hex | Produces a hexadecimal string representation of a bytes object. |
bytes_to_bin | Produces a binary string representation of a bytes object. |
map_enum | Searches an enum class for a member with a specified integer value. |
format_msg_info | Provides a standard way to represent INM communication events as strings. |
def get_timedelta( secs = 0, musecs = 0 )
Produces a datetime.timedelta with a specified duration.
secs | An integer or float representing a number of seconds. |
musecs | An integer or float representing a number of microseconds. |
A datetime.timedelta representing a duration of (secs + musecs/1000000) seconds.
def bytes_to_hex( bs, sep = None, bytes_per_sep = 1, big_endian = False )
Produces a hexadecimal string representation of a bytes object.
bs | A bytes object. |
sep | Group separator. Either None or a one-character string. |
bytes_per_sep | Group size. |
big_endian | If true, the order of byte representations in the returned string will be reversed relative to the order of bytes in bs (i.e. the representation of bs[0] will be at the end of the string, etc.). |
A hexadecimal string representation of bs. No prefix is included.
def bytes_to_bin( bs, sep = None, bytes_per_sep = 1, big_endian = False )
Produces a binary string representation of a bytes object.
bs | A bytes object. |
sep | Group separator. Either None or a one-character string. |
bytes_per_sep | Group size. |
big_endian | If true, the order of byte representations in the returned string will be reversed relative to the order of bytes in bs (i.e. the representation of bs[0] will be at the end of the string, etc.). |
A binary string representation of bs. No prefix is included.
def map_enum( enum_class, i, defval = None )
Searches an enum class for a member with a specified integer value.
enum_class | An enum class. |
i | An integer. |
defval | Default return value. |
If a member with integer value i is found in enum_class, then that member is returned. Otherwise, defval is returned.
def format_msg_info( obj, event = None, header = None, link_adr = None, event_colw = 0, timestamp = False )
Provides a standard way to represent INM communication events as strings. This can be useful for logging and debugging.
obj | An object describing some event of interest (e.g. a Message). |
event | An optional string identifying the type of event (e.g. ‘RECV’). |
header | An optional MessageHeader. |
link_adr | An optional INM link address (e.g. an (ip_adr, udp_port) pair). |
event_colw | Minimum width of the event column. |
timestamp | If this parameter is true, a representation of the current time will be included in the returned string. If this parameter is a nonempty string, it will be used as the timestamp format string. |
A string representation of the specified event, in the following format:
'{timestamp} {event} [{header.srcadr}.{header.msg_id} => {header.dstadr}]{link_adr}: {obj}'
Enumerations | |
StandardTypes | Standard INM message types. |
StandardResults | Standard INM result codes. |
StandardRegisters | Standard INM register identifiers. |
ResultCode | Result codes for the INM module. |
ValueConversions | Type conversion specifiers for INM message values. |
Strictness | Multipart formatting strictness specifiers for INM message values. |
Standard INM message types. Message type identifiers are transmitted as 8-bit unsigned integers and MUST be specified as Python integers in the range 0-255 (inclusive).
NOTE: Application-specific message type identifiers SHOULD be greater than or equal to APPLICATION (i.e. 0x40/64).
DEFAULT | Default message type. |
RESULT | Generic TLV operation response (StandardResults code). |
INM_RESULT | Generic INM operation response (StandardResults code and request ID). |
REG_READ | Logical register read request. |
REG_READ_RES | Logical TLV register read response. |
INM_REG_READ_RES | Logical INM register read response (with request ID). |
REG_WRITE | Logical register write (R = V) request. |
REG_TOGGLE | Logical register toggle (R ^= V; ret R) request. |
REG_RW_EXCH | Logical register read-write (X = R; R = V; ret X) request. |
REG_WR_EXCH | Logical register write-read (R = V; ret R) request. |
REGPAIR_READ | Logical register pair read (ret R) request. |
REGPAIR_READ_RES | Logical TLV register pair read response. |
INM_REGPAIR_READ_RES | Logical INM register pair read response (with request ID). |
REGPAIR_WRITE | Logical register pair write request. |
REGPAIR_TOGGLE | Logical register pair toggle request. |
REGPAIR_RW_EXCH | Logical register pair read-write request. |
REGPAIR_WR_EXCH | Logical register pair write-read request. |
MEMMON_DATA | Memory monitor notification. Variable-length message. |
MEMMON_CTRL | Memory monitor control request. Not implemented. |
APPLICATION | Start of application-specific identifier range. |
Standard INM result codes. Result codes are transmitted as 8-bit unsigned integers and MUST be specified as Python integers in the range 0-255 (inclusive).
NOTE: Application-specific result codes SHOULD be greater than or equal to APPLICATION (i.e. 0x40/64) and not equal to NONE (i.e. 0xff/255).
Standard INM register identifiers. Identifiers are transmitted as 8-bit unsigned integers and MUST be specified as Python integers in the range 0-255 (inclusive).
NOTE: Application-specific register identifiers SHOULD be greater than or equal to APPLICATION (i.e. 0x40/64).
Result codes for the INM module.
Multipart formatting strictness specifiers for INM message values.
class Message
Instances of subclasses of this abstract class represent INM messages. This class provides methods that inspect and format the content of a message in various ways.
Variables | |
MESSAGE_TYP_SIZE | Size in bytes of the message type identifier field in an INM message. |
Functions and Properties | |
__init__ | Instance initializer. |
typ | Message type identifier. |
val | Message value/payload. |
__len__ | Message (value) length. |
__str__ | String conversion. |
__repr__ | String representation. |
check_tl | Message type and length check predicate. |
format_str | Applies string formatting to the INM message type and value. |
format | Applies formatting to the INM message type and value. |
format_type | Applies formatting to the INM message type. |
format_val_str | Applies string formatting to the INM message value. |
format_val | Applies formatting to the INM message value. |
format_mval | Applies multipart formatting to the INM message value. |
format_mval_0 | Applies multipart formatting to the INM message value, but returns only the first field. |
to_bytes | Converts the Message to a bytes object containing the message in standard binary on-wire format. |
def __init__( self, typ, val )
Instance initializer.
typ | Message type identifier, e.g. one of the StandardTypes. |
val | Message value/payload. MUST be a bytes object. |
def __len__( self )
Message (value) length.
NOTE: The return value does NOT include the size of the message type and length fields that are part of the standard binary on-wire representation of an INM message.
The INM message length, determined by the len() of the val attribute.
def check_tl( self, typ, length )
Message type and length check predicate.
typ | Required message type identifier. |
length | Required minimum message length. |
True if and only if the typ attribute is equal to the typ argument and len(self) is greater than or equal to the length argument.
def format( self, formatter = None, conv = None )
Applies formatting to the INM message type and value.
formatter | The message formatter to use, or None to use the default formatter. |
conv | Message value conversion specifier (e.g. from ValueConversions), or None to apply the default conversion. |
f_typ | Formatted message type. |
f_val | Formatted message value. |
def format_val( self, formatter = None, conv = None )
Applies formatting to the INM message value.
formatter | The message formatter to use, or None to use the default formatter. |
conv | Message value conversion specifier (e.g. from ValueConversions), or None to apply the default conversion. |
Formatted message value.
def format_mval( self, formatter = None, conv = None, size = None, n_vals = None, strict = None )
Applies multipart formatting to the INM message value.
formatter | The message formatter to use, or None to use the default formatter. |
conv | Field value conversion specifiers (e.g. from ValueConversions). May be a scalar (to apply the same conversion to all fields), tuple or list. If this is None, default conversions are applied. |
size | Multipart value field sizes. May be a scalar (if all fields have the same size), tuple or list. If this is None, the message type is used to infer field sizes, if possible. |
n_vals | Multipart value field count. If this is None, the field count is inferred from the conv and size arguments (or their default values). |
strict | Multipart formatting Strictness specifier, or None to apply the default strictness level. |
The formatted multipart message value (list of formatted fields), if formatting was successful. Otherwise None.
def format_mval_0( self, formatter = None, conv = None, size = None, n_vals = None, strict = None )
Applies multipart formatting to the INM message value, but returns only the first field. (I.e. return the field at index 0 in the list of formatted fields).
formatter | The message formatter to use, or None to use the default formatter. |
conv | Field value conversion specifiers (e.g. from ValueConversions). May be a scalar (to apply the same conversion to all fields), tuple or list. If this is None, default conversions are applied. |
size | Multipart value field sizes. May be a scalar (if all fields have the same size), tuple or list. If this is None, the message type is used to infer field sizes, if possible. |
n_vals | Multipart value field count. If this is None, the field count is inferred from the conv and size arguments (or their default values). |
strict | Multipart formatting Strictness specifier, or None to apply the default strictness level. |
The first field of the formatted multipart message value, if at least one field was successfully formatted. Otherwise None.
def to_bytes( self, formatter = None )
Converts the Message to a bytes object containing the message in standard binary on-wire format.
formatter | Formatter to use for message type and length conversion, or None to use the default formatter. |
A bytes object containing the INM message represented by this Message in standard binary on-wire format.
class StandardMessage( Message )
Concrete Message subclass for standard-size INM messages. The maximum size of a standard message value/payload is 255 bytes.
Variables | |
MESSAGE_LEN_SIZE | Size in bytes of the message length field in a standard INM message. |
MIN_MESSAGE_SIZE | Minimum size in bytes of a standard INM message. |
MIN_TYPE_NUM | Smallest valid message type identifier for standard INM messages. |
MAX_TYPE_NUM | Largest valid message type identifier for standard INM messages. |
MAX_MESSAGE_LEN | Maximum value of the message length field in a standard INM message, and thereby also the maximum size in bytes of a standard message value field. |
PROTOCOL_TYPE_NUM | Type identifier reserved for INM protocol messages. |
class LargeMessage( Message )
Concrete Message subclass for large-size INM messages. The maximum size of a large message value/payload is 4294967295 bytes.
Variables | |
MESSAGE_LEN_SIZE | Size in bytes of the message length field in a large INM message. |
MIN_MESSAGE_SIZE | Minimum size in bytes of a large INM message. |
MIN_TYPE_NUM | Smallest valid message type identifier for large INM messages. |
MAX_TYPE_NUM | Largest valid message type identifier for large INM messages. |
MAX_MESSAGE_LEN | Maximum value of the message length field in a large INM message, and thereby also the maximum size in bytes of a large message value field. |
class MessageFactory
A configurable factory class for INM messages. Provides various methods that construct and parse Message objects and INM message payloads.
Variables | |
MAKE_VAL_ATTR_NAME | Name of attribute to use for custom conversion of objects into INM message values/payloads. |
DEFAULT_RES_ENUM_MSG_TYPES | Default message types for result code enum conversion. |
DEFAULT_REG_ENUM_MSG_TYPES | Default message types for register identifier enum conversion. |
Functions | |
__init__ | Instance initializer. |
Properties | |
make_val_hex_str | If true, strings will be interpreted as sequences of hexadecimal digits (instead of text) when making message values. |
str_encoding | Name of text encoding to use when making and formatting message values. |
int_size | Default size in bytes of integer fields in message values. |
int_byteorder | Name of default byte order of integer fields in message values. |
byte_sep | Byte group separator for message values formatted as hex or binary strings. |
bytes_per_sep | Byte group size for message values formatted as hex or binary strings. |
byte_str_big_endian | Byte order selector for message values formatted as hex or binary strings. |
default_val_conv | Default conversion for formatted message values. |
str_val_conv | Conversion for string-formatted message values. |
enum_format_val | If true, fields known to contain result codes or message type or register identifiers will be converted to the corresponding enum members (from type_enum_class or res_enum_class) when formatting message values. |
type_enum_class | Enum class to use for conversion of message type identifiers. |
res_enum_class | Enum class to use for conversion of INM result codes. |
res_enum_msg_types | Message types to perform result code enum conversion on. |
reg_enum_class | Enum class to use for conversion of logical register identifiers. |
reg_enum_msg_types | Message types to perform register identifier enum conversion on. |
default_strictness | Default strictness level for multipart message value formatting. |
Functions | |
clone | Copies the MessageFactory. |
get_make_val_int_size | Gets the value construction integer field sizes associated with a specified message type. |
set_make_val_int_size | Sets the value construction integer field sizes associated with a specified message type. |
get_format_val_conv | Gets the value formatting conversion specifier associated with a specified message type. |
set_format_val_conv | Sets the value formatting conversion specifier associated with a specified message type. |
get_format_val_size | Gets the value formatting field sizes associated with a specified message type. |
set_format_val_size | Sets the value formatting field sizes associated with a specified message type. |
make_val | Creates a bytes object containing an INM message value. |
make_mval | Creates a bytes object containing a multipart INM message value. |
format_val_str | Applies string formatting to an INM message value. |
format_val | Applies formatting to an INM message value. |
format_mval | Applies multipart formatting to an INM message value. |
make_msg | Constructs an INM Message with the specified type and value. |
make_msg_mval | Constructs an INM Message with the specified type and multipart value. |
make_large_msg | Constructs a large INM Message with the specified type and value. |
make_large_msg_mval | Constructs a large INM Message with the specified type and multipart value. |
msg_to_bytes | Converts a Message and MessageHeader to a bytes object containing the message and header in standard binary on-wire format. |
MAKE_VAL_ATTR_NAME = 'to_inm_val'
Name of attribute to use for custom conversion of objects into INM message values/payloads. If present, such an attribute MUST be callable, return a bytes object and accept the following positional arguments:
formatter | A formatter object that provides the MessageFactory API. |
int_size | The requested size in bytes of a message value or field produced from an integer. May be None. |
tlv_type | An INM message type specifier. May be None. |
DEFAULT_REG_ENUM_MSG_TYPES = ( StandardTypes.REG_READ, StandardTypes.REG_READ_RES, StandardTypes.INM_REG_READ_RES, StandardTypes.REG_WRITE, StandardTypes.REG_TOGGLE, StandardTypes.REG_RW_EXCH, StandardTypes.REG_WR_EXCH, StandardTypes.REGPAIR_READ, StandardTypes.REGPAIR_READ_RES, StandardTypes.INM_REGPAIR_READ_RES, StandardTypes.REGPAIR_WRITE, StandardTypes.REGPAIR_TOGGLE, StandardTypes.REGPAIR_RW_EXCH, StandardTypes.REGPAIR_WR_EXCH )
Default message types for register identifier enum conversion.
self.default_val_conv
Default conversion for formatted message values. Default: ValueConversions.Bytes
self.str_val_conv
Conversion for string-formatted message values. Default: ValueConversions.Hex
self.enum_format_val
If true, fields known to contain result codes or message type or register identifiers will be converted to the corresponding enum members (from type_enum_class or res_enum_class) when formatting message values. This setting overrides any other conversion for those fields. Default: True
self.type_enum_class
Enum class to use for conversion of message type identifiers. Default: StandardTypes
self.res_enum_class
Enum class to use for conversion of INM result codes. Default: StandardResults
self.res_enum_msg_types
Message types to perform result code enum conversion on. SHOULD be a tuple of message type identifiers. Default: DEFAULT_RES_ENUM_MSG_TYPES
self.reg_enum_class
Enum class to use for conversion of logical register identifiers. Default: StandardRegisters
self.reg_enum_msg_types
Message types to perform register identifier enum conversion on. SHOULD be a tuple of message type identifiers. Default: DEFAULT_REG_ENUM_MSG_TYPES
self.default_strictness
Default strictness level for multipart message value formatting. Default: Strictness.Exact
def get_make_val_int_size( self, tlv_type, default = None )
Gets the value construction integer field sizes associated with a specified message type.
tlv_type | An INM message type identifier. |
default | Value to return if tlv_type is not found in the lookup table. |
The value construction integer field sizes associated with tlv_type, if that type is found in the lookup table. Otherwise default.
def set_make_val_int_size( self, tlv_type, int_size )
Sets the value construction integer field sizes associated with a specified message type. Can also be used to delete entries from the value construction field size table.
tlv_type | An INM message type identifier. |
int_size | Value construction field sizes for tlv_type. SHOULD be a positive integer, a list or tuple of positive integers, or None. If the argument is None, any existing entry for tlv_type is deleted from the lookup table. |
True if and only if the table entry was successfully updated or deleted.
def get_format_val_conv( self, tlv_type, default = None )
Gets the value formatting conversion specifier associated with a specified message type.
tlv_type | An INM message type identifier. |
default | Value to return if tlv_type is not found in the lookup table. |
The value formatting conversion specifier associated with tlv_type, if that type is found in the lookup table. Otherwise default.
def set_format_val_conv( self, tlv_type, conv )
Sets the value formatting conversion specifier associated with a specified message type. Can also be used to delete entries from the value formatting conversion table.
tlv_type | An INM message type identifier. |
conv | Value formatting conversion specifier for tlv_type. SHOULD be a member of ValueConversions, an enum class, a list or tuple of any of the aforementioned types, or None. If the argument is None, any existing entry for tlv_type is deleted from the lookup table. |
True if and only if the table entry was successfully updated or deleted.
def get_format_val_size( self, tlv_type, default = None )
Gets the value formatting field sizes associated with a specified message type.
tlv_type | An INM message type identifier. |
default | Value to return if tlv_type is not found in the lookup table. |
The value formatting field sizes associated with tlv_type, if that type is found in the lookup table. Otherwise default.
def set_format_val_size( self, tlv_type, size )
Sets the value formatting field sizes associated with a specified message type. Can also be used to delete entries from the value formatting field size table.
tlv_type | An INM message type identifier. |
size | Value formatting field sizes for tlv_type. SHOULD be a positive integer, a list or tuple of positive integers, or None. If the argument is None, any existing entry for tlv_type is deleted from the lookup table. |
True if and only if the table entry was successfully updated or deleted.
def make_val( self, val, int_size = None, tlv_type = None )
Creates a bytes object containing an INM message value. Objects representable as message values include bytes objects, strings, integers, enum members and tuples and lists of integers in the unsigned byte range (i.e. 0-255).
val | The object to convert to a message value. |
int_size | The size in bytes of a message value produced from an integer. If this is None, a default size will be used. |
tlv_type | An optional INM message type specifier. Used to determine the default integer value size. |
A bytes object containing a converted representation of val. (Or None, if val couldn’t be converted.)
def make_mval( self, mval, int_size = None, tlv_type = None )
Creates a bytes object containing a multipart INM message value. Objects representable as fields in multipart values include bytes objects, strings, integers, enum members and tuples and lists of integers in the unsigned byte range (i.e. 0-255).
mval | The objects to convert to a multipart message value. MUST be a sequence. |
int_size | The sizes in bytes of message value fields produced from an integer. May be a scalar (if all integer fields have the same size), tuple or list. If this is None, default sizes will be used. |
tlv_type | An optional INM message type specifier. Used to determine the default integer field sizes. |
A bytes object containing a converted representation of mval. (Or None, if some object in mval couldn’t be converted.)
def format_val_str( self, val, tlv_type = None )
Applies string formatting to an INM message value.
val | A bytes object containing the message value to format. |
tlv_type | An optional INM message type specifier. Used to determine appropriate enum mappings. |
The result of applying string formatting (determined by str_val_conv) to val.
def format_val( self, val, conv = None, tlv_type = None )
Applies formatting to an INM message value.
val | A bytes object containing the message value to format. |
conv | Message value conversion specifier (e.g. from ValueConversions), or None to apply the default conversion. |
tlv_type | An optional INM message type specifier. Used to determine the default value conversion and enum mappings. |
The result of applying message value formatting to val.
def format_mval( self, mval, conv = None, size = None, tlv_type = None, n_vals = None, strict = None )
Applies multipart formatting to an INM message value.
mval | A bytes object containing the multipart message value to format. |
conv | Field value conversion specifiers (e.g. from ValueConversions). May be a scalar (to apply the same conversion to all fields), tuple or list. If this is None, default conversions are applied. |
size | Multipart value field sizes. May be a scalar (if all fields have the same size), tuple or list. If this is None, the message type is used to infer field sizes, if possible. |
tlv_type | An optional INM message type specifier. Used to determine the default value conversions, field sizes and enum mappings. |
n_vals | Multipart value field count. If this is None, the field count is inferred from the conv and size arguments (or their default values). |
strict | Multipart formatting Strictness specifier, or None to apply the default strictness level. |
The formatted multipart message value (list of formatted fields), if formatting was successful. Otherwise None.
def make_msg( self, typ, val, int_size = None )
Constructs an INM Message with the specified type and value.
typ | An INM message type specifier. |
val | The object to convert to a message value. |
int_size | The size in bytes of a message value produced from an integer. If this is None, a default size will be used. |
A StandardMessage with type typ and a value constructed by applying make_val to val. (Or None, if a value couldn’t be constructed.)
def make_msg_mval( self, typ, mval, int_size = None )
Constructs an INM Message with the specified type and multipart value.
typ | An INM message type specifier. |
mval | The objects to convert to a multipart message value. MUST be a sequence. |
int_size | The sizes in bytes of message value fields produced from an integer. May be a scalar (if all integer fields have the same size), tuple or list. If this is None, default sizes will be used. |
A StandardMessage with type typ and a value constructed by applying make_mval to mval. (Or None, if a value couldn’t be constructed.)
def make_large_msg( self, typ, val, int_size = None )
Constructs a large INM Message with the specified type and value.
typ | An INM message type specifier. |
val | The object to convert to a message value. |
int_size | The size in bytes of a message value produced from an integer. If this is None, a default size will be used. |
A LargeMessage with type typ and a value constructed by applying make_val to val. (Or None, if a value couldn’t be constructed.)
def make_large_msg_mval( self, typ, mval, int_size = None )
Constructs a large INM Message with the specified type and multipart value.
typ | An INM message type specifier. |
mval | The objects to convert to a multipart message value. MUST be a sequence. |
int_size | The sizes in bytes of message value fields produced from an integer. May be a scalar (if all integer fields have the same size), tuple or list. If this is None, default sizes will be used. |
A LargeMessage with type typ and a value constructed by applying make_mval to mval. (Or None, if a value couldn’t be constructed.)
def msg_to_bytes( self, msg, header = None )
Converts a Message and MessageHeader to a bytes object containing the message and header in standard binary on-wire format.
msg | An instance of Message. |
header | An optional instance of MessageHeader. |
A bytes object containing the INM message represented by msg in standard binary on-wire format, preceded by header (also in standard binary on-wire format), if that argument was provided.
class MessageHeader
Represents the header of an INM message.
Variables | |
MESSAGE_ID_SIZE | Size in bytes of the message identifier field in an INM message header. |
DSTADR_SIZE | Size in bytes of the destination address field in an INM message header. |
SRCADR_SIZE | Size in bytes of the source address field in an INM message header. |
HEADER_SIZE | Size in bytes of a complete INM message header. |
MAX_MESSAGE_ID | Largest valid INM message identifier. |
MAX_MESSAGE_ADR | Largest valid INM node address. |
LOCAL_ADR | Reserved INM node address for the local node. |
BROADCAST_ADR | Reserved INM node address for broadcast messages. |
Functions and Properties | |
__init__ | Instance initializer. |
msg_id | INM message identifier. |
dstadr | Destination INM node address. |
srcadr | Source INM node address. |
__str__ | String conversion. |
__repr__ | String representation. |
to_bytes | Converts the MessageHeader to a bytes object containing the header in standard binary on-wire format. |
def to_bytes( self, formatter = None )
Converts the MessageHeader to a bytes object containing the header in standard binary on-wire format.
formatter | Formatter to use for integer conversion, or None to use the default formatter. |
A bytes object containing the INM message header represented by this MessageHeader in standard binary on-wire format.
Variables | |
default_msg_factory | A default instance of MessageFactory. |
default_msg_factory = MessageFactory()
A default instance of MessageFactory. Used by Message, MessageHeader and MessageChannel if no other message formatter is provided. This is a module-level attribute.
class MessageChannelError( Exception )
Exception class for MessageChannels.
class MessageChannel
Abstract parent class for objects that send and receive INM messages.
A MessageChannel can be used as a context manager, opening itself when the context is entered and then closing itself upon exit from the context (see open and close).
Variables | |
make_default_selector | If this is true, a default selector object (from the standard library module selectors) will be created for each instance of MessageChannel that isn’t provided with a custom selector at initialization. |
Functions | |
__init__ | Instance initializer. |
Properties | |
srcadr | Default INM source address of messages sent via this MessageChannel. |
timeout | Receive timeout. |
msg_factory | The MessageFactory that the MessageChannel uses to create INM Message objects. |
selector | A selector object compatible with the ones provided by the standard library module selectors. |
ch_num | Channel number of this MessageChannel. |
Functions | |
__str__ | String conversion. |
__repr__ | String representation. |
peek_prev_msg_id | Peeks at the most recently auto-generated INM message ID. |
peek_next_msg_id | Peeks at the next INM message ID to be auto-generated. |
get_next_msg_id | Auto-generates an INM message ID. |
is_open | Checks whether the MessageChannel is open. |
open | Opens the MessageChannel. |
close | Closes the MessageChannel. |
readable | Checks whether the MessageChannel is readable. |
get_selector_keys | Gets the selector keys of encapsulated selectable objects from this MessageChannel. |
set_timeout | Updates the timeout attribute. |
send | Sends an INM message. |
recv | Attempts to receive an INM message. |
def __init__( self, srcadr, timeout = None, msg_factory = None, selector = None, ch_num = None )
Instance initializer.
srcadr | INM address of the local node. Will be placed in the source address header field of sent messages for which no other source address is provided. |
timeout | Receive timeout. MUST be an instance of the standard library class datetime.timedelta. If this parameter is None, receive operations will never time out. |
msg_factory | The MessageFactory that the MessageChannel should use to create INM Message objects. If this parameter is None, a default MessageFactory will be used. |
selector | A selector object compatible with the ones provided by the standard library module selectors. The selector is used to implement readable and may also be used internally. If this parameter is None, a default selector may be created (see make_default_selector). If this parameter is False (specifically, not some other false value), a default selector will NOT be created. |
ch_num | Channel number of the MessageChannel. SHOULD be either None or a nonnegative integer. |
self.timeout
Receive timeout. MUST be an instance of the standard library class datetime.timedelta. If this attribute is None, receive operations will never time out.
NOTE: The method set_timeout SHOULD be used to change this attribute.
self.msg_factory
The MessageFactory that the MessageChannel uses to create INM Message objects.
def peek_prev_msg_id( self )
Peeks at the most recently auto-generated INM message ID.
CAUTION: This is not thread-safe. If this MessageChannel is thread-shared, other threads may go ahead and cause auto-generation of additional message IDs at any time, unless measures are taken (outside the inm module) to prevent or handle such occurrences.
The INM message ID most recently auto-generated by this MessageChannel.
def peek_next_msg_id( self )
Peeks at the next INM message ID to be auto-generated.
CAUTION: This is not thread-safe. If this MessageChannel is thread-shared, other threads may go ahead and cause auto-generation of additional message IDs at any time, unless measures are taken (outside the inm module) to prevent or handle such occurrences.
The next INM message ID to be auto-generated by this MessageChannel.
def get_next_msg_id( self )
Auto-generates an INM message ID.
CAUTION: This is not thread-safe. If this MessageChannel is thread-shared, other threads may interfere with the auto-generation, causing duplicate message IDs, unless measures are taken (outside the inm module) to prevent such occurrences.
An auto-generated INM message ID.
def open( self )
Opens the MessageChannel. Subclasses may need to override the base class implementation.
ResultCode.SUCCESS if the channel was successfully opened, otherwise another ResultCode indicating what went wrong.
def readable( self )
Checks whether the MessageChannel is readable.
NOTE: The base class implementation of this method needs a selector to work.
CAUTION: Even if this method returns true, a subsequent call to recv may not return a message without blocking.
True if and only if this MessageChannel is currently open and readable.
def get_selector_keys( self )
Gets the selector keys of encapsulated selectable objects from this MessageChannel.
NOTE: The base class implementation always returns an empty tuple.
A tuple of selector keys compatible with the ones produced by the register method of the standard library class selectors.BaseSelector.
def set_timeout( self, timeout )
Updates the timeout attribute. Subclasses may need to override the base class implementation.
timeout | Receive timeout. MUST be an instance of the standard library class datetime.timedelta. If this parameter is None, receive operations will never time out. |
def send( self, dstadr, msg, msg_id = None, srcadr = None, link_adr = None )
Sends an INM message. This is an abstract method.
dstadr | Destination INM node address of the message to send. |
msg | The INM Message to send. |
msg_id | INM message ID. If this is None, a message ID will be generated internally. |
srcadr | Source INM node address of the message to send. If this is None, the configured srcadr of this MessageChannel will be used. |
link_adr | INM link address to use when sending the message. If this is None, the behavior is implementation-defined (e.g. some subclasses may not use link addresses at all). |
A ResultCode indicating the outcome of the attempted send operation.
def recv( self )
Attempts to receive an INM message. This is an abstract method.
res | A ResultCode indicating the outcome of the attempted receive operation. |
header | The MessageHeader of the received message, or None in case of failure. |
msg | The received Message, or None in case of failure. |
link_adr | The link address of the received message, or None in case of failure. |
class RoutingMessageChannel( MessageChannel )
A MessageChannel with message routing functionality. Maintains collections of other MessageChannels that it uses to receive incoming messages and then retransmit them toward their final destinations. Uses a static routing table to determine on which channel to retransmit each incoming message.
Variables | |
TIMEOUT_DIVISOR | If a receive timeout is set on a RoutingMessageChannel, the timeout set on each of the recv_channels will be the primary timeout divided by TIMEOUT_DIVISOR times the number of receive channels. |
DEFAULT_CH_TIMEOUT | If no receive timeout is set on a RoutingMessageChannel, then the timeout set on each of the recv_channels will be DEFAULT_CH_TIMEOUT. |
Functions | |
__init__ | Instance initializer. |
Properties | |
rtab | The routing table. |
recv_channels | The receive channel table. |
cc_to | List of INM node addresses of CC message destinations. |
close_recv_channels | If this is true, all channels in recv_channels are closed when this RoutingMessageChannel is closed. |
relay_messages | If this is true, routing is applied even to messages where the destination address equals the source address of the local node. |
Functions | |
add_cc_adr | Adds the INM address of a CC message destination node to cc_to. |
remove_cc_adr | Removes the INM address of a CC message destination node from cc_to. |
open | Overrides MessageChannel.open. |
close | Overrides MessageChannel.close. |
get_selector_keys | Returns all selector keys obtained by calling the get_selector_keys methods of the channels in recv_channels. |
set_timeout | Overrides MessageChannel.set_timeout. |
send | Implements MessageChannel.send. |
recv | Implements MessageChannel.recv. |
route | Attempts to receive and then route an INM message. |
TIMEOUT_DIVISOR = 10.0
If a receive timeout is set on a RoutingMessageChannel, the timeout set on each of the recv_channels will be the primary timeout divided by TIMEOUT_DIVISOR times the number of receive channels.
DEFAULT_CH_TIMEOUT = get_timedelta( musecs = 10000 )
If no receive timeout is set on a RoutingMessageChannel, then the timeout set on each of the recv_channels will be DEFAULT_CH_TIMEOUT.
NOTE: Setting a timeout on the receive channels even when there is no timeout on the RoutingMessageChannel itself prevents recv from blocking forever on one receive channel while another receive channel has data available.
def __init__( self, srcadr, rtab, recv_channels, timeout = None, msg_factory = None, selector = None, ch_num = None )
Instance initializer.
srcadr | INM address of the local node. Will be placed in the source address header field of sent messages for which no other source address is provided. |
rtab | A routing table. Used to initialize the rtab attribute, see that entry for more information. |
recv_channels | A receive channel table. Used to initialize the recv_channels attribute, see that entry for more information. |
timeout | Receive timeout. MUST be an instance of the standard library class datetime.timedelta. If this parameter is None, receive operations will never time out. |
msg_factory | The MessageFactory that the RoutingMessageChannel should use to create INM Message objects. If this parameter is None, a default MessageFactory will be used. |
selector | A selector object compatible with the ones provided by the standard library module selectors. This parameter is passed on to MessageChannel.__init__, see that entry for for more information. |
ch_num | Channel number of the RoutingMessageChannel. SHOULD be either None or a nonnegative integer. |
self.rtab
The routing table. MUST be a dictionary that maps INM destination node addresses to lists of link address pairs. Each link address pair MUST consist of a MessageChannel for outgoing messages to the destination node and a channel-specific link address to use when sending messages on the outgoing message channel.
self.recv_channels
The receive channel table. MUST be a dictionary that maps channel numbers to MessageChannels for incoming messages.
self.cc_to
List of INM node addresses of CC message destinations. SHOULD be updated via add_cc_adr and remove_cc_adr.
Any CC destination node on this list will be sent a copy of each non-broadcast, non-CC message sent by this RoutingMessageChannel (sent messages include both routed messages and messages sent from the local node), unless the CC destination is the source of the message.
self.close_recv_channels
If this is true, all channels in recv_channels are closed when this RoutingMessageChannel is closed. Default: True
def open( self )
Overrides MessageChannel.open.
def close( self )
Overrides MessageChannel.close.
def get_selector_keys( self )
Returns all selector keys obtained by calling the get_selector_keys methods of the channels in recv_channels. Overrides MessageChannel.get_selector_keys.
def set_timeout( self, timeout )
Overrides MessageChannel.set_timeout.
def send( self, dstadr, msg, msg_id = None, srcadr = None, link_adr = None, in_link_adr = None, envelope_dstadr = None, send_cc = True )
Implements MessageChannel.send. Adds a few more some optional parameters.
dstadr | Destination INM node address of the message to send. |
msg | The INM Message to send. |
msg_id | INM message ID. If this is None, a message ID will be generated internally. |
srcadr | Source INM node address of the message to send. If this is None, the value of MessageChannel.srcadr will be used. |
link_adr | INM link address to use when sending the message. If this is None, the dstadr argument will be used to look up a link address in rtab. |
in_link_adr | Optional link address via which routed message msg was received. |
envelope_dstadr | Optional INM address that will be sent in the on-wire destination address header field, but NOT used to look up the destination node in rtab (the dstadr argument will be used for that). This parameter is used when sending CC messages, since the original destination address might be of interest to the CC target. |
send_cc | If this is false, no CC message copies of msg will be sent. |
A ResultCode indicating the outcome of the attempted send operation.
def recv( self )
Implements MessageChannel.recv.
def route( self )
Attempts to receive and then route an INM message.
delivery_flag | True if and only if the local node is an INM destination of the received message (as the unicast destination or as receiver of a broadcast message). |
res | A ResultCode indicating the outcome of the attempted route operation. |
header | The MessageHeader of the received message, or None in case of failure. |
msg | The received Message, or None in case of failure. |
link_adr | The link address of the received message, or None in case of failure. |
class BinaryMessageChannel( MessageChannel )
Abstract parent class for MessageChannels that send and receive INM messages encoded in the standard binary on-wire format.
def __init__( self, srcadr, timeout = None, msg_factory = None, selector = None, ch_num = None, send_bfr_size = 0, recv_bfr_size = 0 )
Instance initializer.
srcadr | INM address of the local node. Will be placed in the source address header field of sent messages for which no other source address is provided. |
timeout | Receive timeout. MUST be an instance of the standard library class datetime.timedelta. If this parameter is None, receive operations will never time out. |
msg_factory | The MessageFactory that the BinaryMessageChannel should use to create INM Message objects. If this parameter is None, a default MessageFactory will be used. |
selector | A selector object compatible with the ones provided by the standard library module selectors. This parameter is passed on to MessageChannel.__init__, see that entry for for more information. |
ch_num | Channel number of the BinaryMessageChannel. SHOULD be either None or a nonnegative integer. |
send_bfr_size | Initial capacity in bytes of the send buffer. |
recv_bfr_size | Initial capacity in bytes of the receive buffer. |
class InetMessageChannel( BinaryMessageChannel )
A BinaryMessageChannel that sends and receives messages via a UDP socket.
Variables | |
DEFAULT_IP_ADR | Default IP socket address. |
DEFAULT_UDP_PORT | Default port number of UDP socket. |
DEFAULT_TCP_PORT | Default port number of TCP socket. |
MAX_DATAGRAM_SIZE | Maximum size of sent UDP datagrams. |
Functions and Properties | |
__init__ | Instance initializer. |
ip_adr | IP address of sockets used by this InetMessageChannel, as a hostname or dotted-decimal string. |
udp_port | Port number of UDP socket used by this InetMessageChannel. |
tcp_port | Port number of TCP socket used by this InetMessageChannel. |
__str__ | String conversion. |
open | Overrides MessageChannel.open. |
close | Overrides MessageChannel.close. |
get_selector_keys | Returns the selector key of the UDP socket. |
set_timeout | Overrides MessageChannel.set_timeout. |
send | Implements MessageChannel.send. |
recv | Implements MessageChannel.recv. |
def __init__( self, srcadr, ip_adr = None, udp_port = None, tcp_port = None, timeout = None, msg_factory = None, selector = None, ch_num = None )
Instance initializer.
srcadr | INM address of the local node. Will be placed in the source address header field of sent messages for which no other source address is provided. |
ip_adr | IP address of sockets created by the InetMessageChannel. Specify the address as a hostname or dotted-decimal string. If this parameter is None, the value of DEFAULT_IP_ADR will be used. |
udp_port | Port number of UDP socket created by the InetMessageChannel. If this parameter is None or zero, the value of DEFAULT_UDP_PORT will be used. |
tcp_port | Port number of TCP socket created by the InetMessageChannel. If this parameter is None or zero, the value of DEFAULT_TCP_PORT will be used. |
timeout | Receive timeout. MUST be an instance of the standard library class datetime.timedelta. If this parameter is None, receive operations will never time out. |
msg_factory | The MessageFactory that the InetMessageChannel should use to create INM Message objects. If this parameter is None, a default MessageFactory will be used. |
selector | A selector object compatible with the ones provided by the standard library module selectors. This parameter is passed on to MessageChannel.__init__, see that entry for for more information. |
ch_num | Channel number of the InetMessageChannel. SHOULD be either None or a nonnegative integer. |
def __str__( self )
String conversion. Overrides MessageChannel.__str__.
A string representation of this InetMessageChannel, in the format “class_name(srcadr, ip_adr, udp_port)”.
def open( self )
Overrides MessageChannel.open.
def close( self )
Overrides MessageChannel.close.
def get_selector_keys( self )
Returns the selector key of the UDP socket. Overrides MessageChannel.get_selector_keys.
def set_timeout( self, timeout )
Overrides MessageChannel.set_timeout.
def send( self, dstadr, msg, msg_id = None, srcadr = None, link_adr = None )
Implements MessageChannel.send.
def recv( self )
Implements MessageChannel.recv.
class SerialMessageChannel( BinaryMessageChannel )
A BinaryMessageChannel that sends and receives messages via a serial port.
Variables | |
DEFAULT_BAUDRATE | Default baud rate to set on the opened serial port. |
N_HEADER_BYTES | Total size of the header, type and length fields of an INM message. |
MAX_MESSAGE_LEN | Maximum supported INM message (value) length. |
TIMEOUT_DIVISOR | If a receive timeout is set on a SerialMessageChannel, the timeout set for each attempt to read data from the underlying serial port API will be the primary timeout divided by TIMEOUT_DIVISOR. |
Functions and Properties | |
__init__ | Instance initializer. |
port | Filesystem path of the used serial port device. |
baudrate | Baud rate to open the used serial port at. |
__str__ | String conversion. |
open | Overrides MessageChannel.open. |
close | Overrides MessageChannel.close. |
get_selector_keys | Returns the selector key of the serial port device. |
set_timeout | Overrides MessageChannel.set_timeout. |
send | Implements MessageChannel.send. |
recv | Implements MessageChannel.recv. |
TIMEOUT_DIVISOR = 10.0
If a receive timeout is set on a SerialMessageChannel, the timeout set for each attempt to read data from the underlying serial port API will be the primary timeout divided by TIMEOUT_DIVISOR. This is done because several reads may be needed to obtain a complete message, so if the primary timeout was used for each read, there could be significant overshoot.
def __init__( self, srcadr, port, baudrate = None, timeout = None, msg_factory = None, selector = None, ch_num = None )
Instance initializer.
srcadr | INM address of the local node. Will be placed in the source address header field of sent messages for which no other source address is provided. |
port | Filesystem path of the serial port device to open. |
baudrate | Baud rate to open the serial port at. If this parameter is None, the value of DEFAULT_BAUDRATE will be used. |
timeout | Receive timeout. MUST be an instance of the standard library class datetime.timedelta. If this parameter is None, receive operations will never time out. |
msg_factory | The MessageFactory that the SerialMessageChannel should use to create INM Message objects. If this parameter is None, a default MessageFactory will be used. |
selector | A selector object compatible with the ones provided by the standard library module selectors. This parameter is passed on to MessageChannel.__init__, see that entry for for more information. |
ch_num | Channel number of the SerialMessageChannel. SHOULD be either None or a nonnegative integer. |
def __str__( self )
String conversion. Overrides MessageChannel.__str__.
A string representation of this SerialMessageChannel, in the format “class_name(srcadr, port)”.
def open( self )
Overrides MessageChannel.open.
def close( self )
Overrides MessageChannel.close.
def get_selector_keys( self )
Returns the selector key of the serial port device. Overrides MessageChannel.get_selector_keys.
def set_timeout( self, timeout )
Overrides MessageChannel.set_timeout.
def send( self, dstadr, msg, msg_id = None, srcadr = None, link_adr = None )
Implements MessageChannel.send.
def recv( self )
Implements MessageChannel.recv.
A datetime.timedelta representing a zero duration.
ZERO_DURATION = datetime.timedelta( )
Produces a datetime.datetime representing the current local time.
get_timestamp = datetime.datetime.now
Produces a datetime.timedelta with a specified duration.
def get_timedelta( secs = 0, musecs = 0 )
Produces a hexadecimal string representation of a bytes object.
def bytes_to_hex( bs, sep = None, bytes_per_sep = 1, big_endian = False )
Produces a binary string representation of a bytes object.
def bytes_to_bin( bs, sep = None, bytes_per_sep = 1, big_endian = False )
Searches an enum class for a member with a specified integer value.
def map_enum( enum_class, i, defval = None )
Provides a standard way to represent INM communication events as strings.
def format_msg_info( obj, event = None, header = None, link_adr = None, event_colw = 0, timestamp = False )
Instances of subclasses of this abstract class represent INM messages.
class Message
Size in bytes of the message type identifier field in an INM message.
MESSAGE_TYP_SIZE = 1
Instance initializer.
def __init__( self, typ, val )
Message type identifier.
self.typ
Message value/payload.
self.val
Message (value) length.
def __len__( self )
String conversion.
def __str__( self )
String representation.
def __repr__( self )
Message type and length check predicate.
def check_tl( self, typ, length )
Applies string formatting to the INM message type and value.
def format_str( self, formatter = None )
Applies formatting to the INM message type and value.
def format( self, formatter = None, conv = None )
Applies formatting to the INM message type.
def format_type( self, formatter = None )
Applies string formatting to the INM message value.
def format_val_str( self, formatter = None )
Applies formatting to the INM message value.
def format_val( self, formatter = None, conv = None )
Applies multipart formatting to the INM message value.
def format_mval( self, formatter = None, conv = None, size = None, n_vals = None, strict = None )
Applies multipart formatting to the INM message value, but returns only the first field.
def format_mval_0( self, formatter = None, conv = None, size = None, n_vals = None, strict = None )
Converts the Message to a bytes object containing the message in standard binary on-wire format.
def to_bytes( self, formatter = None )
Concrete Message subclass for standard-size INM messages.
class StandardMessage( Message )
Size in bytes of the message length field in a standard INM message.
MESSAGE_LEN_SIZE = 1
Minimum size in bytes of a standard INM message.
MIN_MESSAGE_SIZE = Message.MESSAGE_TYP_SIZE + MESSAGE_LEN_SIZE
Smallest valid message type identifier for standard INM messages.
MIN_TYPE_NUM = 0x00
Largest valid message type identifier for standard INM messages.
MAX_TYPE_NUM = 0x7f
Maximum value of the message length field in a standard INM message, and thereby also the maximum size in bytes of a standard message value field.
MAX_MESSAGE_LEN = 0xff
Type identifier reserved for INM protocol messages.
PROTOCOL_TYPE_NUM = MAX_TYPE_NUM
Concrete Message subclass for large-size INM messages.
class LargeMessage( Message )
Size in bytes of the message length field in a large INM message.
MESSAGE_LEN_SIZE = 4
Minimum size in bytes of a large INM message.
MIN_MESSAGE_SIZE = Message.MESSAGE_TYP_SIZE + MESSAGE_LEN_SIZE
Smallest valid message type identifier for large INM messages.
MIN_TYPE_NUM = 0x80
Largest valid message type identifier for large INM messages.
MAX_TYPE_NUM = 0xff
Maximum value of the message length field in a large INM message, and thereby also the maximum size in bytes of a large message value field.
MAX_MESSAGE_LEN = 0xffffffff
A configurable factory class for INM messages.
class MessageFactory
Name of attribute to use for custom conversion of objects into INM message values/payloads.
MAKE_VAL_ATTR_NAME = 'to_inm_val'
Default message types for result code enum conversion.
DEFAULT_RES_ENUM_MSG_TYPES = ( StandardTypes.RESULT, StandardTypes.INM_RESULT )
Default message types for register identifier enum conversion.
DEFAULT_REG_ENUM_MSG_TYPES = ( StandardTypes.REG_READ, StandardTypes.REG_READ_RES, StandardTypes.INM_REG_READ_RES, StandardTypes.REG_WRITE, StandardTypes.REG_TOGGLE, StandardTypes.REG_RW_EXCH, StandardTypes.REG_WR_EXCH, StandardTypes.REGPAIR_READ, StandardTypes.REGPAIR_READ_RES, StandardTypes.INM_REGPAIR_READ_RES, StandardTypes.REGPAIR_WRITE, StandardTypes.REGPAIR_TOGGLE, StandardTypes.REGPAIR_RW_EXCH, StandardTypes.REGPAIR_WR_EXCH )
Instance initializer.
def __init__( self, default_type_mappings = True )
If true, strings will be interpreted as sequences of hexadecimal digits (instead of text) when making message values.
self.make_val_hex_str
Name of text encoding to use when making and formatting message values.
self.str_encoding
Default size in bytes of integer fields in message values.
self.int_size
Name of default byte order of integer fields in message values.
self.int_byteorder
Byte group separator for message values formatted as hex or binary strings.
self.byte_sep
Byte group size for message values formatted as hex or binary strings.
self.bytes_per_sep
Byte order selector for message values formatted as hex or binary strings.
self.byte_str_big_endian
Default conversion for formatted message values.
self.default_val_conv
Conversion for string-formatted message values.
self.str_val_conv
If true, fields known to contain result codes or message type or register identifiers will be converted to the corresponding enum members (from type_enum_class or res_enum_class) when formatting message values.
self.enum_format_val
Enum class to use for conversion of message type identifiers.
self.type_enum_class
Enum class to use for conversion of INM result codes.
self.res_enum_class
Message types to perform result code enum conversion on.
self.res_enum_msg_types
Enum class to use for conversion of logical register identifiers.
self.reg_enum_class
Message types to perform register identifier enum conversion on.
self.reg_enum_msg_types
Default strictness level for multipart message value formatting.
self.default_strictness
Copies the MessageFactory.
def clone( self )
Gets the value construction integer field sizes associated with a specified message type.
def get_make_val_int_size( self, tlv_type, default = None )
Sets the value construction integer field sizes associated with a specified message type.
def set_make_val_int_size( self, tlv_type, int_size )
Gets the value formatting conversion specifier associated with a specified message type.
def get_format_val_conv( self, tlv_type, default = None )
Sets the value formatting conversion specifier associated with a specified message type.
def set_format_val_conv( self, tlv_type, conv )
Gets the value formatting field sizes associated with a specified message type.
def get_format_val_size( self, tlv_type, default = None )
Sets the value formatting field sizes associated with a specified message type.
def set_format_val_size( self, tlv_type, size )
Creates a bytes object containing an INM message value.
def make_val( self, val, int_size = None, tlv_type = None )
Creates a bytes object containing a multipart INM message value.
def make_mval( self, mval, int_size = None, tlv_type = None )
Applies string formatting to an INM message value.
def format_val_str( self, val, tlv_type = None )
Applies formatting to an INM message value.
def format_val( self, val, conv = None, tlv_type = None )
Applies multipart formatting to an INM message value.
def format_mval( self, mval, conv = None, size = None, tlv_type = None, n_vals = None, strict = None )
Constructs an INM Message with the specified type and value.
def make_msg( self, typ, val, int_size = None )
Constructs an INM Message with the specified type and multipart value.
def make_msg_mval( self, typ, mval, int_size = None )
Constructs a large INM Message with the specified type and value.
def make_large_msg( self, typ, val, int_size = None )
Constructs a large INM Message with the specified type and multipart value.
def make_large_msg_mval( self, typ, mval, int_size = None )
Converts a Message and MessageHeader to a bytes object containing the message and header in standard binary on-wire format.
def msg_to_bytes( self, msg, header = None )
Represents the header of an INM message.
class MessageHeader
Size in bytes of the message identifier field in an INM message header.
MESSAGE_ID_SIZE = 2
Size in bytes of the destination address field in an INM message header.
DSTADR_SIZE = 1
Size in bytes of the source address field in an INM message header.
SRCADR_SIZE = 1
Size in bytes of a complete INM message header.
HEADER_SIZE = MESSAGE_ID_SIZE + DSTADR_SIZE + SRCADR_SIZE
Largest valid INM message identifier.
MAX_MESSAGE_ID = 0xffff
Largest valid INM node address.
MAX_MESSAGE_ADR = 0xff
Reserved INM node address for the local node.
LOCAL_ADR = 0x00
Reserved INM node address for broadcast messages.
BROADCAST_ADR = MAX_MESSAGE_ADR
Instance initializer.
def __init__( self, msg_id, dstadr, srcadr )
INM message identifier.
self.msg_id
Destination INM node address.
self.dstadr
Source INM node address.
self.srcadr
String conversion.
def __str__( self )
String representation.
def __repr__( self )
Converts the MessageHeader to a bytes object containing the header in standard binary on-wire format.
def to_bytes( self, formatter = None )
A default instance of MessageFactory.
default_msg_factory = MessageFactory()
Exception class for MessageChannels.
class MessageChannelError( Exception )
Abstract parent class for objects that send and receive INM messages.
class MessageChannel
If this is true, a default selector object (from the standard library module selectors) will be created for each instance of MessageChannel that isn’t provided with a custom selector at initialization.
make_default_selector = True
Instance initializer.
def __init__( self, srcadr, timeout = None, msg_factory = None, selector = None, ch_num = None )
Default INM source address of messages sent via this MessageChannel.
self.srcadr
Receive timeout.
self.timeout
The MessageFactory that the MessageChannel uses to create INM Message objects.
self.msg_factory
A selector object compatible with the ones provided by the standard library module selectors.
self.selector
Channel number of this MessageChannel.
self.ch_num
String conversion.
def __str__( self )
String representation.
def __repr__( self )
Peeks at the most recently auto-generated INM message ID.
def peek_prev_msg_id( self )
Peeks at the next INM message ID to be auto-generated.
def peek_next_msg_id( self )
Auto-generates an INM message ID.
def get_next_msg_id( self )
Checks whether the MessageChannel is open.
def is_open( self )
Opens the MessageChannel.
def open( self )
Closes the MessageChannel.
def close( self )
Checks whether the MessageChannel is readable.
def readable( self )
Gets the selector keys of encapsulated selectable objects from this MessageChannel.
def get_selector_keys( self )
Updates the timeout attribute.
def set_timeout( self, timeout )
Sends an INM message.
def send( self, dstadr, msg, msg_id = None, srcadr = None, link_adr = None )
Attempts to receive an INM message.
def recv( self )
A MessageChannel with message routing functionality.
class RoutingMessageChannel( MessageChannel )
If a receive timeout is set on a RoutingMessageChannel, the timeout set on each of the recv_channels will be the primary timeout divided by TIMEOUT_DIVISOR times the number of receive channels.
TIMEOUT_DIVISOR = 10.0
The receive channel table.
self.recv_channels
If no receive timeout is set on a RoutingMessageChannel, then the timeout set on each of the recv_channels will be DEFAULT_CH_TIMEOUT.
DEFAULT_CH_TIMEOUT = get_timedelta( musecs = 10000 )
Instance initializer.
def __init__( self, srcadr, rtab, recv_channels, timeout = None, msg_factory = None, selector = None, ch_num = None )
The routing table.
self.rtab
List of INM node addresses of CC message destinations.
self.cc_to
If this is true, all channels in recv_channels are closed when this RoutingMessageChannel is closed.
self.close_recv_channels
If this is true, routing is applied even to messages where the destination address equals the source address of the local node.
self.relay_messages
Adds the INM address of a CC message destination node to cc_to.
def add_cc_adr( self, cc_adr )
Removes the INM address of a CC message destination node from cc_to.
def remove_cc_adr( self, cc_adr )
Overrides MessageChannel.open.
def open( self )
Overrides MessageChannel.close.
def close( self )
Returns all selector keys obtained by calling the get_selector_keys methods of the channels in recv_channels.
def get_selector_keys( self )
Overrides MessageChannel.set_timeout.
def set_timeout( self, timeout )
Implements MessageChannel.send.
def send( self, dstadr, msg, msg_id = None, srcadr = None, link_adr = None, in_link_adr = None, envelope_dstadr = None, send_cc = True )
Implements MessageChannel.recv.
def recv( self )
Attempts to receive and then route an INM message.
def route( self )
Abstract parent class for MessageChannels that send and receive INM messages encoded in the standard binary on-wire format.
class BinaryMessageChannel( MessageChannel )
Instance initializer.
def __init__( self, srcadr, timeout = None, msg_factory = None, selector = None, ch_num = None, send_bfr_size = 0, recv_bfr_size = 0 )
A BinaryMessageChannel that sends and receives messages via a UDP socket.
class InetMessageChannel( BinaryMessageChannel )
Default IP socket address.
DEFAULT_IP_ADR = '127.0.0.1'
Default port number of UDP socket.
DEFAULT_UDP_PORT = 2357
Default port number of TCP socket.
DEFAULT_TCP_PORT = 2357
Maximum size of sent UDP datagrams.
MAX_DATAGRAM_SIZE = 0xffff
Instance initializer.
def __init__( self, srcadr, ip_adr = None, udp_port = None, tcp_port = None, timeout = None, msg_factory = None, selector = None, ch_num = None )
IP address of sockets used by this InetMessageChannel, as a hostname or dotted-decimal string.
self.ip_adr
Port number of UDP socket used by this InetMessageChannel.
self.udp_port
Port number of TCP socket used by this InetMessageChannel.
self.tcp_port
String conversion.
def __str__( self )
Overrides MessageChannel.open.
def open( self )
Overrides MessageChannel.close.
def close( self )
Returns the selector key of the UDP socket.
def get_selector_keys( self )
Overrides MessageChannel.set_timeout.
def set_timeout( self, timeout )
Implements MessageChannel.send.
def send( self, dstadr, msg, msg_id = None, srcadr = None, link_adr = None )
Implements MessageChannel.recv.
def recv( self )
A BinaryMessageChannel that sends and receives messages via a serial port.
class SerialMessageChannel( BinaryMessageChannel )
Default baud rate to set on the opened serial port.
DEFAULT_BAUDRATE = 38400
Total size of the header, type and length fields of an INM message.
N_HEADER_BYTES = MessageHeader.HEADER_SIZE + StandardMessage.MIN_MESSAGE_SIZE
Maximum supported INM message (value) length.
MAX_MESSAGE_LEN = 0xff - N_HEADER_BYTES
If a receive timeout is set on a SerialMessageChannel, the timeout set for each attempt to read data from the underlying serial port API will be the primary timeout divided by TIMEOUT_DIVISOR.
TIMEOUT_DIVISOR = 10.0
Instance initializer.
def __init__( self, srcadr, port, baudrate = None, timeout = None, msg_factory = None, selector = None, ch_num = None )
Filesystem path of the used serial port device.
self.port
Baud rate to open the used serial port at.
self.baudrate
String conversion.
def __str__( self )
Overrides MessageChannel.open.
def open( self )
Overrides MessageChannel.close.
def close( self )
Returns the selector key of the serial port device.
def get_selector_keys( self )
Overrides MessageChannel.set_timeout.
def set_timeout( self, timeout )
Implements MessageChannel.send.
def send( self, dstadr, msg, msg_id = None, srcadr = None, link_adr = None )
Implements MessageChannel.recv.
def recv( self )
Convenience class for INM communication.
class InmHelper