Usage Overview

To get started, you will need a running instance of Synse Server with a configured plugin to provide device reading data. Below is a simple compose file which will bring up an instance of Synse Server with the emulator plugin connected.

version: '3'
services:
  synse-server:
    container_name: synse-server
    image: vaporio/synse-server
    ports:
    - '5000:5000'
    environment:
      SYNSE_PLUGIN_TCP: emulator-plugin:5001
    links:
    - emulator-plugin

  emulator-plugin:
    container_name: emulator-plugin
    image: vaporio/emulator-plugin
    expose:
    - '5001'

With the above compose file saved locally as docker-compose.yaml, you can start the simple deployment with:

$ docker-compose up -d

Now, the Synse Server API can be reached at localhost:5000.

The Synse Python client package provides a client for both the HTTP API and the WebSocket API. The two APIs are largely similar and provide access to the same device data and control.

HTTP API

Synse Server’s HTTP API can be accessed using an HTTP client. Clients are versioned based on the version of the Synse API they are compatible with, e.g. HTTPClientV3 is compatible with the Synse v3 API.

The client may be initialized and used directly, in which case it must be closed explicitly:

client = HTTPClientV3('localhost')
...
await client.close()

It may also be used as a context manager, which will automatically close the session when the context is exited:

async with HTTPClientV3('localhost') as client:
  ...

Example

Below is an example which creates a client, scans for all devices and for each LED device, turns it on.

import asyncio

from synse.client import HTTPClientV3


async def main():
    """An example function which """

    c = HTTPClientV3(
        host='localhost',
        timeout=3,
    )

    for device in await c.scan():
        if device.type == 'led':
            status = await c.write_sync(
                device=device.id,
                payload={
                    'action': 'state',
                    'data': 'on',
                }
            )

            for s in status:
                assert s.status == 'DONE'

    await c.close()


if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

Reference

class synse.client.HTTPClientV3(host: str, port: Optional[int] = 5000, timeout: Optional[float] = 10, session: Optional[aiohttp.client.ClientSession] = None, loop: Optional[asyncio.events.AbstractEventLoop] = None)[source]

An HTTP client for Synse Server’s v3 API.

Parameters:
  • host – The hostname/IP address for the Synse Server instance.
  • port – The port that Synse Server is listening on. (default: 5000)
  • session – A session for reusing connections.
  • timeout – The timeout (in seconds) for a request to Synse Server. (default: 10s)
  • loop – The event loop to use for the client.
close() → None[source]

Close the client session.

config() → synse.models.Config[source]

Get the unified configuration for the Synse Server instance.

Returns:The Synse v3 API config response.
info(device: str) → synse.models.DeviceInfo[source]

Get all information associated with the specified device.

Parameters:device (str) – The ID of the device to get information for.
Returns:The Synse v3 API info response.
make_request(method: str, url: str, params: Optional[Mapping[str, str]] = None, data: Any = None, json: Any = None, **kwargs) → Union[dict, list][source]

A helper method to issue a request to the configured Synse Server instance.

This method is intended to only be used internally by the client. If finer-grained control over a request is desired, the client user may choose to use this method over the defined API methods at their own risk.

Returns:

The JSON response data marshaled into its Python type (dict or list).

Raises:
  • errors.SynseError – An instance of a SynseError, wrapping any other error
  • which may have occurred. An error will be raised if the client fails to
  • make the request (e.g. connection issue, timeout, etc), or if the response
  • has a non-2xx status code.
plugin(plugin_id: str) → synse.models.PluginInfo[source]

Get all information associated with the specified plugin.

Parameters:plugin_id (str) – The ID of the plugin to get information for.
Returns:The Synse v3 API plugin response.
plugin_health() → synse.models.PluginHealth[source]

Get a summary of the health of all currently registered plugins.

Returns:The Synse v3 API plugin health response.
plugins() → List[synse.models.PluginSummary][source]

Get a summary of all plugins currently registered with the Synse Server instance.

Returns:The Synse v3 API plugins response.
read(ns: str = None, tags: Union[str, Sequence[str], Sequence[Sequence[str]]] = None) → List[synse.models.Reading][source]

Get the latest reading(s) for all devices which match the specified selector(s).

Parameters:
  • ns – The default namespace to use for the tags which do not include a namespace. (default: default)
  • tags – The tags to filter devices on. Tags may be specified in multiple ways. A single string (e.g. ‘foo/bar’) will be taken as a single tag group. Multiple strings (e.g. [‘foo/bar’, ‘abc/123’]) will be taken as a single tag group. Multiple collections of strings (e.g. [[‘foo/bar’], [‘abc/123’, ‘def/456’]]) will be taken as multiple tag groups.
Returns:

The Synse v3 API read response.

read_cache(start: str = None, end: str = None) → AsyncGenerator[synse.models.Reading, None][source]

Get a window of cached device readings.

Parameters:
  • start (str) – An RFC3339 formatted timestamp which specifies a starting bound on the cache data to return. If no timestamp is specified, there will not be a starting bound.
  • end (str) – An RFC3339 formatted timestamp which specifies an ending bound on the cache data to return. If no timestamp is specified, there will not be an ending bound.
Yields:

The Synse v3 API read cache response.

read_device(device: str) → List[synse.models.Reading][source]

Get the latest reading(s) for the specified device.

Parameters:device (str) – The ID of the device to get readings for.
Returns:The Synse v3 API read device response.
scan(force: bool = None, ns: str = None, sort: str = None, tags: Union[str, Sequence[str], Sequence[Sequence[str]]] = None) → List[synse.models.DeviceSummary][source]

Get a summary of all devices currently exposed by the Synse Server instance.

Parameters:
  • force (bool) – Force a re-scan (do not use the cache). If True, the request will take longer since the internal device cache will be rebuilt. Forcing a scan will ensure the set of returned devices is up-to-date.
  • ns (str) – The default namespace to use for the tags which do not include a namespace. (default: default)
  • sort (str) – Specify the fields to sort by. Multiple fields may be specified as a comma-separated string, e.g. “plugin,id”. The “tags” field can not be used for sorting. (default: “plugin,sort_index,id”, where the sort_index is an internal sort preference which a plugin can optionally specify.)
  • tags – The tags to filter devices on. Tags may be specified in multiple ways. A single string (e.g. ‘foo/bar’) will be taken as a single tag group. Multiple strings (e.g. [‘foo/bar’, ‘abc/123’]) will be taken as a single tag group. Multiple collections of strings (e.g. [[‘foo/bar’], [‘abc/123’, ‘def/456’]]) will be taken as multiple tag groups.
Returns:

The Synse v3 API scan response.

status() → synse.models.Status[source]

Check the availability and connectivity status of the Synse Server instance.

If the instance is reachable, this request will resolve; otherwise, it will raise an error.

Returns:The Synse v3 API status response.
stream_request(method: str, url: str, params: Optional[Mapping[str, str]] = None, **kwargs) → AsyncGenerator[Union[dict, list], None][source]

A helper method to issue a request which will return a streamed response from the configured Synse Server instance.

This method is intended to only be used internally by the client. If finer-grained control over a request is desired, the user may choose to use this method over the defined API methods at their own risk.

Returns:

The streamed response data.

Raises:
  • errors.SynseError – An instance of a SynseError, wrapping any other error
  • which may have occurred. An error will be raised if the client fails to
  • make the request (e.g. connection issue, timeout, etc), or if the response
  • has a non-2xx status code.
sync(coro: Coroutine)[source]

Run an asynchronous API call synchronously by wrapping it with this function.

Examples

r = client.sync(client.status())

tags(ns: Union[str, Sequence[str]] = None, ids: bool = False) → List[str][source]

Get a list of the tags currently associated with registered devices.

Parameters:
  • ns – The tag namespace(s) to use when searching for tags. (default: default)
  • ids – Include ID tags in the response. (default: false)
Returns:

The Synse v3 API tags response.

transaction(transaction_id: str) → synse.models.TransactionStatus[source]

Get the status of an asynchronous write transaction.

Parameters:transaction_id (str) – The ID of the transaction to get the status of.
Returns:The Synse v3 API transaction response.
transactions() → List[str][source]

Get a list of the transactions currently tracked by Synse.

Returns:The Synse v3 API transactions response.
version() → synse.models.Version[source]

Get the version information for the configured Synse Server instance.

Returns:The Synse v3 API version response.
write_async(device: str, payload: Union[List[dict], dict]) → List[synse.models.TransactionInfo][source]

Write to the specified device asynchronously.

This method will queue up a write with the device’s plugin and will immediately return information for the transaction associated with the write. This transaction can be checked later to ensure the write completed successfully.

Parameters:
  • device (str) – The ID of the device to write to.
  • payload (list[dict] | dict) – The write payload.
Returns:

The Synse v3 API asynchronous write response.

write_sync(device: str, payload: Union[List[dict], dict]) → List[synse.models.TransactionStatus][source]

Write to the specified device synchronously.

This method will wait until the write action has completed. It is up to the caller to ensure that a suitable timeout is set for the request.

Parameters:
  • device (str) – The ID of the device to write to.
  • payload (list[dict] | dict) – The write payload.
Returns:

The Synse v3 API synchronous write response.

WebSocket API

Synse Server’s WebSocket API can be accessed using a WebSocket client. Clients are versioned based on the version of the Synse API they are compatible with, e.g. WebsocketClientV3 is compatible with the Synse v3 API.

The client may be initialized and used directly, in which case it must be connected and closed explicitly:

client = WebsocketClientV3('localhost')
await client.connect()
...
await client.close()

It may also be used as a context manager, which will automatically connect and close the session when the context is exited:

async with WebsocketClientV3('localhost') as client:
  ...

Example

Below is an example which creates a client, scans for all devices and for each LED device, turns it on.

import asyncio

from synse.client import WebsocketClientV3


async def main():
    """An example function which """

    c = WebsocketClientV3(
        host='localhost',
    )
    await c.connect()

    for device in await c.scan():
        if device.type == 'led':
            status = await c.write_sync(
                device=device.id,
                payload={
                    'action': 'state',
                    'data': 'on',
                }
            )

            for s in status:
                assert s.status == 'DONE'

    await c.close()

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(main())

Reference

class synse.client.WebsocketClientV3(host: str, port: Optional[int] = 5000, session: Optional[aiohttp.client.ClientSession] = None, loop: Optional[asyncio.events.AbstractEventLoop] = None, **connect_kwargs)[source]

A WebSocket client for Synse Server’s v3 API.

Parameters:
  • host – The hostname/IP address for the Synse Server instance.
  • port – The port that Synse Server is listening on. (default: 5000)
  • session – A session for reusing connections.
  • loop – The event loop to use for the client.
close() → None[source]

Close the WebSocket client session.

config() → synse.models.Config[source]

Get the unified configuration for the Synse Server instance.

Returns:The Synse v3 API config response.
connect()[source]

Establish a WebSocket client connection with Synse Server.

info(device: str) → synse.models.DeviceInfo[source]

Get all information associated with the specified device.

Parameters:device – The ID of the device to get information for.
Returns:The Synse v3 API info response.
plugin(plugin_id: str) → synse.models.PluginInfo[source]

Get all information associated with the specified plugin.

Parameters:plugin_id – The ID of the plugin to get information for.
Returns:The Synse v3 API plugin response.
plugin_health() → synse.models.PluginHealth[source]

Get a summary of the health of all currently registered plugins.

Returns:The Synse v3 API plugin health response.
plugins() → List[synse.models.PluginSummary][source]

Get a summary of all plugins currently registered with the Synse Server instance.

Returns:The Synse v3 API plugins response.
read(ns: str = None, tags: Union[str, Sequence[str], Sequence[Sequence[str]]] = None) → List[synse.models.Reading][source]

Get the latest reading(s) for all devices which match the specified selector(s).

Parameters:
  • ns – The default namespace to use for the tags which do not include a namespace. (default: default)
  • tags – The tags to filter devices on. Tags may be specified in multiple ways. A single string (e.g. ‘foo/bar’) will be taken as a single tag group. Multiple strings (e.g. [‘foo/bar’, ‘abc/123’]) will be taken as a single tag group. Multiple collections of strings (e.g. [[‘foo/bar’], [‘abc/123’, ‘def/456’]]) will be taken as multiple tag groups.
Returns:

The Synse v3 API read response.

read_cache(start: str = None, end: str = None) → Generator[[synse.models.Reading, None], None][source]

Get a window of cached device readings.

Parameters:
  • start – An RFC3339 formatted timestamp which specifies a starting bound on the cache data to return. If no timestamp is specified, there will not be a starting bound.
  • end – An RFC3339 formatted timestamp which specifies an ending bound on the cache data to return. If no timestamp is specified, there will not be an ending bound.
Yields:

The Synse v3 API read cache response.

read_device(device: str) → List[synse.models.Reading][source]

Get the latest reading(s) for the specified device.

Parameters:device – The ID of the device to get readings for.
Returns:The Synse v3 API read device response.
read_stream(ids: List[str] = None, tags: Union[str, Sequence[str], Sequence[Sequence[str]]] = None, stop: bool = False) → Generator[[synse.models.Reading, None], None][source]

Get a stream of current reading data from Synse Server.

When the stream starts, all new readings will be provided as they are read. In order to stop the stream, this method needs to be called again with the stop parameter set to True.

Parameters:
  • ids – A list of device IDs which can be used to constrain the devices for which readings should be streamed. If no IDs are specified, no filtering by ID is done.
  • tags – A collection of tag groups to constrain the devices for which readings should be streamed. The tags within a group are subtractive (e.g. a device must match all tags in the group to match the filter), but each tag group specified is additive (e.g. readings will be streamed for the union of all specified groups). If no tag groups are specified, no filtering by tags is done.
  • stop – A boolean value indicating whether or not to stop the reading stream.
Returns:

A stream of current reading data.

request(event, data=None) → Union[dict, list][source]

A helper method to issue a WebSocket API request to the configured Synse Server instance.

This method is intended to only be used internally by the client. If finer-grained control over a request is desired, the client user may choose to use this method over the defined API methods at their own risk.

Returns:

The JSON response data marshaled into its Python type (e.g., dict or list).

Raises:
  • errors.SynseError – An instance of a SynseError, wrapping any other error
  • which may have occurred. An error will be raised if the client fails to
  • make the request (e.g. connection issue, timeout, etc).
scan(force: bool = None, ns: str = None, sort: str = None, tags: Union[str, Sequence[str], Sequence[Sequence[str]]] = None) → Generator[[synse.models.DeviceSummary, None], None][source]

Get a summary of all devices currently exposed by the Synse Server instance.

Parameters:
  • force – Force a re-scan (do not use the cache). If True, the request will take longer since the internal device cache will be rebuilt. Forcing a scan will ensure the set of returned devices is up-to-date.
  • ns – The default namespace to use for the tags which do not include a namespace. (default: default)
  • sort – Specify the fields to sort by. Multiple fields may be specified as a comma-separated string, e.g. “plugin,id”. The “tags” field can not be used for sorting. (default: “plugin,sort_index,id”, where the sort_index is an internal sort preference which a plugin can optionally specify.)
  • tags – The tags to filter devices on. Tags may be specified in multiple ways. A single string (e.g. ‘foo/bar’) will be taken as a single tag group. Multiple strings (e.g. [‘foo/bar’, ‘abc/123’]) will be taken as a single tag group. Multiple collections of strings (e.g. [[‘foo/bar’], [‘abc/123’, ‘def/456’]]) will be taken as multiple tag groups.
Returns:

The Synse v3 API scan response.

status() → synse.models.Status[source]

Check the availability and connectivity status of the Synse Server instance.

If the instance is reachable, this request will resolve; otherwise, it will raise an error.

Returns:The Synse v3 API status response.
stream_request(event, data=None) → Generator[[Union[dict, list], None], None][source]

A helper method to issue a WebSocket API request to the configured Synse Server instance where the response is expected to be streamed back as multiple individual messages.

This method is intended to only be used internally by the client. If finer-grained control over a request is desired, the client user may choose to use this method over the defined API methods at their own risk.

Yields:

The JSON response data marshaled into its Python type (e.g., dict or list).

Raises:
  • errors.SynseError – An instance of a SynseError, wrapping any other error
  • which may have occurred. An error will be raised if the client fails to
  • make the request (e.g. connection issue, timeout, etc).
tags(ns: str = None, ids: bool = None) → List[str][source]

Get a list of the tags currently associated with registered devices.

Parameters:
  • ns – The tag namespace(s) to use when searching for tags.
  • ids – Include ID tags in the response. (default: false)
Returns:

The Synse v3 API tags response.

transaction(transaction_id: str) → synse.models.TransactionStatus[source]

Get the status of an asynchronous write transaction.

Parameters:transaction_id – The ID of the transaction to get the status of.
Returns:The Synse v3 API transaction response.
transactions() → List[str][source]

Get a list of the transactions currently tracked by Synse.

Returns:The Synse v3 API transactions response.
version() → synse.models.Version[source]

Get the version information for the configured Synse Server instance.

Returns:The Synse v3 API version response.
write_async(device: str, payload: Union[List[dict], dict]) → List[synse.models.TransactionInfo][source]

Write to the specified device asynchronously.

This method will queue up a write with the device’s plugin and will immediately return information for the transaction associated with the write. This transaction can be checked later to ensure the write completed successfully.

Parameters:
  • device – The ID of the device to write to.
  • payload – The write payload.
Returns:

The Synse v3 API asynchronous write response.

write_sync(device: str, payload: Union[List[dict], dict]) → List[synse.models.TransactionStatus][source]

Write to the specified device synchronously.

This method will wait until the write action has completed. It is up to the caller to ensure that a suitable timeout is set for the request.

Parameters:
  • device – The ID of the device to write to.
  • payload – The write payload.
Returns:

The Synse v3 API synchronous write response.