[英]Run Python scripts from JavaScript functions
We need to run a Python code which will control the GPIO of Raspberry Pi 3 from within the JavaScript. 我们需要运行一个Python代码,该代码将从JavaScript中控制Raspberry Pi 3的GPIO。 (JavaScript is listening for changes on database and when changes are made, function gets triggered and it should run the Python Code.
(JavaScript正在侦听数据库上的更改,并且在进行更改时,将触发函数,并且该函数应运行Python代码。
(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?) (此代码无法正常工作,例如会弹出警报消息,但python代码未运行,否则应打开LED指示灯。我在做什么错了?)
index.html file index.html文件
function runPython()
{
$.ajax({
type: "POST",
url: "/home/pi/Desktop/Web/led.py",
data :{},
success: callbackFunc
});
}
function callbackFunc(response)
{
alert("working");
}
led.py file 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)
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
. 您的代码无法正常工作,因为您无法直接从浏览器访问和运行服务器上的脚本,只能使用
ajax
将数据传递到服务器,因此ajax
的url
应该是服务器url,并且您必须发送data
。
On your server (ie your Raspberry Pi), you need to have a http(web) server. 在您的服务器(即Raspberry Pi)上,您需要有一台http(web)服务器。 The server will handle the post request coming from your javascript and control the GPIO accordingly.
服务器将处理来自您的javascript的发布请求,并相应地控制GPIO。 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.
像其他提到的一样,您可以使用Flask Web开发框架来创建用于处理请求的Web服务器,或者我经常使用http.server(它是python标准库的一部分)来创建自己的GET和POST请求处理程序,以简化操作像这样的应用程序。
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. 这是一种使用
http.server
的方法,其中do_GET
方法创建网页并在将浏览器指向服务器/ RPi IP / URL时运行javascript,而'do_POST'方法处理ajax发送的发布数据以控制GPIO 。
web_gpio.py (in Python 3 syntax) 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()
Run the python script on the server: 在服务器上运行python脚本:
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. 启动浏览器并将浏览器指向服务器/ RPi ip(在我的示例中为
192.168.0.115:8000
),或者在另一个终端会话中运行curl
命令以模拟GET请求。
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. 希望本示例将使您了解如何使用简单的Web服务器控制服务器上的某些内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.