Last active
October 2, 2022 18:20
-
-
Save pepijndevos/9d55dd4b53f630186545fa6361fc229a to your computer and use it in GitHub Desktop.
Upload code to the Robot Inventor hub
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import base64 | |
import json | |
import sys | |
import serial | |
import random | |
import os | |
if len(sys.argv) != 4: | |
print(f"Usage\n{sys.argv[1]} tty code.py slot") | |
exit() | |
_, tty, path, slot = sys.argv | |
hub = serial.Serial(tty, 115200) | |
def waitfor(cmdid): | |
while True: | |
try: | |
dat = json.loads(hub.read_until(b'\r')) | |
except json.JSONDecodeError as e: | |
print(e) | |
continue | |
print(dat) | |
if dat.get('i') == cmd_id: | |
return dat | |
### start_write_program | |
stat = os.stat(path) | |
cmd_id = base64.b64encode(random.randbytes(3)).decode() | |
project_id = base64.b64encode(random.randbytes(9)).decode() | |
dat = json.dumps({ | |
"i": cmd_id, | |
"m": "start_write_program", | |
"p": { | |
"meta": { | |
"created": int(stat.st_ctime), | |
"modified": int(stat.st_mtime), | |
"project_id": project_id, | |
"name": base64.b64encode(path.encode()).decode(), | |
"type": "python"}, | |
"size": stat.st_size, | |
"slotid": int(slot)}}) | |
print(dat) | |
hub.write(dat.encode() + b'\r') | |
dat = waitfor(cmd_id) | |
blocksize = dat['r']['blocksize'] | |
transferid = dat['r']['transferid'] | |
### write_package | |
with open(path, 'rb') as f: | |
for chunk in iter(lambda:f.read(blocksize), b''): | |
enc = base64.b64encode(chunk).decode() | |
cmd_id = base64.b64encode(random.randbytes(3)).decode() | |
dat = json.dumps({ | |
"i": cmd_id, | |
"m": "write_package", | |
"p": {"data": enc, "transferid": transferid} | |
}) | |
print(dat) | |
hub.write(dat.encode() + b'\r') | |
dat = waitfor(cmd_id) | |
# wait for error | |
while True: | |
try: | |
dat = json.loads(hub.read_until(b'\r')) | |
except json.JSONDecodeError as e: | |
print(e) | |
continue | |
print(dat) | |
if dat.get('m') in {"runtime_error", "user_program_error"}: | |
version, key, py, err, unk = dat['p'] | |
print(base64.b64decode(err).decode()) | |
break |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment