var Board = require("../lib/firmata").Board;
var board = new Board("/dev/tty.usbmodem1421");

board.on("ready", function() {
  var SW_SERIAL0 = board.SERIAL_PORT_IDs.SW_SERIAL0;
  var last = 0;

  board.serialConfig({
    portId: SW_SERIAL0,
    baud: 9600,
    bytesToRead: 0,
    rxPin: 10,
    txPin: 11
  });

  board.analogRead(0, function(value) {
    var pulse = scale(value, 0, 1023, 1000, 2000) | 0;

    if (last !== pulse) {
      console.log(pulse);
      position(0, pulse);
      // position(1, pulse);
    }
    last = pulse;
  });

  function position(channel, pulse) {
    var target = pulse < 4000 ? pulse * 4 : pulse;

    var data = [
      0x84,
      channel,
      target & 0x7F,
      (target >> 7) & 0x7F
    ];

    board.serialWrite(SW_SERIAL0, data);
  }

  position(1, 1500);
});

function scale(value, fromLow, fromHigh, toLow, toHigh) {
  return (value - fromLow) * (toHigh - toLow) /
    (fromHigh - fromLow) + toLow;
}
