Create a User Function to Automate the Process

User 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 User Functions section to create your Function.

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

  • The Function enables you to create a custom-base function and subscribe to an “Event Trigger”.
  • A Trigger is a component that is capable of invoking serverless User Functions from an event source. Triggers work as a listener to a particular endpoint. It enables the capturing of events and messages from different sources and redirects them to one or more User Functions. Triggers convert incoming events to HTTP requests to asynchronously invoke all the User Functions that match certain criteria.
  1. Create the Function 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 json 
    from iots import API
    from function import variables
    
    SPACE = "enter-your-spaceID"
    THING_UID = "enter-your-thingUID"
    
    my_scopes = ["thing.read", "thing.update"]
    
    
    def handle(req):
    
    
      if variables.exists("my_client_id"): 
        my_client_id = variables.get("my_client_id")
    
      if variables.exists("my_client_secret"):
        my_client_secret = variables.get("my_client_secret")
    
      body = req.body.decode("utf-8")
      body = json.loads(body)
      temperature = body['temperature']
    
      with API().set_credentials(my_client_id, my_client_secret, my_scopes) as api:
        if temperature >= 70:
          status = "Warning"
        else:
          status = "Normal"
    
        response = api.spaces(SPACE).things(THING_UID).properties("lamp-state").update(status)
    
      return {
        "body": response.dict(),
        "status_code": response.http_response().status_code
      }
    
  2. Add the following Event Trigger:
    spaces/yourspaceID/things/yourthingUID/properties/temperature
  3. Create an MQTT trigger to subscribe to the topic entered as Event Trigger in the Function.
    Figure 2.


    Note: MQTT credentials can be obtained by clicking Create Credentials in the Interfaces tab of the Thing menu, under the MQTT section, as shown below.
    Figure 3.


  4. Open the MQTT Inspector to track the messages received and check that the Function works as expected:
    Figure 4.