47
Relayr Python Client Documentation Release 0.3.0 relayr.io Apr 27, 2017

Relayr Python Client Documentation - Read the Docs · 1.6 OpenWRT ... server status ok: True (0.42 s ... this should print incoming MQTT messages from

  • Upload
    vantu

  • View
    252

  • Download
    0

Embed Size (px)

Citation preview

Relayr Python Client DocumentationRelease 0.3.0

relayr.io

Apr 27, 2017

Contents

1 User’s Guide 31.1 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31.2 Testing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51.3 Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61.4 Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71.5 Raspberry Pi . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 311.6 OpenWRT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 321.7 Documentation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 351.8 Contributing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

2 Indices and tables 37

Python Module Index 39

i

ii

Relayr Python Client Documentation, Release 0.3.0

Welcome to the relayr Python Library Documentation Reference. Here you will find the full reference to the classesincluded in the library, code samples as well as examples which will assist you in getting started with your own relayrPython projects.

See the full relayr API Reference for information about the relayr API.

Contents 1

Relayr Python Client Documentation, Release 0.3.0

2 Contents

CHAPTER 1

User’s Guide

Installation

This part of the documentation covers the installation of the relayr library. If you are an experienced Python user ordeveloper you will likely already be familiar with much of the information below and may want to skip this section.In case you are new to Python you may find the below information useful.

Installing the installer

The recommended installation tool for Python packages today is pip. If it is not already installed on your machine youcan do so easily as follows:

$ wget https://bootstrap.pypa.io/get-pip.py$ python get-pip.py

Using easy_install from setuptools is deprecated for various reasons. You can find more about packaging in thePython Packaging User Guide.

Creating a virtual environment

In order not to risk your existing Python installation it is recommended to create a virtual Python environment (short:a virtualenv), in which you can install the relayr library and its dependencies. To do that in Python 2.x you need tohave a package named virtualenv installed (a simple pip install virtualenv will do):

$ virtualenv rvenvNew python executable in rvenv/bin/pythonInstalling setuptools, pip...done.$

In Python 3.3 and higher a tool named pyvenv is part of the standard Python installation:

3

Relayr Python Client Documentation, Release 0.3.0

$ pyvenv rvenv$

In both cases the above lines will create a subfolder named rvenv containing a separate Python installation, plusadditional tools like pip. You can activate and deactivate this environment using the following commands in aterminal:

$ source rvenv/bin/activate(rvenv) $ # do some work... download, test, install, use...(rvenv) $ deactivate$

Installing a release

You can install a release of the relayr library from PyPI with a single pip command. Inside a virtual Python environmentthis should be done after activating that environment first (at the point of # do some work... in the previoussection above). This will install the latest version from PyPI:

$ pip install relayr

You can also run a source distribution of a release from PyPI if you want to run the test suite and/or generate thedocumentation yourself (more about this option below). Just download a tarball of the sources and unpack as follows:

$ wget https://pypi.python.org/packages/source/r/relayr/relayr-0.3.0.tar.gz$ tar xfz relayr-0.3.0.tar.gz$ cd relayr-0.3.0$ python setup.py install

Installing a development version

The relayr library is hosted and developed on GitHub. If you wish to work with the development version of relayr,you have two options (again, both recommended for a virtual environment):

1. Checking out from the repository with git

You can operate on a git checkout. This will pull in the dependencies and activate the git head as the currentversion inside the virtualenv. Then all you have to do is run git pull origin to update to the latest version,before installing the package itself:

$ git clone http://github.com/relayr/python-sdk.gitCloning into 'python-sdk'...[...]$ cd python-sdk$ git pull origin$ python setup.py install

2. Downloading the repository with pip

You could also let pip itself pull in the development version without git:

4 Chapter 1. User’s Guide

Relayr Python Client Documentation, Release 0.3.0

$ pip install git+git://github.com/relayr/python-sdk.git[...]Cleaning up...$ python setup.py install

If you want to create the local documentation using Sphinx and/or run the test suite using pytest please read therespective sections, Documentation and Testing.

Testing

The source code distribution of the relayr Python library contains a testsuite that can be run after downloading the fullcode archive. It is not installed together with the Python package itself, but needs to be run from the unarchived codedistribution. This has been tested mainly on Linux and OS X, and to some degree on a Raspberry Pi running Rasbianand a WRTnode running OpenWRT.

Testing on a single Python version

The test suite is located inside the tests subdirectory and can be run using the PyTest framework which, unlike theunittest framework, does not require writing much boilerplate code. This allows, among other things, reusingsingle test snippets more easily outside of the test suite.

To run the tests you don’t even need to have PyTest installed, since the archive contains a file named runtests.pywhich is essentially a minimized version of PyTest itself (generated by the respective py.test tool).

Running the full test suite from the main directory of the unarchived code distribution is as simple as this:

$ python runtests.py tests

If you have PyTest installed (pip install pytest will do) you can ignore the runtests.py file:

$ py.test tests

In both cases the output should be something like this, when everything runs correctly (the s indicates a skipped test,here because of platform limitations):

=========================== test session starts ============================platform darwin -- Python 2.7.8 -- py-1.4.26 -- pytest-2.6.4collected 49 items

tests/test_anonymous.py ............tests/test_bluetooth.py sstests/test_config.py .tests/test_data_access.py ...ss.tests/test_registered.py ............................

================== 45 passed, 4 skipped in 103.02 seconds ==================

Of course, you can add more verbosity, run selected test modules or methods if desired and much more. Please see thePyTest documentation for more information!

1.2. Testing 5

Relayr Python Client Documentation, Release 0.3.0

Testing on multiple Python versions

One other, and significant, advantage of using the PyTest framework is being able to run the tests easily over a wholerange of Python versions. A nice tool for automating this is tox, which can be easily installed with pip installtox. Given a short configuration file named tox.ini like the one provided in the top-level directory of this packageone can simply call tox to run the test suite over multiple versions of Python automatically (below only the summaryof a run over four versions is shown):

$ tox

=========================== test session starts ============================[ ... detailed output skipped here ... ]================== 45 passed, 4 skipped in 103.02 seconds ==================_________________________________ summary __________________________________

py26: commands succeededpy27: commands succeededpy33: commands succeededpy34: commands succeeded

Examples

The following is a list of examples created with the existing relayr API.

demos/api_pulse.py

This script shows key entities of the current relayr API on the command-line. It does provide versioning informationand makes a couple of API calls to list current counts of publishers, applications, public devices and more. A typical(slightly abbreviated) output will look something like this:

$ python demos/api_pulse.pyRelayr API Pulse[...]server status ok: True (0.42 s)467 publishers (0.51 s)267 applications (0.69 s)328 public devices (0.74 s)8 device models (0.38 s)8 device model meanings (0.38 s)#public devices by meaning: {

"acceleration": 57,"temperature": 84,"noise_level": 49,"angular_speed": 57,"color": 77,"luminosity": 77,"proximity": 77,"humidity": 84

}

To determine the number of publishers e.g. it runs code similar to this (timing omitted here for brevity reasons):

from relayr import Apiapi = Api()

6 Chapter 1. User’s Guide

Relayr Python Client Documentation, Release 0.3.0

publishers = list(api.get_public_publishers())print('%d publishers' % len(publishers))

demos/noise.py

This script establishes a connection to a WunderBar noise level sensor device, checks the incoming noise level valuesfor some time, compares them to a maximum threshold and sends a reminder, by email, to take action if needed.

Below you can see a version of that code stripped down to only a few lines (omitting the threshold comparison andemail notification part):

import timefrom relayr import Clientfrom relayr.dataconnection import MqttStreamc = Client(token='<my_token>')dev = c.get_device(id='<dev_id>')def mqtt_callback(topic, payload):

print('%s %s' % (topic, payload))stream = MqttStream(mqtt_callback, [dev])stream.start()time.sleep(10)stream.stop()

When running (with the correct token and device ID) this should print incoming MQTT messages from the noise levelsensor with timestamps and sound levels like this (scroll right to see the actual values):

/v1/36fb3b0e-4abd-4598-9e0c-b4952cab4082 {"deviceId":"df088c31-1f12-4969-9b23-→˓f7354b296367","modelId":"4f38b6c6-a8e9-4f93-91cd-2ac4064b7b5a","readings":[{"meaning→˓":"noiseLevel","value":33,"recorded":1431440372993}],"received":1431440129390}/v1/36fb3b0e-4abd-4598-9e0c-b4952cab4082 {"deviceId":"df088c31-1f12-4969-9b23-→˓f7354b296367","modelId":"4f38b6c6-a8e9-4f93-91cd-2ac4064b7b5a","readings":[{"meaning→˓":"noiseLevel","value":60,"recorded":1431440374973}],"received":1431440131539}/v1/36fb3b0e-4abd-4598-9e0c-b4952cab4082 {"deviceId":"df088c31-1f12-4969-9b23-→˓f7354b296367","modelId":"4f38b6c6-a8e9-4f93-91cd-2ac4064b7b5a","readings":[{"meaning→˓":"noiseLevel","value":25,"recorded":1431440377173}],"received":1431440134005}/v1/36fb3b0e-4abd-4598-9e0c-b4952cab4082 {"deviceId":"df088c31-1f12-4969-9b23-→˓f7354b296367","modelId":"4f38b6c6-a8e9-4f93-91cd-2ac4064b7b5a","readings":[{"meaning→˓":"noiseLevel","value":69,"recorded":1431440379373}],"received":1431440136160}/v1/36fb3b0e-4abd-4598-9e0c-b4952cab4082 {"deviceId":"df088c31-1f12-4969-9b23-→˓f7354b296367","modelId":"4f38b6c6-a8e9-4f93-91cd-2ac4064b7b5a","readings":[{"meaning→˓":"noiseLevel","value":18,"recorded":1431440381572}],"received":1431440138298}

Reference

API Layer

Implementation of the relayr HTTP RESTful API as individual endpoints.

This module contains the API class with one method for each API endpoint. All method names start with the HTTPmethod followed by the resource name used in that endpoint e.g. post_user_app for the endpoint POST /users/<id>/apps/<id> with minor modifications.

relayr.api.create_logger(sender)Create a logger for the requesting object.

1.4. Reference 7

Relayr Python Client Documentation, Release 0.3.0

relayr.api.build_curl_call(method, url, data=None, headers=None)Build and return a curl command for use on the command-line.

Parameters

• method (string) – HTTP request method, GET, POST, etc.

• url (string) – Full HTTP path.

• data (object serializable as JSON ) – Data to be transmitted, usually posted.

• headers (dictionary) – Additional HTTP request headers.

Return type string

Example:

cmd = build_curl_call('POST', 'http://foo.com/bar', data={'x': 42},headers={'SUPER_SECRET_KEY': '123'})

print(cmd)curl -X POST "http://foo.com/bar" -H "SUPER_SECRET_KEY: 123" --data "{"x": 42}"

class relayr.api.Api(token=None)This class provides direct access to the relayr API endpoints.

Examples:

# Create an anonymous client and call simple API endpoints:from relayr.api import Apia = Api()assert a.get_server_status() == {'database': 'ok'}assert a.get_users_validate('[email protected]') == {'exists': False}assert a.get_public_device_model_meanings() > 0

__init__(token=None)Object construction.

Parameters token (string) – A token generated on the relayr platform for a combination ofa relayr user and application.

perform_request(method, url, data=None, headers=None)Perform an API call and return a JSON result as Python data structure.

Parameters

• method (string) – HTTP request method, GET, POST, etc.

• url (string) – Full HTTP path.

• data (object serializable as JSON ) – Data to be transmitted, usually posted.

• headers (dictionary) – Additional HTTP request headers.

Return type string

Query parameters are expected in the url parameter. For returned status codes other than 2XX aRelayrApiException is raised which contains the API call (method and URL) plus a curl com-mand replicating the API call for debugging reuse on the command-line.

get_users_validate(userEmail)Get a user email address validation.

Parameters userEmail (string) – The user email address to be validated.

Return type A dict with an exists field and a Boolean result value.

8 Chapter 1. User’s Guide

Relayr Python Client Documentation, Release 0.3.0

Sample result:

{"exists": True}

get_server_status()Get server status.

Return type A dict with certain fields describing the server status.

Sample result:

{"database": "ok"}

post_oauth2_token(clientID, clientSecret, code, redirectURI)Generate and return an OAuth2 access token from supplied parameters.

Parameters

• clientID (string) – The client’s UUID.

• clientSecret (string) – The OAuth client secret.

• code (string) – The OAuth authorization code (valid for five minutes).

• redirectURI (string) – The redirect URI.

Return type dict with two fields, “access_token” and “token_type” (with string values for both)

get_oauth2_appdev_token(appID)Get a token representing a specific relayr application and user.

Parameters appID (string) – The application’s UUID.

Return type A dict with fields describing the token.

Sample result (anonymized token value):

{"token": "...","expiryDate": "2014-10-08T10:14:07.789Z"

}

post_oauth2_appdev_token(appID)Generate a new token representing a user and a relayr application.

Parameters appID (string) – The application’s UUID.

Return type A dict with fields describing the token.

delete_oauth2_appdev_token(appID)Revoke token for an application with given UUID.

Parameters appID (string) – The application’s UUID.

get_oauth2_user_info()Return information about the user initiating the request.

Return type A dictionary with fields describing the user.

Sample result (partly anonymized values):

{"email": "[email protected]","id": "...",

1.4. Reference 9

Relayr Python Client Documentation, Release 0.3.0

"name": "joefoo"}

patch_user(userID, name=None, email=None)Update user’s name or email attribute, or both.

Parameters

• userID (string) – the users’s UUID

• name (string) – the user name to be set

• email (string) – the user email to be set

Return type dict with user info fields

post_user_app(userID, appID)Install a new app for a specific user.

Parameters

• userID (string) – the users’s UUID

• appID (string) – The application’s UUID.

delete_user_app(userID, appID)Uninstall an app of a user with the respective UUIDs.

Parameters

• userID (string) – the users’s UUID

• appID (string) – the app’s UUID

get_user_publishers(userID)Get all publishers owned by a user with a specific UUID.

Parameters userID (string) – the users’s UUID

Return type list of dicts representing publishers

get_user_apps(userID)Get all apps installed for a user with a specific UUID.

Parameters userID (string) – the users’s UUID

Return type list of dicts ... with UUIDs and secrets

get_user_transmitters(userID)Get all transmitters for a user with a specific UUID.

Parameters userID (string) – the users’s UUID

Return type list of dicts with UUIDs and secrets

get_user_devices(userID)Get all devices registered for a user with a specific UUID.

Parameters userID (string) – the users’s UUID

Return type list of dicts ...

get_user_devices_bookmarks(userID)Get a list of devices bookmarked by a specific user.

Parameters userID (string) – the users’s UUID

10 Chapter 1. User’s Guide

Relayr Python Client Documentation, Release 0.3.0

Return type list of dicts, each representing a device

Sample result (anonymized UUIDs):

[{u'firmwareVersion': u'1.0.0',u'id': '...',u'model': '...',u'name': 'My Wunderbar Microphone',u'owner': '...',u'public': True,u'secret': '238885'}]

post_user_devices_bookmark(userID, deviceID)Bookmark a specific public device for a specific user.

Parameters

• userID (string) – the users’s UUID

• deviceID (string) – the UUID of the device to be bookmarked

Return type list of dicts ...

Sample result (anonymized UUIDs):

{'createdAt': '2014-11-05T16:31:06.429Z','deviceId': '...','userId': '...'}

delete_user_devices_bookmark(userID, deviceID)Delete a bookmark for a specific user and device.

Parameters

• userID (string) – the users’s UUID

• deviceID (string) – the device’s UUID

Return type None

post_user_wunderbar(userID)Get the UUIDs and secrets of the master module and sensor modules.

Parameters userID (string) – the users’s UUID

Return type dict with information about master and sensor modules/devices

Sample result (abbreviated, some values anonymized):

{"bridge": { ... },"microphone": {

"name": "My Wunderbar Microphone","public": False,"secret": "......","owner": "...","model": {

"readings": [{

"meaning": "noise_level","unit": "dba"

}],

1.4. Reference 11

Relayr Python Client Documentation, Release 0.3.0

"manufacturer": "Relayr GmbH","id": "...","name": "Wunderbar Microphone"

},"id": "...","firmwareVersion": "1.0.0"

},"light": { ... },"masterModule": {

"owner": "...","secret": "............","id": "...","name": "My Wunderbar Master Module"

},"infrared": { ... },"thermometer": { ... },"gyroscope": { ... }

}

delete_wunderbar(transmitterID)Delete a WunderBar identified by its master module from the relayr cloud. This means that in addition tothe transmitter (the master module) all devices (sensors) associated with it are being deleted.

Parameters transmitterID (string) – the UUID of the master module

post_users_destroy(userID)Delete all WunderBars associated with a specific user from the relayr cloud.

Parameters userID (string) – the users’s UUID

get_user_device_models(userID)Get all device models of a specific user from the relayr cloud.

Parameters userID (string) – the users’s UUID

get_user_device_model(userID, modelID)Get a specific device model of a specific user from the relayr cloud.

Parameters

• userID (string) – the users’s UUID

• modelID (string) – the model’s UUID

get_user_device_model_component(userID, modelID, component)

get_user_device_groups(userID)Get all device groups of a specific user from the relayr cloud.

delete_user_device_groups(userID)Delete all device groups of a specific user from the relayr cloud.

post_user_device_group(name)Create one device group with given name for the implied owner in the relayr cloud.

get_user_device_group(groupID)Get one device group with a specific id from the relayr cloud.

Parameters groupID (string) – the group’s UUID

delete_user_device_group(groupID)Delete one device group with a specific id from the relayr cloud.

12 Chapter 1. User’s Guide

Relayr Python Client Documentation, Release 0.3.0

Parameters groupID (string) – the group’s UUID

patch_user_device_group(groupID, name=None, position=None)Patch one device group with a specific id from the relayr cloud.

Parameters

• groupID (string) – the group’s UUID

• name (integer) – the group’s new name

• position (integer) – the group’s new position

post_user_device_group_device(groupID, deviceIDs=None)Add a list of existing device ids to a device group.

Parameters

• groupID (string) – the group’s UUID

• deviceIDs (list of UUIDs) – devices to be added to the group

delete_user_device_group_device(groupID, deviceID)Delete a device from a device group.

patch_user_device_group_device(groupID, deviceID, position)Change a device position inside a device group.

get_public_apps()Get a list of all public relayr applications on the relayr platform.

Return type list of dicts, each representing a relayr application

post_app(appName, publisherID, redirectURI, appDescription)Register a new application on the relayr platform.

Return type list of dicts, each representing a relayr application

get_app_info(appID)Get information about an app with a specific UUID.

Parameters appID (string) – the app’s UUID

Sample result (anonymized token value):

{"id": "...","name": "My App","description": "My Wunderbar app",...

}

get_app_info_extended(appID)Get extended information about the app with a specific UUID.

Parameters appID (string) – the app’s UUID

Sample result (some values anonymized):

{"id": "...","name": "My App","publisher": "...","clientId": "...","clientSecret": "...",

1.4. Reference 13

Relayr Python Client Documentation, Release 0.3.0

"description": "My Wunderbar app","redirectUri": https://relayr.io

}

patch_app(appID, description=None, name=None, redirectUri=None)Update one or more attributes of an app with a specific UUID.

Parameters

• appID (string) – the application’s UUID

• description (string) – the user name to be set

• name (string) – the user email to be set

• redirectUri (string) – the redirect URI to be set

Sample result (some values anonymized):

{"id": "...","name": "My App","publisher": "...","clientId": "...","clientSecret": "...","description": "My Wunderbar app","redirectUri": https://relayr.io

}

delete_app(appID)Delete an application from the relayr platform.

Parameters appID (string) – the application’s UUID

get_oauth2_app_info()Get info about the app initiating the request (the one in the token).

Sample result (anonymized token value):

{"id": "...","name": "My App","description": "My Wunderbar app"

}

get_public_publishers()Get a list of all publishers on the relayr platform.

Return type list of dicts, each representing a relayr publisher

post_publisher(userID, name)Register a new publisher.

Parameters

• userID (string) – the user UUID of the publisher

• name (string) – the publisher name

Return type a dict with fields describing the new publisher

delete_publisher(publisherID)Delete a specific publisher from the relayr platform.

14 Chapter 1. User’s Guide

Relayr Python Client Documentation, Release 0.3.0

Parameters publisherID (string) – the publisher UUID

Return type an empty dict(?)

get_publisher_apps(publisherID)Return a list of apps published by a specific publisher.

Parameters publisherID (string) – the publisher UUID

Return type A list of apps.

get_publisher_apps_extended(publisherID)Return a list with extended information about the publisher’s apps.

Parameters publisherID (string) – the publisher UUID

Return type A list of apps.

patch_publisher(publisherID, name=None)Update name attribute of a specific publisher.

Parameters

• publisherID (string) – the publisher’s UUID

• name (string) – the publisher name to be set

Return type True, if successful, False otherwise

get_device_configuration(*args, **kwargs)

Get configuration, default values and schema of a specific device.

Example result:

{"version": "1.0.0","configuration": {

"defaultValues": {"frequency": 1000

},"schema": {

"required": ["frequency"

],"type": "object","properties": {

"frequency": {"minimum": 5,"type": "integer","description": "Frequency of the sensor updates in

→˓milliseconds"}

},"title": "Relayr configuration schema"

}}

}

param deviceID the device UUID

type deviceID string

Deprecated method. Please use get_device_configurations() instead.

1.4. Reference 15

Relayr Python Client Documentation, Release 0.3.0

post_device_configuration(*args, **kwargs)

Modify the configuration of a specific device facillitated by a schema.

param deviceID the device UUID

type deviceID string

param frequency the number of milliseconds between two sensor transmissions

type frequency integer

Deprecated method. Please use post_device_configurations() instead.

post_device_configurations(deviceID, config=None)Modify the configuration of a specific device facillitated by a schema.

The config must be a dictionary with three keys, path, name and value, where path is optional.

Parameters

• deviceID (dict) – the device UUID

• config – the configuration to be saved

get_public_devices()Get list of all public devices on the relayr platform filtered by meaning.

Parameters meaning (string) – required meaning in the device model’s readings at-tribute

Return type list of dicts, each representing a relayr device

post_device(name, ownerID, modelID, firmwareVersion)Register a new device on the relayr platform.

Parameters

• name (string) – the device name

• ownerID (string) – the device owner’s UUID

• modelID (string) – the device model’s UUID

• firmwareVersion (string) – the device’s firmware version

Return type list of dicts, each representing a relayr device

post_device_wb2(name, ownerID, modelID, firmwareVersion, mac, transmitterId)Register a new device on the relayr platform.

Parameters

• name (string) – the device name

• ownerID (string) – the device owner’s UUID

• modelID (string) – the device model’s UUID

• firmwareVersion (string) – the device’s firmware version

Return type list of dicts, each representing a relayr device

get_device(deviceID)Get information about a specific device.

Parameters deviceID (string) – the device UUID

Return type a dict with fields containing information about the device

16 Chapter 1. User’s Guide

Relayr Python Client Documentation, Release 0.3.0

Raises exceptions.RelayrApiException for invalid UUIDs or missing credentials.

patch_device(deviceID, name=None, description=None, modelID=None, public=None)Update one or more attributes of a specific device.

Parameters

• deviceID (string) – the device UUID

• name (string) – the device name

• description (string) – the device description

• modelID (string) – the device model UUID

• public (boolean) – the device state (public or not)

Return type a dict with fields containing information about the device

Raises exceptions.RelayrApiException for invalid UUIDs or missing credentials.

delete_device(deviceID)Delete a specific device from the relayr platform.

Parameters deviceID (string) – the device UUID

Return type a dict with fields containing information about the device

post_channel(deviceID, transport)Create a new channel to let the current user receive device data.

The return value is a channel UUID plus credentials to connect to it.

Parameters

• deviceID (string) – the device UUID

• transport (string) – transport for channel (mqtt, websockets, etc.)

Return type dict with channel credentials to connect to the device

Example result (for transport=’mqtt’):

{'channelId': u'62e2ceb8-a63f-11e4-8792-6c400890724a','credentials': {

'password': '012345678901','topic': '/v1/62e2ceb8-a63f-11e4-8792-6c400890724a','user': '62e2ceb8-a63f-11e4-8792-6c400890724a'

}}

delete_channel_id(channelID)Delete an existing specific channel.

Parameters channelID (string) – the UUID of the channel

Return type None

Raises exceptions.RelayrApiException for non-existing channelID.

delete_channels_device_transport(deviceID=None, transport=None)Delete all existing channels for the given device ID and/or transport.

Parameters

• deviceID (string) – the device UUID

1.4. Reference 17

Relayr Python Client Documentation, Release 0.3.0

• transport (string) – transport for channel (mqtt, websockets, etc.)

Return type list of deleted channelIDs

get_device_channels(deviceID)Get all existing channels for a specific device.

Parameters deviceID (string) – the device UUID

Return type dict with a list of attributes for each existing channel

Example output:

{'deviceId': '...','channels': [{'channelId': '...','transport': 'mqtt','appId': '...'

},{'channelId': '...','transport': 'mqtt','appId': '...'

}]

}

post_device_command_led(*args, **kwargs)

Send a command to a specific device’s LED.

param deviceID the device’s UUID

type deviceID string

param data the data to be sent, here {‘cmd’: true/false}

type data dict

rtype dict with connection credentials

Deprecated method. Please use post_device_commands() instead.

post_device_command(*args, **kwargs)

Send a command to a specific device.

param deviceID the device’s UUID

type deviceID string

param command the command to be sent

type command dict

rtype dict with connection credentials

Deprecated method. Please use post_device_commands() instead.

post_device_commands(deviceID, command=None)Send a command to a specific device.

The command must be a dictionary with three keys, path, name and value, where path is optional.

Parameters

18 Chapter 1. User’s Guide

Relayr Python Client Documentation, Release 0.3.0

• deviceID (string) – the device’s UUID

• command (dict) – the command to be sent

Return type dict with connection credentials

post_device_data(deviceID, data)Send JSON formatted data to a device (eg. temperature readings).

Parameters

• deviceID (string) – the device’s UUID

• data (anything serializable as JSON ) – the command data

Return type string

get_device_reading(deviceID, path=None, meaning=None)This endpoint returns only the reading part. Path and meaning are optional. If a path is not provided onlyreadings with empty paths are returned. If meaning is not provided all the matched readings with {path}are returned.

Parameters

• deviceID (string) – the device UUID

• path (string) – the reading’s path

• meaning (string) – the reading’s meaning

Return type a dict with desired readings as specified.

Example:

{"version": {

"number": 100,"ts": 1452525615741

},"readings": [

{"path": "fridge","meaning": "temperature","ts": 1452525615741,"value": 1000

}]

}

get_device_metadata(deviceID, key=None)Get the device metadata with given key.

The key is a multi-level string like this “my.custom.metadata” where each dot identifies a deeper level inthe hierarchy. Wrong keys result in an empty JSON.

Parameters

• deviceID (string) – the device UUID

• key (string) – the reading’s key

Return type a dict with desired key as specified.

Example:

1.4. Reference 19

Relayr Python Client Documentation, Release 0.3.0

{"version": {

"number": 100,"ts": 1452525615741

},"metadata": {

"my": {"custom": {

"metadata": 100}

}}

}

get_device_commands(deviceID, path=None, name=None)Get the device commands with given path and name.

Same as get_devices_readings(), only with a different key. Name is used instead of meaning.

Parameters

• deviceID (string) – the device UUID

• path (string) – the reading’s path

• name (string) – the reading’s name

Return type a dict with desired readings as specified.

Example:

{"commands": [

{"path": "door","name": "led","value": 1000,"ts": 1452525615741

}],"version": {

"number": 100,"ts": 1452525615741

}}

get_device_state(deviceID)Get the whole saved state of a specific device.

This includes readings, commands, configurations, and metadata, as well as simple version numbers forthese items.

Parameters deviceID (string) – the device UUID

Return type a dict with entire device state.

Example:

?

get_device_configurations(deviceID, path=None, name=None)Get the device configurations with given path and name.

20 Chapter 1. User’s Guide

Relayr Python Client Documentation, Release 0.3.0

Parameters

• deviceID (string) – the device UUID

• path (string) – the configuration’s path

• name (string) – the configuration’s name

Return type a dict with desired configuration as specified.

Example:

{

“commands”: [

{ “path”: “door”, “name”: “led”, “value”: 1000, “ts”: 1452525615741

}

], “version”: {

“number”: 100, “ts”: 1452525615741

}

}

post_device_metadata(deviceID, key=None, data=None)Save some metadata for the specified device.

The key is used as prefix. Note that is not possible to send a value (instead of a JSON object) without akey, but a (key, value) pair is fine. So no json=1 and key=EMPTY, but this works: json=1 key=meta. (???)

Parameters

• deviceID (string) – the device UUID

• key (string) – the metadata key

• data (a JSON-serializable object) – the actual metadata data

Return type None

get_device_credentials(deviceID)Get credentials for a specific device.

Parameters deviceID (string) – the device UUID

Return type dict with credentials info

post_device_credentials(deviceID, data)Post credentials for a specific device.

Parameters

• deviceID (string) – the device UUID

• data (dict) – the credentials

Return type string

get_history_devices(deviceID, start=None, end=None, sample=None, meaning=None,path=None, offset=None, limit=None)

Return past data for a specific device after a given starting point.

Parameters

• deviceID (string) – the device UUID

1.4. Reference 21

Relayr Python Client Documentation, Release 0.3.0

• start (long) – unix datetime in ms

• end (long) – unit datetime in ms

• meaning (string) – meaning filter

• path (string) – path filter

• offset (integer) – pagination offset

• limit (integer) – limit for returned values

Return type history response with pagination info

get_public_device_models(headers={‘Content-Type’: ‘application/json’})Get list of all device models available on the relayr platform.

Parameters headers (dict) – additional HTTP headers (default: {'Content-Type':'application/json'})

Return type list or dict, depening on the Content-Type field in headers

get_device_model(devicemodelID)Get information about a specific device model.

Parameters devicemodelID (string) – the device model’s UUID

Return type A nested dictionary structure with fields describing the DM.

get_public_device_model_meanings()Get list of all device model meanings (no credentials needed).

Return type list of dicts, each representing a relayr device model meaning

get_transmitter(transmitterID)Get information about a transmitter with a specific UUID.

Parameters transmitterID (string) – the transmitter UUID

Return type a dict with fields describing the transmitter

post_transmitter(ownerID=None, name=None, integrationType=None)Register a new transmitter on the relayr platform.

Parameters

• ownerID (string) – the transmitter owner’s UUID

• name (string) – the transmitter name

• integrationType (string) – the transmitter integration type

Return type an empty dict(?)

patch_transmitter(transmitterID, name=None)Update the name attribute of a specific transmitter.

Parameters

• transmitterID (string) – the transmitter UUID

• name (string) – the transmitter name

Return type an empty dict(?)

delete_transmitter(transmitterID)Delete a specific transmitter from the relayr platform.

Parameters transmitterID (string) – the transmitter UUID

22 Chapter 1. User’s Guide

Relayr Python Client Documentation, Release 0.3.0

Return type an empty dict(?)

post_transmitter_device(transmitterID, deviceID)Connect a specific transmitter to a specific device.

Parameters

• transmitterID (string) – the transmitter UUID

• deviceID (string) – the device UUID

Return type an empty dict(?)

get_transmitter_devices(transmitterID)Get a list of devices connected to a specific transmitter.

Parameters transmitterID (string) – the transmitter UUID

Return type a list of devices

delete_transmitter_device(transmitterID, deviceID)Disconnect a specific transmitter from a specific device.

Parameters

• transmitterID (string) – the transmitter UUID

• deviceID (string) – the device UUID

Return type an empty dict(?)

API Client

class relayr.client.Client(token=None)A client providing a higher level interface to the relayr cloud platform.

Example:

c = Client(token='...')info = c.get_oauth2_user_info()usr = User(info['id'], client=c)devs = usr.get_devices()d = next(devs)apps = usr.get_apps()

__init__(token=None)

Parameters token (A string.) – A token generated on the relayr site for the combinationof a user and an application.

get_public_apps()Returns a generator for all apps on the relayr platform.

A generator is returned since the called API method always returns the entire results list and not a paginatedone.

Return type A generator for relayr.resources.App objects.

c = Client(token='...')apps = c.get_public_apps()for app in apps:

print('%s %s' % (app.id, app.name))

1.4. Reference 23

Relayr Python Client Documentation, Release 0.3.0

get_public_publishers()Returns a generator for all publishers on the relayr platform.

A generator is returned since the called API method always returns the entire results list and not a paginatedone.

Return type A generator for relayr.resources.Publisher objects.

get_public_devices(meaning=’‘)Returns a generator for all devices on the relayr platform.

A generator is returned since the called API method always returns the entire results list and not a paginatedone.

Parameters meaning (string) – The meaning (type) of the desired devices.

Return type A generator for relayr.resources.Device objects.

get_public_device_models()Returns a generator for all device models on the relayr platform.

A generator is returned since the called API method always returns the entire results list and not a paginatedone.

Return type A generator for relayr.resources.DeviceModel objects.

get_public_device_model_meanings()Returns a generator for all device models’ meanings on the relayr platform.

A device model meaning is a simple dictionary with a key and value field.

A generator is returned since the called API method always returns the entire results list and not a paginatedone.

Return type A device model meaning (as a dictionary) generator.

{'key': 'humidity', 'value': 'humidity'}

get_user()Returns the relayr user owning the API client.

Return type A relayr.resources.User object.

get_app()Returns the relayr application of the API client.

Return type A relayr.resources.App object.

get_device(id)Returns the device with the specified ID.

Parameters id (string) – the unique ID for the desired device.

Return type A relayr.resources.Device object.

get_device_groups()Returns a generator for all device groups on the relayr platform.

A device group is a simple dictionary with a key and value field.

A generator is returned since the called API method always returns the entire results list and not a paginatedone.

Return type A relayr.resources.Group object.

24 Chapter 1. User’s Guide

Relayr Python Client Documentation, Release 0.3.0

API Resources

This module contains abstractions for relayr API resources.

Resources may be entities such as users, publishers, applications, devices, device models and transmitters.

class relayr.resources.User(id=None, client=None)A Relayr user.

__init__(id=None, client=None)

get_publishers()Return a generator of the publishers of the user.

get_apps()Returns a generator of the apps of the user.

get_transmitters()Returns a generator of the transmitters of the user.

get_devices()Returns a generator of the devices of the user.

update(name=None, email=None)

register_wunderbar()Returns registered Wunderbar devices (master and sensor modules).

Return type A generator over the registered devices and one transmitter.

remove_wunderbar()Removes all Wunderbars associated with the user.

get_bookmarked_devices()Retrieves a list of bookmarked devices.

Return type list of device objects

bookmark_device(device)

delete_device_bookmark(device)

class relayr.resources.Publisher(id=None, client=None)A relayr publisher.

A publisher has a few attributes, which can be updated. It can be registered to and deleted from the relayrplatform. It can list all applications it has published on the relayr platform.

__init__(id=None, client=None)

get_apps(extended=False)Get list of apps for this publisher.

If the optional parameter extended is False (default) the response will contain only the fields id,name and description. If it is True it will contain additional fields: publisher, clientId,clientSecret and redirectUri.

Parameters extended (booloean) – Flag indicating if the info should be extended.

Return type A list of relayr.resources.App objects.

update(name=None)Updates certain information fields of the publisher’s.

Parameters name (string) – the user email to be set

1.4. Reference 25

Relayr Python Client Documentation, Release 0.3.0

register(name, id, publisher)Adds the publisher to the relayr platform.

Parameters

• name (string) – the publisher name to be set

• id (string) – the publisher UID to be set

delete()Deletes the publisher from the relayr platform.

class relayr.resources.App(id=None, client=None)A relayr application.

An application has a few attributes, which can be updated. It can be registered to and deleted from the relayrplatform. it can be connected to and disconnected from devices.

__init__(id=None, client=None)

get_info(extended=False)Get application info.

If the optional parameter extended is False (default) the result will contain only the fields id,name and description. If it is True it will contain additional fields: publisher, clientId,clientSecret and redirectUri.

Parameters extended (booloean) – flag indicating if the info should be extended

Return type A dict with certain fields.

update(description=None, name=None, redirectUri=None)Updates certain fields in the application’s description.

Parameters

• description (string) – the user name to be set

• name (string) – the user email to be set

• redirectUri (string) – the redirect URI to be set

delete()Deletes the app from the relayr platform.

register(name, publisher)Adds the app to the relayr platform.

Parameters

• name (string) – the app name to be set

• publisher (string(?)) – the publisher to be set

class relayr.resources.Group(id=None, client=None)A relayr device group.

A device group is simply an ordered list of devices with its own ID, name and owner. The position of the groupis the one where it appears when asking for the list of all groups. This position can be changed.

__init__(id=None, client=None)Instantiate new device group with given UUID and API client.

Parameters

• id (string) – the UUID of this group

26 Chapter 1. User’s Guide

Relayr Python Client Documentation, Release 0.3.0

• client (relayr.client.Client) – the the user’s UUID who is the owner of thisgroup

Return type self

create(name)Create new device group with given name.

Parameters name (string) – the name of this group

Return type self

get_info()Retrieves device group info and stores it as instance attributes.

Return type self.

update(name=None, position=None)Updates position of this group in the list of all groups.

Parameters

• name (string) – the new name of this group

• position (integer) – the new position of this group in the list of all groups

Return type self

delete()Deletes the group from the relayr platform.

Return type self

add_device(device)Add a device from the relayr platform to this device group.

Parameters device (relayr.resources.Device) – a relayr device object

Return type self

remove_device(device)Remove a device from the relayr platform from this device group.

Parameters device (relayr.resources.Device) – a relayr device object

Return type self

update_device(device, position=None)Update a device inside this device group (now only the position field).

Parameters

• device (relayr.resources.Device) – a relayr device object

• position (integer) – the new position of the device in the list of all devices

Return type self

class relayr.resources.Device(id=None, client=None)A relayr device.

__init__(id=None, client=None)

get_info()Retrieves device info and stores it as instance attributes.

Return type self.

1.4. Reference 27

Relayr Python Client Documentation, Release 0.3.0

update(description=None, name=None, modelID=None, public=None)Updates certain fields in the device information.

Parameters

• description (string) – the description to be set

• name (string) – the user name to be set

• modelID (string?) – the device model to be set

• public (bool) – a Boolean flag for making the device public

Return type self

get_connected_apps()Retrieves all apps connected to the device.

Return type A list of apps.

send_command(command)Sends a command to the device.

Parameters command (dict) – the command to be sent (containing three key strings: ‘path’,‘command’ and ‘value’, ‘path’ being optional)

send_data(data)Sends a data package to the device.

Parameters data (dict) – the data to be sent

send_config(config)Sends a config package to configure the device.

Parameters config – the configuration to be sent (containing three key strings: ‘path’, ‘com-mand’ and ‘value’, ‘path’ being optional)

get_config(path=None, name=None)Get a device’s configuration.

Parameters

• path (string) – the configuration’s path

• name (string) – the configuration’s name

delete()Deletes the device from the relayr platform.

switch_led_on(*args, **kwargs)

Switches on device’s LED for ca. 10 seconds or switches it off.

param bool the desired state, on if True (default), off if False

type bool boolean

rtype self

Deprecated method. Please use send_command() instead.

received_data(data)A callback for live data received for this device.

The default implementation is to append the reading to an instance attribute, self.buffered_readings. Morecustomized functionality can be implemented in a subclass or by using an other callable.

28 Chapter 1. User’s Guide

Relayr Python Client Documentation, Release 0.3.0

This is slightly experimental and subject to change!

Parameters reading (whatever is returned by the transport mechanism(usually a dictionary)) – a callable that will be called for each new device reading

Return type self

get_live_data(callback=None, duration=None, transport=’mqtt’)Get a stream of current data for this device.

This is slightly experimental and subject to change!

Parameters

• callback (callable Python function or method) – a callable that will becalled for each new device reading

• duration (string) – duration until the callable is no longer called

• transport – transport method to be used (currently only ‘mqtt’ which is default)

Return type self

stop_live_data(transport=’mqtt’)Stop receiving live data.

This is slightly experimental and subject to change!

get_past_data(start=None, end=None, duration=None, meaning=None, sample=None, off-set=None, limit=None)

Get a chunk of historical data recorded in the past for this device.

Exactly one of the parameters start, end and durationmust be None, else an AssertionError israised. The data will be fetched using a paging mechanism with up to 10000 data points per page (limit).The data will not be stored inside this object.

This is slightly experimental and subject to change!

Parameters

• start (ISO 8601 string or datetime.datetime instance or milliseconds or None) –datetime value

• end (ISO 8601 string or datetime.datetime instance or milliseconds or None) –datetime value

• duration (ISO 8601 duration string or datetime.timedelta instance or millisec-onds or None) – time duration

• meaning (string) – a single device meaning (if unspecified all meanings will be re-ported)

• sample (string) – ...

• offset (integer >= 0) – offset in the list of returned data points

• limit (integer >= 0 (max. 10000)) – max. total number of returned datapoints

Return type a dict with historical data plus meta-information

get_data(*args, **kwargs)Deprecated method, to be superseeded by get_past_data().

create_channel(transport)

delete_channel(channelID)

1.4. Reference 29

Relayr Python Client Documentation, Release 0.3.0

delete_channels()

list_channels()

class relayr.resources.DeviceModel(id=None, client=None)A relayr device model.

__init__(id=None, client=None)

get_info()Returns device model info and stores it as instance attributes.

Return type self.

class relayr.resources.Transmitter(id=None, client=None)A relayr transmitter, The Master Module, for example.

__init__(id=None, client=None)

get_info()Retrieves transmitter info.

Return type self

delete()Deletes the transmitter from the relayr platform.

Return type self

update(name=None)Updates transmitter info.

Return type self

get_connected_devices()Returns a list of devices connected to the specific transmitter.

Return type A list of devices.

Data Access

Data Connection Classes

This module provide connection classes for accessing device data.

class relayr.dataconnection.MqttStream(callback, devices, transport=’mqtt’)MQTT stream reading data from devices in the relayr cloud.

__init__(callback, devices, transport=’mqtt’)Opens an MQTT connection with a callback and one or more devices.

Parameters

• callback (A function/method or object implementing the __call__ method.) – Acallable to be called with two arguments: the topic and payload of a message.

• devices (list) – Device objects from which to receive data.

• transport (string) – Name of the transport method, right now only ‘mqtt’.

run()Thread method, called implicitly after starting the thread.

stop()Mark the connection/thread for being stopped.

30 Chapter 1. User’s Guide

Relayr Python Client Documentation, Release 0.3.0

on_connect(client, userdata, flags, rc)

on_disconnect(client, userdata, rc)

on_subscribe(client, userdata, mid, granted_qos)

on_unsubscribe(client, userdata, mid)

on_message(client, userdata, msg)Pass the message topic and payload as strings to our callback.

add_device(device)Add a specific device to the MQTT connection to receive data from.

remove_device(device)Remove a specific device from the MQTT connection to no longer receive data from.

Exceptions

This module contains exceptions raised when an operation on the relayr API or the relayr platform fails due to, forexample: missing credentials, invalid UIDs, etc.

At the moment two exception classes are provided:

• RelayrApiException: raised for exceptions caused by API calls

• RelayrException: raised for other exceptions

exception relayr.exceptions.RelayrApiException

exception relayr.exceptions.RelayrException

Raspberry Pi

Due to its small size, low price and power consumption and its general extensibility the Raspberry Pi (or any othersimilar device) is considered an interesting platform for projects related to the Internet of Things.

Examples of use to come so stay tuned!

Updating BlueZ

The version of BlueZ available for standard distributions for a Raspberry Pi such as Raspbian, may be old (prior toversion 5) and thus incapable of handling Bluetooth LE well, if at all. It is therefore strongly recommended to installthe most recent version, using a procedure like the one below (compiling BlueZ on the Raspberry Pi itself takes about20-30 minutes):

sudo apt-get --purge remove bluezsudo apt-get updatesudo apt-get install libusb-dev libdbus-1-dev libglib2.0-dev libudev-dev libical-dev→˓libreadline-devwget https://www.kernel.org/pub/linux/bluetooth/bluez-5.24.tar.xztar xf bluez-5.24.tar.xzcd bluez-5.24./configure --prefix=/usr --enable-library --disable-systemdmakesudo make installsudo cp attrib/gatttool /usr/bin

1.5. Raspberry Pi 31

Relayr Python Client Documentation, Release 0.3.0

OpenWRT

This page describes how to get the relayr Python API running on OpenWRT, a popular open, minimized Linuxdistribution for embedded systems. One of the widely available boards running OpenWRT is the WRTnode whichincludes a WiFi controller and therefore seems especially well-suited for IoT applications.

Although OpenWRT is heavily minimized (running in only 16 MB of memory) it has its own package managementsystem (see opkg -h) with dependancy tracking and many interesting packages, including a MQTT broker namedMosquitto. It is also a nice platform for Python (versions 2.7 and 3.4) since it provides many packages, either separate(big) ones from the Python standard library or by third parties, like even OpenCV!

Install or upgrade Python

Before installing the Python-SDK on OpenWRT a few additional steps are necessary to establish the baseline. Ifa Python interpreter is already installed it might well be Python 2.7.3. For security reasons it is recommended toreplace this with Python 2.7.9 (or Python 3.4.3), or install it from scratch. Two extra packages are also needed, namelypython-codecs and python-openssl (the names may have a python3- prefix if you prefer Python 3 - therelayr Python API runs on Python 2.7 and 3.4).

You can install these packages like this (shown here for Python 2.7):

opkg install python-baseopkg install python-codecsopkg install python-lightopkg install python-openssl

Then you should see this list when asking for installed Python packages with opkg list-installed | greppython:

python-base - 2.7.9-5python-codecs - 2.7.9-5python-light - 2.7.9-5python-openssl - 2.7.9-5

This will eat some of your memory, but you can include these packages into a custom firmware image (which will beheavily compressed) and flash your board with it in order to gain space, again, if you need it.

Install temporary tools

Since OpenWRT contains only minimal versions of some common GNU/Linux tools, we need to install the real onesin a preliminary step like this (first updating the package menagement system):

opkg updateopkg install wget tar

Later, when everything needed is installed, you can remove these packages and their dependancies again with:

opkg remove wget libpcreopkg remove tar bzip2 libbz2 libacl

If, for whatever reasons, you don’t want to install these helpers, you can, of course, download a source code tarball ona normal machine and transfer the unpacked directory via scp -r to your board.

32 Chapter 1. User’s Guide

Relayr Python Client Documentation, Release 0.3.0

Install dependancies

The usual way of installing Python packages is pip or easy_install where the latter builds on the setuptoolspackage, an alternative for the distutils package in the Python standard library. While there are opkg packagesfor pip and setuptools these are pretty heavy and bring in other dependancies. Therefore they are not used here,but instead all the dependancies for the relayr Python API are installed individually.

For the packages to build and install now it is recommended to create a source directory in the volatile RAM of yourboard (the WRTnode has 128 MB), for example like this:

mkdir /tmp/srccd /tmp/src

MQTT

OpenWRT does not provide the Python package paho-mqtt, but it’s very simple to build and install from source:

wget --no-check-certificate https://pypi.python.org/packages/source/p/paho-mqtt/paho-→˓mqtt-1.1.tar.gztar xfz paho-mqtt-1.1.tar.gzcd paho-mqtt-1.1python setup.py installcd ..

You have successfully installed it if you can run this in Python without any error: import paho.

Requests

wget --no-check-certificate https://pypi.python.org/packages/source/r/requests/→˓requests-2.7.0.tar.gztar xfz requests-2.7.0.tar.gzcd requests-2.7.0python setup.py installcd ..

Certifi

wget --no-check-certificate https://github.com/certifi/python-certifi/archive/2015.04.→˓28.tar.gztar xfz 2015.04.28.tar.gzcd python-certifi-2015.04.28cp -r certifi /usr/lib/python2.7/site-packagescd ..

Miscellaneous

The remaining modules are not strictly needed for being able to use the relayr Python API, like termcolor (used ina demo). Or they are not strictly needed yet, like isodate.

wget --no-check-certificate https://pypi.python.org/packages/source/t/termcolor/→˓termcolor-1.1.0.tar.gztar xfz termcolor-1.1.0.tar.gz

1.6. OpenWRT 33

Relayr Python Client Documentation, Release 0.3.0

cd termcolor-1.1.0python setup.py installcd ..

wget --no-check-certificate https://pypi.python.org/packages/source/i/isodate/isodate-→˓0.5.1.tar.gztar xfz isodate-0.5.1.tar.gzcd isodate-0.5.1/srccp -r isodate /usr/lib/python2.7/site-packagescd ../..

relayr Python API

Since we don’t want to use pip or easy_install you can fetch a tarball from Github or PyPI and unpack it asusual. After that you need to copy the relayr folder manually into the site-packages folder as shown here forPython 2.7:

wget --no-check-certificate https://github.com/relayr/python-sdk/archive/0.3.0.tar.gz# or wget --no-check-certificate https://pypi.python.org/packages/source/r/relayr/→˓relayr-0.2.4.tar.gztar xfz 0.3.0.tar.gzcd 0.3.0cp -r relayr /usr/lib/python2.7/site-packages

If everything worked fine you can run e.g. these commands from the unpacked directory to test that the installationwas successful:

python demos/api_pulse.pypython runtests.py tests/test_anonymous.py

If you edit the file tests/fixture_registered.py and provide IDs of your WunderBar you can run the entiretestsuite like this: python runtests.py tests.

Digression on minimizing Python code

Code minimization is usually performed on Javacript libraries to reduce download times in webbrowsers. On embed-ded devices the precious resource is memory (on a WRTnode it’s 16 MB of flash user memory). Therefore, it cansometimes be helpful to reduce the size of any larger Python software to be installed, too, either by a third party or byyourself.

The recommended tool for minimizing Python code is pyminifier which in its simple forms will strip-off docstringsand comments and minimize the indentation of Python source files. You can use it on the relayr Python-SDK forexample as follows, before installing it on OpenWRT:

pip install pyminifierwget --no-check-certificate https://github.com/relayr/python-sdk/archive/0.3.0.tar.gztar xfz 0.3.0.tar.gzcd 0.3.0pyminifier *.py

34 Chapter 1. User’s Guide

Relayr Python Client Documentation, Release 0.3.0

Documentation

The official documentation of the relayr Python library is hosted on ReadTheDocs. It is also included inside thedocs/manual subdirectory of the source code distribution. You can render it in various formats using Sphinx, apopular tool for creating documentation. If you don’t use it already, please run the following command in the topdirectory of the source code tree:

$ pip install -r requirements_doc.txt

This will also install a theme named sphinx_rtd_theme for reusing the same style locally as the one used onReadTheDocs by default.

Then you could run a little Bash script named make_docs.sh inside the same directory to generate the documenta-tion:

$ ./make_docs.sh

By default this renders only the HTML version under docs/manual/_build/html, but if you uncomment therespective lines inside you can also render versions in EPUB and PDF format (and perform some link-checking).Please note that for the PDF version you need to have a working LaTeX installation.

Contributing

Contributions are highly welcome and much appreciated, so please do not hesitate! Apart from bug reports we alsowelcome little self-contained examples that others may find useful. If you write code please make sure to provide aclean pull request on GitHub, test it at least on Python 2.7 and 3.4 and provide a test case in the testsuite. It makesyour contributions more likely to get included more quickly.

The various relayr SDKs are still in development stages. You can find the code of the Python-SDK on GitHub whichis also the place for reporting any bugs and/or patches (the latter preferably in the form of a pull request). If you reporta bug please make sure to include information about your OS platform and Python version.

On GitHub you can also find SDKs for other languages or platforms such as iOS and Mac and Android.

If you have more general questions you are more than welcome to reach out to us on the relayr Forum

1.7. Documentation 35

Relayr Python Client Documentation, Release 0.3.0

36 Chapter 1. User’s Guide

CHAPTER 2

Indices and tables

• genindex

• modindex

• search

37

Relayr Python Client Documentation, Release 0.3.0

38 Chapter 2. Indices and tables

Python Module Index

rrelayr.api, 7relayr.client, 23relayr.dataconnection, 30relayr.exceptions, 31relayr.resources, 25

39

Relayr Python Client Documentation, Release 0.3.0

40 Python Module Index

Index

Symbols__init__() (relayr.api.Api method), 8__init__() (relayr.client.Client method), 23__init__() (relayr.dataconnection.MqttStream method),

30__init__() (relayr.resources.App method), 26__init__() (relayr.resources.Device method), 27__init__() (relayr.resources.DeviceModel method), 30__init__() (relayr.resources.Group method), 26__init__() (relayr.resources.Publisher method), 25__init__() (relayr.resources.Transmitter method), 30__init__() (relayr.resources.User method), 25

Aadd_device() (relayr.dataconnection.MqttStream

method), 31add_device() (relayr.resources.Group method), 27Api (class in relayr.api), 8App (class in relayr.resources), 26

Bbookmark_device() (relayr.resources.User method), 25build_curl_call() (in module relayr.api), 7

CClient (class in relayr.client), 23create() (relayr.resources.Group method), 27create_channel() (relayr.resources.Device method), 29create_logger() (in module relayr.api), 7

Ddelete() (relayr.resources.App method), 26delete() (relayr.resources.Device method), 28delete() (relayr.resources.Group method), 27delete() (relayr.resources.Publisher method), 26delete() (relayr.resources.Transmitter method), 30delete_app() (relayr.api.Api method), 14delete_channel() (relayr.resources.Device method), 29delete_channel_id() (relayr.api.Api method), 17

delete_channels() (relayr.resources.Device method), 29delete_channels_device_transport() (relayr.api.Api

method), 17delete_device() (relayr.api.Api method), 17delete_device_bookmark() (relayr.resources.User

method), 25delete_oauth2_appdev_token() (relayr.api.Api method), 9delete_publisher() (relayr.api.Api method), 14delete_transmitter() (relayr.api.Api method), 22delete_transmitter_device() (relayr.api.Api method), 23delete_user_app() (relayr.api.Api method), 10delete_user_device_group() (relayr.api.Api method), 12delete_user_device_group_device() (relayr.api.Api

method), 13delete_user_device_groups() (relayr.api.Api method), 12delete_user_devices_bookmark() (relayr.api.Api

method), 11delete_wunderbar() (relayr.api.Api method), 12Device (class in relayr.resources), 27DeviceModel (class in relayr.resources), 30

Gget_app() (relayr.client.Client method), 24get_app_info() (relayr.api.Api method), 13get_app_info_extended() (relayr.api.Api method), 13get_apps() (relayr.resources.Publisher method), 25get_apps() (relayr.resources.User method), 25get_bookmarked_devices() (relayr.resources.User

method), 25get_config() (relayr.resources.Device method), 28get_connected_apps() (relayr.resources.Device method),

28get_connected_devices() (relayr.resources.Transmitter

method), 30get_data() (relayr.resources.Device method), 29get_device() (relayr.api.Api method), 16get_device() (relayr.client.Client method), 24get_device_channels() (relayr.api.Api method), 18get_device_commands() (relayr.api.Api method), 20get_device_configuration() (relayr.api.Api method), 15

41

Relayr Python Client Documentation, Release 0.3.0

get_device_configurations() (relayr.api.Api method), 20get_device_credentials() (relayr.api.Api method), 21get_device_groups() (relayr.client.Client method), 24get_device_metadata() (relayr.api.Api method), 19get_device_model() (relayr.api.Api method), 22get_device_reading() (relayr.api.Api method), 19get_device_state() (relayr.api.Api method), 20get_devices() (relayr.resources.User method), 25get_history_devices() (relayr.api.Api method), 21get_info() (relayr.resources.App method), 26get_info() (relayr.resources.Device method), 27get_info() (relayr.resources.DeviceModel method), 30get_info() (relayr.resources.Group method), 27get_info() (relayr.resources.Transmitter method), 30get_live_data() (relayr.resources.Device method), 29get_oauth2_app_info() (relayr.api.Api method), 14get_oauth2_appdev_token() (relayr.api.Api method), 9get_oauth2_user_info() (relayr.api.Api method), 9get_past_data() (relayr.resources.Device method), 29get_public_apps() (relayr.api.Api method), 13get_public_apps() (relayr.client.Client method), 23get_public_device_model_meanings() (relayr.api.Api

method), 22get_public_device_model_meanings() (re-

layr.client.Client method), 24get_public_device_models() (relayr.api.Api method), 22get_public_device_models() (relayr.client.Client

method), 24get_public_devices() (relayr.api.Api method), 16get_public_devices() (relayr.client.Client method), 24get_public_publishers() (relayr.api.Api method), 14get_public_publishers() (relayr.client.Client method), 23get_publisher_apps() (relayr.api.Api method), 15get_publisher_apps_extended() (relayr.api.Api method),

15get_publishers() (relayr.resources.User method), 25get_server_status() (relayr.api.Api method), 9get_transmitter() (relayr.api.Api method), 22get_transmitter_devices() (relayr.api.Api method), 23get_transmitters() (relayr.resources.User method), 25get_user() (relayr.client.Client method), 24get_user_apps() (relayr.api.Api method), 10get_user_device_group() (relayr.api.Api method), 12get_user_device_groups() (relayr.api.Api method), 12get_user_device_model() (relayr.api.Api method), 12get_user_device_model_component() (relayr.api.Api

method), 12get_user_device_models() (relayr.api.Api method), 12get_user_devices() (relayr.api.Api method), 10get_user_devices_bookmarks() (relayr.api.Api method),

10get_user_publishers() (relayr.api.Api method), 10get_user_transmitters() (relayr.api.Api method), 10get_users_validate() (relayr.api.Api method), 8

Group (class in relayr.resources), 26

Llist_channels() (relayr.resources.Device method), 30

MMqttStream (class in relayr.dataconnection), 30

Oon_connect() (relayr.dataconnection.MqttStream

method), 30on_disconnect() (relayr.dataconnection.MqttStream

method), 31on_message() (relayr.dataconnection.MqttStream

method), 31on_subscribe() (relayr.dataconnection.MqttStream

method), 31on_unsubscribe() (relayr.dataconnection.MqttStream

method), 31

Ppatch_app() (relayr.api.Api method), 14patch_device() (relayr.api.Api method), 17patch_publisher() (relayr.api.Api method), 15patch_transmitter() (relayr.api.Api method), 22patch_user() (relayr.api.Api method), 10patch_user_device_group() (relayr.api.Api method), 13patch_user_device_group_device() (relayr.api.Api

method), 13perform_request() (relayr.api.Api method), 8post_app() (relayr.api.Api method), 13post_channel() (relayr.api.Api method), 17post_device() (relayr.api.Api method), 16post_device_command() (relayr.api.Api method), 18post_device_command_led() (relayr.api.Api method), 18post_device_commands() (relayr.api.Api method), 18post_device_configuration() (relayr.api.Api method), 16post_device_configurations() (relayr.api.Api method), 16post_device_credentials() (relayr.api.Api method), 21post_device_data() (relayr.api.Api method), 19post_device_metadata() (relayr.api.Api method), 21post_device_wb2() (relayr.api.Api method), 16post_oauth2_appdev_token() (relayr.api.Api method), 9post_oauth2_token() (relayr.api.Api method), 9post_publisher() (relayr.api.Api method), 14post_transmitter() (relayr.api.Api method), 22post_transmitter_device() (relayr.api.Api method), 23post_user_app() (relayr.api.Api method), 10post_user_device_group() (relayr.api.Api method), 12post_user_device_group_device() (relayr.api.Api

method), 13post_user_devices_bookmark() (relayr.api.Api method),

11

42 Index

Relayr Python Client Documentation, Release 0.3.0

post_user_wunderbar() (relayr.api.Api method), 11post_users_destroy() (relayr.api.Api method), 12Publisher (class in relayr.resources), 25

Rreceived_data() (relayr.resources.Device method), 28register() (relayr.resources.App method), 26register() (relayr.resources.Publisher method), 25register_wunderbar() (relayr.resources.User method), 25relayr.api (module), 7relayr.client (module), 23relayr.dataconnection (module), 30relayr.exceptions (module), 31relayr.resources (module), 25RelayrApiException, 31RelayrException, 31remove_device() (relayr.dataconnection.MqttStream

method), 31remove_device() (relayr.resources.Group method), 27remove_wunderbar() (relayr.resources.User method), 25run() (relayr.dataconnection.MqttStream method), 30

Ssend_command() (relayr.resources.Device method), 28send_config() (relayr.resources.Device method), 28send_data() (relayr.resources.Device method), 28stop() (relayr.dataconnection.MqttStream method), 30stop_live_data() (relayr.resources.Device method), 29switch_led_on() (relayr.resources.Device method), 28

TTransmitter (class in relayr.resources), 30

Uupdate() (relayr.resources.App method), 26update() (relayr.resources.Device method), 27update() (relayr.resources.Group method), 27update() (relayr.resources.Publisher method), 25update() (relayr.resources.Transmitter method), 30update() (relayr.resources.User method), 25update_device() (relayr.resources.Group method), 27User (class in relayr.resources), 25

Index 43