Home

Up: Smart Plug

Previous: Smart Plug Prototype 0.4

Smart Plug Prototype 0.5

Here we finally do the real thing. We wire up a GPIO pin and a ground pin to a commercial relay1.

Using the control protocol written for the Beaglebone’s onboard LEDs (and pointing the code to a different pin), we can now fully control a lamp remotely. We now have a usable prototype; however, this is only a demo of controlled, high-voltage switching. There are a couple more steps before we have a full proof-of-concept. The next is controlling over the home network, not over a USB network.

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

// controlling different GPIO pin for relay
var LEDS = ['P8_7'];

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');
});

  1. https://www.sparkfun.com/products/14236 ↩︎

Next: Smart Plug Prototype 0.6

Creative Commons License