user3331063
user3331063

Reputation: 23

get request for flask data

Very new to web development and writing a web page that will interact with my raspberry pi. I got flask working correctly and when pin 23 is set to Hi and Low on my raspberry pi, it correctly prints "High" and "Low" when I run the python script and browse to http:192.168.1.45:8080. I can't figure out how to do a "get" in the HTML document to return "High", "Low", or "Error" from flask.

Here are my files:

test5.html:

<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
    var countDownSecs = 10;
    var check = null;

    function printCountDown() {
        if (check == null && document.getElementById("counter").innerHTML != 'Launched!') {
            var cnt = countDownSecs;
                check = setInterval(function () {
                    cnt -= 1;
                    document.getElementById("counter").innerHTML = cnt;
                    if (cnt == 0) {
                    launch();
                      }
                }, 1000);
        }
    }

    function stop() {
        clearInterval(check);
        check = null;
        document.getElementById("counter").innerHTML = countDownSecs;
    }

    function launch() {
        $.ajax({
                type: "POST",
                url: "cgi-bin/launch.cgi"
            })
        clearInterval(check);
        check = null;
        document.getElementById("counter").innerHTML = 'Launch';
        setTimeout(function(){
            document.getElementById("counter").innerHTML = countDownSecs;
            $("#launch").attr("disabled","disabled");
        } ,5000);
    }

        function ckcont() {
                $.ajax({
                        type: "POST",
                        url: "cgi-bin/ckconttest.cgi"
            })
        alert ("test");
    }

</script>
</head>
<body>
<style type="text/css">
* {
    -webkit-touch-callout: none;
    -webkit-user-select: none;
}
div.ex
{
font-size:350%;
width:230px;
padding:10px;
border:5px solid gray;
margin:0px;
}
</style>
<div class="ex"; div align="center"><span id="counter"><script>document.write(countDownSecs);</script></span></div>
<button id="continuity" style="font-size:20pt;font-weight:600;padding: 20px 15px">Check Continuity</button>

<script>
$(document).ready(function(){
  $("#continuity").click(function(){
    $("p").toggleClass("main");
    $("#launch").removeAttr("disabled");
    ckcont();
  });
});
</script>
<button id="launch" disabled="disabled" style="font-size:20pt;font-weight:600;padding: 20px 15px">Hold to Launch
</button>

<script>
$("#launch").bind( "touchend mouseup", function(e) {
    if (check != null){
        stop();
    }
//$( "body" ).append( "<span style='color:#f00;'>Mouse up.</span><br>" );
});

$("#launch").bind( "touchstart mousedown", function(e) {
printCountDown();
//$( "body" ).append( "<span style='color:#00f;'>Mouse down.</span><br>" );
});
</script>
</body>
</html>

The CGI script simply runs the python script as root: ckconttest.cgi:

#!/bin/bash
sudo ./ckconttest.py

ckconttest.py:

#!/usr/bin/env python
from flask import Flask, render_template
import datetime
import RPi.GPIO as GPIO
app = Flask(__name__)
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
GPIO.setup(18, GPIO.OUT)
GPIO.output(18, True)
GPIO.setup(23, GPIO.IN)
@app.route("/")
def readPin():
    try:
        if GPIO.input(23) == True:
            return "High"
        else:
            return "Low"
    except:
            return "Error"

app.run(host='0.0.0.0', port=8080, debug=True)

In function ckcont(), how do I read the High, Low, and Error text strings being delivered by flask and print the string to a message box?

Thanks much, Ed

Upvotes: 1

Views: 772

Answers (2)

miku
miku

Reputation: 188014

You'll need to modify your ckcont function, which currently looks like:

function ckcont() {
    $.ajax({
        type: "POST",
        url: "/cgi-bin/ckconttest.cgi"
    })
    alert ("test");
};

First, your @app.route("/") does not accept POST requests, only GET. And you'll need to specify some callback for the success (and error) condition. Something along these lines: http://jsfiddle.net/FQeg8/4/:

$.ajax({
    url: "/cgi-bin/ckconttest.cgi",
    type: "GET",
    success: function(data, status, xhr) {
        alert(data.ip);
    },
    error: function(xhr, status, error) {
        console.log(xhr, status, error);
    }
});

Upvotes: 0

Shreyas
Shreyas

Reputation: 1534

Assuming that rest of your code is correct, I see at least one problem with the way you are using cgi and python scripts.

Going by your description, the cgi-bin/ckconttest.cgi script is just calling the ./ckconttest.py in sudo mode, and the ./ckconttest.py returns strings "High" or "Low" based on the GPIO pin status.

Since the web-server is calling cgi-bin/ckconttest.cgi, and that cgi script is just consuming output of ckcontest.py and not returning anything back, you wont get the High and Low back to the browser.

You have two options -

  1. directly invoke the ckconttest.py instead of cgi-bin/ckconttest.cgi
  2. if for some reason you can't, then use subprocess module to call the PY file, read its output, and return it.

Here is a nice reference on using subprocess to invoke other executables - http://pymotw.com/2/subprocess/

Upvotes: 1

Related Questions