require '../Win32Serial'

class Win32Serial
  def read_line(params = {} )
    unless params[:max_reads]
      params[:max_reads] = 100
    end
    unless params[:end_line]
      params[:end_line] = "\r\n"
    end
    max_reads, end_line = params.values_at(:max_reads, :end_line)
    count = 0
    line = ""
    char = read(1)
    line << char
    while line[-2..-1] != end_line && count < max_reads
      char = read(1)
      line << char
      count += 1
    end
    line
  end

  def flush_buffer
    puts "flushing..."
    char = " "
    while char && char[0]
      char = read(1)
    end
    puts "done flushing"
  end
end

class AcmCurrentMeter 
  def open(port)
    @s = Win32Serial.new
    @s.open(port)
    @s.config(9600, 8, Win32Serial::NOPARITY, Win32Serial::ONESTOPBIT)
    #timeouts are: read_interval, read_mult, read_const, write_mult, write_const
    @s.timeouts(20, 10, 100, 10, 100)
  end 

  def test
    puts "going to run mode"
    @s.write("***R\n")
    sleep(10)
    @s.flush_buffer
    #after going into run mode, instrument will take awhile to start returning
    #data
    @s.write("\n")
    line = @s.read_line
    puts "line read: #{line}"
    @s.write("\n")
    line = @s.read_line
    puts "line read: #{line}"
  end

  def close
    @s.close
  end
end

raise "USAGE: 2D_acm_current_meter.rb <COMPORT>" if !ARGV[0]
port = ARGV[0]
meter = AcmCurrentMeter.new
meter.open(port)
meter.test
meter.close
