Local process control
This topic uses a typical process control scenario to demonstrate how to implement complex local process control using edge Function Compute.
Prerequisites
- This example applies only to Link IoT Edge Pro Edition. Ensure that you have created an edge instance. For more information, see Set up the environment for the Pro Edition.
- Create a light sensor product and a living room light product. Then, create the LightSensor and Light devices under these products and assign the devices to an edge instance. For more information, see Sample driver.
- This scenario requires the local database storage assistant to store data that is reported by the sensor to the local database of the gateway. Therefore, you must first complete the steps in Local database storage assistant.
Background information
In traditional Internet of Things (IoT) scenarios, such as home automation, petroleum, and electric power, various on-site sensors collect data in real time. This data is transmitted to remote data center servers through data links, such as 3G, 4G, or wired broadband. The remote data center servers convert the data format and then process, analyze, and compute the data. The processing results and generated control instructions are then transmitted back to the on-site instrument layer over the Internet to implement process control. In production, you may also need to combine historical sensor data with industry-specific algorithm models, such as linear regression or Isolation Forest, to analyze and determine the on-site status and then control the behavior of other devices. For these scenarios, you can use the edge Function Compute feature provided by IoT Edge to implement local process control.
IoT Edge is designed to build a new model where the near-end edge layer and the cloud computing layer work together. In the field of automation, the near-end edge layer can process or correct sensor data, pre-diagnose and pre-process sensor faults, and complete on-site control and fault diagnosis. At the same time, the corrected data is uploaded to the cloud in real time for computation, which completes a layered data processing procedure.
This topic uses the LightSensor sensor and the Light device as an example. It demonstrates how to retrieve all data reported by the LightSensor sensor within a 5-minute period (historical data). If the average value of the data exceeds a specific threshold, the Light device is turned off.
Step 1: Create a process control function
- Download the local process control function querySqliteDB-code.zip.
- Log on to the Function Compute console.If you have not activated this service, read the terms and select I have read and agree to the terms. Then, click Activate Now.
- (Optional) In the navigation pane on the left, click Services & Functions. On the Services & Functions page, in the Service List section, click Create Service to create a service.The Service Name parameter is required. Set this parameter to EdgeFC. You can configure the other parameters as needed or use their default settings.Note
- If this is your first time creating a service in Function Compute, follow the configuration wizard.
- If you have already created the EdgeFC service for other scenarios or miniprogram examples, you do not need to create it again.
- After the service is created, on the Services & Functions page, find the EdgeFC service and click Create Function.
- On the Create Function page, click Configure and Deploy in the Event Function section.
- Set the basic management configuration parameters for the process control function.
Parameter Description Function TypeKeep the default option.ServiceSelect the EdgeFC service that you created.Function NameSet it to querySqliteDB. RuntimeSet the function runtime and select a method to upload the code. In this example, select Python 3. To the right of Upload Code, select Upload a ZIP file. Click Upload Code and upload the querySqliteDB-code.zip package that you downloaded in Step 1.
HandlerUse the default value: index.handler.You can configure the other parameters as needed or use their default settings. For more information, see Function Compute.
After you confirm the function information, click Create.
- After the function is created, the system automatically navigates to the function details page. On the Code tab, in the Code Execution Management section, select the Edit Online radio button to view the source code.
Note The sample code for querySqliteDB consists of three steps.- Parses the productKey and deviceName from the received device data (the event parameter) to form the database table name.
edict = json.loads(event) topic = edict['topic'] tlist = topic.split('/') if tlist[1] == 'sys': productKey = tlist[2] deviceName = tlist[3] tableName = productKey+'_'+deviceName print("-- Table Name : "+tableName) - Retrieves all data reported by the LightSensor sensor within the last 5 minutes and calculates the average value.
cursor.execute("SELECT avg(VALUE) FROM {} WHERE KEY = ? AND TIMESTAMP >= datetime('now','-5 minutes','localtime')".format(tableName), [key]) avg_value = cursor.fetchone()[0] - If the average value of the data reported by the LightSensor sensor is greater than a specific threshold (in this case, a light intensity of 240), it turns off the Light device.
if avg_value > 240: print("-- Turn off the Light.") set_params = {"productKey": "a1ZJTVs****","deviceName": "LightDev","payload": {"LightSwitch":0}} res = lesdk.setThingProperties(set_params)
- Parses the productKey and deviceName from the received device data (the event parameter) to form the database table name.
Step 2: Assign the function to an edge instance
- Log on to the IoT Edge console.
- In the navigation pane on the left, click Application Management.
- Create an edge application of the Function Compute type using the function that you created in Step 1. For more information, see Function Compute application.
The application information parameters are described as follows:
Parameter Description Application Name Set a name for your application, for example, querySqliteDB. Application Type Select Function Compute. Region Select the region where your service was created. Service Select the EdgeFC service. Function Select the querySqliteDB function. Authorization Select AliyunIOTAccessingFCRole. Application Version Set the version for the application. The version number must be unique for this application. You cannot set two identical version numbers for the same application. In the Function Configuration section, set Enable Default Configurations to Yes. The other parameters can be left at their default settings.
- In the navigation pane on the left, click Edge Instances.
- Find the edge instance that you created in the "Prerequisites" section and click View.
- On the Instance Details page, go to the Edge Applications tab and click Assign Application.
- In the Assign Application panel, find the created process control function querySqliteDB, click Assign in the Actions column, and then click Close .
Step 3: Configure message routing
This topic explains how to add messages and describes each parameter. For more information, see Set message routing.
- On the Instance Details page, click the Message Routing tab.
- Click Assign Route to add a message route from the LightSensor device to Function Compute.Set the following parameters as prompted on the page, and then click OK .
Parameter Description Route Name Set a name for the message route. Message Source In this example, select Device, and then select . Topic Filter In this example, select All. Message Target In this example, select Edge Application and the EdgeFC/querySqliteDB function.
Step 4: Deploy the edge instance
- On the Instance Details page, click Deploy in the upper-right corner. In the dialog box that appears, click OK to deploy resources, such as sub-devices and functions, to the edge.
- Log on to your gateway using Secure Shell (SSH) and run the
tail -f /linkedge/run/logger/fc-base/querySqliteDB/log.INFOcommand.The local process control function of edge Function Compute runs as a background service. You can view the logs of this function to monitor its operation.
You have now completed the process of using edge Function Compute to implement local process control.