Thursday, February 16, 2017

MIKROTIK API - Graph real-time interface traffic with Highcharts and PHP


MIKROTIK API - Graph real-time interface traffic with Highcharts and PHP


I'll teach you how to graph live a particular interface of your RouterOS. The example I put together this time with the fabulous, amazing graphics highcharts.com . (As requested by Cesar Maffini).
Update: a faithful reader named Alejandro Mogollon we made a video tutorial to prove that it is very easy to start up.
republished in English by Ambassador Ted Green
The code has 3 files:
1) api_mt_include2.php : RouterOS API. 
2) data.php : Connects to RouterOS, brings TX, RX and prints them in JSON format. 
3) index.html : Use Ajax to call data.php every 1 second and plot points in real time using highcharts.
Highchart_tech-nico.com_API_MIKROTIK
The code is very very easy. Let's summarize:
Index.html
1
2
3
4
5
6
7
Referring to Fig.
Referring to Fig.
10
eleven
12
13
  chart = new Highcharts.Chart({
      chart: {
       renderTo: 'container',
       animation: Highcharts.svg,
       type: 'spline',
       events: {
           load: function () {
               setInterval(function () {
                   requestDatta(document.getElementById("interface").value);
               }, 1000);
           }
   }
},
This is certainly the most important part of the code. In the line where the setInterval starts, what it does is to call the function requestDatta () and pass it as parameter the name of the network interface of our Mikrotik that we want to graph in real time, each 1 second. This works with any interface. Bridge, Vlan, pppoe, Wlan, etc. In this case, the parameter with the name of the interface that we are going to pass to the requestDatta function assigns it to an editable text field to make it a little more interesting.
1
2
3
4
5
6
7
Referring to Fig.
Referring to Fig.
10
eleven
12
13
14
fifteen
16
17
18
function requestDatta(interface) {
    $.ajax({
        url: 'data.php?interface='+interface,
        datatype: "json",
        success: function(data) {
            var midata = JSON.parse(data);
            if( midata.length > 0 ) {
                var TX=parseInt(midata[0].data);
                var RX=parseInt(midata[1].data);
                var x = (new Date()).getTime();
                shift=chart.series[0].data.length > 19;
                chart.series[0].addPoint([x, TX], true, shift);
                chart.series[1].addPoint([x, RX], true, shift);
                document.getElementById("trafico").innerHTML=TX + " / " + RX;
            }else{
                document.getElementById("trafico").innerHTML="- / -";
            }
        }
Here, as explained above, we have the function that connects to the RouterOS and brings us the TX / RX data of the interface that we ask. 
The data we bring from data.php is in JSON format, so we have to parse it to put each data in a variable and then plot the point in the Highchart. If they are fixed, it is very important to convert the value that comes in JSON to number "parseINT".
The line, shift = chart.series [0] .data.length> 19; We use it so that, every time we add a new point, keep an index with the number of points, which will tell the chart when you start treading the old values ​​of the series.
Here I hit the lines with comment:
1
2
3
4
5
6
var TX=parseInt(midata[0].data);   // UPLOAD
var RX=parseInt(midata[1].data);   // DOWNLOAD
var x = (new Date()).getTime();    // tooltip cuando hacemos hover en el punto
shift=chart.series[0].data.length > 19;  // indice de cantidad de puntos
chart.series[0].addPoint([x, TX], true, shift);  // agrego TX en SERIE 0
chart.series[1].addPoint([x, RX], true, shift);  // agrego RX en SERIE 1
We can add as many series as we want; Only that below we have to define them like this:
1
2
3
4
5
6
7
series: [{
    name: 'TX',
    data: []
}, {
    name: 'RX',
    data: []
}]
With this from above, we would have serie0 and serie1 (we always count from top to bottom). 
Note that "data" is empty, as we add points at runtime. 
If we think of graphing a third value alongside TX and RX we would define another series, like this:
Series: [{ 
name: 'TX', 
data: [] 
}, { 
name: 'RX', 
data: [] 
}, { 
name: 'RX', 
data: [] 
}]
Here we would have, serie0, serie1 and serie2. 
I hope you understand.
Data.php
This file as mentioned above is the one that connects to the routerOS and does its work. Edit the first lines with the data of your Mikrotik server.
We will use the command / interfaces / monitor-traffic 
This asks us for the name of the interface , which we already bring from the other file.
1
2
3
$API->write("/interface/monitor-traffic",false);
$API->write("=interface=".$interface,false);
$API->write("=once=",true);
This has already been explained in the previous posts, so I just want to detail that the last line says = once = for the trafic monitor, run the command 1 time and stop. If we do not put this command, it gets stuck, bringing and bringing the traffic in real time, but infinitely, with this we make sure we do it 1 time.
I hope they like it as much as I do. Investigate a little the nice graphics that has higcharts because they are fantastic and of course if they have modifications, improvements, etc. do not hesitate to pass an email that we post them !!
I'm thinking of using github for version control Eur-lex.europa.eu eur-lex.europa.eu
It was first written on Tech-nico.com by Nicolas Daistch

9 comments:

  1. Hello, its a great article, if you figured out made it possible. I tried this but unfortunately its not working may be i wrong somewhere. I have a doubt where i can define ros api user name and password, also the username and password field in data.php are written as $ipRouteros $Pass & $api_puerto=8728; Are they defined correctly?
    Any help
    Thanks

    ReplyDelete
    Replies
    1. I have the solution:

      email me at furqan.naveed@gmail.com

      Delete
    2. I have the solution:

      email me at furqan.naveed@gmail.com

      Delete
  2. This looks great... is there a current working version of this script?

    ReplyDelete
  3. Dear sir, i have try it. its not working .graph is blank.. if possible to make a vedio. and share me on my mail verma.bunty87@gmail.com

    ReplyDelete
    Replies
    1. I have the solution:

      email me at furqan.naveed@gmail.com

      Delete
  4. I have it working perfectly! great work on this! However is there a way to make it so it wont log in and out of the router for each time it updates? It is flooding my log files and not allowing me to be able to see any issues.

    ReplyDelete
  5. https://sarang.id/knowledgebase/2/Highchart-Live-Traffic-Interface-Mikrotik-PHP.html

    ReplyDelete