基于外部事件的节点POST请求

时间:2014-04-02 19:42:50

标签: python node.js api post raspberry-pi

我有一个门传感器连接到Raspberry Pi,目标是让Node脚本在门打开时向我的外部API服务器发出POST请求,并在门关闭后发出另一个POST请求。

逻辑是在我的Pi上运行下面的python脚本,定期检查门是打开还是关闭。我的python脚本运行成功,检查门是打开还是关闭;但是,它只检查状态1次。

以下Node脚本也正常工作,它使用python脚本的输出发出POST请求。

问:如何修改以下脚本,以便在门打开后向我的服务器发送POST请求,并在门关闭后发送另一个。

我的第一个想法是使用Node Events& EventEmitter功能,但我不确定这个的实现。另外,我假设python脚本必须不断地轮询门;所以在这里,可以使用while循环吗?

door.py

import time
import RPi.GPIO as io
io.setmode(io.BCM)

door_pin = 23

io.setup(door_pin, io.IN, pull_up_down=io.PUD_UP)

if io.input(door_pin):
    print("Door Opened")
else:
    print("Door Closed")

door.js

var exec = require('child_process').exec;
var rest = require('restler');

// String that will be sent to the command line, generating the door status
var doorCommand = "sudo python door.py"

exec(doorCommand, function cb(error, stdout, stderr){
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
    if (error !== null){
        console.log('exec error: ' + error);
    }

    var doorStatus = stdout; // stdout shows if the door is opened or closed

    // Creates the door status POST request to the Rails server
    rest.post('http://192.168.6.109:3000/door/save', {
        data: {
          door: doorStatus
        }
    }).on('complete', function(data, response){
        console.log('door status code: ' + response.statusCode);
    });
});

1 个答案:

答案 0 :(得分:1)

你走在正确的轨道上。我建议使用Node.js模块(如pi-gpio)直接读取GPIO端口,而不是调用Python脚本。然后,您将在Node.js中使用setInterval调用来重复检查门状态,并在状态更改时调用POST。希望这会有所帮助。

相关问题