Skip to content

Commit

Permalink
Add JSON status output for all commands and errors
Browse files Browse the repository at this point in the history
This commit adds JSON output to all CLI commands, if the --json switch
is set.
If the command does not output anything: Return an empty message.

It also makes sure that error messages are output in JSON, if it is an
Exception, that the CLI has already handled before.
Thus the key ``error-message`` will be present if the return code is
``!= 0``.
  • Loading branch information
SmithChart committed Dec 18, 2023
1 parent 458bf81 commit bff90ca
Showing 1 changed file with 30 additions and 21 deletions.
51 changes: 30 additions & 21 deletions usbsdmux/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,26 +77,43 @@ def main():
sys.exit(1)
mode = args.mode

error_msg = None
try:
if mode == "off":
ctl.mode_disconnect()
if args.json:
print(json.dumps({}))

elif mode in ("dut", "client"):
ctl.mode_DUT()
if args.json:
print(json.dumps({}))

elif mode == "host":
ctl.mode_host()
if args.json:
print(json.dumps({}))

elif mode == "get":
print(ctl.get_mode())
if args.json:
print(json.dumps({"switch-state": ctl.get_mode()}))
else:
print(ctl.get_mode())

elif mode == "gpio":
if args.action == "get":
print(ctl.gpio_get(args.gpio))
if args.json:
print(json.dumps({"gpio-state": {"gpio": args.gpio, "state:": ctl.gpio_get(args.gpio)}}))
else:
print(ctl.gpio_get(args.gpio))
elif args.action in ["0", "low"]:
ctl.gpio_set_low(args.gpio)
if args.json:
print(json.dumps({}))
elif args.action in ["1", "high"]:
ctl.gpio_set_high(args.gpio)
if args.json:
print(json.dumps({}))

elif mode == "info":
info = ctl.get_card_info()
Expand All @@ -108,33 +125,25 @@ def main():
print("CSD: {}".format(info["csd"]["raw"]))

except FileNotFoundError as fnfe:
print(fnfe, file=sys.stderr)
sys.exit(1)
error_msg = str(fnfe)
except PermissionError as perr:
print(perr, file=sys.stderr)
sys.exit(1)
error_msg = str(perr)
except OSError as ose:
if ose.errno == errno.ENOTTY:
# ENOTTY is raised when an error occurred when calling an ioctl
print(ose, file=sys.stderr)
print(
f"Does '{args.sg}' really point to an USB-SD-Mux?",
file=sys.stderr,
)
sys.exit(1)
error_msg = ose + "\n" + f"Does '{args.sg}' really point to an USB-SD-Mux?"
else:
raise ose
except NotInHostModeException:
print(
"Card information is only available in host mode.",
file=sys.stderr,
)
sys.exit(1)
error_msg = "Card information is only available in host mode."
except NotImplementedError:
print(
"This USB-SD-Mux does not support GPIOs.",
file=sys.stderr,
)
error_msg = "This USB-SD-Mux does not support GPIOs."

if error_msg:
if args.json:
print(json.dumps({"error-message": error_msg}))
else:
print(error_msg, file=sys.stderr)
sys.exit(1)


Expand Down

0 comments on commit bff90ca

Please sign in to comment.