Disruptive Technologies Disruptive Developers

Generating events with the Sensor Emulator API

In this code example, we will create a Python console application that will

  1. Create an Emulated Touch Sensor
  2. Create one emulated Touch Event for that Sensor every second

Service Account

In order to follow this example, you must have created a Service Account and key as described in the code example and noted down the Key Secret for a Key ID, this is needed later. Please note that you need to change the Role of the Service Account to Project Administrator to be able to create an Emulated Device.

Prerequisites

To test try out this code example you need to have Python 3 installed.

Create a new folder for this example open a command line console in this folder, run the following 3 lines:

1
2
3
python3 -m venv venv
source venv/bin/activate
pip3 install requests

This will

  1. setup a standard Python 3 virtual environment (or venv),
  2. activate this environment and finally
  3. install the required packages via the built in Python package manager.

Keep this console window open as we will use it to run the example in a moment.

Code

Using your favorite editor, create a new file called sensor-emulator.py with the following content:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
import requests
import json
import pprint
import time
from datetime import datetime
import urllib

# Fill in from the Service Account and Project:
username="SERVICE_ACCOUNT_KEY"  # this is the key
password="SERVICE_ACCOUNT_SECRET" # this is the secret
projectId="PROJECT_ID"

# Configure URLs, JSON POST data and default names
studioUrlBase="https://studio.disruptive-technologies.com"
apiUrlBase="https://api.disruptive-technologies.com/v2"
emulatorUrlBase="https://emulator.disruptive-technologies.com/v2"
apiDeviceUrl="{}/projects/{}/devices".format(apiUrlBase,projectId)
emulatedDeviceUrl="{}/projects/{}/devices".format(emulatorUrlBase,projectId)
codeExampleSensorDisplayName="Code Example Touch Sensor"
createEmulatedSensorJSON = {
  "type": "touch",
  "labels": {
    "name": codeExampleSensorDisplayName,
    "virtual-sensor": ""
  }
}
publishEmulatedTouchJSON = {
  "touch": {
    "touch": {
    }
  }
}

def getCodeExampleDeviceName(displayName):
  # URL encode label=value
  urlParamFormatNameLabel = urllib.parse.quote("name={}".format(codeExampleSensorDisplayName))
  # Get devices with Label name=displayName
  device_listing = requests.get(apiDeviceUrl + "?label_filters=" + urlParamFormatNameLabel, auth=(username,password))
  # If found, return full resource name, else False
  devices = device_listing.json()['devices']
  if len(devices) > 0:
    return devices[0]["name"]
  return False

### Run code-example
def main():
  # Check if code-example Sensor already exists
  name = getCodeExampleDeviceName(codeExampleSensorDisplayName)
  if not name:
    # If not, create it
    print("Creating code-example Touch Sensor '{}'".format(codeExampleSensorDisplayName))
    device = requests.post(emulatedDeviceUrl, data=json.dumps(createEmulatedSensorJSON), auth=(username,password))
    name = device.json()["name"]
  else:
    print("Found already existing code-example Touch Sensor '{}'".format(codeExampleSensorDisplayName))

  print()
  print("Direct link to Sensor in Studio: {}".format(studioUrlBase + "/" + name))
  print()

  print("Starting to generate one emulated TouchEvent per second... (press CTRL-C to abort)")
  while True:
    time.sleep(1)
    print("{} - Touching Sensor".format(datetime.now()))
    r = requests.post(emulatorUrlBase + "/{}:publish".format(name), data=json.dumps(publishEmulatedTouchJSON), auth=(username,password))

if __name__ == "__main__":
  main()

Next, open up the Service Account tab in Studio and replace

  1. SERVICE_ACCOUNT_KEY with the KEY ID
  2. SERVICE_ACCOUNT_SECRET with the Key Secret you saved when you created the Key
  3. PROJECT_ID with the part of the URL in the browser between /projects/ and /serviceaccounts/..., e.g. b8rsrqnh2nqg00c0s9bg

Using the console you used to setup the development environment, run:

python3 sensor-emulator.py

Example Output

You should now see the console outputting one new line per second each representing a sent Touch Event.

To see the events coming in, follow the link to the Sensor in Studio that is also part of the code example output.

Found already existing code-example Touch Sensor 'Code Example Touch Sensor'

Direct link to Sensor in Studio: https://studio.d21s.com/projects/b7s3e550fee000ba5dhg/devices/emuba7ucmk4o3qg008pbu2g

Starting to generate one emulated TouchEvent per second:
2018-02-23 11:28:14.077600 - Touching Sensor
2018-02-23 11:28:15.300588 - Touching Sensor
2018-02-23 11:28:16.523049 - Touching Sensor
2018-02-23 11:28:17.740090 - Touching Sensor
2018-02-23 11:28:18.990783 - Touching Sensor
2018-02-23 11:28:20.209312 - Touching Sensor
2018-02-23 11:28:21.432176 - Touching Sensor
2018-02-23 11:28:22.685985 - Touching Sensor

Clean up

A new emulated Touch Sensor was created as part of the code example.

To delete it you have two options.

Delete via Emulator UI

To do this:

  1. Go to
  2. Open Manage Projects
  3. Click on the Project you used for the code example
  4. Click on OPEN VIRTUAL SENSOR EMULATOR
  5. Click the left arrow until you find the sensor named “Code Example Touch Sensor”
  6. Press the DELETE button in the lower right corner
  7. Confirm with DELETE SENSOR

Delete via ´curl´

See the curl article on how to get started with curl if you have not used it before.

In the following command,

curl -X DELETE "https://emulator.disruptive-technologies.com/v2/PATH_TO_DEVICE" -u "SERVICE_ACCOUNT_KEY:SERVICE_ACCOUNT_SECRET"

replace PATH_TO_DEVICE with the path after https://studio.disruptive-technologies.com/ as output by the code example (e.g. projects/b7s3e550fee000ba5dhg/devices/emuba81hbekkdh000cmid20).

Then replace SERVICE_ACCOUNT_KEY with the KEY ID and SERVICE_ACCOUNT_SECRET with the Key Secret you saved when you created the Key. The last two you should be able to copy-paste from the code example.