from machine import UART
from uart_repl import UartRepl
u = UART(2, 115200)
r = UartRepl(u)
r.enter_raw_repl()
while True:
cmd = input('B# ') # 在 A 端敲命令
if cmd == 'exit':
break
print( r.exec_(cmd) )
r.exit_raw_repl()
四、功能 2:把 B 的文件拉回 A
思路:
远端分块读取 → base64 → print;
本地收到后解码 → 写 SD/Flash;
最后远端发一行 ###EOF### 当结束标记。
def pull(remote, local, chunk=512):
script = f'''
import ubinascii, gc
with open('{remote}','rb') as f:
while 1:
blk=f.read({chunk})
if not blk:break
print(ubinascii.b2a_base64(blk),end='')
print('###EOF###')
'''
r.enter_raw_repl()
data = r.exec_(script)
r.exit_raw_repl()
# 本地还原
with open(local,'wb') as fout:
for line in data.splitlines():
if line=='###EOF###':break
fout.write(binascii.a2b_base64(line))
print('pull done', local)
用例:
>>> pull('main.py', '/sd/main_remote.py')
五、功能 3:把 A 的文件推到 B
推之前先读本地文件 → base64 分块 → 发脚本 → 远端解码写盘。
def push(local, remote, chunk=512):
import ubinascii
r.enter_raw_repl()
with open(local,'rb') as f:
while 1:
blk = f.read(chunk)
if not blk: break
b64 = binascii.b2a_base64(blk).strip()
r.exec_(f"""
import ubinascii, gc
with open('{remote}','ab') as fo:
fo.write(ubinascii.a2b_base64({repr(b64)}))
""")
# 文件开头先 truncate
r.exec_(f"import uos; uos.remove('{remote}') if '{remote}' in uos.listdir() else 0")
r.exec_(f"import uos; uos.rename('{remote}.tmp','{remote}')") # 原子替换
r.exit_raw_repl()
print('push done', remote)
用例:
>>> push('/sd/new_boot.py', 'boot.py')
六、做成 A 上的“远程文件管理”命令行
把上面函数再包一层交互:
if __name__ == '__main__':
import sys, machine, uart_repl
u = machine.UART(2, 115200)
r = uart_repl.UartRepl(u)
cmd = sys.argv[1]
if cmd == 'pull':
pull(sys.argv[2], sys.argv[3])
elif cmd == 'push':
push(sys.argv[2], sys.argv[3])
elif cmd == 'sh':
shell_mode(r) # 前面 while True 那个函数