require "socket"

class Tello
  def initialize(host="192.168.10.1", port=8889, bind=9000)
    @udps = UDPSocket.open
    @sockaddr = Socket.pack_sockaddr_in(port, host)
    @udps.bind('0.0.0.0', bind)
    @log = []

    @th = Thread.start do
      loop do
        begin
          sleep(0.1)
          #puts "#   response #{@udps.recv(1518)}"
          @udps.recv(1518)
        rescue StandardError => e
          puts "#   error #{e.message}"
        end
      end
    end
    @t2 = Thread.start do
      @stateudp = UDPSocket.open
      @stateudp.bind('0.0.0.0', 8890)
      loop do
        l = @stateudp.recv(65535)
        @status = l if l && l>""
        sleep 0.1
      end
    end
  end

  def close
    # puts '# close Tello'
    @udps.send('land', 0, @sockaddr)
    Thread.kill(@th)
    Thread.kill(@t2)
    @udps.close
    @stateudp.close
  end

  def send_command(message)
    # puts "# send #{message}"
    @udps.send(message, 0, @sockaddr)
  end
  def getlog
    @log.shift
  end
  def getstatus
    @status
  end
end

if __FILE__ == $0 then
  tello = Tello.new
  tello.send_command('command')
  tello.send_command('takeoff')
  sleep(3)
  tello.send_command('land')
  tello.close
end
