繁体   English   中英

从JavaScript函数运行Python脚本

[英]Run Python scripts from JavaScript functions

我们需要运行一个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)

您的代码无法正常工作,因为您无法直接从浏览器访问和运行服务器上的脚本,只能使用ajax将数据传递到服务器,因此ajaxurl应该是服务器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'方法处理ajax发送的发布数据以控制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服务器控制服务器上的某些内容。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM