3

The values returned from rasp.py are : the first one is the data of my sensor connected to raspberry and the second one is the current time . These values have to be sent from my Django application views to my html file in order to show a curve but the result is a blank page .

rasp.py

#!/usr/bin/env python
from datetime import datetime, timedelta
futuredate = datetime.now() + timedelta(days=10)
def foo ( ) :
 i = 0 
 for i in range(0,19):
    i += 1
    tfile = open("/sys/bus/w1/devices/28-000007101990/w1_slave")
    text = tfile.read()
    tfile.close()
    secondline = text.split("\n")[1]
    temp = secondline.split(" ")[9]
    temperature  = float(temp[2:])
    temperature = temperature/1000
    mystr = str(temperature)
    y =  mystr.replace(",",".")
    x = datetime.now() + timedelta(days=10)
 return x,y 

views.py

from django.shortcuts import render
from rasp import foo
import json 
def index(request):
  return render(request, 'index.html', {'t' : foo()})

index.html the script is in the head of the html

{% load staticfiles %}
<!DOCTYPE HTML>
<html>
    <head>
       
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
                 <meta name="viewport" content="width=device-width, initial-scale=1.0">
           	<title>Temperature sensor graph</title>
                <!-- Core CSS - Include with every page -->
                <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet">
                
	
	

		<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
		<style type="text/css">
${demo.css}
		</style>
		<script type="text/javascript">
$(function () {
    $(document).ready(function () {
        Highcharts.setOptions({
            global: {
                useUTC: false
            }
        });

        $('#container').highcharts({
            chart: {
                type: 'spline',
                animation: Highcharts.svg, // don't animate in old IE
                marginRight: 10,
                events: {
                    load: function () {

                        // set up the updating of the chart each second
                        var series = this.series[0];
                        setInterval(function () {
                       
                            series.addPoint([{{ t }}], true, true);
                        }, 3000);
                    }
                }
            },
            title: {
                text: 'Live temperature sensor values'

            },
            xAxis: {
                type: 'datetime',
                tickPixelInterval: 150
            },
            yAxis: {
                title: {
                    text: 'Value'
                },
                plotLines: [{
                    value: 0,
                    width: 1,
                    color: '#808080'
                }]
            },
            tooltip: {
                formatter: function () {
                    return '<b>' + this.series.name + '</b><br/>' +
                        Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
                        Highcharts.numberFormat(this.y, 2);
                }
            },
            legend: {
                enabled: false
            },
            exporting: {
                enabled: false
            },
            series: [{
                name: 'Sensor data',
                data: (function () {
                    // generate an array of sensor data
                    var data = [],
                        time = (new Date()).getTime(),
                        i;

                   
                        data.push({ {{ t }}  }
                    return data;
                }())
            }]
        });
    });
});
		</script>
	</head>
	<body>
 <nav class="navbar navbar-default">
                        <div class="container-fluid">
                            <div class="navbar-header">
                                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                                    <span class="sr-only">Toggle navigation</span>
                                    <span class="icon-bar"></span>
                                    <span class="icon-bar"></span>
                                    <span class="icon-bar"></span>
                                </button>
                       {% if user.is_authenticated %}
                                <a class="navbar-brand" href="/accueil">Accueil </a>
                                <a class="navbar-brand" href="/aps">Graphe </a>
                             </div>
                            <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
                                <ul class="nav navbar-nav navbar-right">
                                    <li class="dropdown">
                                        <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Account
                                            <span class="caret"></span>
                                        </a>

                                        <ul class="dropdown-menu" role="menu">
                                            <li>
                                                <a href="/mail">changer mail</a>
                                            </li>
                                            <li>
                                                <a href="#">changer temps</a>
                                            </li>
                                            <li class="divider"></li>
                                            <li>
                                                <a href="/logout">Logout</a>
                                            </li>
                                        </ul>
                                    </li>
                                </ul>
                            </div>
                           </nav>
                       
                      {% else %}

                                <a class="navbar-brand" href="/accueil">Accueil </a>
                                <a class="navbar-brand" href="/aps">Graphe </a>

                                <a class="navbar-brand" href="/login">S'authentifier </a>
                                
                            </div>
                         </nav>
                      {% endif %}



                    <!-- Core Scripts - Include with every page -->
                    <script src = "{% static 'js/jquery.min.js' %}"></script>
                    <script src = "{% static 'js/bootstrap.min.js' %}"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>

<div id="container" style="min-width: 310px; height: 400px; margin: 0 auto"></div>

	</body>
</html>
my old index.html

<script type="text/javascript">
$(function () {
    $(document).ready(function () {
        Highcharts.setOptions({
            global: {
                useUTC: false
            }
        });

        $('#container').highcharts({
            chart: {
                type: 'spline',
                animation: Highcharts.svg, // don't animate in old IE
                marginRight: 10,
                events: {
                    load: function () {

                        // set up the updating of the chart each second
                        var series = this.series[0];
                        setInterval(function () {
                            var x = (new Date()).getTime(), // current time
                                y =  {{ t }} ;
                            series.addPoint([x, y], true, true);
                        }, 3000);
                    }
                }
            },
            title: {
                text: 'Live temperature sensor values'

            },
            xAxis: {
                type: 'datetime',
                tickPixelInterval: 150
            },
            yAxis: {
                title: {
                    text: 'Value'
                },
                plotLines: [{
                    value: 0,
                    width: 1,
                    color: '#808080'
                }]
            },
            tooltip: {
                formatter: function () {
                    return '<b>' + this.series.name + '</b><br/>' +
                        Highcharts.dateFormat('%Y-%m-%d %H:%M:%S', this.x) + '<br/>' +
                        Highcharts.numberFormat(this.y, 2);
                }
            },
            legend: {
                enabled: false
            },
            exporting: {
                enabled: false
            },
            series: [{
                name: 'Sensor data',
                data: (function () {
                    // generate an array of sensor data
                    var data = [],
                        time = (new Date()).getTime(),
                        i;

                    for (i = -19; i <= 0; i += 1) {
                        data.push({
                            x: time + i * 1000,
                            y: {{ t }}
                        });
                    }
                    return data;
                }())
            }]
        });
    });
});
		</script>

0

1 Answer 1

1

First of all, you need to test your foo() function independent of the view. If you are not using unit tests, it's still a simple matter to call foo() from the django shell to determine that it works.

If you do call foo() from the command like, you will find that it just returns a tuple. An x and a y value. Is this what you want? It's pretty hard to plot a curve with just one point.

Secondly, in your template

series.addPoint([{{ t }}], true, true);

would be the equivalent to something like

series.addPoint([(10.1, 11.11)])

Is this what you really want? Looking further, this would lead to a javascript syntax error

 data.push({ {{ t }}  }
                return data;

brackets ( not closed missing ). You can check for javascript errors with the chrome developer console (Ctrl Shift J)

Note that the proper way to iterate through a list in a template is something like this:

{% for item in t %}
   {{ item.x }}, {{ item.y }}
{% endfor %}
Sign up to request clarification or add additional context in comments.

4 Comments

please look at my edited question I've added my old html file my for loop was in the html not in the rasp.py and it was rendering the same data it returns a line not a curve but when I changed it . it returns a blank page
Updated, answer. The old html doesn't seem to have the syntax error. But your rasp.py still returns only a single Tuple instead of a list of tuples.
yes and I didn't know how to send data every 3 seconds from rasp to my html in order to gett different data from my sensor
Create a view that gives an x, y pair every three seconds (you can do so with the setInterval javascript method) and hit it with ajax (jquery .get in case if you haven't used it before). Add the response to the chart dataset and refresh the chart.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.