【发布时间】:2015-08-20 18:11:34
【问题描述】:
我正在尝试在 Raspberry Pi 上托管本地服务器(使用 Node.js)。 Pi 有一个 ADC (MCP3008) 连接到它,我有一个 Python 脚本,可以连续采样 ADC 并打印当前值。我想让 Node 服务器运行 Python 脚本,并且每当它看到打印语句时,暂时只执行一个 console.log(current value)。我一般是 Node 和 Web 开发的新手,所以我可能缺少一些简单的东西,以便 Node 将不断地从 Python 脚本接收数据。我目前正在尝试使用 Socket.io,因为这似乎是 Node 从 Python 脚本中查看更改的方法,但也许这不是最好的方法。基本网页来自我找到的教程 (http://www.jaredwolff.com/blog/raspberry-pi-getting-interactive-with-your-server-using-websockets/)。我目前使用的代码在这里:
var app = require('http').createServer(handler)
, io = require('socket.io').listen(app)
, url= require('url')
, fs = require('fs')
, gpio = require('onoff').Gpio
, PythonShell = require('python-shell');
app.listen(5000);
function handler (req, res) {
var path = url.parse(req.url).pathname;
if (path == '/') {
index = fs.readFile(__dirname+'/public/index.html',
function(error,data) {
if (error) {
res.writeHead(500);
return res.end("Error: unable to load index.html");
}
res.writeHead(200,{'Content-Type': 'text/html'});
res.end(data);
});
} else if( /\.(js)$/.test(path) ) {
index = fs.readFile(__dirname+'/public'+path,
function(error,data) {
if (error) {
res.writeHead(500);
return res.end("Error: unable to load " + path);
}
res.writeHead(200,{'Content-Type': 'text/plain'});
res.end(data);
});
} else {
res.writeHead(404);
res.end("Error: 404 - File not found.");
}
}
// Python
var pyshell = new PythonShell('mcp3008.py');
pyshell.run('mcp3008.py', function (err, results) {
if (err) throw err;
console.log('Results: %j', results);
});
io.sockets.on('connection', function (socket) {
pyshell.on('message', function (message) {
console.log(message);
});
});
感谢您提供的任何提示或帮助!
【问题讨论】:
-
为什么不在 node.js 中编写 ADC 访问代码,而不是做这种跨语言的东西?您可能会找到一些现有的代码来开始。
标签: python node.js socket.io raspberry-pi