Advertisement
Guest User

Untitled

a guest
Feb 9th, 2016
58
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.22 KB | None | 0 0
  1. // console.log(process.argv);
  2.  
  3. var port = parseInt(process.argv[2]);
  4. if ( !port || isNaN(port) ) {
  5. console.log('\nPort arg must be int.\n\n');
  6. process.exit();
  7. }
  8.  
  9. var status = [0, 0, 0, 0, 0, 0, 0, 0];
  10.  
  11. require('net').createServer(function(socket) {
  12.  
  13. console.log('\nNew connection...');
  14. socket.setEncoding('utf8');
  15.  
  16. function writeStatus() {
  17. var dec = 0;
  18. status.forEach(function(on, i) {
  19. dec += on * Math.pow(2, i);
  20. });
  21.  
  22. socket.write(String.fromCharCode(dec));
  23. }
  24.  
  25. socket.on('data', function(data) {
  26. var cmd = data.charCodeAt(0);
  27. console.log('Incoming data...', cmd);
  28.  
  29. if ( cmd == 91 ) {
  30. // get status
  31. writeStatus();
  32. }
  33.  
  34. else if ( cmd == 100 ) {
  35. // all on
  36. status.forEach(function(on, i) {
  37. status[i] = 1;
  38. });
  39. writeStatus();
  40. }
  41. else if ( cmd >= 101 && cmd <= 108 ) {
  42. // one on
  43. var relayIndex = cmd - 100 - 1;
  44. status[relayIndex] = 1;
  45. writeStatus();
  46. }
  47.  
  48. else if ( cmd == 110 ) {
  49. // all off
  50. status.forEach(function(on, i) {
  51. status[i] = 0;
  52. });
  53. writeStatus();
  54. }
  55. else if ( cmd >= 111 && cmd <= 118 ) {
  56. // one off
  57. var relayIndex = cmd - 110 - 1;
  58. status[relayIndex] = 0;
  59. writeStatus();
  60. }
  61.  
  62. console.log('New status:', status.join(''));
  63. });
  64.  
  65. }).listen(port);
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement