Save wip...

This commit is contained in:
Gino D
2023-01-04 18:28:31 +01:00
parent 967b5b0f93
commit c44c5af856
2 changed files with 48 additions and 28 deletions

3
.picowatch Normal file
View File

@@ -0,0 +1,3 @@
DEVICE = 'COM5'
BAUDRATE = 115200
PROJECT_NAME = 'dist'

View File

@@ -33,10 +33,11 @@ import textwrap
import subprocess import subprocess
from serial import Serial from serial import Serial
from dotenv import dotenv_values
from typing import List, Optional, Tuple, Union from typing import List, Optional, Tuple, Union
BUFFER_SIZE: int = 126 BUFFER_SIZE: int = 256
class Tab(): class Tab():
@@ -156,7 +157,7 @@ class Pyboard(object):
except: except:
time.sleep(1) time.sleep(1)
else: else:
raise Exception(f'Failed to access {device}') raise Exception(f'Failed to access device: {device}')
def close(self): def close(self):
self.serial.close() self.serial.close()
@@ -341,7 +342,7 @@ class FileSystem(object):
sys.stdout.write(ubinascii.hexlify(result)) sys.stdout.write(ubinascii.hexlify(result))
""") """)
output = binascii.unhexlify(output) output = binascii.unhexlify(output)
return (output, self.checksum(filename, output)) return (output, self.checksum(filename, output))
def download(self, source: str, destination: str) -> str: def download(self, source: str, destination: str) -> str:
@@ -385,8 +386,7 @@ class FileSystem(object):
return checksum return checksum
def ls(self, dirname: str = '/') -> Tuple[int, List, str]: def ls(self, dirname: str = '/') -> Tuple[int, List, str]:
if not dirname.startswith('/'): dirname = dirname.strip('./').strip('/')
dirname = '/' + dirname
output = self.terminal(f""" output = self.terminal(f"""
try: try:
@@ -403,6 +403,8 @@ class FileSystem(object):
if not dirname.endswith("/"): if not dirname.endswith("/"):
dirname += "/" dirname += "/"
for t in os.ilistdir(dirname): for t in os.ilistdir(dirname):
if dirname.startswith('/'):
dirname = dirname[1:]
if t[1] == 0x4000: if t[1] == 0x4000:
e.append((dirname + t[0] + '/', -1)) e.append((dirname + t[0] + '/', -1))
e.extend(ls(dirname + t[0] + '/')) e.extend(ls(dirname + t[0] + '/'))
@@ -443,6 +445,8 @@ class FileSystem(object):
if not dirname.endswith("/"): if not dirname.endswith("/"):
dirname += "/" dirname += "/"
for t in os.ilistdir(dirname): for t in os.ilistdir(dirname):
if dirname.startswith('/'):
dirname = dirname[1:]
if t[1] == 0x4000: if t[1] == 0x4000:
e.append((dirname + t[0] + '/', -1)) e.append((dirname + t[0] + '/', -1))
e.extend(ls(dirname + t[0] + '/')) e.extend(ls(dirname + t[0] + '/'))
@@ -549,14 +553,17 @@ class Picowatch(object):
def __init__(self, pyboard: Pyboard, project_name: str = 'src'): def __init__(self, pyboard: Pyboard, project_name: str = 'src'):
self.filesystem = FileSystem(pyboard) self.filesystem = FileSystem(pyboard)
project_name = project_name.strip('./').strip('/') project_name = project_name.strip('./').strip('/')
if project_name == '/': if not project_name or project_name == '/':
raise Exception('Project name is incorrect!') raise Exception('Project name is incorrect, can not be empty or only a forward slash "/"!')
self.project_name = project_name.replace(os.sep, '/') self.project_name = project_name.replace(os.sep, '/')
self.project_dirname = os.path.join(os.getcwd(), self.project_name).replace(os.sep, '/') self.project_dirname = os.path.join(os.getcwd(), self.project_name).replace(os.sep, '/')
if not os.path.isdir(self.project_dirname):
raise Exception('Project is not a directory!')
signal.signal(signal.SIGINT, lambda a, b: self.interupt()) signal.signal(signal.SIGINT, lambda a, b: self.interupt())
def interupt(self): def interupt(self):
@@ -567,7 +574,7 @@ class Picowatch(object):
def listing(self, filepath: str = '/'): def listing(self, filepath: str = '/'):
filepath = filepath.strip('./') filepath = filepath.strip('./')
tab = Tab(4, 30, 15, 30) tab = Tab(4, 30, 15, 100)
tab.labels('[ ]', 'Filename', 'Size (kb)', 'Exception') tab.labels('[ ]', 'Filename', 'Size (kb)', 'Exception')
status, output, exception = self.filesystem.ls(filepath) status, output, exception = self.filesystem.ls(filepath)
@@ -576,7 +583,7 @@ class Picowatch(object):
if size == -1: if size == -1:
tab.print('[*]', filename, '-') tab.print('[*]', filename, '-')
else: else:
tab.print('[*]', filename, f'{size}b') tab.print('[*]', filename, f'{round(size / 1024, 2)} kb')
else: else:
tab.print('[?]', filepath, '', str(exception)) tab.print('[?]', filepath, '', str(exception))
@@ -601,9 +608,9 @@ class Picowatch(object):
elif os.path.exists(source): elif os.path.exists(source):
queue.append((source, filepath)) queue.append((source, filepath))
tab = Tab(4, 30, 15, 30) tab = Tab(4, 30, 15, 100)
tab.labels('[ ]', 'Filename', 'Checksum', 'Exception') tab.labels('[ ]', 'Filename', 'Checksum', 'Exception')
for source, destination in queue: for source, destination in queue:
destination = destination.strip('/') destination = destination.strip('/')
@@ -614,7 +621,7 @@ class Picowatch(object):
def download(self, filepath: str): def download(self, filepath: str):
filepath = filepath.strip('./').strip('/') filepath = filepath.strip('./').strip('/')
tab = Tab(4, 30, 15, 30) tab = Tab(4, 30, 15, 100)
tab.labels('', 'Filename', 'Checksum', 'Exception') tab.labels('', 'Filename', 'Checksum', 'Exception')
status, output, exception = self.filesystem.ls(filepath) status, output, exception = self.filesystem.ls(filepath)
@@ -624,9 +631,11 @@ class Picowatch(object):
os.makedirs(os.path.join(self.project_dirname, remote), 777, exist_ok=True) os.makedirs(os.path.join(self.project_dirname, remote), 777, exist_ok=True)
for remote, size in output: for remote, size in output:
destination = os.path.join(self.project_dirname, remote).replace(os.sep, '/')
if not size == -1: if not size == -1:
try: try:
tab.print('[↓]', remote, self.filesystem.download(remote, os.path.join(self.project_dirname, remote))) tab.print('[↓]', remote, self.filesystem.download(remote, destination))
except Exception as e: except Exception as e:
tab.print('[?]', remote, '', str(e)) tab.print('[?]', remote, '', str(e))
else: else:
@@ -634,7 +643,7 @@ class Picowatch(object):
def delete(self, filepath: str): def delete(self, filepath: str):
filepath = filepath.strip('./') filepath = filepath.strip('./')
tab = Tab(4, 30, 30) tab = Tab(4, 30, 100)
tab.labels('[ ]', 'Filename', 'Exception') tab.labels('[ ]', 'Filename', 'Exception')
status, output, exception = self.filesystem.rm(filepath) status, output, exception = self.filesystem.rm(filepath)
@@ -691,7 +700,7 @@ class Picowatch(object):
tab.print('[+]' if status == 1 else '[-]', filename) tab.print('[+]' if status == 1 else '[-]', filename)
def push(self): def push(self):
tab = Tab(4, 30, 15, 30) tab = Tab(4, 30, 15, 100)
tab.labels('[ ]', 'Filename', 'Checksum', 'Exception') tab.labels('[ ]', 'Filename', 'Checksum', 'Exception')
changes = self.status(return_output=True) changes = self.status(return_output=True)
@@ -743,19 +752,24 @@ class Picowatch(object):
print('Welcome to Picowatch Terminal') print('Welcome to Picowatch Terminal')
picowatch = False picowatch = False
while not picowatch: try:
print('-' * 30) env = dotenv_values('.picowatch')
device = input('Port: ').strip() picowatch = Picowatch(Pyboard(env["DEVICE"], env["BAUDRATE"]), env["PROJECT_NAME"])
baudrate = input('Baudrate (115200): ').strip() or 115200 print(f'Connected automatically to device: {env["DEVICE"]} at a baudrate of: {env["BAUDRATE"]}. Listening to project: ./{env["PROJECT_NAME"]}')
project_name = input('Project name (src): ').strip() or 'src' except:
while not picowatch:
print('-' * 50)
device = input('Port: ').strip()
baudrate = input('Baudrate (115200): ').strip() or 115200
project_name = input('Project name (src): ').strip() or 'src'
try:
picowatch = Picowatch(Pyboard(device, baudrate), project_name)
print('-' * 50)
print(f'Connected to device: {picowatch} at a baudrate of: {baudrate}. Listening to project: ./{project_name}')
except Exception as e:
print(str(e))
try:
picowatch = Picowatch(Pyboard(device, baudrate), project_name)
print(f'Connected to device: {device} at a baudrate of: {baudrate}. Listening to project: {project_name}')
print('-' * 30)
except Exception as e:
print(str(e))
picowatch.interupt() picowatch.interupt()
while True: while True:
@@ -766,6 +780,8 @@ while True:
match message.strip().split(' '): match message.strip().split(' '):
case ['exit']: case ['exit']:
sys.exit() sys.exit()
case ['help']:
print('TODO')
case ['reboot']: case ['reboot']:
picowatch.terminal('help()') picowatch.terminal('help()')
case ['ls' | 'list', *source]: case ['ls' | 'list', *source]:
@@ -785,6 +801,7 @@ while True:
case ['push']: case ['push']:
picowatch.push() picowatch.push()
case ['compile', filename]: case ['compile', filename]:
# https://pypi.org/project/mpy-cross/
pass pass
case ['install', package_name]: case ['install', package_name]:
pass pass