Advertisement
Guest User

doorbell.js

a guest
Jul 12th, 2013
500
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. var gpio = require("gpio");
  2. var net = require('net');
  3.  
  4. var host = '192.168.1.101';
  5. var port = 5000;
  6. var client = false;
  7. var canRing = true;
  8.  
  9.  
  10. var gpio4 = gpio.export(4, {
  11.   direction: 'in',
  12.  
  13.   interval: 200,
  14.  
  15.   ready: function() {
  16.     console.log("Initialized gpio pin4.")
  17.     net.createServer(function (sock) {
  18.       console.log('Client connected!');
  19.       client = sock;
  20.       if (canRing == false) {
  21.         // should practically never happen, but whatever:
  22.         alertClient();
  23.       }
  24.     }).listen(port, host);
  25.     console.log('Server listening...');
  26.   }
  27. });
  28.  
  29. gpio4.on("change", function(val) {
  30.   if (0 == val) {
  31.     // pin 4 connected to ground:
  32.     onDoorbellPress();
  33.   }
  34. });
  35.  
  36. function alertClient() {
  37.   console.log('Alerting client...');
  38.   client.write('RINGRING\n');
  39.   client.on('data', function(data) {
  40.     console.log('Received OK message. Closing connection.');
  41.     sock.destroy();
  42.   });
  43.   client.on('error', function (err) {
  44.     console.log('Error alerting client ' + client + ':' + err);
  45.     client = false;
  46.   });
  47.   console.log('Message sent.');
  48. }
  49.  
  50. function onDoorbellPress() {
  51.     if (canRing) {
  52.   canRing = false;
  53.   console.log("RINGRING");
  54.   // prevent multiple alerts within the same second:
  55.   setTimeout(function onTimer() {
  56.       canRing = true;
  57.     }, 1000);
  58.       if (client) {
  59.         alertClient();
  60.       } else {
  61.         console.log('No client connected.');
  62.       }
  63.   }
  64. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement