Using Highcharts to realize real-time data presentation

Source: Internet
Author: User
Tags netbeans
In the field of industrial control system, the data of temperature, pressure and torque are collected in real time, which is of great guiding value for the monitor personnel to carry on the scene situation perception and forecast the future trend. Engineering control Staff If only read a large number of data reports, the overall situation in the field control will be very difficult, so often want to use some charts to show, which trend chart is commonly used in real-time data display one way. At present, the implementation of trend map, graph tools are very mature, some are developed through the CS model, the need for engineering control personnel to operate the computer installation of the corresponding software, this way has its unique advantages, but sometimes there are inconvenient places. So some of the mode of presentation based on BS is naturally widely used. The use of BS mode of display engineering control personnel can connect to a Web server through any PC, through the common browser can be real-time view of the current environment of the various indicators of the parameters, the convenience is obvious. Below I will introduce this BS mode of real-time data display graph method. As the purpose of this article is not to implement a field environment available application products, so just for the technology involved to explain, play a guiding role, so the reference to the actual needs of their own project to the code involved in the optimization of the use of this article.
Through the BS system to achieve the trend chart, the graph of the choice of many, this article mainly through the highcharts.com's Highcharts API package to achieve. Since this package is implemented through a JS script, the individual thinks it might be better to adapt to the surface, but it can also be done through tools such as Jfreechart.
So, let's talk about how you can use the Highcharts API to make the trend chart appear on the page.
First we need to simply plan the architecture of our system. Because of the trend graph rendering of real-time data, the system can be roughly designed into three layers: display layer, logic layer, data source. As shown in the following illustration:

Display layer is the data presented to the project control personnel of the display page, this layer mainly by JSP, JS, CSS and other documents, engineering control personnel through the browser (such as IE, Firefox, etc.) can directly see the hope of the graph. The display layer is only responsible for display, and the data displayed needs to be cleaned and normalized, the display layer gets the data that conforms to the normalization requirements, it can be displayed directly and responds to the interaction with the person. The data cleaning and normalization are realized in the logic layer, and the logical layer makes the necessary data logic conversion, data cleaning and data normalization processing through obtaining the data source information. Data source is a complex and important, it can be directly from the lower computer data communication, can also be the next computer to store data in the intermediate database, can also be a series of data files.
In this article, the data source is only simulated and not read by the data source. and corresponding to the logical layer of processing, also ignored, this part of the content because of the specific data acquisition, cleaning, conversion, normalization, and specific project requirements have a greater relationship, and also is not the center of this paper planning, so this part of the code design implementation of this article is not involved.
The implementation of the display layer involves JSON, JQuery, Highcharts, we first set up a standard Web application (in fact, if we use an HTML file for example), I plan to extend this case later to implement some functions such as logic layer, So set up a Web application engineering, a little superfluous, but also please forgive me. I am using the NetBeans IDE Version 7.2 development (how to use the NetBeans IDE to develop Web applications please refer to my other articles), so after the establishment of the completion of the project structure is as follows:

To use highcharts, we need to import the Highcharts.js file. Highcharts.js files can be obtained from the Highcharts official website (official address: http://www.highcharts.com/), Downloaded from the official website of the compressed file contains our development needs of the Highcharts.js file, but also contains a number of other documents, such as example files.
Highcharts is implemented using JS, and applies to the jquery technology, so you need to get the latest version of the jquery package (website address: http://jquery.com/).
The above two pieces are ready, we will add it to the new project, in the project document we plan a place all JS files, have a JS directory, will highcharts.js, jquery-1.8.3.min.js files are placed to this directory. You see my project in the JS directory under a modules subdirectory, this subdirectory placed under the Exporting.js file is optional, if you want to use the chart export functions such as the need to use this file, so you need to import the project, otherwise you can not need.
The engineering environment is ready, we can open the project's default, but also the only one JSP page, make a write modification to this page. There are several major modifications:
First, in the JSP page header introduction highcharts.js, Jquery-1.8.3.min.js file, the application code reference is as follows:

<script type= "Text/javascript" src= "Http://zhaowenbinmail.blog.163.com/blog/js/jquery-1.8.3.min.js" ></ Script>

<script src= "Http://zhaowenbinmail.blog.163.com/blog/js/highcharts.js" ></script> second, Add a DIV element to the body of the JSP page, and Highcharts will draw the graph in this div element.

<div id= "Container" style= "min-width:100px; height:400px; margin:0 Auto "></div> Note: We have given this div an ID value that will be useful to us in the future, and it is the source of the Highcharts knowing where to draw the chart.
Third, we need to add our own JS file in the JSP page. This file is used to implement specific business rendering logic.

<script type= "Text/javascript" src= "Http://zhaowenbinmail.blog.163.com/blog/js/chart.js" ></script>
Now let me explain the general requirements of the business I need to achieve. I need to show on the page the temperature change of the bridge surface 24 hours a day (of course these temperature changes are generated by random numbers in this case). In our very axis direction we need to show the timescale from 0 o'clock to 23 o'clock in the evening, it also requires a fixed display of 0 to 23 of these 24 scales, showing the maximum temperature within this hour detected by the deck sensor in the longitudinal direction, and then simulating the time lapse to show the temperature curve per hour.
Based on the above requirements analysis, in the page rendering, we have to read this day from 0 o'clock to the current moment of data, and the data is plotted as graphs. So we're going to edit our own JS file--chart.js next. Create the Highcharts object in this file to influence the graph rendering to meet our requirements by setting the related properties.
We first define a global chart object, we name it chart, and sample the Highcharts object, as shown in the following code:

var chart;

$ (function () {$ (document). Ready (function () {chart = new Highcharts.chart ({chart: {renderto: ' container ', type: ' Li Ne ', marginright:130, marginbottom:80, events: {Load:loadtime}}, Title: {text: ' Bridge acquisition Data ', X: -20}, subtitle: {text: ' Sensor number: Sensor 1 ', x: -20}, Xaxis: {title: {enabled:true, Text: ' Time (Hours) '}, Max:23, min:0, tickpixelinterval:50}, YAxis: {title: {text: ' Pressure (℃) '}, plotlines: [{value:0, width:1, color: ' #808080 '}]}, tooltip: {formatter:function () { Return ' <b> ' + this.series.name + ' </b><br/> ' + this.x + ': ' + this.y + ' ℃ '; }, Legend: {x: -50, Y:10, enabled:true}, exporting: {Enabled:false}, Plotoptions: {line: {gapsize:100}}, Ser IES: [{name: ' Max ', Data:getfirstdata ()}]}; }); }); In the code above we instantiate a Highcharts object and specify some properties for this object. In the definition we can see the following code:

     Chart: {
                renderto: ' Container ',
                type: ' line ',
                marginright:130,
                marginbottom:80,
                events: {
                    Load:loadtime
                }
            }
In this code you know the div element that the chart needs to draw, and look at the Red font section above. The container of this place is the ID value of the div on the JSP page (you can go back and check the code in front of me).
The type of the chart is then specified (see the Blue Font section in the code above). The line type specified here, which is plotted as a curve.
The diagram's events are also specified in the code, and only one load event is currently specified, and the function that executes the load time is called when the chart is mounted. The loadtime behind the code is a JS function I wrote, which is described later in this function.
By title, subtitle to specify the caption of the chart, subheadings, see the following code:
     Title: {
                text: ' Bridge acquisition Data ',
                x: -20 
            },
            subtitle: {
                text: ' Sensor number: Sensor 1 ',
                x: -20
            },
By changing the settings here can affect the effect of the display on the chart, the display effect below the red box to select some of the contents.

Through Xaxis, YAxis set the horizontal axis, ordinate the properties of the chart.
      Xaxis: {
                title: {
                    enabled:true,
                    text: ' Time (Hours) '
                },
                max:23,
                min:0,
                tickpixelinterval:50
            },
            YAxis: {
                title: {
                    text: ' Pressure (℃) '
                },
                plotlines: [{
                    value:0,
                    width:1,
                    Color: ' #808080 '
                }]
            },
By setting the Title property in Xaxis and YAxis, the text description on the horizontal axis and the ordinate is displayed.
Sometimes in the horizontal axis we need to specify the text to be displayed for each coordinate point in the coordinates, and then we need to use a Categories property to pass an array value to the Categories property, In this way, each coordinate point on the horizontal axis displays the coordinate point information according to the specified property content. To achieve this, we need to set a variable and assign the variable to the Categories property. For details, see below:
var x_arr=[' 0:00 ', ' 1:00 ', ' 2:00 ', ' 3:00 ', ' 4:00 ', ' 5:00 ',
' 6:00 ', ' 7:00 ', ' 8:00 ', ' 9:00 ', ' 10:00 ', ' 11:00 ', '
12: ', ' 13:00 ', ' 14:00 ', ' 15:00 ', ' 16:00 ', ' 17:00 ',
' 18:00 ', ' 19:00 ', ' 20:00 ', ' 21:00 ', ' 22:00 ', ' 23:00 '];

By using the code snippet above, we define a variable and then see how to assign it to the Chart object, and notice that the Red department in the following code is the place to add to the previous code end:

Xaxis: {title: {enabled:true, Text: ' Time (Hours) '}, Categories:x_arr, max:23, min:0, tickpixelinterval:50}, now the chart displayed on the page is as follows As shown in the figure:

The horizontal axis is shown in terms of what we set in the X_arr variable. If the content is less than the coordinate point of the horizontal axis, the preceding coordinates will be displayed in the X_arr variable, and the following coordinate points are displayed in the default coordinate point information.
Engineering control staff through this curve can know the highest temperature at each point in time, but the specific point of temperature is how much, engineers hope that by pointing the mouse point to the collection point in the chart can be displayed. To implement this feature, we need to specify the ToolTip attribute in the chart object, as shown in the following code:

ToolTip: {formatter:function () {return ' <b> ' + this.series.name + ' </b><br/> ' + this.x + ': ' + this.y + ' ℃ '; }, configure this property to get the effect shown in the following illustration:

When the mouse is moved to the collection point at 10, the temperature is immediately displayed on the screen.
For some applications, we in a chart will show multiple lines to represent different meanings, then need to use the legend to explain what color lines represent what the meaning of the case, you need to enable the legend description, to enable the legend description must be configured through the following properties:

    Egend: {
                x: -50,
                y:10,
                enabled:true
            },

You can simply make the Enabled property in the Egend object set to True. Set to False, the legend is not displayed.
It describes the basic property settings of the legend, now we need to simulate some of the bridge sensors to obtain the data, based on these data to display graphs. Here we first have to define two JS functions, these three functions is to simulate the acquisition of data, please see below:

function Loadtime () {window.settimeout (getdata,timeout);} This function is the one specified by the Load event in the events that we set up in the Chart object. In this function, the main start of a timer, after more than the specified time count seconds, will call the function GetData.

function Getfirstdata () {var data = []; var y_mx=math.round (Math.random () *10); var i; for (i = 0; I <= 0; i++) {DATA.P Ush ({x:current_time, y:y_mx}); if (current_time<=23) {current_time++}}} return data; This function is used to simulate the value of the bridge deck temperature when initializing the chart object. It returns an Array object with each object in the array containing the X, Y properties, which are used to tell the chart the Y-value of one of the coordinates on the x-axis of the object, and where a coordinate point is displayed, and a curve is formed between adjacent two coordinate points. The Current_time in the code is a global variable used to count the number of current collection displays.

function GetData () {
    var current_x=x_arr[current_time];
    
    Get maximum value
    var series_mx = chart.series[0];
    var y_mx=math.round (Math.random () *10);
    
    Series_mx.addpoint ([Current_time, Y_mx], true, false);
    
    current_time++;
    
    if (current_time<=23) {
        window.settimeout (getdata,timeout);
    }
}

The other parts of this function are simple, and one key focus code is

Series_mx.addpoint ([Current_time, Y_mx], true, false);
In this section, this code adds a new coordinate point to the chart chart.
Up to now, all the code has been written to complete, now run it, you can simulate the bridge deck stability 24-hour detection of real-time trend chart.

In fact, the use of highcharts to do real-time trend map simple processing is relatively simple, more applications can also be extended in these basic applications.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.