Advertisement
Guest User

Untitled

a guest
Jun 25th, 2019
51
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.92 KB | None | 0 0
  1. var http = require('http').createServer(handler); //require http server, and create server with function handler()
  2. var fs = require('fs'); //require filesystem module
  3. var io = require('socket.io')(http) //require socket.io module and pass the http object (server)
  4. var Gpio = require('onoff').Gpio; //include onoff to interact with the GPIO
  5. var LED = new Gpio(4, 'out'); //use GPIO pin 4 as output
  6. var pushButton = new Gpio(18, 'in', 'both'); //use GPIO pin 17 as input, and 'both' button presses, and releases should be handled
  7.  
  8. http.listen(8080); //listen to port 8080
  9.  
  10. function handler (req, res) { //create server
  11. fs.readFile(__dirname + '/public/index.html', function(err, data) { //read file index.html in public folder
  12. if (err) {
  13. res.writeHead(404, {'Content-Type': 'text/html'}); //display 404 on error
  14. return res.end("404 Not Found");
  15. }
  16. res.writeHead(200, {'Content-Type': 'text/html'}); //write HTML
  17. res.write(data); //write data from index.html
  18. return res.end();
  19. });
  20. }
  21.  
  22. io.sockets.on('connection', function (socket) {// WebSocket Connection
  23. var lightvalue = 0; //static variable for current status
  24. pushButton.watch(function (err, value) { //Watch for hardware interrupts on pushButton
  25. if (err) { //if an error
  26. console.error('There was an error', err); //output error message to console
  27. return;
  28. }
  29. lightvalue = value;
  30. socket.emit('light', lightvalue); //send button status to client
  31. });
  32. socket.on('light', function(data) { //get light switch status from client
  33. lightvalue = data;
  34. if (lightvalue != LED.readSync()) { //only change LED if status has changed
  35. LED.writeSync(lightvalue); //turn LED on or off
  36. }
  37. });
  38. });
  39.  
  40. process.on('SIGINT', function () { //on ctrl+c
  41. LED.writeSync(0); // Turn LED off
  42. LED.unexport(); // Unexport LED GPIO to free resources
  43. pushButton.unexport(); // Unexport Button GPIO to free resources
  44. process.exit(); //exit completely
  45. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement