#!/usr/bin/env python3 import os import sys import struct import serial import subprocess def eprint(*args, **kargs): print(*args, file=sys.stderr, **kargs) def flash(): pipe = subprocess.PIPE p = subprocess.Popen(['platformio', 'run', '-e', 'uno', '--target', 'upload'], stdout=sys.stderr, stdin=pipe) stdout, stderr = p.communicate("") def get_serial(): import serial.tools.list_ports ports = serial.tools.list_ports.comports() devices = [ p.device for p in ports ] devices.sort() return devices[-1] def main(argv): eprint(argv[0]) script_dir = os.path.split(argv[0])[0] if len(script_dir) > 0: os.chdir(script_dir) flash() dev = get_serial() ser = serial.Serial(dev, baudrate=115200, timeout=5) def uart_read(): r = ser.read(1) if len(r) != 1: raise Exception("Serial read error") return r[0] def uart_write(c): b = struct.pack("B", c) r = ser.write(b) if r != len(b): raise Exception("Serial write error") return r def uart_recvframe(): while 1: tag_old = 0 tag = 0xf3 while tag_old != 0xf3 or tag != 0xf9: tag_old = tag tag = uart_read() tag_old = tag l = uart_read() if l & 0x80: l &= 0x7f l |= uart_read() << 7 fcs = 0 buf = [] for i in range(l): info = uart_read() buf.append(info) fcs = (fcs + info) & 0xff fcs = (fcs + uart_read()) & 0xff tag = uart_read() if fcs == 0xff: if tag == 0xf3: buf = bytes(buf) if len(buf) >= 1 and buf[0] == 0xde: sys.stderr.buffer.write(buf[1:]) sys.stderr.flush() else: return buf def uart_sendframe(buf): uart_write(0xf9) len_ind_0 = 0xff & len(buf) len_ind_1 = 0xff & (len(buf) >> 7) if len(buf) < 128: uart_write(len_ind_0) else: uart_write(len_ind_0 | 0x80) uart_write(len_ind_1) fcs = 0 for i in range(len(buf)): info = buf[i] fcs = (fcs + info) & 0xff uart_write(buf[i]) fcs = (0xff - fcs) & 0xff uart_write(fcs) uart_write(0xf3) def stdin_read(n): b = sys.stdin.buffer.read(n) if len(b) != n: sys.exit(1) return b def stdin_readvar(): l = stdin_read(4) (l, ) = struct.unpack("