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.
-
To create a Function, click
.
- Click New Function.
- Add the Function name as low-humidity-event.
-
Select the Python 3 template.
-
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 json from iots import API SPACE = "enter-your-space" THING_UID = "enter-your-thingUID" CLIENT_ID = "enter-your-client-id" CLIENT_SECRET = "enter-your-client-secret" my_scopes = ["thing"] def handle(req): with API().set_credentials(CLIENT_ID,CLIENT_SECRET,my_scopes) as api: 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" update_property= api.spaces(SPACE).things(THING_UID).properties("humidity_status").update(humidity) return { "status_code": 200, "body": "ok" }
-
Add an Event trigger as follows:
spaces/your-space_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. -
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.
-
You can edit the code in the Code tab as necessary.