Run Python scripts from JavaScript functions
Asked Answered
B

1

1

We need to run a Python code which will control the GPIO of Raspberry Pi 3 from within the JavaScript. (JavaScript is listening for changes on database and when changes are made, function gets triggered and it should run the Python Code.

(This code is not working, like the alert message will pop-up but the python code isn't running which otherwise should turn the LED on. What am i doing wrong?)

index.html file

function runPython()
{
    $.ajax({
    type: "POST", 
    url: "/home/pi/Desktop/Web/led.py",
    data :{},
    success: callbackFunc
    });
}

function callbackFunc(response)
{
    alert("working");
}

led.py file

import RPi.GPIO as GPIO
import timemGPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(18, GPIO.OUT)
print "LED on"
GPIO.output(18, GPIO.HIGH)
time.sleep(10)
print "LED off"
GPIO.output(18,GPIO.LOW)
Batavia answered 20/4, 2018 at 5:39 Comment(21)
Why is this tagged with PHP?Inattention
you forgot the question....Expectorant
if this is possible through PHP? @Magnus ErikssonBatavia
everything is possible if you put your mind to itExpectorant
Is what possible through PHP? Running a Python script or replace your Python script with a PHP script? If you want to run a python script from Ajax, just set up your system/web server to be able to parse Python.Inattention
Another thing... "it's not working" is a really bad error description. You need to give us more info. Tell us what actually happens, or we won't have any chance at all to even know where to begin.Inattention
@Magnus Eriksson - Could you please help me with that? (i am not lazy but i got no time researching as i need to submit this project by tomorrow)Batavia
@MagnusEriksson When the function is called, alert dialog will pop-up but the python code is'nt running. (led is not turning ON)Batavia
You need to set up a server. I recommend flaskGolgotha
@ᴡʜᴀᴄᴋᴀᴍᴀᴅᴏᴏᴅʟᴇ3000 What is flask? I guess i am not using it.Batavia
flask.pocoo.org It allows you to set up a server in python. Then you can make a request to the server to light up the LED. Quickstart: flask.pocoo.org/docs/0.12/quickstartGolgotha
1. Help you with what? You still haven't said what you actually want to do. 2. Both options (rewriting the code or set up your server) are too broad for SO. 3. SO isn't a substitute for doing research. SO is not a free coding service.Inattention
I'm curious about why someone actually up voted this question? It's both too broad an very unclear.Inattention
@MagnusEriksson I am Sorry but may i know if I could run Python code directly from JavaScript function?Batavia
@MagnusEriksson I didn't upvote it but I can say that different communities on SO have different tolerance for "too broad", including GPIO/embedded (and Fortran too!).Marga
So I'm guessing your Raspberry Pi has an open browser window to some server? And based on something that server sends your browser, you want the browser to trigger a Python script? Is that right? Or are you running Node on the Raspberry Pi?Marga
@AhmedFasih - Yes exactly!Batavia
Ok. So. For a million security reasons, browsers will not let you run an arbitrary script on your computer, and certainly you can't POST an AJAX request to a real file outside the browser. You can, however, run a web server locally (that's listening to 127.0.0.1:SOMEPORT), post an AJAX request to that webserver, and that webserver can invoke the Python call. Someone recommended Flask, that's a great super-simple webserver for Python and I recommend it.Marga
(Note that you can choose run the webserver from any language you have available on the Raspberry Pi (Node, Ruby, Java, etc., as long as it can shell out to the system), but since your script is Python, Flask or another lightweight Python webserver like webapp2 might make the most sense.)Marga
@AhmedFasih Thankyou, you made it clear.Batavia
For future questions. Note how this question had nothing to do with Raspberry Pi or GPIO or anything fancy. The simplest form of this question might be, “how do I start a local script, e.g., Python, via my web browser?” Seek out the simplest MCVE that captures all the relevant aspects of your problem when you ask questions, so that the most people can help you.Marga
D
3

You code is not working because you can't access and run script on server directly from a browser, you can only pass the data to the server using ajax, therefore the url in the ajax should be the server url, and you have to send the data.

On your server (i.e. your Raspberry Pi), you need to have a http(web) server. The server will handle the post request coming from your javascript and control the GPIO accordingly. Like other mentioned, you can use Flask web development framework to create a web server for handling the request(s), or alternatively I often uses http.server which is part of python standard library to create my own GET and POST request handlers for simple applications like this one.

Here is an approach of using http.server where do_GET method create a web page and run the javascript when pointing the browser to the server/RPi IP/URL, and 'do_POST' method handle the post data sent by the ajax to control the GPIO.

web_gpio.py (in Python 3 syntax)

import time
import RPi.GPIO as GPIO
from http.server import BaseHTTPRequestHandler, HTTPServer


host_name = '192.168.0.115'    # Change this to your Raspberry Pi IP address
host_port = 8000


class MyHandler(BaseHTTPRequestHandler):
    """ 
    A special implementation of BaseHTTPRequestHander for reading data 
    from and control GPIO of a Raspberry Pi
    """

    def do_HEAD(self):
        self.send_response(200)
        self.send_header('Content-type', 'text/html')
        self.end_headers()

    def _redirect(self, path):
        self.send_response(303)
        self.send_header('Content-type', 'text/html')
        self.send_header('Location', path)
        self.end_headers()

    def do_GET(self):
        html = '''
        <html>
        <body>
        <p>this webpage turn on and then turn off LED after 2 seconds</p>
        <script src="http://code.jquery.com/jquery-1.12.4.min.js"></script>
        <script>
          function setLED()
            {{
              $.ajax({
              type: "POST",
              url: "http://%s:%s",
              data :"on",
              success: function(response) {
                alert("LED triggered")
              }
            });
          }}
          setLED();
        </script>
        </body>
        </html>
        '''
        self.do_HEAD()
        html=html % (self.server.server_name, self.server.server_port)
        self.wfile.write(html.encode("utf-8"))

    def do_POST(self):
        # Get the post data
        content_length = int(self.headers['Content-Length'])
        post_data = self.rfile.read(content_length).decode("utf-8")
        if post_data == "on":
            GPIO.setmode(GPIO.BCM)
            GPIO.setwarnings(False)
            GPIO.setup(18, GPIO.OUT)
            GPIO.output(18, GPIO.HIGH)
            time.sleep(2)
            GPIO.output(18, GPIO.LOW)
        self._redirect('/')


if __name__ == '__main__':

    http_server = HTTPServer((host_name, host_port), MyHandler)
    print("Running server on %s:%s" % (host_name, host_port))
    http_server.serve_forever()

Run the python script on the server:

python3 web_gpio.py

Either launch your browser and point the browser to the server/RPi ip (in my example, it is 192.168.0.115:8000) or run curl command form another terminal session to simulate the GET request.

curl http://192.168.0.115:8000

Hope this example would give you the idea on how to control something on your server using a simple web server.

Dirty answered 21/4, 2018 at 0:41 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.