Raspberry PI 服务器 - GPIO 端口状态 JSON 响应

Raspberry PI server - GPIO ports status JSON response

我挣扎了几天。问题很简单,有没有一种方法可以在 Raspberry PI 上创建一个服务器,它将 return GPIO 端口的当前状态 JSON 格式?

示例:

Http://192.168.1.109:3000/led

{
  "Name": "green led",
  "Status": "on"
}

我发现 Adafruit gpio-stream library 很有用,但不知道如何将数据发送为 JSON 格式。

谢谢

node.js 有多种用于 gpio 交互的库。一个问题是您可能需要 运行 它作为 root 才能访问 gpio,除非您可以调整这些设备的读取访问权限。这应该在最新版本的 rasbian 中得到修复。

我最近构建了一个由运动传感器触发的 node.js 应用程序,以激活屏幕(并在一段时间后停用它)。我尝试了各种 gpio 库,但我最终使用的是 "onoff" https://www.npmjs.com/package/onoff 主要是因为它似乎使用了一种适当的方式来识别 GPIO 引脚上的变化(使用中断)。

现在,你说你想发送数据,但你没有具体说明应该如何发生。如果我们使用您想通过 HTTP 使用 POST 请求发送数据的示例,并将 JSON 作为正文发送,这意味着您将初始化已连接的 GPIO 引脚,然后为它们附加事件处理程序(以侦听更改)。

发生更改时,您将调用 http 请求并从 javascript 对象序列化 JSON(有些库也可以处理此问题)。您需要自己保留一个名称引用,因为您只能按编号寻址 GPIO 引脚。

示例:

var GPIO = require('onoff').Gpio;
var request = require('request');
var x = new GPIO(4, 'in', 'both');

function exit() {
  x.unexport();
}

x.watch(function (err, value) {
  if (err) {
    console.error(err);
    return;
  }

  request({
    uri: 'http://example.org/',
    method: 'POST',
    json: true,
    body: { x: value } // This is the actual JSON data that you are sending
  }, function () {
    // this is the callback from when the request is finished
  });
});

process.on('SIGINT', exit);

我正在使用 npm 模块 onoff 和 request。 request 用于简化 http 请求的 JSON 序列化。

如您所见,我这里只设置了一个GPIO。如果您需要跟踪多个,您必须确保将它们全部初始化,用某种名称区分它们,并且还记得在退出回调中取消导出它们。不确定如果你不这样做会发生什么,但你可能会为其他进程锁定它。

谢谢,这很有帮助。我没有很好地表达自己,对此感到抱歉。我不想发送数据(暂时)我只想输入 192.168.1.109/led 之类的网址并接收 json 响应。这是我现在设法做的。我不知道这是否是正确的方法。 PLS 你能回顾一下这个或建议更好的方法吗..

var http = require('http'); 
var url = require('url');  
var Gpio = require('onoff').Gpio;

var led = new Gpio(23, 'out');

http.createServer(function (req, res) {

   res.writeHead(200, {'Content-Type': 'text/html'});
   var command = url.parse(req.url).pathname.slice(1);
    switch(command) {
     case "on":
        //led.writeSync(1);
        var x = led.readSync();
        res.write(JSON.stringify({ msgId: x }));
        //res.end("It's ON");
        res.end();
        break;
     case "off":
       led.writeSync(0);
       res.end("It's OFF");
       break;
    default:
       res.end('Hello? yes, this is pi!');
     }
}).listen(8080);