簡體   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