Python to chart.js

πŸ‘:0

I am sharing my example which I used using Google charts .I am fetching live data from OPC Server using ajax and updated my real-time graph. It won’t be a big difference if you use database instead of opc server. I hope you can relate it with your example.

Html

<div class="row" id="grap">
    <div class="col-lg-12">
        <div class="row">
            <div class="col-12">
                <div class="card">
                    <div class="chart-wrapper">
                      <div id="graph"></div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

This is django file from where I am passing data to gettemp() function via ajax call in json format. In your case it is database and there wont be issue.
Views.py

def plcdata(request):
    url="opc.tcp://127.0.0.1:9000"
    client=Client(url)
    client.connect()
    print("Client Connected")
    data={}
    dt=[]
    while True:
        pres=client.get_node("ns=2;i=2")
        Pressure=pres.get_value()
        adp=client.get_node("ns=2;i=3")
        ap=adp.get_value()
        rh=client.get_node("ns=2;i=4")
        r=rh.get_value()
        sp=client.get_node("ns=2;i=5")
        s=sp.get_value()
        nitro=client.get_node("ns=2;i=6")
        n=nitro.get_value()
        o2n=client.get_node("ns=2;i=7")
        o=o2n.get_value()
        hgl=client.get_node("ns=2;i=8")
        h=hgl.get_value()
        stempress=client.get_node("ns=2;i=9")
        sps=stempress.get_value()
        cond=client.get_node("ns=2;i=10")
        co=cond.get_value()
        dmwp=client.get_node("ns=2;i=11")
        dmp=dmwp.get_value()
        dmwf=client.get_node("ns=2;i=12")
        dmf=dmwf.get_value()
        chwp=client.get_node("ns=2;i=13")
        chp=chwp.get_value()
        chwt=client.get_node("ns=2;i=14")
        cht=chwt.get_value()
        icp=client.get_node("ns=2;i=16")
        ip=icp.get_value()
        icf=client.get_node("ns=2;i=15")
        iff=icf.get_value()
        ict=client.get_node("ns=2;i=17")
        it=ict.get_value()
        dcpp=client.get_node("ns=2;i=19")
        dpp=dcpp.get_value()
        dcff=client.get_node("ns=2;i=18")
        dff=dcff.get_value()
        dctt=client.get_node("ns=2;i=20")
        dtt=dctt.get_value()
        #Time=client.get_node("ns=2;i=3")
        #Ti=Time.get_value()
        #Ti1=datetime.time(Ti.hour,Ti.minute,Ti.second)

        ti=datetime.now()
        ti1=(str(ti.strftime('%Y-%m-%d %H:%M:%S')))
        dt.append(str(Pressure)+','+ti1+','+str(ap)+','+str(r)+','+str(s)+','+str(n)+','+str(o)+','+str(h)+','+str(sps)+','+str(co)+','+str(dmp)+','+str(dmf)+','+str(chp)+','+str(cht)+','+str(ip)+','+str(it)+','+str(iff)+','+str(dpp)+','+str(dtt)+','+str(dff))
        data['final']=dt
        return JsonResponse(data)

Please check the getTemp() function as data is recieved from django in the success function. This is the part where you will have to make changes as per your requirement.

JS

<script type="text/javascript">

google.charts.load('current', {
  callback: function () {
    var chart = new google.visualization.LineChart(document.getElementById('graph'));
    var options = {'title' : 'CTL-2 AIR PRESSURE (Bar)',    
    titleTextStyle: {
        fontName: "Arial", 
        fontSize: 18, 
    },
      animation: {
        duration: 1000,
        easing: 'out',
        startup: true
      },
      hAxis: {
        title: 'Time',
        format: "HH:mm:ss",

        textStyle: {
          fontSize : 14,
          bold:'true',
        },
      },
      vAxis: {
        title: 'Air Pressure',
        format: '0.00',
        textStyle: {
          fontSize : 14,
          bold:'true',
        },
      },
      height: 450,
      width:1000,
      legend:'bottom'
    };
    var data = new google.visualization.DataTable();
    data.addColumn('datetime', 'Time');
    data.addColumn('number', 'Air Pressure');

    var go=[];
    function getTemp() {

          $.ajax({
        type:"get",
        url:"{% url 'plcdata' %}",
        success:function(dat){
            for(i=0;i<dat.final.length;i++){
                var go=dat.final[i].split(',');
                var tm = new Date();
                if(data.hg.length>15){
                  data.removeRow(0);
                }                 
                data.addRow([tm, Number(go[0])]);
                chart.draw(data, options);

            }
            return dat;
        },
        error: function(){
            console.log("Error Occurred");
        }
    })
    }

    getTemp();
    setInterval(getTemp, 3000);

  },
  packages:['corechart']
});
</script>


  [1]: https://i.stack.imgur.com/bMWVB.png

Leave a comment