Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 12 additions & 4 deletions src/blueapi/cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@

from blueapi import __version__
from blueapi.cli.event_bus_client import BlueskyRemoteError, EventBusClient
from blueapi.cli.format import OutputFormat
from blueapi.config import ApplicationConfig, ConfigLoader
from blueapi.core import DataEvent
from blueapi.messaging import MessageContext
Expand Down Expand Up @@ -88,8 +89,14 @@ def start_application(obj: dict):


@main.group()
@click.option(
"-o",
"--output",
Comment thread
tpoliaw marked this conversation as resolved.
Resolved
type=click.Choice([o.name.lower() for o in OutputFormat]),
default="compact",
)
@click.pass_context
def controller(ctx: click.Context) -> None:
def controller(ctx: click.Context, output: str) -> None:
"""Client utility for controlling and introspecting the worker"""

if ctx.invoked_subcommand is None:
Expand All @@ -98,6 +105,7 @@ def controller(ctx: click.Context) -> None:

ctx.ensure_object(dict)
config: ApplicationConfig = ctx.obj["config"]
ctx.obj["fmt"] = OutputFormat(output)
ctx.obj["rest_client"] = BlueapiRestClient(config.api)


Expand All @@ -118,7 +126,7 @@ def wrapper(*args, **kwargs):
def get_plans(obj: dict) -> None:
"""Get a list of plans available for the worker to use"""
client: BlueapiRestClient = obj["rest_client"]
pprint(client.get_plans().dict())
obj["fmt"].display(client.get_plans())


@controller.command(name="devices")
Expand All @@ -127,7 +135,7 @@ def get_plans(obj: dict) -> None:
def get_devices(obj: dict) -> None:
"""Get a list of devices available for the worker to use"""
client: BlueapiRestClient = obj["rest_client"]
pprint(client.get_devices().dict())
obj["fmt"].display(client.get_devices())


@controller.command(name="listen")
Expand Down Expand Up @@ -230,7 +238,7 @@ def get_state(obj: dict) -> None:
"""Print the current state of the worker"""

client: BlueapiRestClient = obj["rest_client"]
pprint(client.get_state())
print(client.get_state().name)


@controller.command(name="pause")
Expand Down
106 changes: 106 additions & 0 deletions src/blueapi/cli/format.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import builtins
import enum
import json
import sys
import textwrap
from functools import partial
from pprint import pprint
from textwrap import dedent, indent
from typing import Any, TextIO

from pydantic import BaseModel

from blueapi.service.model import DeviceResponse, PlanResponse

FALLBACK = pprint

Stream = TextIO | None


class OutputFormat(str, enum.Enum):
JSON = "json"
FULL = "full"
COMPACT = "compact"

def display(self, obj: Any, out: Stream = None):
out = out or sys.stdout
match self:
case OutputFormat.FULL:
display_full(obj, out)
case OutputFormat.COMPACT:
display_compact(obj, out)
case OutputFormat.JSON:
display_json(obj, out)


def display_full(obj: Any, stream: Stream):
print = partial(builtins.print, file=stream)
match obj:
case PlanResponse(plans=plans):
for plan in plans:
print(plan.name)
if desc := plan.description:
print(indent(dedent(desc).strip(), " "))
if schema := plan.parameter_schema:
print(" Schema")
print(indent(json.dumps(schema, indent=2), " "))
case DeviceResponse(devices=devices):
for dev in devices:
print(dev.name)
for proto in dev.protocols:
print(" " + proto)
case other:
FALLBACK(other, stream=stream)


def display_json(obj: Any, stream: Stream):
print = partial(builtins.print, file=stream)
match obj:
case PlanResponse(plans=plans):
print(json.dumps([p.dict() for p in plans], indent=2))
case DeviceResponse(devices=devices):
print(json.dumps([d.dict() for d in devices], indent=2))
Comment thread
tpoliaw marked this conversation as resolved.
Resolved
case BaseModel():
print(json.dumps(obj.dict(), indent=2))
case _:
print(json.dumps(obj))


def display_compact(obj: Any, stream: Stream):
print = partial(builtins.print, file=stream)
match obj:
case PlanResponse(plans=plans):
for plan in plans:
print(plan.name)
if desc := plan.description:
print(indent(dedent(desc.split("\n\n")[0].strip("\n")), " "))
if schema := plan.parameter_schema:
print(" Args")
for arg, spec in schema.get("properties", {}).items():
req = arg in schema.get("required", {})
print(f" {arg}={_describe_type(spec, req)}")
case DeviceResponse(devices=devices):
for dev in devices:
print(dev.name)
print(indent(textwrap.fill(", ".join(dev.protocols), 80), " "))
case other:
FALLBACK(other, stream=stream)


def _describe_type(spec: dict[Any, Any], required: bool = False):
disp = ""
match spec.get("type"):
case None:
if all_of := spec.get("allOf"):
items = (_describe_type(f, False) for f in all_of)
disp += f'{" & ".join(items)}'
else:
disp += "Any"
case "array":
element = spec.get("items", {}).get("type", "Any")
disp += f"[{element}]"
case other:
disp += other
if required:
disp += " (Required)"
return disp
1 change: 1 addition & 0 deletions src/blueapi/startup/example_plans.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ def stp_snapshot(
"""
Moves devices for pressure and temperature (defaults fetched from the context)
and captures a single frame from a collection of devices

Args:
detectors (List[Readable]): A list of devices to read while the sample is at STP
temperature (Optional[Movable]): A device controlling temperature of the sample,
Expand Down
Loading