############################## relay_board.rb achase@mbari.org #################
#
# Control the (temporary) relay board for switching power on the rover
#
################################################################################

require 'rover_environment'
require 'posix/serialport'

class RelayBoard
  attr_reader :serial_port

  def initialize config, portname='/dev/com1'
    unless config
      config = SerialPort::Configuration.default
      config.baud = 9600
    end
    @serial_port = Posix::SerialPort.new portname, config
  end

  def valid_relay?(relay_num)
    if relay_num && relay_num > -1 && relay_num < 9
      true
    else
      false
    end
  end

  def turn_relay_on(relay_num)
    if !valid_relay?(relay_num)
      puts "invalid relay number"
      return
    end
    num_bytes = @serial_port.write("N#{relay_num}\r")
    read = @serial_port.read(num_bytes)
    #clear out the newline and the propmpt from the buffer
    read = @serial_port.read(2)
  end

  def turn_relay_off(relay_num)
    if !valid_relay?(relay_num)
      puts "invalid relay number"
      return
    end
    num_bytes = @serial_port.write("F#{relay_num}\r")
    read = @serial_port.read(num_bytes)
    #clear out the newline and the propmpt from the buffer
    read = @serial_port.read(2)
  end

  def get_relay_status(relay_num)
    if !valid_relay?(relay_num)
      puts "invalid relay number"
      return
    end
    num_bytes = @s.write("S#{relay_num}\r")
    #+1 is to include the newline
    line = @serial_port.read(num_bytes + 1)
    if(relay_num == 0)
      line = @serial_port.read(2)
    else
      line = @serial_port.read(1)
    end
    line 
  end
end

#raise "USAGE: modem.rb <SERIALPORT>" if !ARGV[0]
#port = ARGV[0]
#board = RelayBoard.new nil, port
#board.turn_relay_on(1)
#puts "status = #{board.get_relay_status(1)}"
#board.turn_relay_off(1)
#puts "status = #{board.get_relay_status(1)}"
#board.close
