#!/usr/bin/env ruby


# UART test
#
# This test is pretty simple, just a UART smoke test, using
# the debug callback on the quad

GEAR_ON = 170800
GEAR_OFF = 118300

GEAR = "virt-quad-fifos/pwm-input-gear"
UART_RX = "virt-quad-fifos/uart-rx"
UART_TX = "virt-quad-fifos/uart-tx"

require 'test/unit/assertions'
require 'thread'
include Test::Unit::Assertions

puts("Setting up...")

script_dir = File.expand_path(File.dirname(__FILE__))
bin_dir = script_dir + "/../../bin/"
Dir.chdir(bin_dir)

sleep 1

# Start virtual quad
quad = Process.spawn("./virt-quad")

sleep 1

#################
#  Begin Tests
#################

begin

  puts("Beginning tests...")

  # Flip gear on
  File.write(GEAR, GEAR_ON)
  sleep 0.015

  for j in 1..10
    # Send a debug command
    File.write(UART_RX, [0xBE, 1, 0, 0, 0, 0, 0, 0xBF].pack("CCCCCCCC"))

    fifo = File.open(UART_TX)
    msg = []
    for i in 1..7
      sleep 0.010
      msg.push(fifo.read(1))
    end
    length = msg[5..7].join().unpack("S")[0]
    msg = []
    for i in 1..length
      sleep 0.010
      msg.push(fifo.read(1))
    end
    fifo.close

    puts msg.join()
    assert_equal(msg.join().force_encoding("UTF-8"), "Packets received: #{j}")
  end

  puts "Basic UART test passed."

ensure

  Process.kill(9, quad)

end