Create a Function to Automate the Process

Functions provide the capability to execute custom business rules. For this project, a function will be created to update the state of the lamp based on the temperature.

  1. Add two new properties to the Thing.

    Figure 1.
  2. Change to the Functions section to create your function.

    Figure 2.

Functions are divided into two main parts, called Workers and Triggers.

A Worker is the Function itself. It allows to create its custom-base function and enables to subscribe to an “Event Trigger”.

  1. Create the function itself (worker) using the following code. Complete the PATH with your own values.
    Note: Add your thing’s Client ID and Secret ID from the Interface tab inside the Thing.
    import time
    import requests
    import json
    API_HOST = ''
    PATH = "/spaces/YourSpaceID/collections/YourCollectionName/things/YpurThingUID/properties/lamp-state"
    CLIENT_ID = "EnterYourValues"
    CLIENT_SECRET = "EnterYourValues"
    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 revoke_token(token):
        payload = f'token={token}&' \
                  f'client_id={CLIENT_ID}&' \
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        response = requests.request("POST", API_HOST + "/oauth2/revoke",
                                    headers=headers, data=payload)
        return response
    def handle(req):
        body = req.body.decode("utf-8")
        body = json.loads(body)
        temperature = body['temperature']
        if temperature >= 70:
            state = "Warning"
            state = "Normal"
        headers = {"Authorization": "Bearer " + token}
        response = requests.request("PUT", API_HOST + PATH, headers=headers,
                            json={"lamp-state": state})
        return {
        	"body": response.json(),
        	"status_code": response.status_code

  2. Add the following event trigger:

    Figure 3.

A Trigger is a component that is capable of invoking serverless Functions from an event source. Triggers work as a listener to a particular endpoint, capturing events and messages from different sources and redirecting them to one or more Functions.

  1. Create a MQTT trigger to subscribe to the topic entered as Event Trigger in the worker.

    Figure 4.
    Note: MQTT credentials can be obtained as shown below:

    Figure 5.
  2. Open the MQTT Inspector to track the messages received:

    Figure 6.
  3. Check that the function works as expected:

    Figure 7.