Skip to content
Closed
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
5 changes: 5 additions & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,11 @@
("py:obj", r"fastcs.*.DType_T"),
(r"py:.*", r"fastcs\.demo.*"),
(r"py:.*", r"tickit.*"),
# httpx doesn't have intersphinx mapping
(r"py:.*", r"httpx\..*"),
("any", r"httpx\..*"),
# pyserial doesn't have intersphinx mapping
(r"py:.*", r"serial\..*"),
("py:class", r"numpy.*"),
]

Expand Down
47 changes: 47 additions & 0 deletions docs/explanations/connections.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
# Connections

A `Connection` is a link to a device. A controller takes its connections as constructor
arguments. FastCS opens them before constructing the controller, and closes them when
the application stops.

## Built-in connections

| Connection | Link | Install |
|---|---|---|
| `IPConnection` | TCP | included |
| `SerialConnection` | Serial port | `pip install "fastcs[serial]"` |
| `HTTPConnection` | HTTP | `pip install "fastcs[http]"` |

`IPConnection` and `SerialConnection` exchange text messages that end with a
terminator, `\r\n` by default:

```python
connection = IPConnection("10.0.0.5", 4000, terminator="\r\n", timeout=5.0)

await connection.write("R=5") # sends "R=5\r\n"
reply = await connection.query("R?") # sends "R?\r\n", returns the reply without "\r\n"
```

For binary protocols, `write_bytes` and `query_bytes` send raw bytes without a
terminator. If an exchange fails or takes longer than `timeout`, the link is closed and
later calls raise `DisconnectedError`. If the link fails, such as the device closing the
socket or a serial adapter being unplugged, the exchange raises `ConnectionError`, which
`DisconnectedError` subclasses, so
`except (ConnectionError, TimeoutError)` catches any link failure.

`HTTPConnection` talks to a device with a JSON API. `get`, `put`, `post` and `delete`
take a path relative to its `url`, send JSON, and return the parsed reply. An error
status raises `httpx.HTTPStatusError`. For replies that aren't JSON, `request` returns
the raw response:

```python
connection = HTTPConnection("http://10.0.0.5:8000/api", timeout=5.0)

await connection.put("/rate", json=5)
rate = await connection.get("/rate")
```

Like the other connections, it raises `TimeoutError` when the device doesn't answer in
time, but leaves the link open, as one slow request doesn't mean the server has gone. It
raises `ConnectionError` when the server can't be reached, and closes the link so later
calls raise `DisconnectedError`.
20 changes: 10 additions & 10 deletions docs/how-to/update-attributes-from-device.md
Original file line number Diff line number Diff line change
Expand Up @@ -33,11 +33,11 @@ class MyDeviceIO(AttributeIO[float, MyDeviceIORef]):
self._connection = connection

async def update(self, attr: AttrR[float, MyDeviceIORef]):
response = await self._connection.send_query(f"{attr.io_ref.register}?\r\n")
await attr.update(float(response.strip()))
response = await self._connection.query(f"{attr.io_ref.register}?")
await attr.update(float(response))

async def send(self, attr: AttrW[float, MyDeviceIORef], value: float):
await self._connection.send_command(f"{attr.io_ref.register}={value}\r\n")
await self._connection.write(f"{attr.io_ref.register}={value}")


class MyController(Controller):
Expand Down Expand Up @@ -95,13 +95,13 @@ class MyDeviceIO(AttributeIO[float, MyDeviceIORef]):
self._on_put_response = on_put_response

async def update(self, attr: AttrR[float, MyDeviceIORef]):
response = await self._connection.send_query(f"{attr.io_ref.register}?\r\n")
await attr.update(float(response.strip()))
response = await self._connection.query(f"{attr.io_ref.register}?")
await attr.update(float(response))

async def send(self, attr: AttrW[float, MyDeviceIORef], value: float):
# Device responds with a snapshot of all current values after a set
response = await self._connection.send_query(
f"{attr.io_ref.register}={value}\r\n"
response = await self._connection.query(
f"{attr.io_ref.register}={value}"
)
if self._on_put_response is not None:
await self._on_put_response(response)
Expand All @@ -117,7 +117,7 @@ class MyController(Controller):
super().__init__(ios=[MyDeviceIO(connection, self._handle_put_response)])

async def _handle_put_response(self, response: str) -> None:
actual, power, status = response.strip().split(",")
actual, power, status = response.split(",")
await self.actual_temperature.update(float(actual))
await self.power.update(float(power))
await self.status.update(float(status))
Expand Down Expand Up @@ -169,7 +169,7 @@ class MultiChannelController(Controller):
async def update_voltages(self):
# One request returns all channel voltages
voltages = json.loads(
(await self._connection.send_query("V?\r\n")).strip()
await self._connection.query("V?")
)
for channel, voltage in zip(self._channels, voltages):
await channel.voltage.update(float(voltage))
Expand Down Expand Up @@ -235,7 +235,7 @@ class MultiChannelController(Controller):
@scan(0.1)
async def fetch_voltages(self):
voltages = json.loads(
(await self._connection.send_query("V?\r\n")).strip()
await self._connection.query("V?")
)
self._channel_io.update_cache(dict(enumerate(map(float, voltages))))
```
Expand Down
12 changes: 5 additions & 7 deletions docs/snippets/dynamic.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,9 @@ class TemperatureIntrospection:

class TemperatureConnection(IPConnection[TemperatureIntrospection]):
async def introspect(self) -> TemperatureIntrospection:
response = await self.send_query("API?\r\n")
parameters = json.loads(response.strip("\r\n"))
ramps = parameters.pop("Ramps")
return TemperatureIntrospection(parameters, ramps)
api = json.loads(await self.query("API?"))
ramps = api.pop("Ramps")
return TemperatureIntrospection(parameters=api, ramps=ramps)


NumberT = TypeVar("NumberT", int, float)
Expand All @@ -94,16 +93,15 @@ def __init__(self, connection: TemperatureConnection):

async def update(self, attr: AttrR[NumberT, TemperatureControllerAttributeIORef]):
query = f"{attr.io_ref.name}?"
response = await self._connection.send_query(f"{query}\r\n")
value = response.strip("\r\n")
value = await self._connection.query(query)

await attr.update(attr.dtype(value))

async def send(
self, attr: AttrW[NumberT, TemperatureControllerAttributeIORef], value: NumberT
) -> None:
command = f"{attr.io_ref.name}={attr.dtype(value)}"
await self._connection.send_command(f"{command}\r\n")
await self._connection.write(command)


class TemperatureRampController(Controller):
Expand Down
3 changes: 1 addition & 2 deletions docs/snippets/static07.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,8 +25,7 @@ def __init__(self, connection: IPConnection):
self._connection = connection

async def update(self, attr: AttrR[NumberT, IDAttributeIORef]):
response = await self._connection.send_query("ID?\r\n")
value = response.strip("\r\n")
value = await self._connection.query("ID?")

await attr.update(attr.dtype(value))

Expand Down
3 changes: 1 addition & 2 deletions docs/snippets/static08.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,7 @@ def __init__(self, connection: IPConnection):

async def update(self, attr: AttrR[NumberT, TemperatureControllerAttributeIORef]):
query = f"{attr.io_ref.name}?"
response = await self._connection.send_query(f"{query}\r\n")
value = response.strip("\r\n")
value = await self._connection.query(query)

await attr.update(attr.dtype(value))

Expand Down
5 changes: 2 additions & 3 deletions docs/snippets/static09.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,15 @@ def __init__(self, connection: IPConnection):

async def update(self, attr: AttrR[NumberT, TemperatureControllerAttributeIORef]):
query = f"{attr.io_ref.name}?"
response = await self._connection.send_query(f"{query}\r\n")
value = response.strip("\r\n")
value = await self._connection.query(query)

await attr.update(attr.dtype(value))

async def send(
self, attr: AttrW[NumberT, TemperatureControllerAttributeIORef], value: NumberT
) -> None:
command = f"{attr.io_ref.name}={attr.dtype(value)}"
await self._connection.send_command(f"{command}\r\n")
await self._connection.write(command)


class TemperatureController(Controller):
Expand Down
5 changes: 2 additions & 3 deletions docs/snippets/static10.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,16 +31,15 @@ def __init__(self, connection: IPConnection, suffix: str = ""):

async def update(self, attr: AttrR[NumberT, TemperatureControllerAttributeIORef]):
query = f"{attr.io_ref.name}{self._suffix}?"
response = await self._connection.send_query(f"{query}\r\n")
value = response.strip("\r\n")
value = await self._connection.query(query)

await attr.update(attr.dtype(value))

async def send(
self, attr: AttrW[NumberT, TemperatureControllerAttributeIORef], value: NumberT
) -> None:
command = f"{attr.io_ref.name}{self._suffix}={attr.dtype(value)}"
await self._connection.send_command(f"{command}\r\n")
await self._connection.write(command)


class TemperatureRampController(Controller):
Expand Down
5 changes: 2 additions & 3 deletions docs/snippets/static11.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,16 +32,15 @@ def __init__(self, connection: IPConnection, suffix: str = ""):

async def update(self, attr: AttrR[NumberT, TemperatureControllerAttributeIORef]):
query = f"{attr.io_ref.name}{self._suffix}?"
response = await self._connection.send_query(f"{query}\r\n")
value = response.strip("\r\n")
value = await self._connection.query(query)

await attr.update(attr.dtype(value))

async def send(
self, attr: AttrW[NumberT, TemperatureControllerAttributeIORef], value: NumberT
) -> None:
command = f"{attr.io_ref.name}{self._suffix}={attr.dtype(value)}"
await self._connection.send_command(f"{command}\r\n")
await self._connection.write(command)


class OnOffEnum(enum.StrEnum):
Expand Down
9 changes: 3 additions & 6 deletions docs/snippets/static12.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,16 +34,15 @@ def __init__(self, connection: IPConnection, suffix: str = ""):

async def update(self, attr: AttrR[NumberT, TemperatureControllerAttributeIORef]):
query = f"{attr.io_ref.name}{self._suffix}?"
response = await self._connection.send_query(f"{query}\r\n")
value = response.strip("\r\n")
value = await self._connection.query(query)

await attr.update(attr.dtype(value))

async def send(
self, attr: AttrW[NumberT, TemperatureControllerAttributeIORef], value: NumberT
) -> None:
command = f"{attr.io_ref.name}{self._suffix}={attr.dtype(value)}"
await self._connection.send_command(f"{command}\r\n")
await self._connection.write(command)


class OnOffEnum(enum.StrEnum):
Expand Down Expand Up @@ -84,9 +83,7 @@ def __init__(self, ramp_count: int, connection: IPConnection):

@scan(0.1)
async def update_voltages(self):
voltages = json.loads(
(await self._connection.send_query("V?\r\n")).strip("\r\n")
)
voltages = json.loads(await self._connection.query("V?"))
for index, controller in enumerate(self._ramp_controllers):
await controller.voltage.update(float(voltages[index]))

Expand Down
9 changes: 3 additions & 6 deletions docs/snippets/static13.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,16 +35,15 @@ def __init__(self, connection: IPConnection, suffix: str = ""):

async def update(self, attr: AttrR[NumberT, TemperatureControllerAttributeIORef]):
query = f"{attr.io_ref.name}{self._suffix}?"
response = await self._connection.send_query(f"{query}\r\n")
value = response.strip("\r\n")
value = await self._connection.query(query)

await attr.update(attr.dtype(value))

async def send(
self, attr: AttrW[NumberT, TemperatureControllerAttributeIORef], value: NumberT
) -> None:
command = f"{attr.io_ref.name}{self._suffix}={attr.dtype(value)}"
await self._connection.send_command(f"{command}\r\n")
await self._connection.write(command)


class OnOffEnum(enum.StrEnum):
Expand Down Expand Up @@ -85,9 +84,7 @@ def __init__(self, ramp_count: int, connection: IPConnection):

@scan(0.1)
async def update_voltages(self):
voltages = json.loads(
(await self._connection.send_query("V?\r\n")).strip("\r\n")
)
voltages = json.loads(await self._connection.query("V?"))
for index, controller in enumerate(self._ramp_controllers):
await controller.voltage.update(float(voltages[index]))

Expand Down
9 changes: 3 additions & 6 deletions docs/snippets/static14.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@ def __init__(self, connection: IPConnection, suffix: str = ""):

async def update(self, attr: AttrR[NumberT, TemperatureControllerAttributeIORef]):
query = f"{attr.io_ref.name}{self._suffix}?"
response = await self._connection.send_query(f"{query}\r\n")
value = response.strip("\r\n")
value = await self._connection.query(query)
await attr.update(attr.dtype(value))

async def send(
Expand All @@ -47,7 +46,7 @@ async def send(

logger.info("Sending attribute value", command=command, attribute=attr)

await self._connection.send_command(f"{command}\r\n")
await self._connection.write(command)


class OnOffEnum(enum.StrEnum):
Expand Down Expand Up @@ -88,9 +87,7 @@ def __init__(self, ramp_count: int, connection: IPConnection):

@scan(0.1)
async def update_voltages(self):
voltages = json.loads(
(await self._connection.send_query("V?\r\n")).strip("\r\n")
)
voltages = json.loads(await self._connection.query("V?"))
for index, controller in enumerate(self._ramp_controllers):
await controller.voltage.update(float(voltages[index]))

Expand Down
9 changes: 3 additions & 6 deletions docs/snippets/static15.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,7 @@ def __init__(self, connection: IPConnection, suffix: str = ""):

async def update(self, attr: AttrR[NumberT, TemperatureControllerAttributeIORef]):
query = f"{attr.io_ref.name}{self._suffix}?"
response = await self._connection.send_query(f"{query}\r\n")
value = response.strip("\r\n")
value = await self._connection.query(query)

self.log_event("Query for attribute", query=query, response=value, topic=attr)

Expand All @@ -50,7 +49,7 @@ async def send(

logger.info("Sending attribute value", command=command, attribute=attr)

await self._connection.send_command(f"{command}\r\n")
await self._connection.write(command)


class OnOffEnum(enum.StrEnum):
Expand Down Expand Up @@ -91,9 +90,7 @@ def __init__(self, ramp_count: int, connection: IPConnection):

@scan(0.1)
async def update_voltages(self):
voltages = json.loads(
(await self._connection.send_query("V?\r\n")).strip("\r\n")
)
voltages = json.loads(await self._connection.query("V?"))
for index, controller in enumerate(self._ramp_controllers):
await controller.voltage.update(float(voltages[index]))

Expand Down
4 changes: 2 additions & 2 deletions docs/tutorials/dynamic-drivers.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,14 +58,14 @@ Define a type for the introspection, and a connection whose `introspect` queries
`IPConnection[TemperatureIntrospection]`, is the type that `introspect` returns.

:::{literalinclude} /snippets/dynamic.py
:lines: 63-74
:lines: 63-73
:::

Update the controllers to create their attributes from `connection.introspection` in
`__init__`, instead of defining them statically.

:::{literalinclude} /snippets/dynamic.py
:lines: 109-133
:lines: 107-131
:::

The `suffix` field should also be removed from `TemperatureController` and
Expand Down
Loading
Loading