Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
48 commits
Select commit Hold shift + click to select a range
955881a
hand over lifecycle to the runner
tomkane-dls Nov 5, 2026
2c84ab7
move location of runner.py and remove pointless guards
tomkane-dls Nov 6, 2026
89f3153
simplify runner [properties and checks
tomkane-dls Nov 6, 2026
5f00263
clean up comments
tomkane-dls Nov 9, 2026
4eeb4e2
fix backtick issue
tomkane-dls Nov 9, 2026
1ca591d
make build_api public
tomkane-dls Nov 10, 2026
9780e96
make build a classmethod
tomkane-dls Nov 10, 2026
7078aa3
make connected read only so we can avoid private member access, add m…
tomkane-dls Nov 10, 2026
146f3ad
make new tests event driven
tomkane-dls Nov 10, 2026
976ffb9
naming and event fixes
tomkane-dls Nov 10, 2026
c98a3e5
add distinct connections object, added to controllers via the runner
tomkane-dls Nov 6, 2026
6eddcaf
ensure clean shutdown
tomkane-dls Nov 6, 2026
37ce946
create Connection base class, and use it for connection logic, hand o…
tomkane-dls Nov 9, 2026
08b65e6
add depends_on to Connection, allowing reconnect order to be defined …
tomkane-dls Nov 9, 2026
2d45e12
allow Connections to return device introspection (type IntrospectionT)
tomkane-dls Nov 9, 2026
cff998c
simplify docstrings
tomkane-dls Nov 9, 2026
2b6b298
add setup() method to controllers, called by the runner in start()
tomkane-dls Nov 9, 2026
8a6b648
remove initialise, post_initialise, and add seal() which stops attrib…
tomkane-dls Nov 9, 2026
f5e5a8a
move introspection to its own method, update IP Serial connections to…
tomkane-dls Nov 9, 2026
774d34d
update example to define its own introspection type
tomkane-dls Nov 9, 2026
fb5d76a
cleanup
tomkane-dls Nov 9, 2026
0668d98
remove depends_on docstring
tomkane-dls Nov 11, 2026
0e7991e
add a setter to introspection, to remove noqa and raise an error if t…
tomkane-dls Nov 11, 2026
69fa5cd
make seal a public method, raise if set twice
tomkane-dls Nov 11, 2026
cd66d0e
update docstrings so they are clearer to authors who look at them
tomkane-dls Nov 11, 2026
8fe0660
make ControllerSpec id required and use kw args in docs and examples
tomkane-dls Nov 11, 2026
4e316ef
fix setup docstring
tomkane-dls Nov 11, 2026
e049792
use specific connection name in examples to make things more clear
tomkane-dls Nov 11, 2026
9e4aa51
rename FastCS attribute to specs
tomkane-dls Nov 11, 2026
02a547c
fix launch bugs
tomkane-dls Nov 11, 2026
c027e03
tidy up
tomkane-dls Nov 11, 2026
455d80f
document IntrospectionT so the docs build can link to it
tomkane-dls Nov 11, 2026
607e829
fix startup/cleanup issues, and add tests to fail on these types of m…
tomkane-dls Nov 12, 2026
b008a3d
fix keyword only connections appear in schema, and add test
tomkane-dls Nov 12, 2026
4c05462
fix stale references in tutorial
tomkane-dls Nov 12, 2026
64ddd9a
make sure we wait for scans to actually stop
tomkane-dls Nov 12, 2026
e0ced9c
fix the root path issue, add test to check for correct paths
tomkane-dls Nov 12, 2026
f0b769f
standardise path names in new tests
tomkane-dls Nov 12, 2026
2a33384
add clear fail if a connection is shared across two sister top level …
tomkane-dls Nov 12, 2026
94cba78
improve base controller checks with sensible error raising
tomkane-dls Nov 12, 2026
10c3e09
accept lists of spec only
tomkane-dls Nov 12, 2026
ff234cb
remove duplicate check and use ids directly from fastcs
tomkane-dls Nov 12, 2026
231c3c9
move the fail route above on build entry model
tomkane-dls Nov 12, 2026
f4b5a77
improve test examples
tomkane-dls Nov 12, 2026
43e099a
tidy up tests, remove lambdas where easy
tomkane-dls Nov 12, 2026
273b084
fix launch framework how to documentation
tomkane-dls Nov 12, 2026
92117da
replace kind with hinted types in validation messages
tomkane-dls Nov 16, 2026
fabab71
Merge pull request #450 from DiamondLightSource/basic-connections
tomkane-dls Nov 17, 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
58 changes: 24 additions & 34 deletions docs/explanations/controllers.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,23 +7,25 @@ FastCS provides three controller classes: `Controller`, `ControllerVector`, and

`Controller` is the primary building block for FastCS drivers. It can serve two roles:

**Root controller:** passed directly to the `FastCS` launcher. In this role, FastCS
will call its lifecycle hooks and run the scan tasks it creates on the event loop.
**Root controller:** passed to the `FastCS` launcher in a `ControllerSpec`. In this
role, FastCS opens the `Connection`s it is given, constructs it, calls its lifecycle
hooks and runs the scan tasks it creates on the event loop.

**Sub controller:** attached to a parent controller via `add_sub_controller()` or by
assigning it as an attribute. In this role, the sub controller's lifecycle hooks
(`connect`, `reconnect`, `initialise`, `disconnect`) are not called automatically by
FastCS. The parent controller is responsible for calling them as part of its own
lifecycle, if required.
assigning it as an attribute. In this role, the sub controller's `reconnect` hook is
not called automatically by FastCS. The parent controller is responsible for calling it
as part of its own lifecycle, if required.

### Lifecycle hooks

| Method | Purpose |
|---|---|
| `initialise` | Dynamically add attributes on startup, before the API is built |
| `connect` | Open connection to device |
| `setup` | Called by the framework after all attributes are added, before serving the application. Called on every controller in the tree |
| `reconnect` | Re-open connection after scan error |
| `disconnect` | Release device resources before shutdown |

Connections to the device are not opened by the controller. They are `Connection`s
passed to its constructor, which FastCS opens before constructing it and closes on
shutdown.

### Scan task behaviour

Expand All @@ -44,51 +46,45 @@ class TemperatureController(Controller):
temperature = AttrR(Float(units="degC"))
setpoint = AttrRW(Float(units="degC"))

async def connect(self):
self._client = await DeviceClient.connect(self._host, self._port)
self._connected = True
def __init__(self, connection: DeviceConnection):
super().__init__()
self._connection = connection

async def reconnect(self):
try:
self._client = await DeviceClient.connect(self._host, self._port)
await self._connection.close()
await self._connection.connect()
self._connected = True
except Exception:
logger.error("Failed to reconnect")

async def disconnect(self):
await self._client.close()

@scan(period=1.0)
async def update_temperature(self):
value = await self._client.get_temperature()
value = await self._connection.get_temperature()
await self.temperature.update(value)
```

### Using Controller as a sub controller

When a `Controller` is nested inside another, it organises the driver into logical
sections and its attributes are exposed under a prefixed path. If the sub
controller also has connection logic, the parent must invoke it explicitly:
controller needs the connection, the parent passes it down:

```python
class ChannelController(Controller):
value = AttrR(Float())

async def connect(self):
...
self._connected = True
def __init__(self, connection: DeviceConnection):
super().__init__()
self._connection = connection


class RootController(Controller):
channel: ChannelController

def __init__(self):
def __init__(self, connection: DeviceConnection):
super().__init__()
self.channel = ChannelController()

async def connect(self):
await self.channel.connect()
self._connected = True
self.channel = ChannelController(connection)
```

## ControllerVector
Expand Down Expand Up @@ -120,12 +116,6 @@ class RootController(Controller):
{i: ChannelController() for i in range(num_channels)}
)

async def connect(self):
for channel in self.channels.values():
await channel.connect()

self._connected = True

async def update_all(self):
for index, channel in self.channels.items():
value = await self._client.get_channel(index)
Expand All @@ -145,7 +135,7 @@ Use `ControllerVector` when:

- The device has a set of identical channels, axes, or modules identified by number
- You need to iterate over sub controllers and perform the same action on each
- The number of instances may vary (e.g. determined at runtime during `initialise`)
- The number of instances may vary (e.g. determined from the connection's introspection)

Use a plain `Controller` with named sub controllers when the sub controllers are
distinct components with different types or roles.
Expand Down
4 changes: 2 additions & 2 deletions docs/explanations/what-is-fastcs.md
Original file line number Diff line number Diff line change
Expand Up @@ -54,8 +54,8 @@ using `ControllerVector`. See [Controllers](controllers.md) for details.
## Writing a driver

To create a driver, subclass `Controller`, declare attributes and commands as typed
class members, and implement lifecycle hooks (`connect`, `reconnect`, `disconnect`) and
periodic scan tasks. The [tutorials](../tutorials.md) walk through a complete example.
class members, take the `Connection`s it needs as constructor arguments, and implement
lifecycle hooks (`setup`, `reconnect`) and periodic scan tasks. The [tutorials](../tutorials.md) walk through a complete example.

## Deploying as an application

Expand Down
55 changes: 54 additions & 1 deletion docs/how-to/launch-framework.md
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,57 @@ if __name__ == "__main__":
launch(DeviceController, version="1.0.0")
```

## Adding Connections

Any `__init__` argument whose type is a `Connection` becomes a block under the
entry's `connections:` key, named after the argument. Its fields are the
connection's constructor arguments. FastCS opens each connection before
constructing the controller, and closes it on shutdown.

The address and port now belong to the connection, so they move out of
`DeviceSettings` and into the `connections:` block:

```python
from dataclasses import dataclass

from fastcs.connections import IPConnection
from fastcs.controllers import Controller

@dataclass
class DeviceSettings:
timeout: float = 5.0

class DeviceController(Controller):
def __init__(self, connection: IPConnection, settings: DeviceSettings):
super().__init__()
self.connection = connection
self.settings = settings
```

```yaml
controllers:
- id: DEVICE
type: my_driver.DeviceController
connections:
connection:
ip: "192.168.1.100"
port: 25565
timeout: 10.0
```

If one connection needs another to be open first, declare it on the connection
class with `depends_on`. FastCS then opens the connections it depends on first,
and closes them last:

```python
class OdinConnection(Connection):
depends_on = EigerConnection
```

For several types, use a list: `depends_on = [EigerConnection, OtherConnection]`.
A connection depends on every connection of the listed types in the same
controller entry.

## YAML Configuration Files

Create a YAML configuration file matching the schema. The conventional
Expand Down Expand Up @@ -204,8 +255,10 @@ FastCS: 0.12.0

The `launch()` function requires:

1. Controller `__init__` must have at most 2 arguments (including `self`)
1. Controller `__init__` may take any number of `Connection` arguments, and at most
one other argument, the configuration
2. If a configuration argument exists, it must have a type hint
3. Every constructor argument of a `Connection` must have a type hint

Using a dataclass or Pydantic model is recommended for the configuration type, as it enables JSON schema generation. Other type-hinted types will work, but will not produce a useful schema.

Expand Down
15 changes: 8 additions & 7 deletions docs/how-to/migrate-to-multi-controller.md
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ transport:
The same applies to PVA. If you construct transports in Python rather
than via YAML, replace `EpicsCATransport(epicsca=EpicsIOCOptions(
pv_prefix="DEVICE"))` with `EpicsCATransport()` plus
`controller.set_path(["DEVICE"])` (or set the id from the YAML entry's
`ControllerSpec("DEVICE", MyController)` (or set the id from the YAML entry's
`id:` field when using `launch()`).

## 4. `type:` discriminator is required on every entry
Expand Down Expand Up @@ -103,13 +103,14 @@ transport:
- epicsca: {}
```

## 5. Direct `FastCS(...)` usage is unchanged for the single-controller case
## 5. Direct `FastCS(...)` usage takes `ControllerSpec`s

If you instantiate `FastCS` directly rather than via `launch()`, the
single-controller form `FastCS(controller, transports)` still works.
For multi-controller, pass a sequence:
`FastCS([controller_a, controller_b], transports)`. Each Controller
must have had `set_path([...])` called before being handed to `FastCS`.
If you instantiate `FastCS` directly rather than via `launch()`, pass a
list of `ControllerSpec`s instead of a constructed controller:
`FastCS([ControllerSpec("DEVICE", MyController)], transports)`. For
multi-controller, add more specs to the list:
`FastCS([ControllerSpec("A", ControllerA), ControllerSpec("B", ControllerB)], transports)`.
The spec's id replaces calling `set_path([...])`.

## 6. GUI/docs emission output is now a directory

Expand Down
16 changes: 8 additions & 8 deletions docs/how-to/multiple-transports.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,17 +8,18 @@ Pass a list of transports to `FastCS`:

```python
from fastcs.control_system import FastCS
from fastcs.controllers import ControllerSpec
from fastcs.transports import (
EpicsCATransport,
GraphQLTransport,
RestTransport,
)

controller = MyController()
controller.set_path(["DEVICE"]) # PV prefix for EPICS / route prefix for REST
# "DEVICE" is the PV prefix for EPICS / route prefix for REST
spec = ControllerSpec("DEVICE", MyController)

fastcs = FastCS(
controller,
[spec],
[
EpicsCATransport(),
RestTransport(),
Expand Down Expand Up @@ -72,9 +73,8 @@ Each transport has its own options:

### EPICS Channel Access

The PV prefix is the first segment of the controller's path (set via
`controller.set_path([...])` or auto-seeded by `launch()` from the YAML
entry's `id:`).
The PV prefix is the first segment of the controller's path (the id given
to its `ControllerSpec`, or the YAML entry's `id:` when using `launch()`).

```python
from pathlib import Path
Expand Down Expand Up @@ -161,10 +161,10 @@ from fastcs.transports import (
EpicsPVATransport,
)

controller.set_path(["DEVICE"])
spec = ControllerSpec("DEVICE", MyController)

fastcs = FastCS(
controller,
[spec],
[
EpicsCATransport(
gui=EpicsGUIOptions(output_dir=Path("./opis")),
Expand Down
3 changes: 1 addition & 2 deletions docs/how-to/update-attributes-from-device.md
Original file line number Diff line number Diff line change
Expand Up @@ -261,13 +261,12 @@ class SubscriptionController(Controller):
super().__init__()
self._client = subscription_client

async def connect(self):
async def setup(self):
# Register an async callback that forwards updates into the attribute.
async def on_temperature_change(value: float) -> None:
await self.temperature.update(value)

await self._client.subscribe("temperature", on_temperature_change)
await super().connect()
```

If the library only supports synchronous callbacks, schedule the coroutine onto the
Expand Down
Loading
Loading