Touch to Identify

An example of how to use the REST API with a simple script that identifies devices by touch.

Overview

A feature in DT Studio popular with our customers is the ability to locate a sensor by simply touching it. Like all functions in DT Studio, the implementation is based on our REST API. We will in this example show how simple it is to recreate using the stream endpoint.

Preliminaries

  • Basic Auth For simplicity, we here use Basic Auth for authentication. We recommend replacing this with an OAuth2 flow for integrations more complex than local experimentation.

  • Service Account Credentials You must create and know the credentials of a Service Account. Any role will suffice.

  • Streaming Best Practices While this example is based on our other example for Streaming Events, it does not implement the same retry policy or other best practices as it is not the focus here. You are, however, free to combine the two examples for a more robust touch-event-listening loop.

Example Code

The following points summarize the provided example code.

  • Sends a GET request to the REST API to initialize an event stream.

  • Keep the TCP connection open while receiving events.

  • When receiving a Touch Event, fetch and print the source device information.

  • Break the stream.

Environment Setup

If you wish to run the code locally, make sure you have a working runtime environment.

The following packages are required by the example code and must be installed.

pip install requests==2.31.0

Add the following environment variables as they will be used to authenticate the API.

export DT_SERVICE_ACCOUNT_KEY_ID=<YOUR_SERVICE_ACCOUNT_KEY_ID>
export DT_SERVICE_ACCOUNT_SECRET=<YOUR_SERVICE_ACCOUNT_SECRET>
export DT_SERVICE_ACCOUNT_EMAIL=<YOUR_SERVICE_ACCOUNT_EMAIL>
export DT_PROJECT_ID=<YOUR_PROJECT_ID>

Source

The following code snippet implements the touch-to-identify listening loop.

import os
import json

import requests

# Service Account credentials.
SERVICE_ACCOUNT_KEY_ID = os.getenv('DT_SERVICE_ACCOUNT_KEY_ID')
SERVICE_ACCOUNT_SECRET = os.getenv('DT_SERVICE_ACCOUNT_SECRET')

# Construct API URL.
PROJECT_ID = os.getenv('DT_PROJECT_ID')
API_BASE = 'https://api.d21s.com/v2/'
DEVICES_STREAM_URL = '{}projects/{}/devices:stream'.format(
    API_BASE,
    PROJECT_ID
)

if __name__ == '__main__':
    # Set up a stream connection.
    print('Waiting for touch event...')
    stream = requests.get(
        url=DEVICES_STREAM_URL,
        auth=(SERVICE_ACCOUNT_KEY_ID, SERVICE_ACCOUNT_SECRET),
        stream=True,
        params={
            'event_types': ['touch'],
        },
    )

    # Iterate through the events as they come in (one event per line).
    for line in stream.iter_lines():
        # Decode the response payload and isolate event dictionary.
        payload = json.loads(line.decode('ascii'))

        # Halt at missing key.
        if 'result' not in payload.keys():
            print(payload)
            break

        # Fetch touched device blob for more detailed information.
        event = payload['result']['event']
        device = requests.get(
            url=API_BASE + event['targetName'],
            auth=(SERVICE_ACCOUNT_KEY_ID, SERVICE_ACCOUNT_SECRET),
        ).json()

        # Print some device information.
        print('\nTouch event received:')
        print(json.dumps(device, indent=4))

        # Stop stream as we've found a device.
        break

Expected Output

Once a touch event has been received, the device information is printed and stream terminated.

Waiting for touch event...

Touch event received:
{
    "name": "projects/c0md3mm0c7bet3vico8g/devices/emuc0uc989qdqebrvv29so0",
    "type": "touch",
    "labels": {
        "name": "my-favorite-sensor",
        "virtual-sensor": ""
    },
    "reported": {
        "networkStatus": {
            "signalStrength": 99,
            "rssi": 0,
            "updateTime": "2021-03-03T17:21:53.080314Z",
            "cloudConnectors": [
                {
                    "id": "emulated-ccon",
                    "signalStrength": 99,
                    "rssi": 0
                }
            ],
            "transmissionMode": "LOW_POWER_STANDARD_MODE"
        },
        "batteryStatus": null,
        "touch": {
            "updateTime": "2021-03-03T17:22:51.059514Z"
        }
    }
}

Terminating stream.

Last updated