Display Cloud Monitor alert history in IoT Studio

Updated at:
Copy as MD

When you develop an O&M screen in IoT Studio, you can display the alert history for your devices. This enables O&M engineers to monitor device status and quickly troubleshoot issues. This topic describes how to use the business logic and web application development features of IoT Studio to display device alert history.

Scenario

This topic uses a blower as an example. It demonstrates how to create a threshold alert rule in IoT Platform for the blower's inlet and outlet temperatures. For example, an alert is triggered if the outlet temperature exceeds the upper limit or the inlet temperature falls below the lower limit. You will then develop a service in IoT Studio to retrieve the alert history from Cloud Monitor and display it in a web application.

image

Prerequisites

A device is connected to IoT Platform and reports thing model property data.

This topic uses a blower as an example to explain how to display alerts for abnormal values of the inlet temperature (inlet_temperature) and outlet temperature (outlet_temperature) properties. For details, see the following topics:

  1. Purchase an Enterprise Edition instance: The IoT Studio service and the feature for creating a threshold alert rule for a thing model metric are available only for an Enterprise Edition instance in the China (Shanghai) region. This example uses an Enterprise Edition instance in the China (Shanghai) region.

  2. Log on to the IoT Platform console. In the upper-left corner, select the Enterprise Edition instance.

  3. Create an IoT Studio project.

  4. Create a product in the project: Blower.

  5. Add a thing model for the product: inlet temperature (inlet_temperature) and outlet temperature (outlet_temperature).

  6. Create a device under the product: device_demo01.

  7. Connect by using a device SDK: Develop the device to connect to IoT Platform and report thing model data.

Step 1: Create alert rules

This section describes how to create a threshold alert rule for a thing model property metric.

  1. Log on to the IoT Platform console. In the upper-left corner of the console, select your instance's region.

  2. On the Instance Overview page, find your target IoT Platform instance and click the instance card.

  3. In the left-side navigation pane, choose Monitoring and O&M > Real-Time Monitoring.

  4. On the Real-Time Monitoring page, click the Alert Rules tab.

  5. Click Create Alert Rule.

  6. In the right-side panel, configure the alert rule and click Next.

    Configure an alert rule named Outlet Temperature Exceeds Upper Limit. For more information about the parameters, see Configure a threshold alert rule.

    Example configuration: For Metric, select Thing model property metric. For Metric Dimension, select Blower > Default Module > Outlet Temperature, and then select the target device. For Statistical Field, select Latest Value. Set Operator to > and Threshold to 160. Set Duration to 1 and Data Aggregation Period to 1 minute.

  7. Configure the effective period, mute period, notification target, and alert level, and then click Confirm.

    For example, set Effective Period from 00:00 to 23:59, set Mute For to 30 minutes, set Notification Target to alert contact, and set Alert Level to Phone + SMS + Email + DingTalk Bot (Critical).

  8. Repeat the preceding steps to create an alert rule named Inlet Temperature Is Too Low.

    Set Metric to Thing model property metric. For Metric Dimension, select Blower > Default Module > Inlet Temperature. For Device, select device_demo01. For Statistical Field, select Latest Value. Set Operator to < and Threshold to 60. Set Duration to 1 and Data Aggregation Period to 1 minute.

Step 2: Develop an alert history service

  1. In the IoT Platform console, choose Project Management from the left-side navigation pane.

  2. Click the card of your target project.

  3. On the project's Home page, under Project Development, click the Business Logic tab.

  4. Above the application list, click New > New Blank Business Service.

  5. In the New Business Logic dialog box, enter a name for the business logic, such as Get Cloud Monitor alert history, and a description. Then, click Confirm.

    For more information about the parameters, see Business logic editor.

  6. In the business logic editor, configure the nodes.

    1. In the left-side pane, click the Node image.png icon and drag an HTTP Request node onto the canvas.

      This example uses the default configuration for the HTTP Request node. For more information about how to configure this node, see HTTP Request.

    2. Drag a Node.js script node onto the canvas, connect the HTTP Request node to it, and then configure the Node.js script node.

      1. In the Node.js script node configuration panel, click Extension Library Management. In the dialog box that appears, search for the @alicloud/pop-core package and click Install in the Action column.

      2. After the installation is complete, return to the node configuration panel. For Script, select Blank Template, and then copy the following sample code into the code editor.

        This sample code calls the Cloud Monitor API DescribeAlertLogList to query the alert history. This example displays the RuleName (alert rule name) and AlertTime (timestamp when the alert occurred) from the API response. You can modify the code to display other fields returned by the DescribeAlertLogList API based on your business requirements.

        Replace parameters such as accessKeyId and accessKeySecret with your actual values. For more information about how to use the SDK for Cloud Monitor APIs, see SDK reference and Python SDK call example.

        /**
        * @param {Object} payload The output of the previous node.
        * @param {Object} node The output of a specified node.
        * @param {Object} query The output of the first node in the service flow.
        * @param {Object} context  { appKey, appSecret }.
        * @param {Object} global Global variables.
        */
        module.exports = async function(payload, node, query, context, global) {
          const Core = require('@alicloud/pop-core');
          const moment = require('moment');
          var client = new Core({
            accessKeyId: '<YOUR-ACCESSKEY-ID>',
            accessKeySecret: '<YOUR-ACCESSKEY-SECRET>',
            // securityToken: '<YOUR-STS-TOKEN>', // Use an STS token.
            endpoint: 'https://metrics.cn-shanghai.aliyuncs.com',
            apiVersion: '2019-01-01'
          });
          var params = {
            // Query the 50 most recent data entries from the last 7 days. You can set the request parameters as needed.
            "StartTime": Date.now() - 7 * 24 * 60 * 60 * 1000,
            "EndTime": Date.now(),
            "PageSize": 50,
          };
          var requestOption = {
            method: 'POST',
            formatParams: false,
          };
          const data = await client.request('DescribeAlertLogList', params, requestOption);
          const { AlertLogList = [] } = data;
          const result = AlertLogList.map(item => {
            return {
              // You can add other fields to be displayed here.
              alertName: item.RuleName,
              alertTime: moment(item.AlertTime).utcOffset(8).format('YYYY/MM/DD HH:mm:ss'),
            };
          });
          return {
            data: result,
          };
        }
    3. Drag an HTTP Response node onto the canvas and connect the Node.js script node to it. Set the node output to Previous Node (payload).

  7. Debug and publish the business logic service.

    1. On the business service editing page, click the Deploy and Debug image.png icon in the upper-right corner to deploy and debug the service.

      All nodes in the API orchestration workflow (HTTP Request → Node.js script → HTTP Response) run successfully. In the returned JSON data, the value of code is 200, and the data array contains alert records. Each record includes the alertName (such as "Inlet Temperature Is Too Low" or "Outlet Temperature Exceeds Upper Limit") and alertTime fields.

    2. After successful debugging, click the Publish image.png icon to publish the service.

      Important

      You must publish the business logic service to the cloud before you can call it.

Step 3: Display alert history in the web application

  1. On the project's Home page, under Project Development, click the Web App tab.

  2. Create a web application. For more information, see Create a web application.

  3. On the web application editing page, click the Component image.png icon in the left-side pane. From the component list, drag a Repeater component onto the canvas. For more information about how to configure the component, see Repeater.

  4. Click the Edit Data Source image.png icon to the right of Display Data. In the Data Source Configuration panel, set Select Data Source to API, set API Source to Business Logic, and set Select Business Service to the service you created: Get Cloud Monitor alert history. You can also enable scheduled refresh. For details, see API.

  5. Double-click the Repeater component to edit its child components.

    1. Delete the default components.

    2. Drag two Text components onto the canvas. For each component, set the data source for the text content to the corresponding field in the Parent Component Data Source. For more information, see Text.

      In this example, select alertName (alert rule name) and alertTime (time when the alert occurred). In the Field settings, bind the alertName and alertTime fields.

  6. Exit the Repeater's editing mode. Set Layout to Vertical, and then add Text components as column headers.

    You can also configure other component styles. For example, add a Rectangle component as a background or set up pagination for the Repeater. After configuration, the Repeater component displays two columns on the canvas: Time and Alert Information. In the style panel on the right, set Row Spacing to Small (12px) and Items per Column to Unlimited.

  7. On the top bar, click Save image.png, Preview image.png, and then Publish image.png.

    The published web application displays the alert history in two columns: Time and Alert Information. It records events such as Inlet Temperature Is Too Low and Outlet Temperature Exceeds Upper Limit and their occurrence times.

Next steps

After you publish the application, you can select the following options based on your needs: Bind Domain Name, Set a token to embed the application into other websites, and Modify devices bound to the published application.

Note If you bind a domain name and set a token for authentication, other users can access the published web application.