python运行js文件,从JavaScript函数运行Python脚本

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)

解决方案

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 = '''

this webpage turn on and then turn off LED after 2 seconds

function setLED()

{{

$.ajax({

type: "POST",

url: "http://%s:%s",

data :"on",

success: function(response) {

alert("LED triggered")

}

});

}}

setLED();

'''

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值