Connect

Usage

from mbed_cloud import ConnectAPI
connectApi = ConnectAPI()

# List all connected devices
devices = connectApi.list_connected_devices()

# Get the first connected device
device = devices.data[0]

# Get resources of the first connected endpoint
resources = connectApi.list_resources(device.id)

# Get resources which are observable
observable = filter(lambda r: r.observable, resources)

# Subscribe to observable resource
connectApi.add_resource_subscription(device.id, observable[0].path)

# Register a webhook to send all updates to
connectApi.update_webhook(WEBHOOK_URL)

# Remove webhook, and now use notifications instead
connectApi.delete_webhook()
connectApi.start_notifications()

# Read the current resource value by blocking
resource_value = connectApi.get_resource_value(device.id, observable[0].path)

# Get next one, but do it async waiting for it to finish
async_handler = connectApi.get_resource_value_async(device.id, observable[0].path)
while not async_handler.is_done:
  time.sleep(1)
if async_handler.error:
  raise Exception("Something went wrong: %s" % (async_handler.error))
resource_value = async_handler.value
from mbed_cloud import ConnectAPI
connectApi = ConnectAPI()

# Get Metrics from the last 30 days grouped in 1 day interval
metrics = list(connectApi.list_metrics(interval="1d", period="30d"))
for idx, metric in enumerate(metrics):
    print(metric)

More examples

See full listing of examples in the examples directory.

Reference

class mbed_cloud.connect.ConnectAPI(params=None)

API reference for the Connect API.

Exposing functionality for doing a range of device related actions:
  • Listing connected devices
  • Exploring and managing resources and resource values on connected devices
  • Setup resource subscriptions and webhooks for resource monitoring
add_resource_subscription(device_id, resource_path, fix_path=True, queue_size=5)

Subscribe to resource updates.

When called on a valid device and resource path a subscription is setup so that any update on the resource path value triggers a new element on the FIFO queue. The returned object is a native Python Queue object.

Parameters:
  • device_id – Name of device to subscribe on (Required)
  • resource_path – The resource path on device to observe (Required)
  • fix_path – Removes leading / on resource_path if found
  • queue_size – Sets the Queue size. If set to 0, no queue object will be created
Returns:

a queue of resource updates

Return type:

Queue

add_resource_subscription_async(device_id, resource_path, callback_fn, fix_path=True, queue_size=5)

Subscribe to resource updates with callback function.

When called on a valid device and resource path a subscription is setup so that any update on the resource path value triggers an update on the callback function.

Parameters:
  • device_id – Name of device to set the subscription on (Required)
  • resource_path – The resource path on device to observe (Required)
  • callback_fn – Callback function to be executed on update to subscribed resource
  • fix_path – Removes leading / on resource_path if found
  • queue_size – Sets the Queue size. If set to 0, no queue object will be created
Returns:

void

delete_device_subscriptions(device_id)

Removes a device’s subscriptions

Parameters:device_id – ID of the device (Required)
Returns:None
delete_presubscriptions()

Deletes pre-subscription data.

Returns:None
delete_resource_subscription(device_id=None, resource_path=None, fix_path=True)

Unsubscribe from device and/or resource_path updates.

If device_id or resource_path is None, or this method is called without arguments, all subscriptions are removed. Calling it with only device_id removes subscriptions for all resources on the given device.

Parameters:
  • device_id – device to unsubscribe events from. If not provided, all registered devices will be unsubscribed.
  • resource_path – resource_path to unsubscribe events from. If not provided, all resource paths will be unsubscribed.
  • fix_path – remove trailing / in resouce path to ensure API works.
Returns:

void

delete_subscriptions()

Remove all subscriptions.

Warning: This could be slow for large numbers of connected devices. If possible, explicitly delete subscriptions known to have been created.

Returns:None
delete_webhook()

Delete/remove registered webhook.

If no webhook is registered, an exception (404) will be raised.

Note that every registered subscription will be deleted as part of deregistering a webhook.

Returns:void
ensure_notifications_thread()

Ensure notification thread is running

execute_resource(device_id, resource_path, fix_path=True, timeout=None)

Execute a function on a resource.

Will block and wait for response to come through. Usage:

try:
    v = api.execute_resource(device, path)
    print("Success, returned value:", v)
except AsyncError, e:
    print("Error", e)
Parameters:
  • device_id (str) – The name/id of the device (Required)
  • resource_path (str) – The resource path to update (Required)
  • resource_function (str) – Unused
  • fix_path – Unused
  • timeout – Timeout in seconds
Raises:

AsyncError

Returns:

The value returned from the function executed on the resource

Return type:

str

execute_resource_async(device_id, resource_path, fix_path=True)

Execute a function on a resource.

Will not block. Returns immediately. Usage:

a = api.execute_resource_async(device, path)
while not a.is_done:
    time.sleep(0.1)
if a.error:
    print("Error", a.error)
print("Success, returned value:", a.value)
Parameters:
  • device_id (str) – The name/id of the device (Required)
  • resource_path (str) – The resource path to update (Required)
  • fix_path – Unused
Returns:

An async consumer object holding reference to request

Return type:

AsyncConsumer

get_resource(device_id, resource_path)

Get a resource.

Parameters:
  • device_id (str) – ID of the device (Required)
  • path (str) – Path of the resource to get (Required)
Returns:

Device resource

:rtype Resource

get_resource_subscription(device_id, resource_path, fix_path=True)

Read subscription status.

Parameters:
  • device_id – Name of device to set the subscription on (Required)
  • resource_path – The resource path on device to observe (Required)
  • fix_path – Removes leading / on resource_path if found
Returns:

status of subscription

get_resource_value(device_id, resource_path, fix_path=True, timeout=None)

Get a resource value for a given device and resource path by blocking thread.

Example usage:

try:
    v = api.get_resource_value(device_id, path)
    print("Current value", v)
except CloudAsyncError, e:
    print("Error", e)
Parameters:
  • device_id (str) – The name/id of the device (Required)
  • resource_path (str) – The resource path to get (Required)
  • fix_path – if True then the leading /, if found, will be stripped before doing request to backend. This is a requirement for the API to work properly
  • timeout – Seconds to request value for before timeout. If not provided, the program might hang indefinitely.
Raises:

CloudAsyncError, CloudTimeoutError

Returns:

The resource value for the requested resource path

Return type:

str

get_resource_value_async(device_id, resource_path, fix_path=True)

Get a resource value for a given device and resource path.

Will not block, but instead return an AsyncConsumer. Example usage:

a = api.get_resource_value_async(device, path)
while not a.is_done:
    time.sleep(0.1)
if a.error:
    print("Error", a.error)
print("Current value", a.value)
Parameters:
  • device_id (str) – The name/id of the device (Required)
  • resource_path (str) – The resource path to get (Required)
  • fix_path (bool) – strip leading / of path if present
Returns:

Consumer object to control asynchronous request

Return type:

AsyncConsumer

get_webhook()

Get the current callback URL if it exists.

Returns:The currently set webhook
has_active_notification_thread

Has active notification thread

list_connected_devices(**kwargs)

List connected devices.

Example usage, listing all registered devices in the catalog:

filters = {
    'created_at': {'$gte': datetime.datetime(2017,01,01),
                   '$lte': datetime.datetime(2017,12,31)
                  }
}
devices = api.list_connected_devices(order='asc', filters=filters)
for idx, device in enumerate(devices):
    print(device)

## Other example filters

# Directly connected devices (not via gateways):
filters = {
    'host_gateway': {'$eq': ''},
    'device_type': {'$eq': ''}
}

# Devices connected via gateways:
filters = {
    'host_gateway': {'$neq': ''}
}

# Gateway devices:
filters = {
    'device_type': {'$eq': 'MBED_GW'}
}
Parameters:
  • limit (int) – The number of devices to retrieve.
  • order (str) – The ordering direction, ascending (asc) or descending (desc)
  • after (str) – Get devices after/starting at given device_id
  • filters – Dictionary of filters to apply.
Returns:

a list of connected Device objects.

Return type:

PaginatedResponse

list_device_subscriptions(device_id, **kwargs)

Lists all subscribed resources from a single device

Parameters:device_id – ID of the device (Required)
Returns:a list of subscribed resources
Return type:list of str
list_metrics(include=None, interval=‘1d’, **kwargs)

Get statistics.

Parameters:
  • include (list[str]) – List of fields included in response. None, or an empty list will return all fields. Fields: transactions, successful_api_calls, failed_api_calls, successful_handshakes, pending_bootstraps, successful_bootstraps, failed_bootstraps, registrations, updated_registrations, expired_registrations, deleted_registrations
  • interval (str) – Group data by this interval in days, weeks or hours. Sample values: 2h, 3w, 4d.
  • start (datetime) – Fetch the data with timestamp greater than or equal to this value. The parameter is not mandatory, if the period is specified.
  • end (datetime) – Fetch the data with timestamp less than this value. The parameter is not mandatory, if the period is specified.
  • period (str) – Period. Fetch the data for the period in days, weeks or hours. Sample values: 2h, 3w, 4d. The parameter is not mandatory, if the start and end time are specified
  • limit (int) – The number of devices to retrieve
  • order (str) – The ordering direction, ascending (asc) or descending (desc)
  • after (str) – Get metrics after/starting at given metric ID
Returns:

a list of Metric objects

Return type:

PaginatedResponse

list_presubscriptions(**kwargs)

Get a list of pre-subscription data

Returns:a list of Presubscription objects
Return type:list of mbed_cloud.presubscription.Presubscription
list_resources(device_id)

List all resources registered to a connected device.

>>> for r in api.list_resources(device_id):
        print(r.name, r.observable, r.uri)
None,True,/3/0/1
Update,False,/5/0/3
...
Parameters:device_id (str) – The ID of the device (Required)
Returns:A list of Resource objects for the device
Return type:list
notify_webhook_received(payload)

Callback function for triggering notification channel handlers.

Use this in conjunction with a webserver to complete the loop when using webhooks as the notification channel.

Parameters:payload (str) – the encoded payload, as sent by the notification channel
set_resource_value(device_id, resource_path, resource_value, fix_path=True, timeout=None)

Set resource value for given resource path, on device.

Will block and wait for response to come through. Usage:

try:
    v = api.set_resource_value(device, path, value)
    print("Success, new value:", v)
except AsyncError, e:
    print("Error", e)
Parameters:
  • device_id (str) – The name/id of the device (Required)
  • resource_path (str) – The resource path to update (Required)
  • resource_value (str) – The new value to set for given path
  • fix_path – Unused
  • timeout – Timeout in seconds
Raises:

AsyncError

Returns:

The value of the new resource

Return type:

str

set_resource_value_async(device_id, resource_path, resource_value=None, fix_path=True)

Set resource value for given resource path, on device.

Will not block. Returns immediately. Usage:

a = api.set_resource_value_async(device, path, value)
while not a.is_done:
    time.sleep(0.1)
if a.error:
    print("Error", a.error)
print("Success, new value:", a.value)
Parameters:
  • device_id (str) – The name/id of the device (Required)
  • resource_path (str) – The resource path to update (Required)
  • resource_value (str) – The new value to set for given path
  • fix_path – Unused
Returns:

An async consumer object holding reference to request

Return type:

AsyncConsumer

start_notifications()

Start the notifications thread.

If an external callback is not set up (using update_webhook) then calling this function is mandatory to get or set resource.

>>> api.start_notifications()
>>> print(api.get_resource_value(device, path))
Some value
>>> api.stop_notifications()
Returns:void
stop_notifications()

Stop the notifications thread.

Returns:
update_presubscriptions(presubscriptions)

Update pre-subscription data. Pre-subscription data will be removed for empty list.

Parameters:presubscriptions – list of Presubscription objects (Required)
Returns:None
update_webhook(url, headers=None)

Register new webhook for incoming subscriptions.

If a webhook is already set, this will do an overwrite.

Parameters:
  • url (str) – the URL with listening webhook (Required)
  • headers (dict) – K/V dict with additional headers to send with request
Returns:

void

class mbed_cloud.connect.AsyncConsumer(async_id, db)

Consumer object for reading values from a notifications thread.

Example usage:

async_resp = api.get_resource_value(device, resource)
while not async_resp.is_done:
    time.sleep(0.1)
if async_resp.error:
    raise Exception("Async error: %r" % async_resp.error)
print("Got value: %r" % (async_resp.value,))
check_error()

Check if the async response is an error.

Take care to call is_done before calling error. Note that the error messages are always encoded as strings.

Raises:CloudUnhandledError – When not checking is_done first
Returns:status_code, error_msg, payload
Return type:tuple
error

Check if the async response is an error.

Take care to call is_done before calling error. Note that the error messages are always encoded as strings.

Raises:CloudUnhandledError – When not checking is_done first
Returns:the error value/payload, if found.
Return type:str
is_done

Check if the DB has received an event with the specified async ID.

Returns:Whether the async request has finished or not
Return type:bool
to_dict()

JSON serializable representation of the consumer.

value

Get the value of the finished async request, if it is available.

Raises:CloudUnhandledError – When not checking value of error or is_done first
Returns:the payload value
Return type:str
wait(timeout=0)

Blocks until timeout (seconds) or forever

Parameters:timeout – time to wait, in seconds
Returns:
class mbed_cloud.connect.Metric(dictionary)

Describes Metric object from statistics.

deleted_registrations

The number of deleted registrations (deregistrations) linked to the account.

Deregistration is the process of removing the device registration from the Mbed Cloud Connect registry. The deregistration is usually initiated by the device. Mbed Cloud Connect no longer handles requests for a deregistered device.

Return type:int
expired_registrations

The number of expired registrations linked to the account.

Mbed Cloud Connect removes the device registrations when the devices cannot update their registration before the expiry of the lifetime. Mbed Cloud Connect no longer handles requests for a device whose registration has expired already.

Return type:int
failed_api_calls

The number of failed requests the account has performed.

Return type:int
failed_bootstraps

The number of failed bootstraps the account has performed.

Bootstrap is the process of provisioning a Lightweight Machine to Machine Client to a state where it can initiate a management session to a new Lightweight Machine to Machine Server.

Return type:int
failed_proxy_requests

The number of failed proxy requests from Mbed Cloud Connect to devices.

The proxy requests are made from Mbed Cloud Connect to devices linked to the account when you try to read or write values to device resources using Connect API endpoints.

Return type:int
failed_subscription_requests

The number of failed subscription requests from Mbed Cloud Connect to devices.

The subscription requests are made from Mbed Cloud Connect to devices linked to the account when you try to subscribe to a resource path using Connect API endpoints.

Return type:int
full_registrations

The number of full registrations linked to the account.

Full registration is the process of registering a device with the Mbed Cloud Connect by providing its lifetime and capabilities such as the resource structure. The registered status of the device does not guarantee that the device is active and accessible from Mebd Cloud Connect at any point of time.

Return type:int
handshakes

The number of successful TLS handshakes the account has performed.

The SSL or TLS handshake enables the SSL or TLS client and server to establish the secret keys with which they communicate. A successful TLS handshake is required for establishing a connection with Mbed Cloud Connect for any operaton such as registration, registration update and deregistration.

Return type:int
id

The ID of the metric.

Return type:string
observations

The number of observations received by Mbed Cloud Connect from the devices.

The observations are pushed from the devices linked to the account to Mbed Cloud Connect when you have successfully subscribed to the device resources using Connect API endpoints.

Return type:int
pending_bootstraps

The number of pending bootstraps the account has performed.

Bootstrap is the process of provisioning a Lightweight Machine to Machine Client to a state where it can initiate a management session to a new Lightweight Machine to Machine Server.

Return type:int
successful_api_calls

The number of successful requests the account has performed.

Return type:int
successful_bootstraps

The number of successful bootstraps the account has performed.

Bootstrap is the process of provisioning a Lightweight Machine to Machine Client to a state where it can initiate a management session to a new Lightweight Machine to Machine Server.

Return type:int
successful_proxy_requests

The number of successful proxy requests from Mbed Cloud Connect to devices.

The proxy requests are made from Mbed Cloud Connect to devices linked to the account when you try to read or write values to device resources using Connect API endpoints.

Return type:int
successful_subscription_requests

The number of successful subscription requests from Mbed Cloud Connect to devices.

The subscription requests are made from Mbed Cloud Connect to devices linked to the account when you try to subscribe to a resource path using Connect API endpoints.

Return type:int
timestamp

UTC time in RFC3339 format.

The timestamp is the starting point of the interval for which the data is aggregated. Each interval includes data for the time greater than or equal to the timestamp and less than the next interval’s starting point.

Returns:The timestamp of this Metric.
Return type:datetime
transactions

The number of transaction events from or to devices linked to the account.

A transaction is a 512-byte block of data processed by Mbed Cloud. It can be either sent by the device (device –> Mbed Cloud) or received by the device (Mbed Cloud –> device). A transaction does not include IP, TCP or UDP, TLS or DTLS packet overhead. It only contains the packet payload (full CoAP packet including CoAP headers).

Return type:int
update_attributes(updates)

Update attributes.

updated_registrations

The number of registration updates linked to the account.

Registration update is the process of updating the registration status with the Mbed Cloud Connect to update or extend the lifetime of the device.

Return type:int
class mbed_cloud.connect.Resource(resource_obj)

Describes resource type from device.

Example usage:

>>> resources = api.list_resources(device_id)
>>> for r in resources:
        print(r.uri, r.name, r.observable)
/3/0/1,None,True
/5/0/2,Update,False
...
content_type

The content type of this Resource, if set.

Returns:The content type of the Resource.
Return type:str
observable

Get the observability of this Resource.

Whether the resource is observable or not (true/false)

Returns:The observability of this ResourcesData.
Return type:bool
path

Get the URI of this Resource.

Returns:The URI of this Resource.
Return type:str
to_dict()

Return dictionary of object.

type

Get the type of this Resource, if set.

Returns:The type of the Resource.
Return type:str
class mbed_cloud.connect.Webhook(dictionary)

Describes webhook object.

headers

Get the headers of this Webhook.

Headers (key/value) that are sent with the notification. Optional.

Returns:The headers of this Webhook.
Return type:dict(str, str)
update_attributes(updates)

Update attributes.

url

Get the URL of this Webhook.

The URL to which the notifications are sent. We recommend that you serve this URL over HTTPS.

Returns:The url of this Webhook.
Return type:str