Create a Function to Automate the Process

  1. To create a function, click Functions > Workers.

    Figure 1.
  2. Click New Worker.
  3. Add the Function name as update-cpu-state and description if desired.
  4. Select the Python 3 template.
  5. Enter the following code. In the provided code, complete with the information required at the beginning. Also, complete the PATH with your own values.
    import requests 
    import json
    from swx.auth.token import get_token 
    API_URL = '' 
    #Complete with your own values
    SPACE = '<A-SPACE-NAME>'  
    def handle(req): 
        with get_token(CLIENT_ID, CLIENT_SECRET, ["thing.update",""]) as token: 
            body = req.body.decode("utf-8")
            body = json.loads(body)
            cpu = body['cpu']
            if cpu >= 85:
                state = "Critical usage"
            elif 50 < cpu < 85:
                state = "Normal usage"
                state = "Low usage"
            url = f"{API_URL}/spaces/{SPACE}/categories/{CATEGORY}/things/{THING_UID}/properties" 
            response = requests.put(url,headers={"Authorization": f"Bearer {token.access_token}"},json={"statecpu": state}) 
        return { 
            "status_code": 200, 
            "body": response.json() 

    Figure 2. New Function form
    Note: You can edit the code as necessary.

    Figure 3. Edit Function code tab
  6. Add an Event trigger as follows:

    When using this method, the function will be invoked whenever there is a change on the Property cpu 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. Test the function created in the Test tab by sending the input parameters to the function and receiving the solution in the test response field.
    1. In Test Request Input field enter, enter {"cpu": 57.9}.
    2. Click Run.
      The Test Response field shows Normal usage.

      Figure 4.