我想在Raspberry Pi上托管本地服务器(使用Node.js)。 Pi有一个连接到它的ADC(MCP3008),并且我有一个Python脚本可以持续采样ADC并打印当前值。我想让Node服务器运行Python脚本,并且每当它看到一个打印语句时,就暂时只做一个console.log(当前值)。我对Node和一般的Web开发并不陌生,所以我可能会错过一些简单的事情,这样Node就会不断从Python脚本接收数据。我现在试图使用Socket.io,因为这看起来有点合理,因为Node可以查看Python脚本的更改,但这可能不是实现它的最佳方法。基本网页来自我发现的教程(http://www.jaredwolff.com/blog/raspberry-pi-getting-interactive-with-your-server-using-websockets/)。我目前正在使用的代码是在这里:Raspberry Pi - Node.js运行Python脚本来连续采样ADC
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访问进行编码,而不是使用跨语言的东西呢?你可能会找到一些现有的代码开始。 – jfriend00