Home

Up: Smart Plug

Previous: Smart Plug Prototype 0.3

Smart Plug Prototype 0.4

In this verison, we've now created a server that can open a duplex communication channel with a client. The server will send update the client on its state every 10 seconds, or any time its state changes. State is represented as a UTF-8 encoded 0 (off) or 1 (on) byte. In addition to the server updates, the client can at any point send a 0 or a 1 to the server, which will change the state of the light and update all other connected clients.

This time we're using Netcat instead of Telnet. Our interface has gotten a bit more complex with the server, since it's now listening for commands, not just connections. Netcat is a little newer and more modern than Telnet. The material difference in our case is that Telnet always sends \r\n line endings, but we only want \n.

var b = require('bonescript');
var net = require('net');

var LEDS = [
  'USR0',
  'USR1',
  'USR2',
  'USR3'
];
var open_sockets = [];
var state = b.HIGH;
function setState(new_state) {
  if (new_state !== state) {
    state = new_state;
    LEDS.forEach(function (LED) {
      b.pinMode(LED, b.OUTPUT);
      b.digitalWrite(LED, state);
    });
    writeStateAllSockets();
    return true;
  } else {
    return false;
  }
}
setState(b.LOW);
function writeState(socket) {
  socket.write(state + '\n');
}
function writeStateAllSockets() {
  open_sockets.forEach(writeState);
}
setInterval(writeStateAllSockets, 10000);
var server = net.createServer(function (socket) {
  writeState(socket);  
  open_sockets.push(socket);
  socket.on('end', function () {
    open_sockets = open_sockets.filter(function (remove_socket) {
      return remove_socket !== socket;
    });
  });
  socket.on('error', function (error) {
    console.log('error', error);
  });
  socket.on('data', function (data) {
    var command_character = data.slice(0, 1);
    var ascii_signal = parseInt(command_character.toString('ascii'), 10);
    var state_changed = false;
    if (ascii_signal === 1) {
      state_changed = setState(b.HIGH);
    } else if (ascii_signal === 0) {
      state_changed = setState(b.LOW);
    } else {
      socket.write('!\n');
      return;
    }
    if (!state_changed) {
      writeState(socket);
    }
  });
});
server.listen(9999, function () {
  console.log('Ready for commands');
});

This is pretty much where the protocol needs to be for now. We have full control, and can monitor its state in real time. The next step is to connect this to a real, high-voltage application.

Next: Smart Plug Prototype 0.5

Creative Commons License