Нужна помощь в кодировании веб-сокета для освещения светодиодов на пи от других входов кода - PullRequest
0 голосов
/ 26 апреля 2019

Я ищу код моего raspberry pi 3+ для включения и выключения светодиодов из приложения веб-сокета, запущенного на другом устройстве.

У меня есть светодиоды, работающие с выводами GPIO, но я изо всех сил пытаюсь закодировать 2 отдельных веб-сокета, чтобы облегчить работу различных устройств (pc & Pi). У меня запущен простой web-сокет от pi, поэтому я могу включать и выключать в своем браузере, но я не могу оттуда прогрессировать. (Не уверен, как создать приложение веб-сокета и запустить его на моем компьютере)

пример кода для веб-сервера pi:

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('onoff').Gpio; //include onoff to interact with the GPIO
var LED = new Gpio(4, 'out'); //use GPIO pin 4 as output
var pushButton = new Gpio(18, 'in', 'both'); //use GPIO pin 17 as input, and 'both' button presses, and releases should be handled

http.listen(8080); //listen to port 8080

function handler (req, res) { //create server
  fs.readFile(__dirname + '/public/index.html', function(err, data) { //read file index.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 index.html
    return res.end();
  });
}

io.sockets.on('connection', function (socket) {// WebSocket Connection
  var lightvalue = 0; //static variable for current status
  pushButton.watch(function (err, value) { //Watch for hardware interrupts on pushButton
    if (err) { //if an error
      console.error('There was an error', err); //output error message to console
      return;
    }
    lightvalue = value;
    socket.emit('light', lightvalue); //send button status to client
  });
  socket.on('light', function(data) { //get light switch status from client
    lightvalue = data;
    if (lightvalue != LED.readSync()) { //only change LED if status has changed
      LED.writeSync(lightvalue); //turn LED on or off
    }
  });
});

process.on('SIGINT', function () { //on ctrl+c
  LED.writeSync(0); // Turn LED off
  LED.unexport(); // Unexport LED GPIO to free resources
  pushButton.unexport(); // Unexport Button GPIO to free resources
  process.exit(); //exit completely
});

светодиод горит при щелчке в разъеме браузера, как я могу добавить еще 6 светодиодных выходов к этому коду, чтобы я мог иметь всего 7 светодиодных выходов. Как бы я кодировал сокет на стороне ПК для тестирования, чтобы сервер не размещал сервер, просто беря данные из сокета?

...