Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
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
27 changes: 13 additions & 14 deletions src/blueapi/cli/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@
from click.exceptions import ClickException
from observability_utils.tracing import setup_tracing
from pydantic import ValidationError
from requests.exceptions import ConnectionError

from blueapi import __version__, config
from blueapi.cli.format import OutputFormat
Expand All @@ -26,6 +25,7 @@
from blueapi.client.rest import (
BlueskyRemoteControlError,
InvalidParametersError,
ServiceUnavailableError,
UnauthorisedAccessError,
UnknownPlanError,
)
Expand All @@ -36,7 +36,7 @@
from blueapi.core import OTLP_EXPORT_ENABLED, DataEvent
from blueapi.log import set_up_logging
from blueapi.service.authentication import SessionCacheManager, SessionManager
from blueapi.service.model import SourceInfo, TaskRequest
from blueapi.service.model import DeviceResponse, PlanResponse, SourceInfo, TaskRequest
from blueapi.worker import ProgressEvent, WorkerEvent

from .scratch import setup_scratch
Expand Down Expand Up @@ -183,7 +183,7 @@ def check_connection(func: Callable[P, T]) -> Callable[P, T]:
def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
try:
return func(*args, **kwargs)
except ConnectionError as ce:
except ServiceUnavailableError as ce:
raise ClickException(
"Failed to establish connection to blueapi server."
) from ce
Expand All @@ -204,7 +204,7 @@ def wrapper(*args: P.args, **kwargs: P.kwargs) -> T:
def get_plans(obj: dict) -> None:
"""Get a list of plans available for the worker to use"""
client: BlueapiClient = obj["client"]
obj["fmt"].display(client.get_plans())
obj["fmt"].display(PlanResponse(plans=[p.model for p in client.plans]))


@controller.command(name="devices")
Expand All @@ -213,7 +213,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: BlueapiClient = obj["client"]
obj["fmt"].display(client.get_devices())
obj["fmt"].display(DeviceResponse(devices=[dev.model for dev in client.devices]))


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

client: BlueapiClient = obj["client"]
print(client.get_state().name)
print(client.state.name)


@controller.command(name="pause")
Expand Down Expand Up @@ -428,7 +428,7 @@ def env(
status = client.reload_environment(timeout=timeout)
print("Environment is initialized")
else:
status = client.get_environment()
status = client.environment
print(status)


Expand Down Expand Up @@ -470,14 +470,13 @@ def login(obj: dict) -> None:
print("Logged in")
except Exception:
client = BlueapiClient.from_config(config)
oidc_config = client.get_oidc_config()
if oidc_config is None:
if oidc := client.oidc_config:
auth = SessionManager(
oidc, cache_manager=SessionCacheManager(config.auth_token_path)
)
auth.start_device_flow()
else:
print("Server is not configured to use authentication!")
return
auth = SessionManager(
oidc_config, cache_manager=SessionCacheManager(config.auth_token_path)
)
auth.start_device_flow()


@main.command(name="logout")
Expand Down
68 changes: 40 additions & 28 deletions src/blueapi/cli/format.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@

from blueapi.core.bluesky_types import DataEvent
from blueapi.service.model import (
DeviceModel,
DeviceResponse,
PlanModel,
PlanResponse,
PythonEnvironmentResponse,
SourceInfo,
Expand Down Expand Up @@ -54,17 +56,21 @@ def display_full(obj: Any, stream: 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), " "))
display_full(plan, stream)
case PlanModel(name=name, description=desc, parameter_schema=schema):
print(name)
if desc:
print(indent(dedent(desc).strip(), " "))
if 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(f" {proto}")
display_full(dev, stream)
case DeviceModel(name=name, protocols=protocols):
print(name)
for proto in protocols:
print(f" {proto}")
case DataEvent(name=name, doc=doc):
print(f"{name.title()}:{fmt_dict(doc)}")
case WorkerEvent(state=st, task_status=task):
Expand Down Expand Up @@ -100,11 +106,13 @@ def display_json(obj: Any, stream: Stream):
print = partial(builtins.print, file=stream)
match obj:
case PlanResponse(plans=plans):
print(json.dumps([p.model_dump() for p in plans], indent=2))
display_json(plans, stream)
case DeviceResponse(devices=devices):
print(json.dumps([d.model_dump() for d in devices], indent=2))
display_json(devices, stream)
case BaseModel():
print(json.dumps(obj.model_dump()))
case list():
print(json.dumps([it.model_dump() for it in obj], indent=2))
case _:
print(json.dumps(obj))

Expand All @@ -114,26 +122,30 @@ def display_compact(obj: Any, stream: 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)}")
display_compact(plan, stream)
case PlanModel(name=name, description=desc, parameter_schema=schema):
print(name)
if desc:
print(indent(dedent(desc.split("\n\n")[0].strip("\n")), " "))
if 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(str(proto) for proto in dev.protocols),
80,
),
" ",
)
display_compact(dev, stream)
case DeviceModel(name=name, protocols=protocols):
print(name)
print(
indent(
textwrap.fill(
", ".join(str(proto) for proto in protocols),
80,
),
" ",
)
)
case DataEvent(name=name):
print(f"Data Event: {name}")
case WorkerEvent(state=state):
Expand Down
Loading