#!/usr/bin/env python
from SocketServer import StreamRequestHandler, TCPServer
import subprocess
import encodings
import threading
import time
import sys

def sim_format(lld, data):
  return '%s\t%s\n' % (lld , encodings.codecs.encode(data, 'hex'))

class SIMIO(StreamRequestHandler):
  def handle(self):
    print '[SIMIO] CONNECT'

    button_thread = threading.Thread(target=self.simulate_button)
    button_thread.setDaemon(True)
    button_thread.start()

    for line in self.rfile:
      header, code = line.strip().split('\t', 1)
      data = code.decode('hex')
      sys.stdout.write('[%s] <- %s' % (header, data))

  def simulate_button(self):
    sys.stdin.readline()
    print '[%s] -> %r' % ('EXT_IO', '\x00')
    msg = sim_format('EXT_IO', '\x00')
    self.wfile.write(msg)

# prevent bind errors on relaunch
TCPServer.allow_reuse_address = True

# listen for simio connections
simio = TCPServer(('localhost', 27000), SIMIO)
simio_thread = threading.Thread(target=simio.serve_forever)
simio_thread.setDaemon(True)
simio_thread.start()

# spawn the unit test
subprocess.check_call(['./build/ch.elf'])
# subprocess.check_call(['gdb', './build/ch.elf'])
