# "Driver" to talk to the HackaDaySuperConBadge6 assembler
# This is required due to the Serial bug, and only regulates the timing
# It does no processing of the data

from serial import Serial
from sys import argv
from time import sleep


# Filename is required as arg1. Input is <name>.asm and output is <name>.hex
FI = open(argv[1]+".asm","r") # this content is sent to badge
FO = open(argv[1]+".hex","wb") # badge output writte (binary) to this file
 
#open badge
Badge = Serial('COM6',9600,timeout=1)

# V01 interface.
Line = FI.readline() # the whole program is one line
FI.close()
print(" - RUN Badge now -")
# expect header
Badge.timeout=10 # Longer timeout, to have chance to push button
Buf = Badge.read(size=6)
if len(Buf)!=6:
  print("Failure of header")
  exit()
Badge.timeout=5
print(F"Header x{Buf.hex()} ")
FO.write(Buf)
# First 4 chars sent, expect 2 bytes return
print(F"Length \"{Line[0:4]} ",end="")
Badge.write(Line[0:4].encode())
Buf = Badge.read(size=2)
print(F" became x{Buf.hex()} ")
FO.write(Buf)
# Loop doing 3 chars to 2 bytes, with a pause
P = 4 ; Len = 0
while P < len(Line):
  sleep(0.01)
  Badge.write(Line[P:P+3].encode())
  Buf = Badge.read(size=2)
  print(F"Code \"{Line[P:P+3]} became x{Buf.hex()}")
  FO.write(Buf)
  P += 3
  Len += 1
#Terminate and get 2 byte checksum
print(F"{Len} codes converted.\nSend EOT ",end="")
Badge.write(b'\004')
Buf = Badge.read(size=2)
print(F" got checksum x{Buf.hex()}")
FO.write(Buf)
# Done
FO.close()
Badge.close()
if int(Line[0:4],16)!=Len :
  print("Length mismatch")
