this section describes the Python API used inside the Gateway, which provides a set of feature-rich interfaces that enable you to write Python scripts to perform various operations and data processing on the Gateway. This section provides the necessary information and sample code to help you take full advantage of the features and performance of the product.
1.1 publishing data such as measuring points, alarms, and customizations to the cloud (publishing fast functions)¶
wizard_data: Failed to push the message for the first time. The message is stored in the offline cache according to the topic, payload, qos specified by wizard_data (if wizard_data is not specified, the sent topic, payload, qos is used). After the connection is restored, the message is uploaded to the MQTT server in chronological order. The format of wizard_data is as follows:{"topic": <topic>, "qos ": <qos>, "payload ": <payload>}
cloud_name: specifies the cloud to which the cloud is published. It is available for multi-cloud collaboration.
When configuring the "publish" fast function, there are two formats for the parameter message of the fast function (determined by whether to pass the wizard_api)
the entry function contains the wizard_api parameter. The script example is as follows (the default script)
## Enter your python code.importjsonfromcommon.Loggerimportloggerfromquickfaas.remotebusimportpublishdefmain(message,wizard_api,cloudName):logger.debug("publish topic:%s, payload: %s, cloudName: %s"%(__topic__,message,cloudName))publish(__topic__,json.dumps(message),__qos__,cloud_name=cloudName)
Example of the format of the incoming message data:
## Enter your python code.importjsonfromcommon.Loggerimportloggerfromquickfaas.remotebusimportpublishdefmain(message,cloudName):logger.debug("publish topic:%s, payload: %s, cloudName: %s"%(__topic__,message,cloudName))publish(__topic__,json.dumps(message),__qos__,cloud_name=cloudName)
example of the format of the incoming message data:
message: write a measuring point message in the following format:
format 1:{"measures1": 12}. If the measuring point name is duplicated or does not exist, an exception will be thrown to indicate that the value has failed to be written.
Format 2:{"controller1": {"measures1": 12}}
format 3:[{"name": "controller1", "measures":[{"name": "measures1", "value": 12}]}]
timeout: write point response timeout, 60s by default
cloudName: indicates which cloud platform calls the write command (used to determine whether the measuring point under the current cloud platform is blocked or renamed), optional.
message: write a measuring point message in the following format:
Format 1:{"measures1": 12}. If the measuring point name is duplicated or does not exist, an exception will be thrown to indicate that the value has failed to be written.
Format 2:{"controller1": {"measures1": 12}}
format 3:[{"name": "controller1", "measures":[{"name": "measures1", "value": 12}]}]
callback: the callback function executed when the PLC value is written and returned. In order to be compatible with DS1.0, the callback function also supports three parameters.
userdata: parameters passed to the callback function
timeout: write point response timeout, 60s by default
cloudName: indicates which cloud platform calls the write command (used to determine whether the measuring point under the current cloud platform is blocked or renamed). Optional
"measure": recall the data according to the measuring point (if names =[], that is, if no measuring point name is specified, all measuring point data on the equipment will be recalled)
"group": recall data according to the measuring point (this mode data is uploaded through the group data Message Channel)
When recall_type is "measure:
None or [], which means to obtain all measuring point data under all controllers
[{"name": "controller1", "measures": []}], representing the acquisition of all measurement point data under the controller (controller1)
[{"name": "controller1", "measures": ["measure1", "measure2"]}], representing the data of "measure1" and "measure2" under the controller (controller1)
when recall_type is "group:
["group1", "group2"], which means to obtain the data of groups "group1" and "group2"
timeout: recall timeout of the measurement point response. The default value is 10 seconds.
realTime: Whether to read real-time data. If it is set to True, the measuring point of recall will be re-read immediately and the newly read value will be returned. The default value is False, valid only when recall_type = "measure"
fromcommon.Loggerimportloggerfromquickfaas.measureimportrecalldefaction_name():# Recall all measurement point data under all controllerslogger.debug('recall all plc measures: %s'%recall())# Recall all measurement point data under controller (controller1)logger.debug('recall controller1 plc measures: %s'%recall([{"name":"controller1","measures":[]}]))# Recall the data of the measurement points "measure1" and "measure2" under the controller (controller1)logger.debug('recall controller1 plc measures: %s'%recall([{"name":"controller1","measures":["measure1","measure2"]}]))# Recall data from groups "group1" and "group2"recall(["group1","group2"],"group")
"measure": recall the data according to the measuring point (if names =[], that is, if no measuring point name is specified, all measuring point data on the equipment will be recalled)
"group": recall data according to the measuring point (this mode data is uploaded through the group data Message Channel)
when recall_type is "measure:
None or [], which means to obtain all measuring point data under all controllers
[{"name": "controller1", "measures": []}], representing the acquisition of all measurement point data under the controller (controller1)
[{"name": "controller1", "measures": ["measure1", "measure2"]}], representing the data of "measure1" and "measure2" under the controller (controller1)
when recall_type is "group:
["group1", "group2"], which means to obtain the data of groups "group1" and "group2"
callback: the callback function executed when data is recalled. To be compatible with DS1.0, the callback function also supports three parameters
userdata: parameters passed to the callback function
timeout: recall timeout of the measurement point response. The default value is 10 seconds.
realTime: Whether to read real-time data. If it is set to True, the measuring point of recall will be re-read immediately and the newly read value will be returned. The default value is False, valid only when recall_type = "measure"
fromcommon.Loggerimportloggerfromquickfaas.measureimportrecall2defrecall2_callback(message,userdata):logger.debug("recall2 response message: %s, userdata:%s"%(message,userdata))defrecall2_callback2(message,userdata,wizard_api):logger.debug("recall2 response message: %s, userdata:%s"%(message,userdata))defaction_name():# Recall all measurement point data under all controllersrecall2(callback=recall2_callback,userdata="")# Recall all measurement point data under controller (controller1)recall2(names=[{"name":"controller1","measures":[]}],callback=recall2_callback,userdata="")# Recall the data of the measurement points "measure1" and "measure2" under the controller (controller1)recall2(names=[{"name":"controller1","measures":["measure1","measure2"]}],callback=recall2_callback2,userdata="")# Recall data from groups "group1" and "group2"recall2(["group1","group2"],"group")
fromcommon.Loggerimportloggerfromquickfaas.global_dictimportget_global_parameterdefaction_name():logger.debug('get global dict: %s'%get_global_parameter())
mode:mode determines the mode in which the file is opened: Read-only, write, append, etc. See the full list below for all possible values. This parameter is not mandatory, and the default file access mode is read-only (r). Same as the mode parameter in the open function interface in python
encode: The encoding format is the same as the encoding parameter in the open function interface in python. The default value is utf-8
size: The length of bytes read. If size is not specified, the entire file is returned, which is consistent with the size parameter in the read function interface in python.
## Enter your python code.importjsonfromcommon.Loggerimportloggerfromquickfaas.fileimportfaas_read_filedefmain(message):try:file_path="/var/user/app/device_supervisor/test.txt"data=faas_read_file(file_path,mode='r',encode='utf-8')ifdata:logger.info("data: %s"%data)exceptExceptionase:logger.error("Exception: %s"%(e))
Return data content:
The string of all the contents of the file; If there is an error, an exception will be thrown¶
mode:mode determines the mode in which the file is opened: Read-only, write, append, etc. See the full list below for all possible values. This parameter is not mandatory, and the default file access mode is write-only 'w '. Same as the mode parameter in the open function interface in python
data: the content (string) to be written to the file; The default is an empty string
encode: The encoding format is the same as the encoding parameter in the open function interface in python. The default value is utf-8
## Enter your python code.importjsonfromcommon.Loggerimportloggerfromquickfaas.fileimportfaas_write_file,faas_read_filedefmain(message):try:file_path="/var/user/app/device_supervisor/test.txt"faas_write_file(file_path,mode='w',data="test3",encode='utf-8')exceptExceptionase:logger.error("Exception: %s"%(e))
return data content: none; If an error occurs, an exception will be thrown.
## Enter your python code.importjsonfromcommon.Loggerimportloggerdefmain(message,wizard_api):# Get group configurationresponse=wizard_api.get_group()logger.debug("group config:%s"%response)
## Enter your python code.importjsonfromcommon.Loggerimportloggerdefmain(message,wizard_api):# Update group configuration informationgroup_data={"group_name":"group1","upload_interval":10}response=wizard_api.update_group(group_data)logger.debug("update group config response:%s"%response)
insert_data: Data to be inserted into the database
the format is::{"<timestamp>": {" controller1 ": {" measure1 ": [ \, \], "measure2": [ \, \] }}}
noack: whether a response is required; 0: A response is required, 1: no response is required
callback: callback function for returning data; It can be None to indicate that the returned data is not received (this parameter is meaningful only when noack is 0)
prototype::def insert_callback(message, userdata)
userdata: parameter of the callback function (this parameter is meaningful only when noack is 0)
importtimefromcommon.Loggerimportloggerfromquickfaas.LWTSDBimportinsert_requestdefinsert_callback(message,userdata):logger.debug("%s response message:%s"%(userdata,message))defaction_name():insert_data=[{str(int(time.time())):{"controller1":{"measure1":[1,100],"measure2":[1,"test"]}}}]# Insert a piece of data into the time series database without requiring a responseinsert_request('default',insert_data,1)# Insert a piece of data into the time series database and need a responseinsert_request('default',insert_data,0,callback=insert_callback,userdata="insert")
fromcommon.Loggerimportloggerfromquickfaas.LWTSDBimportquery_requestdefquery_callback(message,userdata):logger.debug("%s response message:%s"%(userdata,message))defaction_name():# Query all data in the default data tablequery_request('default',callback=query_callback,userdata="query")# Query the default data table data (data after '2023-01-09 12:00:00')query_request('default','2023-01-09 12:00:00',callback=query_callback,userdata="query")# Query the default data table data (the latest data after '2023-01-09 16:00:00')query_request('default','2022-12-09 16:00:00',limit=1,callback=query_callback,userdata="query")# Query the default data table data (data before '2023-01-09 16:00:00')query_request('default',end_time='2023-01-09 16:00:00',callback=query_callback,userdata="query")# Query the default data table data (the last data before '2023-01-09 16:00:00')query_request('default',end_time='2023-01-09 16:00:00',limit=1,callback=query_callback,userdata="query")# Query the default data table data (from '2023-01-09 12:00:00' to '2023-01-09 16:00:00')query_request('default','2023-01-09 12:00:00','2023-01-09 16:00:00',callback=query_callback,userdata="query")# Query the default data table data (from '2023-01-09 12:00:00' to '2023-01-09 16:00:00', and filter out the measurement points with the measurement point name "measure1")filter={"default":"accept_all","black_list":{"controller1":["measure1"]}}query_request('default','2023-01-09 12:00:00','2023-01-09 16:00:00',filter,callback=query_callback,userdata="query")# Query the default data table data (from '2023-01-09 12:00:00' to '2023-01-09 16:00:00', and only the measurement point named "measure1")filter={"default":"deny_all","white_list":{"controller1":["measure1"]}}query_request('default','2023-01-09 12:00:00','2023-01-09 16:00:00',filter,callback=query_callback,userdata="query")
start_time: The start time of the time series data; When start_time is None, it indicates that TIMESTAMP < end_time
end_time: the deadline of the time series data; When end_time is None, TIMESTAMP > start_time
noack: whether a response is required; 0: A response is required, 1: no response is required
callback: callback function for returning data; It can be None to indicate that the returned data is not received (this parameter is meaningful only when noack is 0)
prototype: def remove_callback(message, userdata)
userdata: parameter of the callback function (this parameter is meaningful only when noack is 0)
timeout: Request timeout (default 30 seconds)
Note: When start_time and end_time are both None, the entire data table is cleared.
fromcommon.Loggerimportloggerfromquickfaas.LWTSDBimportremove_requestdefremove_callback(message,userdata):logger.debug("%s response message:%s"%(userdata,message))defaction_name():# Clear the time series database data and require a responseremove_request('default',callback=remove_callback,userdata="remove")# Clear the time series database data, no response requiredremove_request('default',noack=1)# Delete the time series database data (from '2023-01-09 12:00:00' to '2023-01-09 16:00:00') and require a responseremove_request('default','2023-01-09 12:00:00','2022-12-09 16:00:00',0,callback=remove_callback,userdata="remove")# Delete the time series database data (delete the data after '2023-01-09 16:00:00'), and a response is requiredremove_request('default','2023-01-09 16:00:00',callback=remove_callback,userdata="remove")# Delete the time series database data (delete the data before '2023-01-09 16:00:00'), and a response is requiredremove_request('default',end_time='2023-01-09 16:00:00',callback=remove_callback,userdata="remove")
cloud_name: name of the cloud service that is successfully connected
nbirth_pub_metrics: The custom metric to be published. The format must be as follows: {"Cloud service name": {"metric name": {"value": "specific value or None", "dataType": "metric data type" }}}
pub_metrics: the metrics to be published in the NDATA message. The format must be as follows [{"name": "metric name","value": None or the actual value to be uploaded}]. ( No "value" field is equivalent to "value": None )
cloud_name: name of the cloud service that publishes the NDATA message
1.13.2 Subscribe to NCMD message: node_cmd_handler¶
this topic describes the important topics and payloads of the message bus inside the gateway. By reading this section, you can learn how to use specific topics and payloads to realize data transmission and processing, which will help you use the Gateway function more flexibly.
create and add a controller and measuring point in measuring point monitoring. As shown in the figure:
after adding the controller and measuring point, enter the background of EC equipment and install mosquitto in the background. Execute the command as shown:
after installation, execute the command shown in the figure to subscribe to the point message published by the driver with driverServiceId 2000:
create a controller and measuring point in the measuring point monitoring, as shown in the figure:
after entering the background of IG Series equipment and executing the following command, you can subscribe to the measuring point message published by the driver with driverServiceId of 2000
{driverServiceId}: the ServiceId of the current driver. You can view the ServiceId of the current driver in logs.
The following figure shows how the enabled ModbusDriver can view the ServiceId (note: ModbusDriver is not fixed or 2000, and the ServiceId varies according to the order in which the controller is enabled. The actual driverServiceId is based on the ServiceId displayed in the log):
controller data: controller[0] represents the controller name, controller[1] represents the controller health status, and controller[2] represents the collection timestamp
measure data: key represents the name of the measuring point, measure[0] represents the health status of the measuring point, and measure[1] represents the value of the measuring point.
2.2.3 Write the measuring point value to the driver¶
{"name":"alarm1","ctrlName":"","measureName":"","priority":1,"timestamp":1234646484,"timestampMsec":1582771955000,"status":0,"value":60,"alarm_value":60,"content":"DATA IS OUT OF RANGE"}
name: alarm name
ctrlName: Controller name
measureName: measuring point name
priority: Built-in alarm level, which can support the definition of 5 level value ranges [1,5]
timestamp: second-level timestamp
timestampMsec: millisecond timestamp
status:0: dismiss alarm 1: trigger alarm
value: current measuring point value
alarm_value: the value of the measuring point when the alarm is triggered
task_id: The task ID. Only "recallType" = = "measure" is valid.
recallType: Support group, measure
when "recallType" = = "group", the measuring point data is uploaded through ds2/eventbus/north/measures/{groupName}. For details, see Measuring Point Grouping Report.
When "recallType" = = "measure", the measuring point data is uploaded through ds2/eventbus/north/recall/measures/response, at this time, the last polling point value will be obtained. , the content is as follows: if controllers = = [], the name of the measuring point is not specified
When "recallType" = = "realtime", the measuring point data is uploaded through ds2/eventbus/north/recall/measures/response, at this time, all called measuring points will be polled in real time. , the content is as follows: if controllers = = [], the name of the measuring point is not specified
groups: A list of measuring point groups. Only "recallType" = = "group" is valid.
controllers: a list of controllers. Only "recallType" = = "measure" is valid. The total number of measuring points needs to be limited, and the specific value is to be determined.
the historical database is a lightweight time series database on the edge computing gateway of the Yinghantong series. It contains the following functions:
DSA can create data tables for measuring point grouping and store the grouped data in the database according to the specified saving strategy; (via Web configuration)
fast functions or other data analysis programs that can query/insert/delete historical data through the MQTT message bus inside the gateway.
: the name of the data table of the operation (that is, the name of the grouping);
\: the ID of the database client, which is used to distinguish different clients. Each client should only subscribe to database messages with its own ID.
\The suggested formatext-<MAC>-<pid>
\: The database operation ID, which is used to distinguish a request operation and is generated by the client. We recommend that you use UUID.
noack:0 means that a response is required; 1 means that no response is required (when there is no noack field in the request payload, the default is 0)
data: data to be inserted. Multiple inserts are supported.
Parameters
description
timestamp
timestamp (in seconds) when the data was inserted
controller1
controller Name
measure1
name of measuring point
measure1_health
health status of measuring points (0: offline, 1 online)
INTEGER: The start time of the time series data, in seconds, including start_time.
When the start_time field is negative or does not exist, it indicates TIMESTAMP < end_time, which is sorted in descending order by default.
1669696164
end_time
INTEGER
deadline time of time series data, in seconds, excluding end_time.
When the end_time field is negative or does not exist, TIMESTAMP >= start_time, which is in ascending order by default
1669697264
filter.default
ENUM
"accept_all": returns all measuring points by default, except those in the blacklist; "deny_all": By default, all measuring points are no return , except for the measuring points in the white list;
if you need to read a specified number of data records in LwTSDB, you can use the Limit method of LwTSDB, which accepts a numeric parameter that specifies the number of records to read from LwTSDB. If you don't specify the parameter in the limit method (or limit is 0), all the data in the collection is displayed.
LwTSDB itself limits the maximum number of reads to xxxx. When the number of prediction queries exceeds the limit, we recommend that the query application query by time period.
limit:100
offset
INTEGER
can be used offset method to skip a specified amount of data, offset method also accepts a numeric argument as the number of records skipped. offset usually used in combination with limit.
offset: 10
note: When start_time and end_time are both negative, the entire data table is queried.
login name and password need to be base64 encrypted and placed in http header; For example, login name: adm and Password: 123456 need to be spliced into "adm:123456" string for base64 encryption to obtain "YWRtOjEyMzQ1Ng = ="
note: web_session is the token information after authentication. This information must be included in the request header for subsequent interface requests.
GET /v1/apps/device/supervisor2/north/basic/status?service=modbustcp-slave
request header: Authorization: Bearer
request URL parameter description:
parameter Name
description
service
the protocol conversion type. modbustcp-slave:Modbus TCP Server iec104-server:IEC 104 Server opcua-server:OPCUA Server modbusrtu-slave:Modbus RTU Server iec101-server:IEC 101 Server sl651-client:SL651-2014 hj212-client:HJ212 Client bacnetbip-server:BACnet IP Server bacnetmstp-server:BACnet MS/TP Server dnp3-server:DNP3 Outstation iec61850Server:IEC 61850 Server snmp_agent:SNMP Agent