Using WebSocket to Bind Data to Advanced Page Widgets
Scenario

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}…
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. |
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.
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
- Create an event.
- Log in to the application designer by referring to Logging In to the Application Designer.
- In the navigation pane, choose Data.
- Click
next to Event. The page for adding an event is displayed.
- 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
- On the event details page, click the custom parameters tab and click New.
- Set the label, name, and field type, and click Save to add the custom event parameter AlarmTitle.
Figure 3 Adding custom event parameters
- 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
- Activate an alarm event.
- On the event details page, click the Basic Information tab.
- 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.
- Create a flow.
- Log in to the application designer by referring to Logging In to the Application Designer.
- In the navigation pane, choose Logic.
- Click
next to Flow to add a flow.
- 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
- 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
- Add variables.
- Select the Send Event diagram element and click
on the right of the canvas.
- Click Context. The context page is displayed.
- Click
next to Variable and add the variables described in Table 4.
Figure 7 Configuring context variables
- Select the Send Event diagram element and click
- 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
- Connect all diagram elements.
Figure 9 Connecting diagram elements
- 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 - Click
to save the flow.
- 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.
- Download the widget template widgetVue3Template.
- On the Huawei Cloud Astro Zero console, click Access Homepage to go to the application development page.
- In the upper left corner of the page, click
and choose Environments > Environment Configuration.
- Choose Maintenance from the main menu.
- In the navigation pane, choose Global Elements > Page Assets > Widget Templates.
- Click the widget template widgetVue3Template. The template details page is displayed.
- Click Download, set the name to alarmDisplayWidget, and click Save.
Figure 11 Setting the widget name
- 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]);
- 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>
- 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; }
- 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" } ] }
- Repack alarmDisplayWidget.zip.
Step 4 Uploading alarmDisplayWidget and Creating an Advanced Page
- Upload the alarmDisplayWidget alarm display widget.
- Log in to the Huawei Cloud Astro Zero console, click Access Homepage to go to the application development page.
- Click
in the upper left corner of the page and choose Environments > Environment Configuration.
- Choose Maintenance from the main menu.
- In the navigation pane, choose Global Elements > Page Assets > Widgets.
- Click Submit New Widget.
- Click Select Source File(.zip) to upload alarmDisplayWidget.zip. Enter the release notes alarmDisplayWidget and click Submit.
- Create a monitor advance page.
- Go to the application designer. In the navigation pane, choose Page.
- Click
next to Advanced Page, set the page label and name to monitor, and click Add.
- 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 - Adjust the position and size of the widget and click
to save the advanced page.
- 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
- Choose Data > Event and activate WebSocketAlarmEvent.
Figure 13 Opening Event
- In the Basic Information tab, click Send Event.
- 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" }
- 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
- Choose Logic > Flow and activate WebSocketAlarmFlow.
Figure 15 Accessing a flow
- Click
to run the flow.
- 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"
- Switch to the monitor preview page. The page has received and displayed the alarm message.
Figure 16 Display effect
Feedback
Was this page helpful?
Provide feedbackThank you very much for your feedback. We will continue working to improve the documentation.See the reply and handling status in My Cloud VOC.
For any further questions, feel free to contact us through the chatbot.
Chatbot