Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
c63ff2c
WIP scruffy first pass at making a user client
tpoliaw Dec 17, 2025
77af278
Cache all devices when first is accessed
tpoliaw Dec 18, 2025
a16aff8
More client refactoring
tpoliaw Dec 18, 2025
2da1a74
Update CLI to use update client
tpoliaw Dec 18, 2025
75f8bb2
Use "BlueapiClient" instead of Self for classmethods
tpoliaw Dec 18, 2025
bd9ed2f
Remove single dispatch stuff
tpoliaw Dec 19, 2025
60fa0e4
Make name a public attribute of Plan
tpoliaw Dec 19, 2025
0fc45d9
Add spans to plans and devices properties
tpoliaw Dec 19, 2025
5f80164
Remove dead comments
tpoliaw Dec 19, 2025
f709bea
Make optional parameters clear in Plan repr
tpoliaw Dec 19, 2025
d0a88a4
Update client and system tests to use new client changes
tpoliaw Dec 19, 2025
1d4e945
Get oidc config via property
tpoliaw Jan 5, 2026
d7a2af9
Add getitem support for plans
tpoliaw Jan 5, 2026
b12d02d
Correct mocking in cli test
tpoliaw Jan 6, 2026
9f1dfb0
Up the coverage
tpoliaw Jan 8, 2026
b944516
Update system tests
tpoliaw Jan 8, 2026
507e6f0
Add repr for caches
tpoliaw Jan 9, 2026
b5e0f87
Add ServiceUnavailableError to wrap requests errors
tpoliaw Jan 9, 2026
ed9ad73
Create re-usable session for rest calls
tpoliaw Jan 9, 2026
5b6c132
Change mock in tests
tpoliaw Jan 13, 2026
d14627d
Catch correct exception in system tests
tpoliaw Jan 13, 2026
53806f0
Up the coverage
tpoliaw Jan 13, 2026
8a5d111
Add callback support
tpoliaw Jan 14, 2026
8435f42
Test fluent instrument_session setter
tpoliaw Jan 14, 2026
45ceb02
Replace removed BlueapiClient methods
tpoliaw Feb 5, 2026
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 @@ -185,7 +185,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 @@ -206,7 +206,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 @@ -215,7 +215,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 @@ -347,7 +347,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 @@ -430,7 +430,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 @@ -472,14 +472,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 @@ -98,11 +104,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 @@ -112,26 +120,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
Loading