Monitor API

Monitor Overview

Provide access to Device Cloud monitor API which can be used to subscribe to topics to receive notifications when data is received on Device Cloud.

SCI API Documentation

devicecloud.monitor.MON_ID_ATTR = <devicecloud.conditions.Attribute object>

System-generated identifier for the monitor.

devicecloud.monitor.MON_CST_ID_ATTR = <devicecloud.conditions.Attribute object>

Device Cloud customer identifier.

devicecloud.monitor.MON_TOPIC_ATTR = <devicecloud.conditions.Attribute object>

One or more topics to monitor separated by comma. See Device Cloud documentation for more details

devicecloud.monitor.MON_FORMAT_TYPE_ATTR = <devicecloud.conditions.Attribute object>

Format for delivered event data: xml, json

devicecloud.monitor.MON_TRANSPORT_TYPE_ATTR = <devicecloud.conditions.Attribute object>

Transport method used to deliver push notifications to the client application: tcp, http

devicecloud.monitor.MON_HTTP_TRANSPORT_URL_ATTR = <devicecloud.conditions.Attribute object>

For HTTP transport type only. URL of the customer web server. For http URLs, the default listening port is 80; for https URLs, the default listening port is 443.

devicecloud.monitor.MON_HTTP_TRANSPORT_TOKEN_ATTR = <devicecloud.conditions.Attribute object>

For HTTP transport type only. Credentials for basic authentication in the following format: username:password

devicecloud.monitor.MON_HTTP_TRANSPORT_METHOD_ATTR = <devicecloud.conditions.Attribute object>

For HTTP transport type only. HTTP method to use for sending data: PUT or POST. The default is PUT.

devicecloud.monitor.MON_HTTP_CONNECT_TIMEOUT_ATTR = <devicecloud.conditions.Attribute object>

For HTTP transport type only. Time in milliseconds Device Cloud waits when attempting to connect to the destination http server. A value of 0 means use the system default of 5000 (5 seconds). Most monitors do not need to configure this setting.

devicecloud.monitor.MON_HTTP_RESPONSE_TIMEOUT_ATTR = <devicecloud.conditions.Attribute object>

For HTTP transport type only. Time in milliseconds Device Cloud waits for a response for pushed events from the http server. A value of 0 means use the system default of 5000 (5 seconds). Most monitors do not need to configure this setting.

devicecloud.monitor.MON_TCP_ACK_OPTION_ATTR = <devicecloud.conditions.Attribute object>

For TCP transport type only. Indicates whether the client will explicitly acknowledge TCP push events or allow Device Cloud to automatically acknowledge events when sent. Options include: explicit or off. The default is off.

devicecloud.monitor.MON_BATCH_SIZE_ATTR = <devicecloud.conditions.Attribute object>

Specifies an upper bound on how many messages are aggregated before sending a batch. The default is 100.

devicecloud.monitor.MON_BATCH_DURATION_ATTR = <devicecloud.conditions.Attribute object>

Specifies an upper bound on the number of seconds messages are aggregated before sending. The default is 10.

devicecloud.monitor.MON_COMPRESSION_ATTR = <devicecloud.conditions.Attribute object>

Keyword that specifies the method used to compress messages. Options include: zlib or none. The default is none. For zlib, the deflate algorithm is used to compress the data; use inflate to decompress the data.

Note: For backwards compatibility, gzip is accepted as a valid keyword. Compression has always been done using the deflate algorithm.

devicecloud.monitor.MON_AUTO_REPLAY_ON_CONNECT = <devicecloud.conditions.Attribute object>

Boolean value that specifies whether Device Cloud replays any missed published events before any new published events are forwarded. True indicates missed published events are replayed. False indicates missed published events are not replayed. The default is false.

devicecloud.monitor.MON_DESCRIPTION_ATTR = <devicecloud.conditions.Attribute object>

Optional text field used to label or describe the monitor.

devicecloud.monitor.MON_LAST_CONNECT_ATTR = <devicecloud.conditions.Attribute object>

Specifies last connection time to the client application.

devicecloud.monitor.MON_LAST_SENT_ATTR = <devicecloud.conditions.Attribute object>

Specifies the last message pushed to the client application

devicecloud.monitor.MON_STATUS_ATTR = <devicecloud.conditions.Attribute object>

Specifies the current connection status to the client application:

  • CONNECTING: For HTTP monitors only. Device Cloud is attempting

    to connect to the configured HTTP server. Once connected, the state changes to ACTIVE.

  • ACTIVE: Monitor is connected and publishing events.

  • INACTIVE: Monitor is not connected and events are not published or recorded.

  • SUSPENDED: For monitors with monAutoReplayOnConnect = True. Monitor has disconnected,

    but publish events are recorded for later replay.

  • DISABLED: For HTTP monitors only. If a monitor has not connected for 24 hours,

    the state is set to DISABLED, and publish events are not recorded for replay. A disabled monitor must be reconfigured via the Monitor web service.

class devicecloud.monitor.MonitorAPI(conn)

Provide access to Device Cloud Monitor API for receiving push notifications

The Monitor API in Device Cloud allows for the creation and destruction of multiple “monitors.” Each monitor is registered against one or more “topics” which describe the data in which it is interested.

There are, in turn, two main ways to receive data matching the topics for a given monitor:

  1. Stream: Device Cloud supports a protocol over TCP (optionally with SSL) over which the batches of events will be sent when they are received.

  2. HTTP: When batches of events are received, a configured web service endpoint will received a POST request with the new data.

Currently, this library supports setting up both types of monitors, but there is no special support provided for parsing HTTP postback requests.

More information on the format for topic strings can be found in the device cloud documentation for monitors.

Here’s a quick example showing a typical pattern used for creating a push monitor and associated listener that triggers a callback. Deletion of existing monitors matching the same topics is not necessary but sometimes done in order to ensure that changes to the monitor configuration in code always make it to the monitor configuration in Device Cloud:

def monitor_callback(json_data):
    print(json_data)
    return True  # message received

# Listen for DataPoint updates
topics = ['DataPoint[U]']
monitor = dc.monitor.get_monitor(topics)
if monitor:
    monitor.delete()
monitor = dc.monitor.create_tcp_monitor(topics)
monitor.add_listener(monitor_callback)

# later...
dc.monitor.stop_listeners()

When updates to any DataPoint in Device Cloud occurs, the callback will be called with a data structure like this one:

{'Document': {'Msg': {'DataPoint': {'cstId': 7603,
                                    'data': 0.411700824929,
                                    'description': '',
                                    'id': '684572e0-12c4-11e5-8507-fa163ed4cf14',
                                    'quality': 0,
                                    'serverTimestamp': 1434307047694,
                                    'streamId': 'test',
                                    'streamUnits': '',
                                    'timestamp': 1434307047694},
                        'group': '*',
                        'operation': 'INSERTION',
                        'timestamp': '2015-06-14T18:37:27.815Z',
                        'topic': '7603/DataPoint/test'}}}
create_tcp_monitor(topics, batch_size=1, batch_duration=0, compression='gzip', format_type='json')

Creates a TCP Monitor instance in Device Cloud for a given list of topics

Parameters
  • topics – a string list of topics (e.g. [‘DeviceCore[U]’, ‘FileDataCore’]).

  • batch_size – How many Msgs received before sending data.

  • batch_duration – How long to wait before sending batch if it does not exceed batch_size.

  • compression – Compression value (i.e. ‘gzip’).

  • format_type – What format server should send data in (i.e. ‘xml’ or ‘json’).

Returns an object of the created Monitor

create_http_monitor(topics, transport_url, transport_token=None, transport_method='PUT', connect_timeout=0, response_timeout=0, batch_size=1, batch_duration=0, compression='none', format_type='json')

Creates a HTTP Monitor instance in Device Cloud for a given list of topics

Parameters
  • topics – a string list of topics (e.g. [‘DeviceCore[U]’, ‘FileDataCore’]).

  • transport_url – URL of the customer web server.

  • transport_token – Credentials for basic authentication in the following format: username:password

  • transport_method – HTTP method to use for sending data: PUT or POST. The default is PUT.

  • connect_timeout – A value of 0 means use the system default of 5000 (5 seconds).

  • response_timeout – A value of 0 means use the system default of 5000 (5 seconds).

  • batch_size – How many Msgs received before sending data.

  • batch_duration – How long to wait before sending batch if it does not exceed batch_size.

  • compression – Compression value (i.e. ‘gzip’).

  • format_type – What format server should send data in (i.e. ‘xml’ or ‘json’).

Returns an object of the created Monitor

get_monitors(condition=None, page_size=1000)

Return an iterator over all monitors matching the provided condition

Get all inactive monitors and print id:

for mon in dc.monitor.get_monitors(MON_STATUS_ATTR == "DISABLED"):
    print(mon.get_id())

Get all the HTTP monitors and print id:

for mon in dc.monitor.get_monitors(MON_TRANSPORT_TYPE_ATTR == "http"):
    print(mon.get_id())

Many other possibilities exist. See the devicecloud.condition documention for additional details on building compound expressions.

Parameters
  • condition (Expression or None) – An Expression which defines the condition which must be matched on the monitor that will be retrieved from Device Cloud. If a condition is unspecified, an iterator over all monitors for this account will be returned.

  • page_size (int) – The number of results to fetch in a single page.

Returns

Generator yielding DeviceCloudMonitor instances matching the provided conditions.

get_monitor(topics)

Attempts to find a Monitor in device cloud that matches the provided topics

Parameters

topics – a string list of topics (e.g. ['DeviceCore[U]', 'FileDataCore']))

Returns a DeviceCloudMonitor if found, otherwise None.

stop_listeners()

Stop any listener threads that may be running and join on them

class devicecloud.monitor.DeviceCloudMonitor(conn, monitor_id, *args, **kwargs)

Provides access to a single monitor instance on Device Cloud

This is a base class that should not be instantiated directly.

get_id()

Get the ID of this monitor as an integer

get_metadata()

Get additional information about this monitor

This method returns a dictionary where the keys contain information about the monitor. The returned data will look something like this:

{
    'cstId': '7603',
    'monBatchDuration': '10',
    'monBatchSize': '1',
    'monCompression': 'zlib',
    'monFormatType': 'json',
    'monId': '178023',
    'monStatus': 'INACTIVE',
    'monTopic': 'DeviceCore,FileDataCore,FileData,DataPoint',
    'monTransportType': 'tcp'
}
delete()

Delete this monitor form Device Cloud

class devicecloud.monitor.HTTPDeviceCloudMonitor(conn, monitor_id, *args, **kwargs)

Device Cloud Monitor with HTTP transport type

class devicecloud.monitor.TCPDeviceCloudMonitor(conn, monitor_id, tcp_client_manager)

Device Cloud Monitor with TCP transport type

add_callback(callback)

Create a secure SSL/TCP listen session to Device Cloud

exception devicecloud.monitor_tcp.PushException

Indicates an issue interacting with Push Functionality.

class devicecloud.monitor_tcp.PushSession(callback, monitor_id, client)

A PushSession is responsible for establishing a socket connection with iDigi to receive events generated by Devices connected to iDigi.

send_connection_request()

Sends a ConnectionRequest to the iDigi server using the credentials established with the id of the monitor as defined in the monitor member.

start()

Creates a TCP connection to Device Cloud and sends a ConnectionRequest message

stop()

Stop/Close this session

Close the socket associated with this session and puts Session into a state such that it can be re-established later.

class devicecloud.monitor_tcp.SecurePushSession(callback, monitor_id, client, ca_certs=None)

SecurePushSession extends PushSession by wrapping the socket connection in SSL. It expects the certificate to match any of those in the passed in ca_certs member file.

start()

Creates a SSL connection to the iDigi Server and sends a ConnectionRequest message.

class devicecloud.monitor_tcp.CallbackWorkerPool(write_queue=None, size=1)

A Worker Pool implementation that creates a number of predefined threads used for invoking Session callbacks.

queue_callback(session, block_id, data)

Queues up a callback event to occur for a session with the given payload data. Will block if the queue is full.

Parameters
  • session – the session with a defined callback function to call.

  • block_id – the block_id of the message received.

  • data – the data payload of the message received.

class devicecloud.monitor_tcp.TCPClientManager(conn, secure=True, ca_certs=None, workers=1)

A Client for the ‘Push’ feature in Device Cloud

create_session(callback, monitor_id)

Creates and Returns a PushSession instance based on the input monitor and callback. When data is received, callback will be invoked. If neither monitor or monitor_id are specified, throws an Exception.

Parameters
  • callback – Callback function to call when PublishMessage messages are received. Expects 1 argument which will contain the payload of the pushed message. Additionally, expects function to return True if callback was able to process the message, False or None otherwise.

  • monitor_id – The id of the Monitor, will be queried to understand parameters of the monitor.

stop()

Stops all session activity.

Blocks until io and writer thread dies