inm.py

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.

Summary
inm.pyThe inm module provides a complete INM messaging API.
General Utilities
Variables
ZERO_DURATIONA datetime.timedelta representing a zero duration.
get_timestampProduces a datetime.datetime representing the current local time.
Functions
get_timedeltaProduces a datetime.timedelta with a specified duration.
bytes_to_hexProduces a hexadecimal string representation of a bytes object.
bytes_to_binProduces a binary string representation of a bytes object.
map_enumSearches an enum class for a member with a specified integer value.
format_msg_infoProvides a standard way to represent INM communication events as strings.
Enum Types
Enumerations
StandardTypesStandard INM message types.
StandardResultsStandard INM result codes.
StandardRegistersStandard INM register identifiers.
ResultCodeResult codes for the INM module.
ValueConversionsType conversion specifiers for INM message values.
StrictnessMultipart formatting strictness specifiers for INM message values.
Messages and Message Processing
MessageInstances of subclasses of this abstract class represent INM messages.
Variables
MESSAGE_TYP_SIZESize in bytes of the message type identifier field in an INM message.
Functions and Properties
__init__Instance initializer.
typMessage type identifier.
valMessage value/payload.
__len__Message (value) length.
__str__String conversion.
__repr__String representation.
check_tlMessage type and length check predicate.
format_strApplies string formatting to the INM message type and value.
formatApplies formatting to the INM message type and value.
format_typeApplies formatting to the INM message type.
format_val_strApplies string formatting to the INM message value.
format_valApplies formatting to the INM message value.
format_mvalApplies multipart formatting to the INM message value.
format_mval_0Applies multipart formatting to the INM message value, but returns only the first field.
to_bytesConverts the Message to a bytes object containing the message in standard binary on-wire format.
StandardMessageConcrete Message subclass for standard-size INM messages.
Variables
MESSAGE_LEN_SIZESize in bytes of the message length field in a standard INM message.
MIN_MESSAGE_SIZEMinimum size in bytes of a standard INM message.
MIN_TYPE_NUMSmallest valid message type identifier for standard INM messages.
MAX_TYPE_NUMLargest valid message type identifier for standard INM messages.
MAX_MESSAGE_LENMaximum 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_NUMType identifier reserved for INM protocol messages.
LargeMessageConcrete Message subclass for large-size INM messages.
Variables
MESSAGE_LEN_SIZESize in bytes of the message length field in a large INM message.
MIN_MESSAGE_SIZEMinimum size in bytes of a large INM message.
MIN_TYPE_NUMSmallest valid message type identifier for large INM messages.
MAX_TYPE_NUMLargest valid message type identifier for large INM messages.
MAX_MESSAGE_LENMaximum 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.
MessageFactoryA configurable factory class for INM messages.
Variables
MAKE_VAL_ATTR_NAMEName of attribute to use for custom conversion of objects into INM message values/payloads.
DEFAULT_RES_ENUM_MSG_TYPESDefault message types for result code enum conversion.
DEFAULT_REG_ENUM_MSG_TYPESDefault message types for register identifier enum conversion.
Functions
__init__Instance initializer.
Properties
make_val_hex_strIf true, strings will be interpreted as sequences of hexadecimal digits (instead of text) when making message values.
str_encodingName of text encoding to use when making and formatting message values.
int_sizeDefault size in bytes of integer fields in message values.
int_byteorderName of default byte order of integer fields in message values.
byte_sepByte group separator for message values formatted as hex or binary strings.
bytes_per_sepByte group size for message values formatted as hex or binary strings.
byte_str_big_endianByte order selector for message values formatted as hex or binary strings.
default_val_convDefault conversion for formatted message values.
str_val_convConversion for string-formatted message values.
enum_format_valIf 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_classEnum class to use for conversion of message type identifiers.
res_enum_classEnum class to use for conversion of INM result codes.
res_enum_msg_typesMessage types to perform result code enum conversion on.
reg_enum_classEnum class to use for conversion of logical register identifiers.
reg_enum_msg_typesMessage types to perform register identifier enum conversion on.
default_strictnessDefault strictness level for multipart message value formatting.
Functions
cloneCopies the MessageFactory.
get_make_val_int_sizeGets the value construction integer field sizes associated with a specified message type.
set_make_val_int_sizeSets the value construction integer field sizes associated with a specified message type.
get_format_val_convGets the value formatting conversion specifier associated with a specified message type.
set_format_val_convSets the value formatting conversion specifier associated with a specified message type.
get_format_val_sizeGets the value formatting field sizes associated with a specified message type.
set_format_val_sizeSets the value formatting field sizes associated with a specified message type.
make_valCreates a bytes object containing an INM message value.
make_mvalCreates a bytes object containing a multipart INM message value.
format_val_strApplies string formatting to an INM message value.
format_valApplies formatting to an INM message value.
format_mvalApplies multipart formatting to an INM message value.
make_msgConstructs an INM Message with the specified type and value.
make_msg_mvalConstructs an INM Message with the specified type and multipart value.
make_large_msgConstructs a large INM Message with the specified type and value.
make_large_msg_mvalConstructs a large INM Message with the specified type and multipart value.
msg_to_bytesConverts a Message and MessageHeader to a bytes object containing the message and header in standard binary on-wire format.
MessageHeaderRepresents the header of an INM message.
Variables
MESSAGE_ID_SIZESize in bytes of the message identifier field in an INM message header.
DSTADR_SIZESize in bytes of the destination address field in an INM message header.
SRCADR_SIZESize in bytes of the source address field in an INM message header.
HEADER_SIZESize in bytes of a complete INM message header.
MAX_MESSAGE_IDLargest valid INM message identifier.
MAX_MESSAGE_ADRLargest valid INM node address.
LOCAL_ADRReserved INM node address for the local node.
BROADCAST_ADRReserved INM node address for broadcast messages.
Functions and Properties
__init__Instance initializer.
msg_idINM message identifier.
dstadrDestination INM node address.
srcadrSource INM node address.
__str__String conversion.
__repr__String representation.
to_bytesConverts the MessageHeader to a bytes object containing the header in standard binary on-wire format.
Default Objects
Variables
default_msg_factoryA default instance of MessageFactory.
Message Channels
MessageChannelErrorException class for MessageChannels.
MessageChannelAbstract parent class for objects that send and receive INM messages.
Variables
make_default_selectorIf 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
srcadrDefault INM source address of messages sent via this MessageChannel.
timeoutReceive timeout.
msg_factoryThe MessageFactory that the MessageChannel uses to create INM Message objects.
selectorA selector object compatible with the ones provided by the standard library module selectors.
ch_numChannel number of this MessageChannel.
Functions
__str__String conversion.
__repr__String representation.
peek_prev_msg_idPeeks at the most recently auto-generated INM message ID.
peek_next_msg_idPeeks at the next INM message ID to be auto-generated.
get_next_msg_idAuto-generates an INM message ID.
is_openChecks whether the MessageChannel is open.
openOpens the MessageChannel.
closeCloses the MessageChannel.
readableChecks whether the MessageChannel is readable.
get_selector_keysGets the selector keys of encapsulated selectable objects from this MessageChannel.
set_timeoutUpdates the timeout attribute.
sendSends an INM message.
recvAttempts to receive an INM message.
RoutingMessageChannelA MessageChannel with message routing functionality.
Variables
TIMEOUT_DIVISORIf 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_TIMEOUTIf 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
rtabThe routing table.
recv_channelsThe receive channel table.
cc_toList of INM node addresses of CC message destinations.
close_recv_channelsIf this is true, all channels in recv_channels are closed when this RoutingMessageChannel is closed.
relay_messagesIf this is true, routing is applied even to messages where the destination address equals the source address of the local node.
Functions
add_cc_adrAdds the INM address of a CC message destination node to cc_to.
remove_cc_adrRemoves the INM address of a CC message destination node from cc_to.
openOverrides MessageChannel.open.
closeOverrides MessageChannel.close.
get_selector_keysReturns all selector keys obtained by calling the get_selector_keys methods of the channels in recv_channels.
set_timeoutOverrides MessageChannel.set_timeout.
sendImplements MessageChannel.send.
recvImplements MessageChannel.recv.
routeAttempts to receive and then route an INM message.
BinaryMessageChannelAbstract parent class for MessageChannels that send and receive INM messages encoded in the standard binary on-wire format.
Functions
__init__Instance initializer.
InetMessageChannelA BinaryMessageChannel that sends and receives messages via a UDP socket.
Variables
DEFAULT_IP_ADRDefault IP socket address.
DEFAULT_UDP_PORTDefault port number of UDP socket.
DEFAULT_TCP_PORTDefault port number of TCP socket.
MAX_DATAGRAM_SIZEMaximum size of sent UDP datagrams.
Functions and Properties
__init__Instance initializer.
ip_adrIP address of sockets used by this InetMessageChannel, as a hostname or dotted-decimal string.
udp_portPort number of UDP socket used by this InetMessageChannel.
tcp_portPort number of TCP socket used by this InetMessageChannel.
__str__String conversion.
openOverrides MessageChannel.open.
closeOverrides MessageChannel.close.
get_selector_keysReturns the selector key of the UDP socket.
set_timeoutOverrides MessageChannel.set_timeout.
sendImplements MessageChannel.send.
recvImplements MessageChannel.recv.
SerialMessageChannelA BinaryMessageChannel that sends and receives messages via a serial port.
Variables
DEFAULT_BAUDRATEDefault baud rate to set on the opened serial port.
N_HEADER_BYTESTotal size of the header, type and length fields of an INM message.
MAX_MESSAGE_LENMaximum supported INM message (value) length.
TIMEOUT_DIVISORIf 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.
portFilesystem path of the used serial port device.
baudrateBaud rate to open the used serial port at.
__str__String conversion.
openOverrides MessageChannel.open.
closeOverrides MessageChannel.close.
get_selector_keysReturns the selector key of the serial port device.
set_timeoutOverrides MessageChannel.set_timeout.
sendImplements MessageChannel.send.
recvImplements MessageChannel.recv.

General Utilities

Summary
Variables
ZERO_DURATIONA datetime.timedelta representing a zero duration.
get_timestampProduces a datetime.datetime representing the current local time.
Functions
get_timedeltaProduces a datetime.timedelta with a specified duration.
bytes_to_hexProduces a hexadecimal string representation of a bytes object.
bytes_to_binProduces a binary string representation of a bytes object.
map_enumSearches an enum class for a member with a specified integer value.
format_msg_infoProvides a standard way to represent INM communication events as strings.

Variables

ZERO_DURATION

ZERO_DURATION = datetime.timedelta()

A datetime.timedelta representing a zero duration.

get_timestamp

get_timestamp = datetime.datetime.now

Produces a datetime.datetime representing the current local time.  Alias of the standard library method datetime.datetime.now.

Functions

get_timedelta

def get_timedelta(secs = 0,
musecs = 0)

Produces a datetime.timedelta with a specified duration.

Parameters

secsAn integer or float representing a number of seconds.
musecsAn integer or float representing a number of microseconds.

Returns

A datetime.timedelta representing a duration of (secs + musecs/1000000) seconds.

bytes_to_hex

def bytes_to_hex(bs,  
sep = None,
bytes_per_sep = 1,
big_endian = False)

Produces a hexadecimal string representation of a bytes object.

Parameters

bsA bytes object.
sepGroup separator.  Either None or a one-character string.
bytes_per_sepGroup size.
big_endianIf 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.).

Returns

A hexadecimal string representation of bs.  No prefix is included.

bytes_to_bin

def bytes_to_bin(bs,  
sep = None,
bytes_per_sep = 1,
big_endian = False)

Produces a binary string representation of a bytes object.

Parameters

bsA bytes object.
sepGroup separator.  Either None or a one-character string.
bytes_per_sepGroup size.
big_endianIf 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.).

Returns

A binary string representation of bs.  No prefix is included.

map_enum

def map_enum(enum_class,  
i,  
defval = None)

Searches an enum class for a member with a specified integer value.

Parameters

enum_classAn enum class.
iAn integer.
defvalDefault return value.

Returns

If a member with integer value i is found in enum_class, then that member is returned.  Otherwise, defval is returned.

format_msg_info

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.

Parameters

objAn object describing some event of interest (e.g. a Message).
eventAn optional string identifying the type of event (e.g.  ‘RECV’).
headerAn optional MessageHeader.
link_adrAn optional INM link address (e.g. an (ip_adr, udp_port) pair).
event_colwMinimum width of the event column.
timestampIf 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.

Returns

A string representation of the specified event, in the following format:

'{timestamp} {event} [{header.srcadr}.{header.msg_id} => {header.dstadr}]{link_adr}: {obj}'

Enum Types

Summary
Enumerations
StandardTypesStandard INM message types.
StandardResultsStandard INM result codes.
StandardRegistersStandard INM register identifiers.
ResultCodeResult codes for the INM module.
ValueConversionsType conversion specifiers for INM message values.
StrictnessMultipart formatting strictness specifiers for INM message values.

Enumerations

StandardTypes

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

DEFAULTDefault message type.
RESULTGeneric TLV operation response (StandardResults code).
INM_RESULTGeneric INM operation response (StandardResults code and request ID).
REG_READLogical register read request.
REG_READ_RESLogical TLV register read response.
INM_REG_READ_RESLogical INM register read response (with request ID).
REG_WRITELogical register write (R = V) request.
REG_TOGGLELogical register toggle (R ^= V; ret R) request.
REG_RW_EXCHLogical register read-write (X = R; R = V; ret X) request.
REG_WR_EXCHLogical register write-read (R = V; ret R) request.
REGPAIR_READLogical register pair read (ret R) request.
REGPAIR_READ_RESLogical TLV register pair read response.
INM_REGPAIR_READ_RESLogical INM register pair read response (with request ID).
REGPAIR_WRITELogical register pair write request.
REGPAIR_TOGGLELogical register pair toggle request.
REGPAIR_RW_EXCHLogical register pair read-write request.
REGPAIR_WR_EXCHLogical register pair write-read request.
MEMMON_DATAMemory monitor notification.  Variable-length message.
MEMMON_CTRLMemory monitor control request.  Not implemented.
APPLICATIONStart of application-specific identifier range.

StandardResults

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

OKRequest successfully handled.
TYPEError: Unrecognized message type.
LENGTHError: Invalid message length.
REGISTERError: Message specified unrecognized logical register.
NOT_IMPLEMENTEDError: Message recognized but cannot be handled.
APPLICATIONStart of application-specific result code range.
NONEInvalid result code.

StandardRegisters

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

NULLNull register.  Yeah.  (What was the idea here again?)
APP_STATUSApplication status.  Zero means normal status, other values are application-specific.
DEBUG[0-9]Registers for general temporary / debugging use.
INDEXLow index byte.  Used to specify an index in array registers.
INDEX_LAlias of INDEX.
INDEX_HHigh index byte.  Used together with INDEX_L to specify an index in large array registers.
PAIR_INDEXAlias of INDEX_L.  Intended for register pair access.
STDINStandard input stream register.
STDOUTStandard output stream register.
STDERRError/debug output stream register.
STDIOStandard I/O stream register.  Intended for exchange operations.
STDIO_LAlias of STDIO.
STDIO_HUpper half of 16-bit standard I/O stream register pair.
PAIR_STDIOAlias of STDIO_L.  Intended for register pair exchange operations.
STDIOERRError/debug I/O stream register.  Intended for exchange operations.
STDIOERR_LAlias of STDIOERR.
STDIOERR_HUpper half of 16-bit error/debug I/O stream register pair.
PAIR_STDIOERRAlias of STDIOERR_L.  Intended for register pair exchange operations.
FWIDFirmware ID, low byte.
FWID_LAlias of FWID.
FWID_HFirmware ID, high byte.
PAIR_FWIDAlias of FWID_L.  Intended for register pair access.
FWVERSIONFirmware version.
APPLICATIONStart of application-specific register identifier range.

ResultCode

Result codes for the INM module.

SUCCESSOperation successfully completed.
RECV_TIMEOUTReceive operation timed out.
RECV_FAILUREReceive operation failed in underlying API.
UNROUTABLEMessage could not be routed toward destination.
LINK_FAILUREError in underlying API.
CHANNEL_FAILUREError in underlying message channel.
INVALID_HEADERInvalid message header received or submitted for sending.
INVALID_MESSAGEInvalid message received or submitted for sending.
INVALID_ARGUMENTInvalid argument in module API function call.
INVALID_STATEModule API function call made in wrong object state.

ValueConversions

Type conversion specifiers for INM message values.

NoConvNo conversion / unspecified conversion
HexHexadecimal string (unprefixed)
BinBinary string (unprefixed)
IntInteger
StrDecoded text string
TupleTuple of byte values (as integers)
ListList of byte values (as integers)
BytesBytes object

Strictness

Multipart formatting strictness specifiers for INM message values.

AnythingAny value whatsoever is accepted.
AllWantedAll requested fields must be present.
OnlyWantedAll requested fields must be present, and only those.
ExactAll requested fields must be present, and only those, and no unparsed bytes are allowed to remain.

Messages and Message Processing

Message

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.

Summary
Variables
MESSAGE_TYP_SIZESize in bytes of the message type identifier field in an INM message.
Functions and Properties
__init__Instance initializer.
typMessage type identifier.
valMessage value/payload.
__len__Message (value) length.
__str__String conversion.
__repr__String representation.
check_tlMessage type and length check predicate.
format_strApplies string formatting to the INM message type and value.
formatApplies formatting to the INM message type and value.
format_typeApplies formatting to the INM message type.
format_val_strApplies string formatting to the INM message value.
format_valApplies formatting to the INM message value.
format_mvalApplies multipart formatting to the INM message value.
format_mval_0Applies multipart formatting to the INM message value, but returns only the first field.
to_bytesConverts the Message to a bytes object containing the message in standard binary on-wire format.

Variables

MESSAGE_TYP_SIZE

MESSAGE_TYP_SIZE = 1

Size in bytes of the message type identifier field in an INM message.

Functions and Properties

__init__

def __init__(self,
typ,
val)

Instance initializer.

Parameters

typMessage type identifier, e.g. one of the StandardTypes.
valMessage value/payload.  MUST be a bytes object.

typ

self.typ

Message type identifier.

val

self.val

Message value/payload.

__len__

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.

Returns

The INM message length, determined by the len() of the val attribute.

__str__

def __str__(self)

String conversion.

Returns

A string representation of the Message, in the format “Message(typ, len, val)”.

__repr__

def __repr__(self)

String representation.

Returns

A string representation of the Message, in the format “<Message(typ, len, val)>”.

check_tl

def check_tl(self,
typ,
length)

Message type and length check predicate.

Parameters

typRequired message type identifier.
lengthRequired minimum message length.

Returns

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.

format_str

def format_str(self,  
formatter = None)

Applies string formatting to the INM message type and value.

Parameters

formatterThe message formatter to use, or None to use the default formatter.

Returns

f_typFormatted message type.
f_valString formatted message value.

format

def format(self,  
formatter = None,
conv = None)

Applies formatting to the INM message type and value.

Parameters

formatterThe message formatter to use, or None to use the default formatter.
convMessage value conversion specifier (e.g. from ValueConversions), or None to apply the default conversion.

Returns

f_typFormatted message type.
f_valFormatted message value.

format_type

def format_type(self,  
formatter = None)

Applies formatting to the INM message type.

Parameters

formatterThe message formatter to use, or None to use the default formatter.

Returns

Formatted message type.

format_val_str

def format_val_str(self,  
formatter = None)

Applies string formatting to the INM message value.

Parameters

formatterThe message formatter to use, or None to use the default formatter.

Returns

String formatted message value.

format_val

def format_val(self,  
formatter = None,
conv = None)

Applies formatting to the INM message value.

Parameters

formatterThe message formatter to use, or None to use the default formatter.
convMessage value conversion specifier (e.g. from ValueConversions), or None to apply the default conversion.

Returns

Formatted message value.

format_mval

def format_mval(self,  
formatter = None,
conv = None,
size = None,
n_vals = None,
strict = None)

Applies multipart formatting to the INM message value.

Parameters

formatterThe message formatter to use, or None to use the default formatter.
convField 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.
sizeMultipart 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_valsMultipart value field count.  If this is None, the field count is inferred from the conv and size arguments (or their default values).
strictMultipart formatting Strictness specifier, or None to apply the default strictness level.

Returns

The formatted multipart message value (list of formatted fields), if formatting was successful.  Otherwise None.

format_mval_0

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

Parameters

formatterThe message formatter to use, or None to use the default formatter.
convField 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.
sizeMultipart 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_valsMultipart value field count.  If this is None, the field count is inferred from the conv and size arguments (or their default values).
strictMultipart formatting Strictness specifier, or None to apply the default strictness level.

Returns

The first field of the formatted multipart message value, if at least one field was successfully formatted.  Otherwise None.

to_bytes

def to_bytes(self,  
formatter = None)

Converts the Message to a bytes object containing the message in standard binary on-wire format.

Parameters

formatterFormatter to use for message type and length conversion, or None to use the default formatter.

Returns

A bytes object containing the INM message represented by this Message in standard binary on-wire format.

StandardMessage

class StandardMessage(Message)

Concrete Message subclass for standard-size INM messages.  The maximum size of a standard message value/payload is 255 bytes.

Summary
Variables
MESSAGE_LEN_SIZESize in bytes of the message length field in a standard INM message.
MIN_MESSAGE_SIZEMinimum size in bytes of a standard INM message.
MIN_TYPE_NUMSmallest valid message type identifier for standard INM messages.
MAX_TYPE_NUMLargest valid message type identifier for standard INM messages.
MAX_MESSAGE_LENMaximum 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_NUMType identifier reserved for INM protocol messages.

Variables

MESSAGE_LEN_SIZE

MESSAGE_LEN_SIZE = 1

Size in bytes of the message length field in a standard INM message.

MIN_MESSAGE_SIZE

MIN_MESSAGE_SIZE = Message.MESSAGE_TYP_SIZE + MESSAGE_LEN_SIZE

Minimum size in bytes of a standard INM message.

MIN_TYPE_NUM

MIN_TYPE_NUM = 0x00

Smallest valid message type identifier for standard INM messages.

MAX_TYPE_NUM

MAX_TYPE_NUM = 0x7f

Largest valid message type identifier for standard INM messages.

MAX_MESSAGE_LEN

MAX_MESSAGE_LEN = 0xff

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

PROTOCOL_TYPE_NUM = MAX_TYPE_NUM

Type identifier reserved for INM protocol messages.

LargeMessage

class LargeMessage(Message)

Concrete Message subclass for large-size INM messages.  The maximum size of a large message value/payload is 4294967295 bytes.

Summary
Variables
MESSAGE_LEN_SIZESize in bytes of the message length field in a large INM message.
MIN_MESSAGE_SIZEMinimum size in bytes of a large INM message.
MIN_TYPE_NUMSmallest valid message type identifier for large INM messages.
MAX_TYPE_NUMLargest valid message type identifier for large INM messages.
MAX_MESSAGE_LENMaximum 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.

Variables

MESSAGE_LEN_SIZE

MESSAGE_LEN_SIZE = 4

Size in bytes of the message length field in a large INM message.

MIN_MESSAGE_SIZE

MIN_MESSAGE_SIZE = Message.MESSAGE_TYP_SIZE + MESSAGE_LEN_SIZE

Minimum size in bytes of a large INM message.

MIN_TYPE_NUM

MIN_TYPE_NUM = 0x80

Smallest valid message type identifier for large INM messages.

MAX_TYPE_NUM

MAX_TYPE_NUM = 0xff

Largest valid message type identifier for large INM messages.

MAX_MESSAGE_LEN

MAX_MESSAGE_LEN = 0xffffffff

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

class MessageFactory

A configurable factory class for INM messages.  Provides various methods that construct and parse Message objects and INM message payloads.

Summary
Variables
MAKE_VAL_ATTR_NAMEName of attribute to use for custom conversion of objects into INM message values/payloads.
DEFAULT_RES_ENUM_MSG_TYPESDefault message types for result code enum conversion.
DEFAULT_REG_ENUM_MSG_TYPESDefault message types for register identifier enum conversion.
Functions
__init__Instance initializer.
Properties
make_val_hex_strIf true, strings will be interpreted as sequences of hexadecimal digits (instead of text) when making message values.
str_encodingName of text encoding to use when making and formatting message values.
int_sizeDefault size in bytes of integer fields in message values.
int_byteorderName of default byte order of integer fields in message values.
byte_sepByte group separator for message values formatted as hex or binary strings.
bytes_per_sepByte group size for message values formatted as hex or binary strings.
byte_str_big_endianByte order selector for message values formatted as hex or binary strings.
default_val_convDefault conversion for formatted message values.
str_val_convConversion for string-formatted message values.
enum_format_valIf 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_classEnum class to use for conversion of message type identifiers.
res_enum_classEnum class to use for conversion of INM result codes.
res_enum_msg_typesMessage types to perform result code enum conversion on.
reg_enum_classEnum class to use for conversion of logical register identifiers.
reg_enum_msg_typesMessage types to perform register identifier enum conversion on.
default_strictnessDefault strictness level for multipart message value formatting.
Functions
cloneCopies the MessageFactory.
get_make_val_int_sizeGets the value construction integer field sizes associated with a specified message type.
set_make_val_int_sizeSets the value construction integer field sizes associated with a specified message type.
get_format_val_convGets the value formatting conversion specifier associated with a specified message type.
set_format_val_convSets the value formatting conversion specifier associated with a specified message type.
get_format_val_sizeGets the value formatting field sizes associated with a specified message type.
set_format_val_sizeSets the value formatting field sizes associated with a specified message type.
make_valCreates a bytes object containing an INM message value.
make_mvalCreates a bytes object containing a multipart INM message value.
format_val_strApplies string formatting to an INM message value.
format_valApplies formatting to an INM message value.
format_mvalApplies multipart formatting to an INM message value.
make_msgConstructs an INM Message with the specified type and value.
make_msg_mvalConstructs an INM Message with the specified type and multipart value.
make_large_msgConstructs a large INM Message with the specified type and value.
make_large_msg_mvalConstructs a large INM Message with the specified type and multipart value.
msg_to_bytesConverts a Message and MessageHeader to a bytes object containing the message and header in standard binary on-wire format.

Variables

MAKE_VAL_ATTR_NAME

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:

formatterA formatter object that provides the MessageFactory API.
int_sizeThe requested size in bytes of a message value or field produced from an integer.  May be None.
tlv_typeAn INM message type specifier.  May be None.

DEFAULT_RES_ENUM_MSG_TYPES

DEFAULT_RES_ENUM_MSG_TYPES = (StandardTypes.RESULT,
StandardTypes.INM_RESULT)

Default message types for result code enum conversion.

DEFAULT_REG_ENUM_MSG_TYPES

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.

Functions

__init__

def __init__(self,  
default_type_mappings = True)

Instance initializer.

Parameters

default_type_mappingsDefault type mappings will be added to the message type lookup tables if and only if this is true.

Properties

make_val_hex_str

self.make_val_hex_str

If true, strings will be interpreted as sequences of hexadecimal digits (instead of text) when making message values.  Default: False

str_encoding

self.str_encoding

Name of text encoding to use when making and formatting message values.  Default: ‘ascii’

int_size

self.int_size

Default size in bytes of integer fields in message values.  Default: 1

int_byteorder

self.int_byteorder

Name of default byte order of integer fields in message values.  Default: ‘little’

byte_sep

self.byte_sep

Byte group separator for message values formatted as hex or binary strings.  Default: None

bytes_per_sep

self.bytes_per_sep

Byte group size for message values formatted as hex or binary strings.  Default: 2

byte_str_big_endian

self.byte_str_big_endian

Byte order selector for message values formatted as hex or binary strings.  Default: False

default_val_conv

self.default_val_conv

Default conversion for formatted message values.  Default: ValueConversions.Bytes

str_val_conv

self.str_val_conv

Conversion for string-formatted message values.  Default: ValueConversions.Hex

enum_format_val

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

type_enum_class

self.type_enum_class

Enum class to use for conversion of message type identifiers.  Default: StandardTypes

res_enum_class

self.res_enum_class

Enum class to use for conversion of INM result codes.  Default: StandardResults

res_enum_msg_types

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

reg_enum_class

self.reg_enum_class

Enum class to use for conversion of logical register identifiers.  Default: StandardRegisters

reg_enum_msg_types

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

default_strictness

self.default_strictness

Default strictness level for multipart message value formatting.  Default: Strictness.Exact

Functions

clone

def clone(self)

Copies the MessageFactory.

Returns

A new MessageFactory with the same formatting configuration as this MessageFactory.  The new object contains no reference to any mutable state of this object (i.e. subsequent changes to this object will not affect the copy, or vice versa).

get_make_val_int_size

def get_make_val_int_size(self,  
tlv_type,  
default = None)

Gets the value construction integer field sizes associated with a specified message type.

Parameters

tlv_typeAn INM message type identifier.
defaultValue to return if tlv_type is not found in the lookup table.

Returns

The value construction integer field sizes associated with tlv_type, if that type is found in the lookup table.  Otherwise default.

set_make_val_int_size

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.

Parameters

tlv_typeAn INM message type identifier.
int_sizeValue 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.

Returns

True if and only if the table entry was successfully updated or deleted.

get_format_val_conv

def get_format_val_conv(self,  
tlv_type,  
default = None)

Gets the value formatting conversion specifier associated with a specified message type.

Parameters

tlv_typeAn INM message type identifier.
defaultValue to return if tlv_type is not found in the lookup table.

Returns

The value formatting conversion specifier associated with tlv_type, if that type is found in the lookup table.  Otherwise default.

set_format_val_conv

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.

Parameters

tlv_typeAn INM message type identifier.
convValue 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.

Returns

True if and only if the table entry was successfully updated or deleted.

get_format_val_size

def get_format_val_size(self,  
tlv_type,  
default = None)

Gets the value formatting field sizes associated with a specified message type.

Parameters

tlv_typeAn INM message type identifier.
defaultValue to return if tlv_type is not found in the lookup table.

Returns

The value formatting field sizes associated with tlv_type, if that type is found in the lookup table.  Otherwise default.

set_format_val_size

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.

Parameters

tlv_typeAn INM message type identifier.
sizeValue 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.

Returns

True if and only if the table entry was successfully updated or deleted.

make_val

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

Parameters

valThe object to convert to a message value.
int_sizeThe size in bytes of a message value produced from an integer.  If this is None, a default size will be used.
tlv_typeAn optional INM message type specifier.  Used to determine the default integer value size.

Returns

A bytes object containing a converted representation of val.  (Or None, if val couldn’t be converted.)

make_mval

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

Parameters

mvalThe objects to convert to a multipart message value.  MUST be a sequence.
int_sizeThe 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_typeAn optional INM message type specifier.  Used to determine the default integer field sizes.

Returns

A bytes object containing a converted representation of mval.  (Or None, if some object in mval couldn’t be converted.)

format_val_str

def format_val_str(self,  
val,  
tlv_type = None)

Applies string formatting to an INM message value.

Parameters

valA bytes object containing the message value to format.
tlv_typeAn optional INM message type specifier.  Used to determine appropriate enum mappings.

Returns

The result of applying string formatting (determined by str_val_conv) to val.

format_val

def format_val(self,  
val,  
conv = None,
tlv_type = None)

Applies formatting to an INM message value.

Parameters

valA bytes object containing the message value to format.
convMessage value conversion specifier (e.g. from ValueConversions), or None to apply the default conversion.
tlv_typeAn optional INM message type specifier.  Used to determine the default value conversion and enum mappings.

Returns

The result of applying message value formatting to val.

format_mval

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.

Parameters

mvalA bytes object containing the multipart message value to format.
convField 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.
sizeMultipart 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_typeAn optional INM message type specifier.  Used to determine the default value conversions, field sizes and enum mappings.
n_valsMultipart value field count.  If this is None, the field count is inferred from the conv and size arguments (or their default values).
strictMultipart formatting Strictness specifier, or None to apply the default strictness level.

Returns

The formatted multipart message value (list of formatted fields), if formatting was successful.  Otherwise None.

make_msg

def make_msg(self,  
typ,  
val,  
int_size = None)

Constructs an INM Message with the specified type and value.

Parameters

typAn INM message type specifier.
valThe object to convert to a message value.
int_sizeThe size in bytes of a message value produced from an integer.  If this is None, a default size will be used.

Returns

A StandardMessage with type typ and a value constructed by applying make_val to val.  (Or None, if a value couldn’t be constructed.)

make_msg_mval

def make_msg_mval(self,  
typ,  
mval,  
int_size = None)

Constructs an INM Message with the specified type and multipart value.

Parameters

typAn INM message type specifier.
mvalThe objects to convert to a multipart message value.  MUST be a sequence.
int_sizeThe 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.

Returns

A StandardMessage with type typ and a value constructed by applying make_mval to mval.  (Or None, if a value couldn’t be constructed.)

make_large_msg

def make_large_msg(self,  
typ,  
val,  
int_size = None)

Constructs a large INM Message with the specified type and value.

Parameters

typAn INM message type specifier.
valThe object to convert to a message value.
int_sizeThe size in bytes of a message value produced from an integer.  If this is None, a default size will be used.

Returns

A LargeMessage with type typ and a value constructed by applying make_val to val.  (Or None, if a value couldn’t be constructed.)

make_large_msg_mval

def make_large_msg_mval(self,  
typ,  
mval,  
int_size = None)

Constructs a large INM Message with the specified type and multipart value.

Parameters

typAn INM message type specifier.
mvalThe objects to convert to a multipart message value.  MUST be a sequence.
int_sizeThe 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.

Returns

A LargeMessage with type typ and a value constructed by applying make_mval to mval.  (Or None, if a value couldn’t be constructed.)

msg_to_bytes

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.

Parameters

msgAn instance of Message.
headerAn optional instance of MessageHeader.

Returns

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.

MessageHeader

class MessageHeader

Represents the header of an INM message.

Summary
Variables
MESSAGE_ID_SIZESize in bytes of the message identifier field in an INM message header.
DSTADR_SIZESize in bytes of the destination address field in an INM message header.
SRCADR_SIZESize in bytes of the source address field in an INM message header.
HEADER_SIZESize in bytes of a complete INM message header.
MAX_MESSAGE_IDLargest valid INM message identifier.
MAX_MESSAGE_ADRLargest valid INM node address.
LOCAL_ADRReserved INM node address for the local node.
BROADCAST_ADRReserved INM node address for broadcast messages.
Functions and Properties
__init__Instance initializer.
msg_idINM message identifier.
dstadrDestination INM node address.
srcadrSource INM node address.
__str__String conversion.
__repr__String representation.
to_bytesConverts the MessageHeader to a bytes object containing the header in standard binary on-wire format.

Variables

MESSAGE_ID_SIZE

MESSAGE_ID_SIZE = 2

Size in bytes of the message identifier field in an INM message header.

DSTADR_SIZE

DSTADR_SIZE = 1

Size in bytes of the destination address field in an INM message header.

SRCADR_SIZE

SRCADR_SIZE = 1

Size in bytes of the source address field in an INM message header.

HEADER_SIZE

HEADER_SIZE = MESSAGE_ID_SIZE + DSTADR_SIZE + SRCADR_SIZE

Size in bytes of a complete INM message header.

MAX_MESSAGE_ID

MAX_MESSAGE_ID = 0xffff

Largest valid INM message identifier.

MAX_MESSAGE_ADR

MAX_MESSAGE_ADR = 0xff

Largest valid INM node address.

LOCAL_ADR

LOCAL_ADR = 0x00

Reserved INM node address for the local node.

BROADCAST_ADR

BROADCAST_ADR = MAX_MESSAGE_ADR

Reserved INM node address for broadcast messages.

Functions and Properties

__init__

def __init__(self,
msg_id,
dstadr,
srcadr)

Instance initializer.

Parameters

msg_idINM message identifier.
dstadrDestionation INM address.
srcadrSource INM address.

msg_id

self.msg_id

INM message identifier.

dstadr

self.dstadr

Destination INM node address.

srcadr

self.srcadr

Source INM node address.

__str__

def __str__(self)

String conversion.

Returns

A string representation of the MessageHeader, in the format “MessageHeader(msg_id, dstadr, srcadr)”.

__repr__

def __repr__(self)

String representation.

Returns

A string representation of the MessageHeader, in the format “<MessageHeader(msg_id, dstadr, srcadr)>”.

to_bytes

def to_bytes(self,  
formatter = None)

Converts the MessageHeader to a bytes object containing the header in standard binary on-wire format.

Parameters

formatterFormatter to use for integer conversion, or None to use the default formatter.

Returns

A bytes object containing the INM message header represented by this MessageHeader in standard binary on-wire format.

Default Objects

Summary

Variables

default_msg_factory

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.

Message Channels

MessageChannelError

class MessageChannelError(Exception)

Exception class for MessageChannels.

MessageChannel

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

Summary
Variables
make_default_selectorIf 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
srcadrDefault INM source address of messages sent via this MessageChannel.
timeoutReceive timeout.
msg_factoryThe MessageFactory that the MessageChannel uses to create INM Message objects.
selectorA selector object compatible with the ones provided by the standard library module selectors.
ch_numChannel number of this MessageChannel.
Functions
__str__String conversion.
__repr__String representation.
peek_prev_msg_idPeeks at the most recently auto-generated INM message ID.
peek_next_msg_idPeeks at the next INM message ID to be auto-generated.
get_next_msg_idAuto-generates an INM message ID.
is_openChecks whether the MessageChannel is open.
openOpens the MessageChannel.
closeCloses the MessageChannel.
readableChecks whether the MessageChannel is readable.
get_selector_keysGets the selector keys of encapsulated selectable objects from this MessageChannel.
set_timeoutUpdates the timeout attribute.
sendSends an INM message.
recvAttempts to receive an INM message.

Variables

make_default_selector

make_default_selector = True

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__

def __init__(self,  
srcadr,  
timeout = None,
msg_factory = None,
selector = None,
ch_num = None)

Instance initializer.

Parameters

srcadrINM 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.
timeoutReceive timeout.  MUST be an instance of the standard library class datetime.timedelta.  If this parameter is None, receive operations will never time out.
msg_factoryThe MessageFactory that the MessageChannel should use to create INM Message objects.  If this parameter is None, a default MessageFactory will be used.
selectorA 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_numChannel number of the MessageChannel.  SHOULD be either None or a nonnegative integer.

Properties

srcadr

self.srcadr

Default INM source address of messages sent via this MessageChannel.

timeout

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.

msg_factory

self.msg_factory

The MessageFactory that the MessageChannel uses to create INM Message objects.

selector

self.selector

A selector object compatible with the ones provided by the standard library module selectors.  May be None.  SHOULD be treated as a read-only attribute.

ch_num

self.ch_num

Channel number of this MessageChannel.  May be None.  SHOULD be treated as a read-only attribute.

Functions

__str__

def __str__(self)

String conversion.

Returns

A string representation of the MessageChannel, in the format “class_name(srcadr)”.

__repr__

def __repr__(self)

String representation.

Returns

A string representation of the MessageChannel, in the format “<class_name(srcadr)>”.

peek_prev_msg_id

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.

Returns

The INM message ID most recently auto-generated by this MessageChannel.

peek_next_msg_id

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.

Returns

The next INM message ID to be auto-generated by this MessageChannel.

get_next_msg_id

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.

Returns

An auto-generated INM message ID.

is_open

def is_open(self)

Checks whether the MessageChannel is open.

Returns

True if and only if this MessageChannel is currently open.

open

def open(self)

Opens the MessageChannel.  Subclasses may need to override the base class implementation.

Returns

ResultCode.SUCCESS if the channel was successfully opened, otherwise another ResultCode indicating what went wrong.

close

def close(self)

Closes the MessageChannel.  Subclasses may need to override the base class implementation.

readable

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.

Returns

True if and only if this MessageChannel is currently open and readable.

get_selector_keys

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.

Returns

A tuple of selector keys compatible with the ones produced by the register method of the standard library class selectors.BaseSelector.

set_timeout

def set_timeout(self,
timeout)

Updates the timeout attribute.  Subclasses may need to override the base class implementation.

Parameters

timeoutReceive timeout.  MUST be an instance of the standard library class datetime.timedelta.  If this parameter is None, receive operations will never time out.

send

def send(self,  
dstadr,  
msg,  
msg_id = None,
srcadr = None,
link_adr = None)

Sends an INM message.  This is an abstract method.

Parameters

dstadrDestination INM node address of the message to send.
msgThe INM Message to send.
msg_idINM message ID.  If this is None, a message ID will be generated internally.
srcadrSource INM node address of the message to send.  If this is None, the configured srcadr of this MessageChannel will be used.
link_adrINM 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).

Returns

A ResultCode indicating the outcome of the attempted send operation.

recv

def recv(self)

Attempts to receive an INM message.  This is an abstract method.

Returns

resA ResultCode indicating the outcome of the attempted receive operation.
headerThe MessageHeader of the received message, or None in case of failure.
msgThe received Message, or None in case of failure.
link_adrThe link address of the received message, or None in case of failure.

RoutingMessageChannel

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.

Summary
Variables
TIMEOUT_DIVISORIf 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_TIMEOUTIf 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
rtabThe routing table.
recv_channelsThe receive channel table.
cc_toList of INM node addresses of CC message destinations.
close_recv_channelsIf this is true, all channels in recv_channels are closed when this RoutingMessageChannel is closed.
relay_messagesIf this is true, routing is applied even to messages where the destination address equals the source address of the local node.
Functions
add_cc_adrAdds the INM address of a CC message destination node to cc_to.
remove_cc_adrRemoves the INM address of a CC message destination node from cc_to.
openOverrides MessageChannel.open.
closeOverrides MessageChannel.close.
get_selector_keysReturns all selector keys obtained by calling the get_selector_keys methods of the channels in recv_channels.
set_timeoutOverrides MessageChannel.set_timeout.
sendImplements MessageChannel.send.
recvImplements MessageChannel.recv.
routeAttempts to receive and then route an INM message.

Variables

TIMEOUT_DIVISOR

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

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.

Functions

__init__

def __init__(self,  
srcadr,  
rtab,  
recv_channels,  
timeout = None,
msg_factory = None,
selector = None,
ch_num = None)

Instance initializer.

Parameters

srcadrINM 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.
rtabA routing table.  Used to initialize the rtab attribute, see that entry for more information.
recv_channelsA receive channel table.  Used to initialize the recv_channels attribute, see that entry for more information.
timeoutReceive timeout.  MUST be an instance of the standard library class datetime.timedelta.  If this parameter is None, receive operations will never time out.
msg_factoryThe MessageFactory that the RoutingMessageChannel should use to create INM Message objects.  If this parameter is None, a default MessageFactory will be used.
selectorA 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_numChannel number of the RoutingMessageChannel.  SHOULD be either None or a nonnegative integer.

Properties

rtab

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.

recv_channels

self.recv_channels

The receive channel table.  MUST be a dictionary that maps channel numbers to MessageChannels for incoming messages.

cc_to

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.

close_recv_channels

self.close_recv_channels

If this is true, all channels in recv_channels are closed when this RoutingMessageChannel is closed.  Default: True

relay_messages

self.relay_messages

If this is true, routing is applied even to messages where the destination address equals the source address of the local node.  Default: False

Functions

add_cc_adr

def add_cc_adr(self,
cc_adr)

Adds the INM address of a CC message destination node to cc_to.

Parameters

cc_adrThe INM address of a CC destination.

Returns

True if and only if cc_adr was successfully added to cc_to.

remove_cc_adr

def remove_cc_adr(self,
cc_adr)

Removes the INM address of a CC message destination node from cc_to.

Parameters

cc_adrThe INM address of a CC destination.

Returns

True if and only if cc_adr was successfully removed from cc_to.

open

def open(self)

Overrides MessageChannel.open.

close

def close(self)

Overrides MessageChannel.close.

get_selector_keys

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.

set_timeout

def set_timeout(self,
timeout)

Overrides MessageChannel.set_timeout.

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.send.  Adds a few more some optional parameters.

Parameters

dstadrDestination INM node address of the message to send.
msgThe INM Message to send.
msg_idINM message ID.  If this is None, a message ID will be generated internally.
srcadrSource INM node address of the message to send.  If this is None, the value of MessageChannel.srcadr will be used.
link_adrINM 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_adrOptional link address via which routed message msg was received.
envelope_dstadrOptional 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_ccIf this is false, no CC message copies of msg will be sent.

Returns

A ResultCode indicating the outcome of the attempted send operation.

recv

def recv(self)

Implements MessageChannel.recv.

route

def route(self)

Attempts to receive and then route an INM message.

Returns

delivery_flagTrue 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).
resA ResultCode indicating the outcome of the attempted route operation.
headerThe MessageHeader of the received message, or None in case of failure.
msgThe received Message, or None in case of failure.
link_adrThe link address of the received message, or None in case of failure.

BinaryMessageChannel

class BinaryMessageChannel(MessageChannel)

Abstract parent class for MessageChannels that send and receive INM messages encoded in the standard binary on-wire format.

Summary
Functions
__init__Instance initializer.

Functions

__init__

def __init__(self,  
srcadr,  
timeout = None,
msg_factory = None,
selector = None,
ch_num = None,
send_bfr_size = 0,
recv_bfr_size = 0)

Instance initializer.

Parameters

srcadrINM 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.
timeoutReceive timeout.  MUST be an instance of the standard library class datetime.timedelta.  If this parameter is None, receive operations will never time out.
msg_factoryThe MessageFactory that the BinaryMessageChannel should use to create INM Message objects.  If this parameter is None, a default MessageFactory will be used.
selectorA 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_numChannel number of the BinaryMessageChannel.  SHOULD be either None or a nonnegative integer.
send_bfr_sizeInitial capacity in bytes of the send buffer.
recv_bfr_sizeInitial capacity in bytes of the receive buffer.

InetMessageChannel

class InetMessageChannel(BinaryMessageChannel)

A BinaryMessageChannel that sends and receives messages via a UDP socket.

Summary
Variables
DEFAULT_IP_ADRDefault IP socket address.
DEFAULT_UDP_PORTDefault port number of UDP socket.
DEFAULT_TCP_PORTDefault port number of TCP socket.
MAX_DATAGRAM_SIZEMaximum size of sent UDP datagrams.
Functions and Properties
__init__Instance initializer.
ip_adrIP address of sockets used by this InetMessageChannel, as a hostname or dotted-decimal string.
udp_portPort number of UDP socket used by this InetMessageChannel.
tcp_portPort number of TCP socket used by this InetMessageChannel.
__str__String conversion.
openOverrides MessageChannel.open.
closeOverrides MessageChannel.close.
get_selector_keysReturns the selector key of the UDP socket.
set_timeoutOverrides MessageChannel.set_timeout.
sendImplements MessageChannel.send.
recvImplements MessageChannel.recv.

Variables

DEFAULT_IP_ADR

DEFAULT_IP_ADR = '127.0.0.1'

Default IP socket address.

DEFAULT_UDP_PORT

DEFAULT_UDP_PORT = 2357

Default port number of UDP socket.

DEFAULT_TCP_PORT

DEFAULT_TCP_PORT = 2357

Default port number of TCP socket.

MAX_DATAGRAM_SIZE

MAX_DATAGRAM_SIZE = 0xffff

Maximum size of sent UDP datagrams.

Functions and Properties

__init__

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.

Parameters

srcadrINM 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_adrIP 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_portPort 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_portPort number of TCP socket created by the InetMessageChannel.  If this parameter is None or zero, the value of DEFAULT_TCP_PORT will be used.
timeoutReceive timeout.  MUST be an instance of the standard library class datetime.timedelta.  If this parameter is None, receive operations will never time out.
msg_factoryThe MessageFactory that the InetMessageChannel should use to create INM Message objects.  If this parameter is None, a default MessageFactory will be used.
selectorA 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_numChannel number of the InetMessageChannel.  SHOULD be either None or a nonnegative integer.

ip_adr

self.ip_adr

IP address of sockets used by this InetMessageChannel, as a hostname or dotted-decimal string.  This SHOULD be treated as a read-only attribute.

udp_port

self.udp_port

Port number of UDP socket used by this InetMessageChannel.  This SHOULD be treated as a read-only attribute.

tcp_port

self.tcp_port

Port number of TCP socket used by this InetMessageChannel.  This SHOULD be treated as a read-only attribute.

NOTE: No TCP socket is actually created or used by the current version of this class.

__str__

def __str__(self)

String conversion.  Overrides MessageChannel.__str__.

Returns

A string representation of this InetMessageChannel, in the format “class_name(srcadr, ip_adr, udp_port)”.

open

def open(self)

Overrides MessageChannel.open.

close

def close(self)

Overrides MessageChannel.close.

get_selector_keys

def get_selector_keys(self)

Returns the selector key of the UDP socket.  Overrides MessageChannel.get_selector_keys.

set_timeout

def set_timeout(self,
timeout)

Overrides MessageChannel.set_timeout.

send

def send(self,  
dstadr,  
msg,  
msg_id = None,
srcadr = None,
link_adr = None)

Implements MessageChannel.send.

recv

def recv(self)

Implements MessageChannel.recv.

SerialMessageChannel

class SerialMessageChannel(BinaryMessageChannel)

A BinaryMessageChannel that sends and receives messages via a serial port.

Summary
Variables
DEFAULT_BAUDRATEDefault baud rate to set on the opened serial port.
N_HEADER_BYTESTotal size of the header, type and length fields of an INM message.
MAX_MESSAGE_LENMaximum supported INM message (value) length.
TIMEOUT_DIVISORIf 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.
portFilesystem path of the used serial port device.
baudrateBaud rate to open the used serial port at.
__str__String conversion.
openOverrides MessageChannel.open.
closeOverrides MessageChannel.close.
get_selector_keysReturns the selector key of the serial port device.
set_timeoutOverrides MessageChannel.set_timeout.
sendImplements MessageChannel.send.
recvImplements MessageChannel.recv.

Variables

DEFAULT_BAUDRATE

DEFAULT_BAUDRATE = 38400

Default baud rate to set on the opened serial port.

N_HEADER_BYTES

N_HEADER_BYTES = MessageHeader.HEADER_SIZE + StandardMessage.MIN_MESSAGE_SIZE

Total size of the header, type and length fields of an INM message.

MAX_MESSAGE_LEN

MAX_MESSAGE_LEN = 0xff - N_HEADER_BYTES

Maximum supported INM message (value) length.

TIMEOUT_DIVISOR

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.

Functions and Properties

__init__

def __init__(self,  
srcadr,  
port,  
baudrate = None,
timeout = None,
msg_factory = None,
selector = None,
ch_num = None)

Instance initializer.

Parameters

srcadrINM 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.
portFilesystem path of the serial port device to open.
baudrateBaud rate to open the serial port at.  If this parameter is None, the value of DEFAULT_BAUDRATE will be used.
timeoutReceive timeout.  MUST be an instance of the standard library class datetime.timedelta.  If this parameter is None, receive operations will never time out.
msg_factoryThe MessageFactory that the SerialMessageChannel should use to create INM Message objects.  If this parameter is None, a default MessageFactory will be used.
selectorA 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_numChannel number of the SerialMessageChannel.  SHOULD be either None or a nonnegative integer.

port

self.port

Filesystem path of the used serial port device.  This SHOULD be treated as a read-only attribute.

baudrate

self.baudrate

Baud rate to open the used serial port at.  This SHOULD be treated as a read-only attribute.

__str__

def __str__(self)

String conversion.  Overrides MessageChannel.__str__.

Returns

A string representation of this SerialMessageChannel, in the format “class_name(srcadr, port)”.

open

def open(self)

Overrides MessageChannel.open.

close

def close(self)

Overrides MessageChannel.close.

get_selector_keys

def get_selector_keys(self)

Returns the selector key of the serial port device.  Overrides MessageChannel.get_selector_keys.

set_timeout

def set_timeout(self,
timeout)

Overrides MessageChannel.set_timeout.

send

def send(self,  
dstadr,  
msg,  
msg_id = None,
srcadr = None,
link_adr = None)

Implements MessageChannel.send.

recv

def recv(self)

Implements MessageChannel.recv.

ZERO_DURATION = datetime.timedelta()
A datetime.timedelta representing a zero duration.
get_timestamp = datetime.datetime.now
Produces a datetime.datetime representing the current local time.
def get_timedelta(secs = 0,
musecs = 0)
Produces a datetime.timedelta with a specified duration.
def bytes_to_hex(bs,  
sep = None,
bytes_per_sep = 1,
big_endian = False)
Produces a hexadecimal string representation of a bytes object.
def bytes_to_bin(bs,  
sep = None,
bytes_per_sep = 1,
big_endian = False)
Produces a binary string representation of a bytes object.
def map_enum(enum_class,  
i,  
defval = None)
Searches an enum class for a member with a specified integer value.
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.
class Message
Instances of subclasses of this abstract class represent INM messages.
MESSAGE_TYP_SIZE = 1
Size in bytes of the message type identifier field in an INM message.
def __init__(self,
typ,
val)
Instance initializer.
self.typ
Message type identifier.
self.val
Message value/payload.
def __len__(self)
Message (value) length.
def __str__(self)
String conversion.
def __repr__(self)
String representation.
def check_tl(self,
typ,
length)
Message type and length check predicate.
def format_str(self,  
formatter = None)
Applies string formatting to the INM message type and value.
def format(self,  
formatter = None,
conv = None)
Applies formatting to the INM message type and value.
def format_type(self,  
formatter = None)
Applies formatting to the INM message type.
def format_val_str(self,  
formatter = None)
Applies string formatting to the INM message value.
def format_val(self,  
formatter = None,
conv = None)
Applies 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.
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.
def to_bytes(self,  
formatter = None)
Converts the Message to a bytes object containing the message in standard binary on-wire format.
class StandardMessage(Message)
Concrete Message subclass for standard-size INM messages.
MESSAGE_LEN_SIZE = 1
Size in bytes of the message length field in a standard INM message.
MIN_MESSAGE_SIZE = Message.MESSAGE_TYP_SIZE + MESSAGE_LEN_SIZE
Minimum size in bytes of a standard INM message.
MIN_TYPE_NUM = 0x00
Smallest valid message type identifier for standard INM messages.
MAX_TYPE_NUM = 0x7f
Largest valid message type identifier for standard INM messages.
MAX_MESSAGE_LEN = 0xff
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 = MAX_TYPE_NUM
Type identifier reserved for INM protocol messages.
class LargeMessage(Message)
Concrete Message subclass for large-size INM messages.
MESSAGE_LEN_SIZE = 4
Size in bytes of the message length field in a large INM message.
MIN_MESSAGE_SIZE = Message.MESSAGE_TYP_SIZE + MESSAGE_LEN_SIZE
Minimum size in bytes of a large INM message.
MIN_TYPE_NUM = 0x80
Smallest valid message type identifier for large INM messages.
MAX_TYPE_NUM = 0xff
Largest valid message type identifier for large INM messages.
MAX_MESSAGE_LEN = 0xffffffff
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.
MAKE_VAL_ATTR_NAME = 'to_inm_val'
Name of attribute to use for custom conversion of objects into INM message values/payloads.
DEFAULT_RES_ENUM_MSG_TYPES = (StandardTypes.RESULT,
StandardTypes.INM_RESULT)
Default message types for result code 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)
Default message types for register identifier enum conversion.
def __init__(self,  
default_type_mappings = True)
Instance initializer.
self.make_val_hex_str
If true, strings will be interpreted as sequences of hexadecimal digits (instead of text) when making message values.
self.str_encoding
Name of text encoding to use when making and formatting message values.
self.int_size
Default size in bytes of integer fields in message values.
self.int_byteorder
Name of default byte order of integer fields in message values.
self.byte_sep
Byte group separator for message values formatted as hex or binary strings.
self.bytes_per_sep
Byte group size for message values formatted as hex or binary strings.
self.byte_str_big_endian
Byte order selector for message values formatted as hex or binary strings.
self.default_val_conv
Default conversion for formatted message values.
self.str_val_conv
Conversion for string-formatted message values.
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.
self.type_enum_class
Enum class to use for conversion of message type identifiers.
self.res_enum_class
Enum class to use for conversion of INM result codes.
self.res_enum_msg_types
Message types to perform result code enum conversion on.
self.reg_enum_class
Enum class to use for conversion of logical register identifiers.
self.reg_enum_msg_types
Message types to perform register identifier enum conversion on.
self.default_strictness
Default strictness level for multipart message value formatting.
def clone(self)
Copies the MessageFactory.
def get_make_val_int_size(self,  
tlv_type,  
default = None)
Gets the value construction integer field sizes associated with a specified message type.
def set_make_val_int_size(self,
tlv_type,
int_size)
Sets the value construction integer field sizes associated with a specified message type.
def get_format_val_conv(self,  
tlv_type,  
default = None)
Gets the value formatting conversion specifier associated with a specified message type.
def set_format_val_conv(self,
tlv_type,
conv)
Sets the value formatting conversion specifier associated with a specified message type.
def get_format_val_size(self,  
tlv_type,  
default = None)
Gets the value formatting field sizes associated with a specified message type.
def set_format_val_size(self,
tlv_type,
size)
Sets the value formatting field sizes associated with a specified message type.
def make_val(self,  
val,  
int_size = None,
tlv_type = None)
Creates a bytes object containing an INM message value.
def make_mval(self,  
mval,  
int_size = None,
tlv_type = None)
Creates a bytes object containing a multipart INM message value.
def format_val_str(self,  
val,  
tlv_type = None)
Applies string formatting to an INM message value.
def format_val(self,  
val,  
conv = None,
tlv_type = None)
Applies formatting to an INM message value.
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.
def make_msg(self,  
typ,  
val,  
int_size = None)
Constructs an INM Message with the specified type and value.
def make_msg_mval(self,  
typ,  
mval,  
int_size = None)
Constructs an INM Message with the specified type and multipart value.
def make_large_msg(self,  
typ,  
val,  
int_size = None)
Constructs a large INM Message with the specified type and value.
def make_large_msg_mval(self,  
typ,  
mval,  
int_size = None)
Constructs a large INM Message with the specified type and multipart value.
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.
class MessageHeader
Represents the header of an INM message.
MESSAGE_ID_SIZE = 2
Size in bytes of the message identifier field in an INM message header.
DSTADR_SIZE = 1
Size in bytes of the destination address field in an INM message header.
SRCADR_SIZE = 1
Size in bytes of the source address field in an INM message header.
HEADER_SIZE = MESSAGE_ID_SIZE + DSTADR_SIZE + SRCADR_SIZE
Size in bytes of a complete INM message header.
MAX_MESSAGE_ID = 0xffff
Largest valid INM message identifier.
MAX_MESSAGE_ADR = 0xff
Largest valid INM node address.
LOCAL_ADR = 0x00
Reserved INM node address for the local node.
BROADCAST_ADR = MAX_MESSAGE_ADR
Reserved INM node address for broadcast messages.
def __init__(self,
msg_id,
dstadr,
srcadr)
Instance initializer.
self.msg_id
INM message identifier.
self.dstadr
Destination INM node address.
self.srcadr
Source INM node address.
def __str__(self)
String conversion.
def __repr__(self)
String representation.
def to_bytes(self,  
formatter = None)
Converts the MessageHeader to a bytes object containing the header in standard binary on-wire format.
default_msg_factory = MessageFactory()
A default instance of MessageFactory.
class MessageChannelError(Exception)
Exception class for MessageChannels.
class MessageChannel
Abstract parent class for objects that send and receive INM messages.
make_default_selector = True
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.
def __init__(self,  
srcadr,  
timeout = None,
msg_factory = None,
selector = None,
ch_num = None)
Instance initializer.
self.srcadr
Default INM source address of messages sent via this MessageChannel.
self.timeout
Receive timeout.
self.msg_factory
The MessageFactory that the MessageChannel uses to create INM Message objects.
self.selector
A selector object compatible with the ones provided by the standard library module selectors.
self.ch_num
Channel number of this MessageChannel.
def __str__(self)
String conversion.
def __repr__(self)
String representation.
def peek_prev_msg_id(self)
Peeks at the most recently auto-generated INM message ID.
def peek_next_msg_id(self)
Peeks at the next INM message ID to be auto-generated.
def get_next_msg_id(self)
Auto-generates an INM message ID.
def is_open(self)
Checks whether the MessageChannel is open.
def open(self)
Opens the MessageChannel.
def close(self)
Closes the MessageChannel.
def readable(self)
Checks whether the MessageChannel is readable.
def get_selector_keys(self)
Gets the selector keys of encapsulated selectable objects from this MessageChannel.
def set_timeout(self,
timeout)
Updates the timeout attribute.
def send(self,  
dstadr,  
msg,  
msg_id = None,
srcadr = None,
link_adr = None)
Sends an INM message.
def recv(self)
Attempts to receive an INM message.
class RoutingMessageChannel(MessageChannel)
A MessageChannel with message routing functionality.
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.
self.recv_channels
The receive channel table.
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.
def __init__(self,  
srcadr,  
rtab,  
recv_channels,  
timeout = None,
msg_factory = None,
selector = None,
ch_num = None)
Instance initializer.
self.rtab
The routing table.
self.cc_to
List of INM node addresses of CC message destinations.
self.close_recv_channels
If this is true, all channels in recv_channels are closed when this RoutingMessageChannel is closed.
self.relay_messages
If this is true, routing is applied even to messages where the destination address equals the source address of the local node.
def add_cc_adr(self,
cc_adr)
Adds the INM address of a CC message destination node to cc_to.
def remove_cc_adr(self,
cc_adr)
Removes the INM address of a CC message destination node from cc_to.
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.
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.
def recv(self)
Implements MessageChannel.recv.
def route(self)
Attempts to receive and then route an INM message.
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.
class InetMessageChannel(BinaryMessageChannel)
A BinaryMessageChannel that sends and receives messages via a UDP socket.
DEFAULT_IP_ADR = '127.0.0.1'
Default IP socket address.
DEFAULT_UDP_PORT = 2357
Default port number of UDP socket.
DEFAULT_TCP_PORT = 2357
Default port number of TCP socket.
MAX_DATAGRAM_SIZE = 0xffff
Maximum size of sent UDP datagrams.
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.
self.ip_adr
IP address of sockets used by this InetMessageChannel, as a hostname or dotted-decimal string.
self.udp_port
Port number of UDP socket used by this InetMessageChannel.
self.tcp_port
Port number of TCP socket used by this InetMessageChannel.
def __str__(self)
String conversion.
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.
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.
DEFAULT_BAUDRATE = 38400
Default baud rate to set on the opened serial port.
N_HEADER_BYTES = MessageHeader.HEADER_SIZE + StandardMessage.MIN_MESSAGE_SIZE
Total size of the header, type and length fields of an INM message.
MAX_MESSAGE_LEN = 0xff - N_HEADER_BYTES
Maximum supported INM message (value) length.
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.
def __init__(self,  
srcadr,  
port,  
baudrate = None,
timeout = None,
msg_factory = None,
selector = None,
ch_num = None)
Instance initializer.
self.port
Filesystem path of the used serial port device.
self.baudrate
Baud rate to open the used serial port at.
def __str__(self)
String conversion.
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.
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 InmHelper
Convenience class for INM communication.
Standard INM result codes.
Standard INM message types.
Type conversion specifiers for INM message values.
Multipart formatting strictness specifiers for INM message values.
Bytes object
Hexadecimal string (unprefixed)
Standard INM register identifiers.
All requested fields must be present, and only those, and no unparsed bytes are allowed to remain.
Operation successfully completed.
Result codes for the INM module.
Close