mirror of
https://github.com/RfidResearchGroup/ChameleonUltra.git
synced 2026-04-01 01:35:47 +00:00
Switched to function for color stings
This commit is contained in:
@@ -10,7 +10,7 @@ import pathlib
|
||||
import prompt_toolkit
|
||||
from prompt_toolkit.formatted_text import ANSI
|
||||
from prompt_toolkit.history import FileHistory
|
||||
from chameleon_utils import CR, CG, CY, C0
|
||||
from chameleon_utils import CR, CG, CY, color_string
|
||||
|
||||
ULTRA = r"""
|
||||
╦ ╦╦ ╔╦╗╦═╗╔═╗
|
||||
@@ -68,10 +68,12 @@ class ChameleonCLI:
|
||||
|
||||
:return: current cmd prompt
|
||||
"""
|
||||
device_string = f"{CG}USB" if self.device_com.isOpen(
|
||||
) else f"{CR}Offline"
|
||||
status = f"[{device_string}{C0}] chameleon --> "
|
||||
return status
|
||||
if device_com.isOpen():
|
||||
status = color_string((CG, 'USB'))
|
||||
else:
|
||||
status = color_string((CR, 'Offline'))
|
||||
|
||||
return ANSI(f"[{status}] chameleon --> ")
|
||||
|
||||
@staticmethod
|
||||
def print_banner():
|
||||
@@ -80,7 +82,7 @@ class ChameleonCLI:
|
||||
|
||||
:return:
|
||||
"""
|
||||
print(f"{CY}{BANNER}{C0}")
|
||||
print(color_string((CY, BANNER)))
|
||||
|
||||
def exec_cmd(self, cmd_str):
|
||||
if cmd_str == '':
|
||||
@@ -102,7 +104,7 @@ class ChameleonCLI:
|
||||
# Found tree node is a group without an implementation, print children
|
||||
print("".ljust(18, "-") + "".ljust(10) + "".ljust(30, "-"))
|
||||
for child in tree_node.children:
|
||||
cmd_title = f"{CG}{child.name}{C0}"
|
||||
cmd_title = color_string((CG, child.name))
|
||||
if not child.cls:
|
||||
help_line = (f" - {cmd_title}".ljust(37)) + f"{{ {child.help_text}... }}"
|
||||
else:
|
||||
@@ -123,7 +125,7 @@ class ChameleonCLI:
|
||||
return
|
||||
except chameleon_utils.ArgsParserError as e:
|
||||
args.print_help()
|
||||
print(f'{CY}'+str(e).strip()+f'{C0}', end="\n\n")
|
||||
print(color_string((CY, str(e).strip())))
|
||||
return
|
||||
except chameleon_utils.ParserExitIntercept:
|
||||
# don't exit process.
|
||||
@@ -144,10 +146,9 @@ class ChameleonCLI:
|
||||
raise error
|
||||
|
||||
except (chameleon_utils.UnexpectedResponseError, chameleon_utils.ArgsParserError) as e:
|
||||
print(f"{CR}{str(e)}{C0}")
|
||||
print(color_string((CR, str(e))))
|
||||
except Exception:
|
||||
print(
|
||||
f"CLI exception: {CR}{traceback.format_exc()}{C0}")
|
||||
print(f"CLI exception: {color_string((CR, traceback.format_exc()))}")
|
||||
|
||||
def startCLI(self):
|
||||
"""
|
||||
@@ -169,7 +170,7 @@ class ChameleonCLI:
|
||||
# wait user input
|
||||
try:
|
||||
cmd_str = self.session.prompt(
|
||||
ANSI(self.get_prompt())).strip()
|
||||
self.get_prompt()).strip()
|
||||
cmd_strs = cmd_str.replace(
|
||||
"\r\n", "\n").replace("\r", "\n").split("\n")
|
||||
cmd_str = cmd_strs.pop(0)
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -4,7 +4,7 @@ import threading
|
||||
import time
|
||||
import serial
|
||||
from typing import Union
|
||||
from chameleon_utils import CR, CG, CC, CY, C0
|
||||
from chameleon_utils import CR, CG, CC, CY, C0, color_string
|
||||
from chameleon_enum import Command, Status
|
||||
|
||||
# each thread is waiting for its data for 100 ms before looping again
|
||||
@@ -213,13 +213,16 @@ class ChameleonCom:
|
||||
try:
|
||||
status_string = str(Status(data_status))
|
||||
if data_status == Status.SUCCESS:
|
||||
status_string = f'{CG}{status_string:30}{C0}'
|
||||
status_string = color_string((CG, status_string.ljust(30)))
|
||||
else:
|
||||
status_string = f'{CR}{status_string:30}{C0}'
|
||||
status_string = color_string((CR, status_string.ljust(30)))
|
||||
except ValueError:
|
||||
status_string = f"{CR}{data_status:30x}{C0}"
|
||||
print(f'<= {CC}{command_string:40}{C0}{status_string}'
|
||||
f'{CY}{data_response.hex() if data_response is not None else ""}{C0}')
|
||||
status_string = color_string((CR, f"{data_status:30x}"))
|
||||
response = data_response.hex() if data_response is not None else ""
|
||||
print(f"<={color_string((CC, command_string.ljust(40)),
|
||||
(C0, status_string),
|
||||
(CY, response))}"
|
||||
)
|
||||
if data_cmd in self.wait_response_map:
|
||||
# call processor
|
||||
if 'callback' in self.wait_response_map[data_cmd]:
|
||||
@@ -341,8 +344,8 @@ class ChameleonCom:
|
||||
except ValueError:
|
||||
command_name = "(UNKNOWN)"
|
||||
cmd_string = f'{cmd:4} {command_name}{f"[{status:04x}]" if status != 0 else ""}'
|
||||
print(f'=> {CC}{cmd_string:40}{C0}'
|
||||
f'{CY}{data.hex() if data is not None else ""}{C0}')
|
||||
hexdata = data.hex() if data is not None else ""
|
||||
print(f"<={color_string((CC, cmd_string.ljust(40)), (CY, hexdata))}")
|
||||
data_frame = self.make_data_frame_bytes(cmd, data, status)
|
||||
task = {'cmd': cmd, 'frame': data_frame, 'timeout': timeout, 'close': close}
|
||||
if callable(callback):
|
||||
|
||||
@@ -66,16 +66,16 @@ class ArgumentParserNoExit(argparse.ArgumentParser):
|
||||
Colorize argparse help
|
||||
"""
|
||||
print("-" * 80)
|
||||
print(f"{CR}{self.prog}{C0}\n")
|
||||
print(color_string((CR, self.prog)))
|
||||
lines = self.format_help().splitlines()
|
||||
usage = lines[:lines.index('')]
|
||||
assert usage[0].startswith('usage:')
|
||||
usage[0] = usage[0].replace('usage:', f'{CG}usage:{C0}\n ')
|
||||
usage[0] = usage[0].replace(self.prog, f'{CR}{self.prog}{C0}')
|
||||
usage[0] = usage[0].replace('usage:', f'{color_string((CG, "usage:"))}\n ')
|
||||
usage[0] = usage[0].replace(self.prog, color_string((CR, self.prog)))
|
||||
usage = [usage[0]] + [x[4:] for x in usage[1:]] + ['']
|
||||
lines = lines[lines.index('')+1:]
|
||||
desc = lines[:lines.index('')]
|
||||
print(f'{CC}'+'\n'.join(desc)+f'{C0}\n')
|
||||
print(color_string((CC, "\n".join(desc))))
|
||||
print('\n'.join(usage))
|
||||
lines = lines[lines.index('')+1:]
|
||||
if '' in lines:
|
||||
@@ -86,7 +86,7 @@ class ArgumentParserNoExit(argparse.ArgumentParser):
|
||||
lines = []
|
||||
if len(options) > 0 and options[0].strip() == 'positional arguments:':
|
||||
positional_args = options
|
||||
positional_args[0] = positional_args[0].replace('positional arguments:', f'{CG}positional arguments:{C0}')
|
||||
positional_args[0] = positional_args[0].replace('positional arguments:', color_string((CG, "positional arguments:")))
|
||||
if len(positional_args) > 1:
|
||||
positional_args.append('')
|
||||
print('\n'.join(positional_args))
|
||||
@@ -99,13 +99,13 @@ class ArgumentParserNoExit(argparse.ArgumentParser):
|
||||
if len(options) > 0:
|
||||
# 2 variants depending on Python version(?)
|
||||
assert options[0].strip() in ['options:', 'optional arguments:']
|
||||
options[0] = options[0].replace('options:', f'{CG}options:{C0}')
|
||||
options[0] = options[0].replace('optional arguments:', f'{CG}optional arguments:{C0}')
|
||||
options[0] = options[0].replace('options:', color_string((CG, "options:")))
|
||||
options[0] = options[0].replace('optional arguments:', color_string((CG, "optional arguments:")))
|
||||
if len(options) > 1:
|
||||
options.append('')
|
||||
print('\n'.join(options))
|
||||
if len(lines) > 0:
|
||||
lines[0] = f'{CG}{lines[0]}{C0}'
|
||||
lines[0] = color_string((CG, lines[0]))
|
||||
print('\n'.join(lines))
|
||||
print('')
|
||||
self.help_requested = True
|
||||
@@ -247,6 +247,14 @@ def expect_response(accepted_responses: Union[int, list[int]]) -> Callable[...,
|
||||
return decorator
|
||||
|
||||
|
||||
def color_string(*args):
|
||||
result = []
|
||||
for arg in args:
|
||||
result.append(f"{arg[0]}{arg[1]}")
|
||||
result.append(C0)
|
||||
return "".join(result)
|
||||
|
||||
|
||||
class CLITree:
|
||||
"""
|
||||
Class holding a
|
||||
|
||||
Reference in New Issue
Block a user