Create a Function to Automate the Process

Functions provide the capability to execute custom business rules.

  1. To create a function, click Functions > Workers.
  2. Click New Worker.
  3. Add the Function name as main.
  4. Select the Python3 Template.
  5. Enter the following code. In the provided code, complete with the information required at the beginning. Also, complete the CLIENT ID, and CLIENT SECRET with your own values collected in Create an App.
    from swx.auth.token import get_token import requests
    
    API_URL = "https://api.swx.altairone.com"
    SPACE = "tutorialebike"    # Change it to your Space name
    
    # We’ll use a Thing credentials to request the access token
    COLLECTION = "esp32-sensors"
    THING_ID = "<user-ride>"
    CLIENT_ID = "tutorialebike::01GE4TZ0XJSR90WNNCYH1F4X35" 
    CLIENT_SECRET = "oBVzl22Mw0a8dvKSG9dCMnS9R6zs4B"
    
    def handle(req):
    #------------------------Get UID of "OPENED" thing-------------------------
    with get_token(CLIENT_ID, CLIENT_SECRET, ["thing", "data"]) as token:
    
        PATH = "/spaces/tutorialebike/categories/esp32-sensors/things/?property:state=opened"
        headers = {"Authorization": "Bearer " + token}
        response = requests.request("GET", API_URL + PATH, headers=headers)
        UID = response.json()["data"][0]["uid"]
    
    #-------------------------GET MQTT USERNAME--------------------------------
        PATH_MQTT = "/spaces/ebike-demo/categories/esp32_sensors/things/" + UID +
        "/mqtt-credentials"
        headers = {"Authorization": "Bearer " + token}
        response = requests.request("GET", API_URL + PATH_MQTT, headers=headers) MQTT_USERNAME = response.json()["username"]
    
    return {
    "status_code": 200,
    "body": {"UID": UID,
    "MQTT_USERNAME": MQTT_USERNAME} 
    }

    The purpose of this Function is to find Things with the Property state set to opened. The Function will help provide the ESP32/microcontroller a Thing to send data to and allow the app to perform actions on the correct Thing by utilizing both the MQTT username and UID specifier.

  6. 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. Test your Function by when you have your Function selected.
  7. Select the Function and navigate to the Test tab to test the Function.


    Figure 1.
  8. Invoke your Function by adding an Event Trigger or by making an HTTP request. Refer to the following API documentation on how to interact with SmartWorks API. To invoke your function, make a POST HTTP request to the invoke function endpoint with your Space and Function names filled in:
    https://api.swx.altairone.com/spaces/yourspace name/functions/your function name/invoke