iotcs.message module

class iotcs.message.AlertMessage(format=None, items=None, description=None, severity=<Severity.SIGNIFICANT: 2>, msgId=None, source=None, destination=None, clientId=None, reliability=<Reliability.GUARANTEED_DELIVERY: 3>, priority=<Priority.HIGHEST: 4>, properties=None, diagnostics=None, eventTime=None, sender=None, direction=None, receivedTime=None, sentTime=None)

Bases: iotcs.message.Message

AlertMessage extends Message class. It can be used for sending alert data to IoT Server.

Construct an AlertMessage. See Message for description of Message paraemters AlertMessage parameters format: the URN of the message format in the data model. items: one or more DataItems to be included in the message severity: defaults to Severity.SIGNIFICANT

Raises:ValueError if format is None
class Encoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)

Bases: iotcs.message.Encoder

An encoder for encoding a AlertMessage to JSON

Constructor for JSONEncoder, with sensible defaults.

If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float or None. If skipkeys is True, such items are simply skipped.

If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure_ascii is false, the output can contain non-ASCII characters.

If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place.

If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.

If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.

If specified, separators should be an (item_separator, key_separator) tuple. The default is (‘, ‘, ‘: ‘) if indent is None and (‘,’, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘,’, ‘:’) to eliminate whitespace.

If specified, default is a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError.

encode(o)

Return a JSON string representation of a Python data structure.

>>> from json.encoder import JSONEncoder
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
class Severity

Bases: enum.Enum

The AlertMessage severity, one of LOW, NORMAL, SIGNIFICANT, CRITICAL

CRITICAL = 1
LOW = 4
NORMAL = 3
SIGNIFICANT = 2
dataItem(key, value)
description
format
fromJson(jsonObject)

Set values in this instance from the jsonObject Typical use case Message().fromJson(jsonObject) :param jsonObject:

getDataItems()

Get message payload as {@link List} of {@link DataItem}s. :return: Payload that is carried by {@link AlertMessage}, never {@code null}.

getDescription()

Gets the description for this alert. :return: the description for this alert.

getFormat()

Get the name of the format for data. :return: data format, never {@code null}.

getSeverity()

Gets the severity of this alert :return: the severity of this alert

getType()
items
setDescription(description)
setFormat(format)
setSeverity(severity)
setSource(source)
severity
toJson()
Returns:
class iotcs.message.DataItem(key, value)

Bases: object

DataItem is a key/value pair for data in DataMessage.

Construct a DataItem. key: the name of the attribute or field value: the value of the attribute or field

class Type

Bases: enum.Enum

An enumeration.

BOOLEAN = 2
DOUBLE = 1
STRING = 0
getKey()
getValue()
key
value
class iotcs.message.DataMessage(format=None, items=None, msgId=None, source=None, destination=None, clientId=None, reliability=<Reliability.BEST_EFFORT: 2>, priority=None, properties=None, diagnostics=None, eventTime=None, sender=None, direction=<Direction.FROM_DEVICE: 0>, receivedTime=None, sentTime=None)

Bases: iotcs.message.Message

DataMessage extends Message class. It can be used for sending sensor data to IoT Server.

Return a DataMessage.

Parameters:
  • format
  • itemslist of iotcs.shared.message.DataItem
  • msgId
  • source
  • destination
  • clientId
  • reliability
  • priority
  • properties
  • diagnostics
  • eventTime
  • sender
  • direction
  • receivedTime
  • sentTime
class Encoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)

Bases: iotcs.message.Encoder

Constructor for JSONEncoder, with sensible defaults.

If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float or None. If skipkeys is True, such items are simply skipped.

If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure_ascii is false, the output can contain non-ASCII characters.

If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place.

If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.

If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.

If specified, separators should be an (item_separator, key_separator) tuple. The default is (‘, ‘, ‘: ‘) if indent is None and (‘,’, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘,’, ‘:’) to eliminate whitespace.

If specified, default is a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError.

encode(o)

Return a JSON string representation of a Python data structure.

>>> from json.encoder import JSONEncoder
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
add(dataItem)
addItem(key, value)
format
fromJson(jsonObject)

Set values in this instance from the jsonObject Typical use case Message().fromJson(jsonObject) :param jsonObject:

getDataItems()
getFormat()
getType()
items
msgType
toJson()

Serialize the message to dict

class iotcs.message.Message(msgId=None, source=None, destination=None, clientId=None, reliability=<Reliability.BEST_EFFORT: 2>, priority=<Priority.LOW: 1>, properties=None, diagnostics=None, eventTime=None, sender=None, direction=None, receivedTime=None, sentTime=None)

Bases: abc.ABC

Constructs a Message object. Only subclasses of Message should be constructed. source: the endpoint id of the device sending the message. clientId: an id that may be used by the client to track the message. If clientId is not provided, one will be generated. reliability: the required reliability of the message priority: the required priority of the message eventTime: the time the event occurred. If eventTime is not provided, the value defaults to the current time.

Validation occurs when converting to and from json

class Direction

Bases: enum.Enum

” The message direction with respect to the device.

FROM_DEVICE = 0
TO_DEVICE = 1
class Encoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)

Bases: json.encoder.JSONEncoder

An encoder for encoding a Message to JSON

Constructor for JSONEncoder, with sensible defaults.

If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float or None. If skipkeys is True, such items are simply skipped.

If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure_ascii is false, the output can contain non-ASCII characters.

If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place.

If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.

If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.

If specified, separators should be an (item_separator, key_separator) tuple. The default is (‘, ‘, ‘: ‘) if indent is None and (‘,’, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘,’, ‘:’) to eliminate whitespace.

If specified, default is a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError.

encode(o)

Return a JSON string representation of a Python data structure.

>>> from json.encoder import JSONEncoder
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
MAX_KEY_LENGTH = 2048
MAX_STRING_VALUE_LENGTH = 65536
class Priority

Bases: enum.Enum

The priorty of the message. Deliviery of a message with a higher priority will take precedence over delivery of a message with lower priority.

HIGH = 3
HIGHEST = 4
LOW = 1
LOWEST = 0
MEDIUM = 2
class Reliability

Bases: enum.Enum

The required reliability of delivery of a message. NO_GUARANTEE: Message will not be persisted, but will be retried a default number of times BEST_EFFORT: Message will be persisted, and will be retried twice the default number of times GUARANTEED_DELIVERY: Message will be persisted, and will be retried until successfully delivered

BEST_EFFORT = 2
GUARANTEED_DELIVERY = 3
NO_GUARANTEE = 1
class Severity

Bases: enum.Enum

The required reliability of delivery of a message. NO_GUARANTEE: Message will not be persisted, but will be retried a default number of times BEST_EFFORT: Message will be persisted, and will be retried twice the default number of times GUARANTEED_DELIVERY: Message will be persisted, and will be retried until successfully delivered

CRITICAL = 1
LOW = 4
NORMAL = 3
SIGNIFICANT = 2
class Type

Bases: enum.Enum

” The message type. Each type corresponds to one type of message.

ALERT = 'ALERT'
DATA = 'DATA'
REQUEST = 'REQUEST'
RESOURCE = 'RESOURCES_REPORT'
RESPONSE = 'RESPONSE'
static checkKeyLengthAndRaiseError(key)
static checkValueLengthAndRaiseError(value)
clientId
static compareMessages(msg1, msg2)

Messages are the same if the object references are equal, Priority is equal, eventTimes are equal, Reliability is equal and ordinals are equal.

msg1 is greater than msg2 if msg1.ordingal is greater than msg2.ordinal, conversely less than, otherwise equal

Parameters:
  • msg1
  • msg2
Returns:

0 if msg1 == msg2, 1 if msg1 > msg2, -1 if msg1 < msg2

static compareTo(a, b)
destination
diagnostic(name, value)
diagnostics
direction
eventTime
fromJson(jsonObject)

Set values in this instance from the jsonObject Typical use case Message().fromJson(jsonObject) :param jsonObject:

getClientId()
getDestination()
getDiagnostics()
getDirection()
getEventTime()
getId()
getPriority()
getProperties()
getReceivedTime()
getReliability()
getRemainingRetries()
getSender()
getSentTime()
getSource()
msgId
priority
properties
receivedTime
reliability
remainingRetries
sender
sentTime
setRemainingRetries(retries)
source
toJson()

Serialize the message to dict

class iotcs.message.MessageProperties(properties=None)

Bases: object

MessageProperties contains a table of key and list of values pairs for extra information to send. This class is immutable

Parameters:properties
addValues(key, values)

Add a new key/values pair. If the key exists, adds the values to the list of existing values. If the key does not exist, puts the key and values to the table. Key or values cannot be {@code null}. Key cannot be empty or long string. Values cannot contain long strings. Maximum length for key is Message.Utils.MAX_KEY_LENGTH bytes, maximum length for any value is Message.Utils.MAX_STRING_VALUE_LENGTH bytes. The length is measured after the string is encoded using UTF-8 encoding.

Parameters:
  • key – property key
  • values – property values as list() or single value
Returns:

MessageProperties.Builder

Raises:

ValueError for None key or if the values are None or any

item in values is None. :raises: ValueError for empty or long key and for any long item in

values.
containsKey(key)

Check if the properties contain the key. :param key: property key :return: True if the properties contain the key

copy(properties)

Copy another MessageProperties by adding all properties to the current MessageProperties :param properties: MessageProperties to copy :return: MessageProperties.Builder

getAllProperties()

Get all properties. :return a Dictionary of key and list of values, never None

getKeys()

Get a set() of the keys. :return: a set of the keys, never None

getProperties(key)

Get a list() of values for a particular key. :param key: property key :return: a list() of str values

getProperty(key, index=-1)

if index is greater than -1 Get the first value for a particular key. :param key: property key :return: value, may return None if the key does not exist or values assigned to this key is empty.

if index is -1 Get a specific value. :param key: property key :param index: index of the list() of the str values :return: value, may return None if the key does not exist or index is out of range.

toJson()

Method to export the message properties to a json object. :return message properties as json object (python object)

validateKey(msgprefix, key)

Raises ValueError with appropriate message for failure if key is None, 0 length, or its length exceeds Message.MAX_KEY_LENGTH bytes after encoing to bytes as utf-8 str :param msgprefix: ValueError message prefix :param key: the key to validate :raises: ValueError if key is invalid.

validateValues(msgprefix, values)

Raises ValueError with appropriate message for failure under the following conditions - values is None - values is a list() or any of its values (of if values is a single value)

meets any of the following conditions
  • a value is None, 0 length or exceeds Messsage.MAX_STRING_VALUE_LENGTH after encoding to bytes as a utf-8 str
Parameters:
  • msgprefixValueError message prefix
  • values – a single or list() of values
Raises:

ValueError if values is invalid.

class iotcs.message.RequestMessage(url=None, method=None, headers=None, body=None, params=None, msgId=None, source=None, destination=None, clientId=None, reliability=<Reliability.BEST_EFFORT: 2>, priority=<Priority.LOW: 1>, properties=None, diagnostics=None, eventTime=None, sender=None, direction=None, receivedTime=None, sentTime=None)

Bases: iotcs.message.Message

ReuestMessage extends Message class. This can be used for processing request messages from server.

Parameters:
  • method
  • url
  • body
  • headers
  • params
Raises:

ValueError if ‘url’ or ‘headers’ is None

class Encoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)

Bases: json.encoder.JSONEncoder

An encoder for encoding a Message to JSON

Constructor for JSONEncoder, with sensible defaults.

If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float or None. If skipkeys is True, such items are simply skipped.

If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure_ascii is false, the output can contain non-ASCII characters.

If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place.

If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.

If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.

If specified, separators should be an (item_separator, key_separator) tuple. The default is (‘, ‘, ‘: ‘) if indent is None and (‘,’, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘,’, ‘:’) to eliminate whitespace.

If specified, default is a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError.

encode(o)

Return a JSON string representation of a Python data structure.

>>> from json.encoder import JSONEncoder
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
body
fromJson(jsonObject)

Set values in this instance from the jsonObject Typical use case Message().fromJson(jsonObject) :param jsonObject:

getBody()
getHeader(name)
getMethod()
getMethodOverride()
getParams()
getType()
getURL()
headers
method
msgType
params
setBody(body)
toJson()

Serialize the message to dict

url
class iotcs.message.Resource(name=None, path=None, endpointName=None, status=None, methods=None)

Bases: object

class Method

Bases: enum.Enum

An enumeration.

DELETE = 8
GET = 1
PATCH = 10
POST = 2
PUT = 4
class Status

Bases: enum.Enum

An enumeration.

ADDED = 0
REMOVED = 1
endpointName
fromJson(jsonObject)

Return a Resource instance from jsonObject :param jsonObject: :return:

methods
name
path
setEndpointName(endpointName)
setMethod(methods)

method can be list or single method :param method: :return:

setName(name)
setPath(path)
setStatus(status)
status
toJson()
class iotcs.message.ResourceMessage(endpointName=None, resources=None, resourceType=None, reconciliationMark=None, msgId=None, source=None, destination=None, clientId=None, reliability=None, priority=None, properties=None, diagnostics=None, eventTime=None, sender=None, direction=<Direction.FROM_DEVICE: 0>, receivedTime=None, sentTime=None)

Bases: iotcs.message.Message

ReuestMessage extends Message class. This can be used for processing request messages from server.

Parameters:
  • endpointName
  • resources
  • resourceType
  • reconciliationMark
Raises:
class ReportResponse(endpointName=None, status=None)

Bases: object

class ResponseStatus

Bases: enum.Enum

An enumeration.

BAD_REPORT = 1
OK = 0
RECONCILIATION = 2
endpointName
fromJson(jsonObject)
fromString(string)
getEndpointName()
getStatus()
setEndpointName(endpointName)

Sets the name or ID of the resource’s endpoint. :return: self

setStatus(status)
status
toJson()
class Type

Bases: enum.Enum

An enumeration.

DELETE = 1
RECONCILIATION = 2
UPDATE = 0
add(resource)

resource may be one or a list of resources, are added to the resources list. :param resource: iotcs.shared.message.Resource or a list of iotcs.shared.message.Resource :return: self

delete()

Set the ResourceMessage type to iotcs.shared.message.ResourceMessage.Type.DELETE and clear the resources list. :return: self

endpointName
fromJson(jsonObject)

Set values in this instance from the jsonObject Typical use case Message().fromJson(jsonObject) :param jsonObject:

getEndpointName()
Returns:the endpoint id for this ResourceMessage
getMD5ofList(resStrings)

Calculates the MD5 hash value for a list of Strings. The String list is being alphabetical ordered before the calculation :param resStrings: List os Strings :return: hash value

getMessageType()

Returns type of the message (Could be iotcs.shared.message.ResourceMessage.UPDATE or iotcs.shared.message.ResourceMessage.Type.DELETE) :return : iotcs.shared.message.ResourceMessage.Type for this ResourceMessage

getReconciliationMark()
Returns:the reconciliation mark.
getResources()

Return the list of iotcs.shared.message.Resource in this ResourceMessage :return:

getType()
Returns:iotcs.shared.message.Message.Type.RESOURCE
reconcile()

Sets the ResoureceMessage type to iotcs.shared.message.ResourceMessage.Type.RECONCILIATION :return: self

reconciliationMark
register(resource)

Set the ResourceMessage type to iotcs.shared.message.ResourceMessage.Type.UPDATE and add the resource to the resources list :param resource: iotcs.shared.message.Resource :return: self

remove(resource)

Set the ResourceMessage type to iotcs.shared.message.ResourceMessage.Type.DELETE and add the resource to the resources list :param resource: iotcs.shared.message.Resource :return: self

resourceType
resources
setEndpointName(endpointName)

Set the endpointName for this message. :param endpointName: this message’s endpointName :return: self

setReconciliationMark(mark)

Set the reconciliation mark. :param mark: reconciliation mark. :return: self

toJson()

Serialize the message to dict

class iotcs.message.ResponseMessage(requestMessage=None, url=None, headers=None, body=None, statusCode=<StatusCode.OK: 200>, msgId=None, source=None, destination=None, clientId=None, reliability=None, priority=None, properties=None, diagnostics=None, eventTime=None, sender=None, direction=<Direction.FROM_DEVICE: 0>, receivedTime=None, sentTime=None)

Bases: iotcs.message.Message

ReuestMessage extends Message class. This can be used for processing request messages from server.

Parameters:
  • requestMessage
  • url
  • headers
  • body – bytearray or str or dict, if str or dict it is converted to bytearray,
  • statusCode
  • msgId
  • source
  • destination
  • clientId
  • reliability
  • priority
  • properties
  • diagnostics
  • eventTime
  • sender
  • direction
  • receivedTime
  • sentTime
class Encoder(*, skipkeys=False, ensure_ascii=True, check_circular=True, allow_nan=True, sort_keys=False, indent=None, separators=None, default=None)

Bases: iotcs.message.Encoder

An encoder for encoding a ResponseMessage to JSON

Constructor for JSONEncoder, with sensible defaults.

If skipkeys is false, then it is a TypeError to attempt encoding of keys that are not str, int, float or None. If skipkeys is True, such items are simply skipped.

If ensure_ascii is true, the output is guaranteed to be str objects with all incoming non-ASCII characters escaped. If ensure_ascii is false, the output can contain non-ASCII characters.

If check_circular is true, then lists, dicts, and custom encoded objects will be checked for circular references during encoding to prevent an infinite recursion (which would cause an OverflowError). Otherwise, no such check takes place.

If allow_nan is true, then NaN, Infinity, and -Infinity will be encoded as such. This behavior is not JSON specification compliant, but is consistent with most JavaScript based encoders and decoders. Otherwise, it will be a ValueError to encode such floats.

If sort_keys is true, then the output of dictionaries will be sorted by key; this is useful for regression tests to ensure that JSON serializations can be compared on a day-to-day basis.

If indent is a non-negative integer, then JSON array elements and object members will be pretty-printed with that indent level. An indent level of 0 will only insert newlines. None is the most compact representation.

If specified, separators should be an (item_separator, key_separator) tuple. The default is (‘, ‘, ‘: ‘) if indent is None and (‘,’, ‘: ‘) otherwise. To get the most compact JSON representation, you should specify (‘,’, ‘:’) to eliminate whitespace.

If specified, default is a function that gets called for objects that can’t otherwise be serialized. It should return a JSON encodable version of the object or raise a TypeError.

encode(o)

Return a JSON string representation of a Python data structure.

>>> from json.encoder import JSONEncoder
>>> JSONEncoder().encode({"foo": ["bar", "baz"]})
'{"foo": ["bar", "baz"]}'
body
fromJson(jsonObject)

Set values in this instance from the jsonObject Typical use case Message().fromJson(jsonObject) :param jsonObject:

getBody()
getStatusCode()
getType()
headers
msgType
requestId
setBody(body)
setStatusCode(code)
statusCode
toJson()

Serialize the Response to JSON

url