Create a Function to Automate the Process

Functions provide the capability to execute the custom business rules.

For example, one of the NodeMCU property’s is "humidity", capturing the humidity level. We want to monitor the humidity level and if it drops below certain level then send an email notification.

  1. To create a function, click Functions > Workers.
  2. Click New Worker.
  3. Add the Function name as low-humidity-event.
  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 time
    import requests
    import json
    from swx.auth.token import get_token, revoke_token
    
    API_HOST = 'https://api.swx.altairone.com'
    PATH = "/spaces/EnterYourSpaceID/collections/EnterYourCollectionName/things/EnterYourThingUID/properties/humidity_status"
    CLIENT_ID = "Add your client ID from the Interface tab inside the Thing"
    CLIENT_SECRET = "Add your client secret from the Interface tab inside the Thing"
    
    def handle(req):
    
      token = get_token(CLIENT_ID_APP, CLIENT_SECRET_APP, ["thing"])
      body = req.body.decode("utf-8")
      body = json.loads(body)
      humidity = body['humidity']
    
      if humidity >= 50:
        humidity = "High Humidity"
      elif 10 < humidity < 49:
        humidity = "Normal Humidity"
      else:
        humidity = "Low Humidity"
    
      headers = {"Authorization": "Bearer " + token.access_token}
      response = requests.request("PUT", API_HOST + PATH, headers=headers,
      json={"humidity_status": humidity})
    
      revoke_token(token.access_token, CLIENT_ID, CLIENT_SECRET)
      return {
      "body": response.json(),
      "status_code": response.status_code
    }
  6. Add an Event trigger as follows:
    status/your-space_name/collections/your_collections_name/things/your_thing_id/properties/humidity

    When using this method, the function will be invoked whenever there is a change on the Property humidity 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.