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.

  1. To create a function, click Functions > Workers.
  2. Click New Worker.
  3. Add the Function name as count-blink.
  4. Select the Python 3 template.

    Figure 1.
  5. 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 = ''
     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' 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):
        headers = {"Authorization": "Bearer " + get_access_token()}
        response = requests.request("GET", API_HOST + PATH , headers=headers)
        blink_count = properties['blink_count']
        led_blink = properties['led_blink']
        if led_blink == "on":
            blink_count =blink_count+1
            response = requests.request("PUT", API_HOST + PATH, headers=headers,json={"blink_count": blink_count})
        return {
            "body": response.json(),
            "status_code": response.status_code
  6. Add an Event trigger as follows:

    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.

  7. 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.
  8. You can edit the code in the Code tab as necessary.

    Figure 2.
  9. 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.

    Figure 3.