import Connection
import time


A_ = ord("A") # Loopback 
B_ = ord("B") # Loopback
V_ = ord("V") # Query version 

COMPORT = 'Com30'

###################################################
def waitForReply(conn, expect):
  for _ in range(10):
    rc = conn.read_raw(len(expect))
    if rc == expect:
      return True
  print (f"Expected {expect} got {rc}")
  print ("Timeout waiting for reply")  
  return False  

###################################################
def LoopbackTest(conn):
  print("Loopback Test")
  ok = True
  conn.read_raw()
  tstart = time.perf_counter()
  for i in range(1000):
    if i % 100 == 0:
      print(".", end= "")
    conn.write_raw(bytes([A_,B_,A_,B_,B_,A_,A_,B_,A_,B_,B_,A_,A_,B_,A_,B_,B_,A_,A_,B_,A_,B_,B_,A_,A_,B_,A_,B_,B_,A_,A_,B_,A_,B_,B_,A_])) 
    rc = conn.read_raw(36)
    if rc != b'ABABBAABABBAABABBAABABBAABABBAABABBA':
      ok = False
      break
  elapsed = time.perf_counter() - tstart 
  bits = (i+1) * 36* 10
  print(f"\nafter {bits} bits in {int(elapsed)} s   = avg {int(bits/elapsed)} bps, received: <{rc}>")
  if ok:
    print("\nPass")
  else:
    print("FAIL")  


###################################################
def GetVersion(conn):
  cmdlist = [V_]      
  conn.write_raw(bytes(cmdlist)) 
  rc = conn.read_raw()
  return chr(rc[1]) 


if  __name__ == "__main__":
  _conn = Connection.CdcConnection() 
  _conn.open(COMPORT)

  LoopbackTest(_conn)
  print(GetVersion(_conn))



  _conn.close()
