我已经尝试了一年多的时间,为在webserver
上运行的本地pi
提供两个图像来控制led灯带。
我可以通过使用图像主机来工作,但是我更希望在本地提供图像。我已将问题缩小到我的nodejs
服务器,并尝试实现express来实现此目的,但无济于事。
图像与公用文件夹中的rgb.html
位于同一文件夹中
var path = require('path');
var http = require('http').createServer(handler); //require http server, and create server with function handler()
var fs = require('fs'); //require filesystem module
var io = require('socket.io')(http) //require socket.io module and pass the http object (server)
var Gpio = require('pigpio').Gpio, //include pigpio to interact with the GPIO
ledRed = new Gpio(17, {mode: Gpio.OUTPUT}), //use GPIO pin 4 as output for RED
ledGreen = new Gpio(22, {mode: Gpio.OUTPUT}), //use GPIO pin 17 as output for GREEN
ledBlue = new Gpio(24, {mode: Gpio.OUTPUT}), //use GPIO pin 27 as output for BLUE
redRGB = 0, //set starting value of RED variable to off (0 for common cathode)
greenRGB = 0, //set starting value of GREEN variable to off (0 for common cathode)
blueRGB = 0; //set starting value of BLUE variable to off (0 for common cathode)
//RESET RGB LED
ledRed.digitalWrite(0); // Turn RED LED off
ledGreen.digitalWrite(0); // Turn GREEN LED off
ledBlue.digitalWrite(0); // Turn BLUE LED off
http.listen(3000); //listen to port 3000
function handler (req, res) { //what to do on requests to port 8080
fs.readFile(__dirname + '/public/rgb.html', function(err, data) { //read file rgb.html in public folder
if (err) {
res.writeHead(404, {'Content-Type': 'text/html'}); //display 404 on error
return res.end("404 Not Found");
}
res.writeHead(200, {'Content-Type': 'text/html'}); //write HTML
res.write(data); //write data from rgb.html
return res.end();
});
}
io.sockets.on('connection', function (socket) {// Web Socket Connection
socket.on('rgbLed', function(data) { //get light switch status from client
console.log(data); //output data from WebSocket connection to console
//for common cathode RGB LED 0 is fully off, and 255 is fully on
redRGB=parseInt(data.red);
greenRGB=parseInt(data.green);
blueRGB=parseInt(data.blue);
ledRed.pwmWrite(redRGB); //set RED LED to specified value
ledGreen.pwmWrite(greenRGB); //set GREEN LED to specified value
ledBlue.pwmWrite(blueRGB); //set BLUE LED to specified value
});
});
process.on('SIGINT', function () { //on ctrl+c
ledRed.digitalWrite(0); // Turn RED LED off
ledGreen.digitalWrite(0); // Turn GREEN LED off
ledBlue.digitalWrite(0); // Turn BLUE LED off
process.exit(); //exit completely
});