从JavaScript函数运行Python脚本

时间:2018-04-20 05:39:36

标签: javascript python raspberry-pi gpio

我们需要运行一个Python代码,它将在JavaScript中控制Raspberry Pi 3的GPIO。 (JavaScript正在侦听数据库的更改,并且在进行更改时,会触发函数并运行Python代码。

(这段代码不起作用,就像警报消息会弹出,但是python代码没有运行,否则应该打开LED。我做错了什么?)

index.html文件

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

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

led.py文件

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)

1 个答案:

答案 0 :(得分:2)

您的代码无效,因为您无法直接从浏览器访问和运行服务器上的脚本,您只能使用ajax将数据传递到服务器,因此url in ajax应该是服务器URL,你必须发送data

在您的服务器(即您的Raspberry Pi)上,您需要有一个http(Web)服务器。服务器将处理来自您的javascript的发布请求并相应地控制GPIO。与其他提到的一样,您可以使用Flask Web开发框架来创建用于处理请求的Web服务器,或者我经常使用http.server作为python标准库的一部分来创建我自己的GET和像这样的简单应用程序的POST请求处理程序。

以下是使用http.server的方法,其中do_GET方法创建网页并在将浏览器指向服务器/ RPi IP / URL时运行javascript,以及' do_POST&#39 ;方法处理ajax发送的post数据以控制GPIO。

web_gpio.py(以Python 3语法编写)

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()

在服务器上运行python脚本:

python3 web_gpio.py

启动浏览器并将浏览器指向服务器/ RPi ip(在我的示例中为192.168.0.115:8000)或从另一个终端会话运行curl命令以模拟GET请求。

curl http://192.168.0.115:8000

希望这个例子可以让您了解如何使用简单的Web服务器控制服务器上的某些内容。