ocoge/lib/pybtool.py

49 lines
1.1 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/usr/bin/env python3
import sys
import pyboard
import serial.tools.list_ports
args = sys.argv
# port = args[1]
mode = args[1]
src = sys.stdin.read()
dest = 'main.py'
chunk_size=256
# USBシリアルポート自動認識アルファベット順で最初に見つけたポートを使用
for p in sorted(serial.tools.list_ports.comports()):
if p.hwid.startswith('USB'):
port = p.device
print ('Device found: ' + port)
break
else:
print('No devices found.', file=sys.stderr)
sys.exit(1)
pyb = pyboard.Pyboard(port)
pyb.enter_raw_repl(False)
if mode == 'r':
print('Run code', flush=True)
pyb.exec_raw_no_follow(src)
elif mode == 'd':
print('Deploy code', flush=True)
pyb.exec("f=open('%s','wb')\nw=f.write" % dest)
pos = 0
while True:
data = src[pos:pos+chunk_size]
if not data:
break
if sys.version_info < (3,):
pyb.exec("w(b" + repr(data) + ")")
else:
pyb.exec("w(" + repr(data) + ")")
pos += chunk_size
pyb.exec("f.close()")
pyb.exit_raw_repl()
pyb.close()