2016年2月2日 星期二

node.js 結合 python 的練習.....用網頁來控制你的RPI



node.js 的實作請參考這篇  http://0975128810.blogspot.tw/2016/01/raspberry-nodejs-javascript.html

led 發亮的實作請參考這篇  http://0975128810.blogspot.tw/2016/01/grovepi-lession-1-led.html


那到底怎麼在node.js 裡面執行 python code呢?

其實就是利用  exec 這個函式....

我直接套用 node.js 那篇的範例......修改    requestHandlers.js

新增兩個function   green_led 和blue_led ....裡面的重點就是執行

exec("sudo ./green_led.py",function(error,stdout,stderr)).....

他就會去執行  green_led.py  ....裡面的第一行就是呼叫 python 去直譯他

=======================================================
function green_led(response) {
  console.log("request handler 'green_led' was called");
  exec("sudo ./green_led.py", function (error,stdout,stderr) {
      response.writeHead(200, {"Content-Type": "text/plain"});
      response.write(stdout);
      response.end();
  });
}

function blue_led(response) {
  console.log("request handler 'blue_led' was called");
  exec("sudo ./blue_led.py", function (error,stdout,stderr) {
      response.writeHead(200, {"Content-Type": "text/plain"});
      response.write(stdout);
      response.end();
  });
}


exports.start = start;
exports.upload = upload;
exports.green_led = green_led;
exports.blue_led = blue_led;

 ===============================================================

接著修改  index.js

增加兩行.... 告訴server ...當得到的字串是 /green_led 就是 requestHandlers.green_led...
                                           當得到的字串是 /green_led 就是 requestHandlers.blue_led...
================================================================

var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");

var handle = {}
handle["/"] = requestHandlers.start;
handle["/start"]  = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;
handle["/green_led"] = requestHandlers.green_led;
handle["/blue_led"] = requestHandlers.blue_led;

server.start(router.route,handle);
=================================================================

改完了之後.....執行  

node  index.js 

然後在web browser 輸入  http://192.168.1.2:8888/blue_led  (192.168.1.2 是我RPI的ID...你必須要改成你的)

                                   輸入  http://192.168.1.2:8888/green_led

你就會看見你的RPI 所接到的GREEN LED 和 BLUE LED 會一直閃來閃去.....


PS :   green_led.py  的內容如下:  因為我有grove shield..所以就直接用了

           你也可以改成你想要的動作.....

 #!/usr/bin/python
import time
from grovepi import *

# Connect the Grove LED to digital port D4
led = 4

pinMode(led,"OUTPUT")
time.sleep(1)


while True:
    try:
        #Blink the LED
        digitalWrite(led,1)  # Send HIGH to switch on LED
        print "LED ON!"
        time.sleep(1)

        digitalWrite(led,0)  # Send LOW to switch off LED
        print "LED OFF!"
        time.sleep(1)

    except KeyboardInterrupt: # Turn LED off before stopping
        digitalWrite(led,0)
        break
    except IOError:    # Print "Error" if communication error encountered
        print ("Error")

沒有留言:

張貼留言