Create a Function to Automate the Process
Functions provide the capability to execute the custom business rules.
For example, one of the Arduino property’s is "led_blink" indicating the status of the on-board led. We want to count the number of times it blinks.
- To create a function, click Functions > Workers.
- Click New Worker.
- Add the Function name as count-blink.
-
Select the Python 3 template.
-
Enter the following code. In the provided code, add your
thing’s Client ID and Secret ID from the Interface tab inside the Thing. Also,
complete the PATH with your own values.
import requests import json API_HOST = 'https://api.swx.altairone.com' CLIENT_ID = "Add your client ID from Interface tab inside the Thing" CLIENT_SECRET = "Add your client Secret from Interface tab inside the Thing" def get_access_token(): payload = f'grant_type=client_credentials&' \ f'client_id={CLIENT_ID}&' \ f'client_secret={CLIENT_SECRET}&' \ f'scope=thing.read thing.update' headers = {'Content-Type': 'application/x-www-form-urlencoded'} response = requests.request("POST", API_HOST + "/oauth2/token", headers=headers, data=payload) return response.json()['access_token'] def handle(req): PATH="/spaces/your_space/collections/your_collection/things-status/your_thing-id" headers = {"Authorization": "Bearer " + get_access_token()} response = requests.request("GET", API_HOST + PATH , headers=headers) properties=response.json()['properties'] blink_count = properties['blink_count'] led_blink = properties['led_blink'] if led_blink == "on": blink_count =blink_count+1 PATH="/spaces/your_space/collections/your_collection/things/your_thing-id/properties/blink_count" response = requests.request("PUT", API_HOST + PATH, headers=headers,json={"blink_count": blink_count}) return { "body": response.json(), "status_code": response.status_code }
-
Add an Event trigger as follows:
status/your_space_name/collections/your_collections_name/things/your_thing_uid/properties/
led_blink
When using this method, the function will be invoked whenever there is a change on the Property
led_blink
on the Thing you have created. -
Deploy your function by clicking Save.
The function is created. This could take a few minutes. The status of your Function will be updated to a Building status and, eventually, it will become Running. At this point, your Function is ready to be called.
-
You can edit the code in the Code tab as necessary.
-
You can test the function created in the Test tab by sending the input
parameters to the function and receive the solution in the test response field.
In Test Request Input field enter,
{"led_blink": “on”}
and click Run.The Test Response field shows blink count result.