#!/usr/bin/env python3

import os.path
import serial
import time
import sys

CHUNK_SIZE=8
LISP='xfer.lsp'

def chunkstring(string, length):
    return (string[0+i:length+i] for i in range(0, len(string), length))

def chunkfile(path):
    with open(path, 'rt') as source:
        return list(chunkstring(source.read(), CHUNK_SIZE))

def readfile(path):
    with open(path, 'rt') as source:
        return source.read()

def select_candidate(clst):
    for cand in clst:
        if os.path.exists(cand):
            print(f'[+] {cand}')
            return cand
    return None

candidates = ['/dev/ttyUSB0', '/dev/ttyACM0', '/dev/tty.usbmodem2101']
candidate = select_candidate(candidates)
seriell = serial.Serial(port=candidate, baudrate=9600)
if len(sys.argv) > 1:
    paths = sys.argv[1:]
else:
    paths = [LISP,]
for path in paths:
    chunked = readfile(path)
    for chunk in chunked:
        print(chunk)
        seriell.write(chunk.encode('ascii'))
        time.sleep(0.1)

