Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
Huawei Cloud Astro Canvas
Huawei Cloud Astro Zero
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive

Using WebSocket to Bind Data to Advanced Page Widgets

Updated on 2025-03-24 GMT+08:00

Scenario

When you develop advance pages, use WebSocket to implement backend data calling to obtain proactive message push and high real-time data display. During daily operation, the campus system often detects personnel exceptions or faults and displays them as alarms on the frontend page. To simplify test cases, enter message data to simulate alarm data collection in the background, trigger alarm events through flow, and push alarm information to the frontend advance page through WebSocket.
Figure 1 WebSocket calling example

WebSocket is a network transmission protocol provided by HTML5. WebSocket allows web browsers to create a long-term connection between the client and the server and implement bidirectional data transmission. That is, the server can push data to the client, and the client can also send information to the server, which is one of the push technologies of the server.

You can trigger a message event to send background messages as JSON objects through the WebScoket server of the platform. All foreground WebScoket clients that subscribe to the event can receive the message data. The WebScoket client subscription service address is as follows:

wss://${location.host}/websocket/v1.0/component/listener?tenantId=${tenantId}&event=${eventName1}&event=${eventName2}
Table 1 Parameters

Parameter

Description

tenantId

Tenant ID, which is automatically obtained from ${tenantId}. You can also log in to the environment configuration page, choose Setup > Company Information to obtain the tenant ID. For details, see Setting the Company Information of the Huawei Cloud Astro Zero Account.

event

Name of the event to be subscribed to. You can obtain the event name on the details page of the event to be subscribed to.

The event parameter can have multiple values. That is, the WebScoket client can subscribe to multiple events.

NOTE:

When you create a message event, you can subscribe to the event through flows, BPMs, external systems, or WebSocket. Message events are usually triggered through flows and data access.

When you develop frontend advance page widgets, create a WebSocket object. The url parameter indicates the address to be connected, that is, the client subscription address.

var ws= new WebSocket(url);

Instantiated objects can listen to the following events. For more WebSocket object properties and methods, see WebSocket.

Table 2 Listening events of WebSocket objects

Event

Description

ws.onopen

Triggered when a connection is set up.

ws.onmessage

Triggered when a client receives data from a server.

ws.onerror

Triggered when a communication error occurs.

ws.onclose

Triggered when a connection is closed.

Step 1 Creating WebSocketAlarmEvent

  1. Create an event.

    1. Log in to the application designer by referring to Logging In to the Application Designer.
    2. In the navigation pane, choose Data.
    3. Click next to Event. The page for adding an event is displayed.
    4. Select Create a New Event, set the label to WebSocketAlarmEvent, and click Add.

      Click the corresponding text box. The system automatically generates an event name based on the label. The actual event name created by the system is Namespace __WebSocketAlarmEvent __e.

      Figure 2 Adding WebSocketAlarmEvent

  2. On the event details page, click the custom parameters tab and click New.
  3. Set the label, name, and field type, and click Save to add the custom event parameter AlarmTitle.

    Figure 3 Adding custom event parameters

  4. Repeat operations in 3 to create the custom event parameters AlarmContent and AlarmDate.

    Table 3 Parameters for customizing an event

    Label

    Name

    Data Type

    AlarmContent

    Click the name text box. The system automatically generates a name based on the tag.

    Sting

    AlarmDate

    Click the name text box. The system automatically generates a name based on the tag.

    Date Time

  5. Activate an alarm event.

    1. On the event details page, click the Basic Information tab.
    2. Click Activate in the upper right corner of the page to activate the event.

      The Activate button changes to Deactivate, and the Is Active label changes to .

      Message event is valid in flows or WebSocket only after it has been activated. After an event is activated, it cannot be edited. To modify event parameters, click Deactivate under Basic Information to deactivate the event.

      Figure 4 Activating an alarm event

Step 2 Creating WebSocketAlarmFlow

Create a WebSocketAlarmFlow alarm flow to trigger an event, and configure global variables and system variables (date/time) in the flow to transfer parameters for the event.

If you want to quickly understand and verify WebSocket, use the message event test function for simple verification. You can skip this step, go to Step 3 Developing alarmDisplayWidget, and use method 1 (directly triggering event verification) in Method 1: Directly Triggering Event Verification to verify the effect.

  1. Create a flow.

    1. Log in to the application designer by referring to Logging In to the Application Designer.
    2. In the navigation pane, choose Logic.
    3. Click next to Flow to add a flow.
    4. Select Create a New Flow, set the label to WebSocketAlarmFlow, and click Add.

      Click the name text box. The system automatically generates a name based on the label.

      Figure 5 Creating WebSocketAlarmFlow

  2. Click Basic on the left of the canvas and drag the Send Event diagram element to the canvas.

    Figure 6 Dragging the Send Event diagram element to the canvas

  3. Add variables.

    1. Select the Send Event diagram element and click on the right of the canvas.
    2. Click Context. The context page is displayed.
    3. Click next to Variable and add the variables described in Table 4.
      Figure 7 Configuring context variables
      Table 4 Flow variables

      Name

      Data Type

      AlarmTitle

      Text

      AlarmContent

      Text

  4. In the Send Event diagram element, configure the event Namespace__WebSocketAlarmEvent__e created in 1 (replace it with the actual event name).

    Set input parameters by referring to the following figure, and use the global variables AlarmTitle and AlarmContent and the system variable $Flow.CurrentDateTime to transfer parameters for the event.
    Figure 8 Configuring the event diagram element

  5. Connect all diagram elements.

    Figure 9 Connecting diagram elements

  6. Select the Start diagram element, click , and configure input parameters for the flow, as shown in the following figure.

    The input parameters are dragged from variables in the context. There are two input parameters for alarm flow: AlarmTitle and AlarmContent.
    Figure 10 Configuring input parameters

  7. Click to save the flow.
  8. Click to activate the flow.

    Flow is valid only after it is activated. After a flow is activated, it cannot be edited. To modify diagram elements or parameters, click to disable the flow first.

Step 3 Developing alarmDisplayWidget

You can perform the following steps to develop the alarmDisplayWidget alarm display widget or click alarmDisplayWidget.zip to obtain the sample development package.

  1. Download the widget template widgetVue3Template.

    1. On the Huawei Cloud Astro Zero console, click Access Homepage to go to the application development page.
    2. In the upper left corner of the page, click and choose Environments > Environment Configuration.
    3. Choose Maintenance from the main menu.
    4. In the navigation pane, choose Global Elements > Page Assets > Widget Templates.
    5. Click the widget template widgetVue3Template. The template details page is displayed.
    6. Click Download, set the name to alarmDisplayWidget, and click Save.
      Figure 11 Setting the widget name

  2. Decompress the downloaded alarmDisplayWidget.zip, then set the variable var ws = new WebSocket(url); in alarmDisplayWidget.js to open a WebSocket and subscribe to WebSocketAlarmEvent.

    ws.onmessage is used to listen to WebSocketAlarmEvent alarm event messages, parse JSON data, and save the data to ListData. To facilitate widget observation, set an initial value for ListData. Replace the following code in the original code. Note that not all code is replaced.

    Vue.createApp({
        data() {
    	return {
               name: widgetProperties.parama || "Bingo Studio"
            }
        }
    }).mount($("#widgetVue3Template",elem)[0]);

    Change Namespace__WebSocketAlarmEvent__e to the name generated by the alarm event created in 1.

             var vm = Vue.createApp({
        data(){
            return {
                listData: [
                    {
                        "title": "device alarm",
                        "content": "Device A1 CPU usage is too high",
                        "date": "2020-12-09 09:15:09"
                    },
                    {
                    "title": "vehicle alarm",
                    "content": "Vehicle-XXXXXXX not registered",
                        "date": "2020-12-10 15:09:20"
                    }
                ],
                ws: null     
            }
    
        },
        mounted() {
            this.init();
        },
        methods: {
            init: function() {
                //Obtain the WebSocket subscription address.
                let urlMessage = "tenantId="+ $.cookie("tenant-id") + "&event=Namespace__WebSocketAlarmEvent__e";
                let url = `wss:///${location.host}/websocket/v1.0/component/listener?${urlMessage}`;
    
                //Open a WebSocket.
                this.ws = new WebSocket(url);
                //Trigger an event when a WebSocket connection is established.
                this.ws.onopen = event => {
                    this.ws.send("");
                    console.log("WebSocket has connected.");
                };
                //Trigger an event when a WebSocket connection is closed.
                this.ws.onclose = event => {                        
                    console.log("WebSocket has closed.");
    
                };
                //Trigger an event when a WebSocket communication error occurs.
                this.ws.onerror = event => {
                    console.log("WebSocket has error.");                        
                };
                //Trigger an event when the WebSocket client receives data from the server.
                this.ws.onmessage = event => {
                    if (event.data) {
                        let dataObj = JSON.parse(event.data);
                        if (dataObj.content) {
                            let data = JSON.parse(dataObj.content);   
                            if (data.payload) {
                                let content = JSON.parse(data.payload);    
                                this.listData.push( {
                                    "title": content.AlarmTitle,
                                    "content": content.AlarmContent,
                                    "date": content.AlarmDate,
                                });
                            }
                        }         
                    }                            
                };
                this.intervalID = setInterval(() => {
                    this.ws.send("");
                }, 50000);
            },                 
        },
        destroyed() {
            if (this.ws) {
                this.ws.close();
            }
        }
    }).mount($("#widgetVue3Template",elem)[0]);

  3. Set the rendering pages in alarmDisplayWidget.ftl, display the title, content, and date of the alarm information, and add dividing lines.

    <div id="widgetVue3Template" style="margin: 20px;">
        <div :data="listData"  class="seamless-warp">
            <ul class="item">
                <li v-for="item in listData">
                    <span class="alarmTitle" v-text="item.title" ></span> 
                    <span class="alarmContent" v-text="item.content"></span>
                    <span class="alarmDate" v-text="item.date"></span>
                    <br><br><hr size="1" noshade="noshade" style="border:1px #cccccc dotted;"/><br>
                </li>
            </ul>
        </div>
    </div>

  4. Define the styles alarmTitle, alarmContent, and alarmDate of title, content, and date in alarmDisplayWidget.css.

    #alarmDisplayWidget.seamless-warp ul li{
        list-style-type:none;
    }
        .alarmTitle {
            font-family:"Microsoft YaHei";
            font-size: 30px;
            font-weight:bold;
            padding: 0.5px 7px;
            margin:8px;
            border-radius: 5px;
            background-color:#FAC700;
            color:honeydew;
        }
        .alarmContent {
            font-family:"Microsoft YaHei";
            font-size: 30px;
            font-weight:bold;
            margin:5px;
        }
        .alarmDate {
            font-family:"Microsoft YaHei";
            font-size: 30px;
            margin:5px 35px;    }

  5. Define the initial width and height of the widget in the packageinfo.json file.

    {
        "widgetApi": [
            {
                "name": "alarmDisplayWidget"
            }
        ],
       "localFileBasePath": "",
        "width": "1000", 
    	"height": "600",
        "requires": [
            {
                "name": "global_Vue3",
                "version": "3.3.4"
            }
        ]
    }

  6. Repack alarmDisplayWidget.zip.

Step 4 Uploading alarmDisplayWidget and Creating an Advanced Page

  1. Upload the alarmDisplayWidget alarm display widget.

    1. Log in to the Huawei Cloud Astro Zero console, click Access Homepage to go to the application development page.
    2. Click in the upper left corner of the page and choose Environments > Environment Configuration.
    3. Choose Maintenance from the main menu.
    4. In the navigation pane, choose Global Elements > Page Assets > Widgets.
    5. Click Submit New Widget.
    6. Click Select Source File(.zip) to upload alarmDisplayWidget.zip. Enter the release notes alarmDisplayWidget and click Submit.

  2. Create a monitor advance page.

    1. Go to the application designer. In the navigation pane, choose Page.
    2. Click next to Advanced Page, set the page label and name to monitor, and click Add.
    3. In the upper left corner, click and drag alarmDisplayWidget from All > Custom to the canvas on the right.
      Figure 12 Dragging alarmDisplayWidget to the canvas
    4. Adjust the position and size of the widget and click to save the advanced page.
    5. Click , publish the advanced page, and click to view the widget display effect.

      After the configuration and development are complete, an alarm event is triggered to push the alarm message to the monitor advance page. In this example, an alarm event can be triggered in either of the following ways:

      • Method 1: Directly trigger event verification, which is used only for simple event commissioning. Before using this method, ensure that the WebSocketAlarmEvent event is activated and the monitor preview page is opened. For details, see Method 1: Directly Triggering Event Verification.
      • Method 2: Verify the event triggered by flow. Before using this method, ensure that the WebSocketAlarmEvent event is activated, the WebSocketAlarmFlow alarm flow is activated, and the monitor preview page is opened. For details, see Method 2: Verifying the Event Triggered by Flow.

Method 1: Directly Triggering Event Verification

  1. Choose Data > Event and activate WebSocketAlarmEvent.

    Figure 13 Opening Event

  2. In the Basic Information tab, click Send Event.
  3. In the displayed dialog box, set parameters. (AlarmDate automatically obtains the system date and time. You can also manually modify the parameters). Click Send.

    {
        "AlarmTitle": "device alarm",
        "AlarmContent":"An error occurred in the local database of device C1",    
        "AlarmDate":"2020-12-12 17:09:20"
    }

  4. Switch to the monitor preview page. The page has received and displayed the alarm message.

    Figure 14 Display effect

Method 2: Verifying the Event Triggered by Flow

  1. Choose Logic > Flow and activate WebSocketAlarmFlow.

    Figure 15 Accessing a flow

  2. Click to run the flow.
  3. On the displayed page, enter the values of AlarmTitle and AlarmContent, and click Run.

        "AlarmTitle": "device alarm",
        "AlarmContent":"An error occurred in the local database of device C1"

  4. Switch to the monitor preview page. The page has received and displayed the alarm message.

    Figure 16 Display effect

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback