stellar generate writes code from the compiled configuration, so that code outside Stellar Control
follows the catalogues and libraries it depends on instead of repeating them by hand:
| Command | From | Writes |
|---|---|---|
stellar generate driver <catalogue> | A catalogue package | The typed skeleton of a driver on the Python SDK: arguments of each telecommand, builders of the raw samples, coverage, and the encoding and decoding to write |
stellar generate client <library> | A library of steps and procedures | One pair of functions per procedure, launching it through the API client with its roles, inputs and environments typed |
stellar generate simulation <catalogue> | A catalogue package | The simulation of the platform, simulations/<name>.yaml: a simulated target that keeps the contract of the catalogue, checked before it is written. See A simulation written from the catalogue |
They compile the configuration repository first, like stellar check: a repository with errors
generates nothing. driver and client write a Python package in their output directory, and
separate what the generator owns from what the developer owns:
| Owner | Written | Meaning |
|---|---|---|
| The generator | Every time | Says what the configuration says; never edited by hand, generated again with each version of the catalogue or library |
| The developer | Only when missing | Written once as a starting point, then yours: stellar generate never overwrites it (kept … (yours)) |
The code is written as ruff format writes it, lines of 100 characters at most, so that
formatting it changes nothing.
Command line#
stellar generate driver <CATALOGUE> -o <DIR> [--software NAME] [--version VERSION]
[--repository DIR] [--lang python] [--check] [--config FILE]
stellar generate client <LIBRARY> -o <DIR>
[--repository DIR] [--lang python] [--check] [--config FILE]| Argument or option | Default | Meaning |
|---|---|---|
CATALOGUE | driver: the catalogue package (hsc-100), or hsc-100@1.0.0 to pick one of several versions; the highest version of the repository otherwise | |
LIBRARY | client: the library of steps and procedures (hsc-100-ops) | |
-o, --output <DIR> | required | Output directory, a Python package; created when missing |
--software <NAME> | the catalogue package | driver: the software name the driver registers with |
--version <VERSION> | 0.1.0 | driver: the version of the driver software |
--repository <DIR> | . | Configuration repository |
--lang | python | Language of the SDK; Python only for now |
--check | off | Write nothing; fail when the generator's files of the output directory do not match the configuration (CI) |
--config <FILE> | STELLAR_CONFIG | Global configuration, for the compilation parameters |
Each file written or kept is reported on standard error (wrote drivers/hsc_100/_generated.py,
kept drivers/hsc_100/driver.py (yours)).
| Exit code | Meaning |
|---|---|
| 0 | Generated; with --check, up to date (`drivers/hsc_100` is up to date) |
| 1 | The repository has errors (its diagnostics are printed, then Nothing generated: fix the errors first.); with --check, a generated file differs from what the configuration gives (`…/_generated.py` does not match the configuration: run `stellar generate` again) |
| 2 | The command could not run: unknown catalogue or library (the message lists those of the repository), a directory that cannot be written |
stellar generate driver#
stellar generate driver hsc-100 --repository . -o drivers/hsc_100 \
--software hsc-100-csp --version 1.0.0At the root of the Payload integration repository, this
command writes the driver of the HSC-100 camera from its catalogue packages/hsc-100.
The package has four files:
| File | Owner | Content |
|---|---|---|
_generated.py | the generator | What the catalogue says: constants, enums, one class per telecommand, one class of sample builders per component, and the abstract base class of the driver |
__init__.py | the developer | The package |
driver.py | the developer | The concrete driver: one encode_… method per telecommand and decode, as placeholders raising NotImplementedError, and main() |
test_driver.py | the developer | One test per telecommand, with example arguments, to compare with the frames of the ICD |
drivers/hsc_100 of that repository is the skeleton of hsc-100, completed from the ICD of the
camera: the CSP packets in driver.py and csp.py, and test_driver.py comparing each frame
with the one the ICD gives. The excerpts below come from it.
_generated.py#
The module starts with the identity of the catalogue and the coverage the driver registers:
PACKAGE = "hsc-100"
VERSION = "1.0.0"
HASH = "9f072328cdcaa10210a52f2150a89bbe4845205e977dc3b695e852efd460638f"
"""Hash of the compiled catalogue the module was generated from."""
CATALOGUE = "hsc-100@^1.0"
"""Catalogue the driver implements, and the versions it fits."""
TELECOMMANDS: list[str] = [
"camera.ping",
"camera.housekeeping",
"camera.set_mode",
"camera.configure_acquisition",
"camera.start_acquisition",
"camera.abort_acquisition",
"camera.set_detector_setpoint",
"camera.release_cover",
"camera.erase_storage",
"files.list_files",
"files.read_chunk",
"files.delete_file",
]
"""Telecommands the driver encodes."""
MEASURES: list[str] = [
"camera.responding",
"camera.mode",
"camera.last_status",
"camera.uptime",
"camera.boot_count",
"camera.input_voltage",
"camera.input_current",
"camera.detector_temperature",
"camera.detector_setpoint",
"camera.optics_temperature",
"camera.electronics_temperature",
"camera.tec_power",
"camera.storage_free",
"camera.files_count",
"camera.acquisitions",
"camera.last_acquisition",
"camera.acquisition_progress",
"camera.cover",
"camera.next_acquisition_in",
"camera.under_voltage",
"camera.over_current",
"camera.electronics_hot",
"camera.detector_hot",
"camera.tec_fault",
"camera.storage_error",
"camera.cover_closed",
]
"""Measures the driver decodes."""CATALOGUEis the requirement the driver registers: this version and the later ones of the same major version (hsc-100@^1.0). See Registration: catalogue and coverage.TELECOMMANDSlists every telecommand of the catalogue, those offilesincluded;MEASURESthe measures the driver decodes, without those offilesandstream, which Stellar Control produces itself.- Each enum of the catalogue is an
enum.StrEnum(CameraMode.STANDBY), those offilesincluded (FilesFileType).
Telecommands. Each telecommand has a frozen dataclass of its typed arguments, with the
defaults of the catalogue, an instance field for a multi-instance component, and semantic, the
SemanticTc as Stellar Control sent it (identifier, target, link, environment). Its docstring carries the
description of the catalogue, its type, unit and range, and whether it is hazardous. from_tc
reads the arguments of a telecommand received, defaults applied, bytes decoded from
hexadecimal, enum values checked:
@dataclass(frozen=True, slots=True, kw_only=True)
class CameraSetDetectorSetpoint:
"""Arguments of `camera.set_detector_setpoint`: Setpoint of the detector temperature (port
15)."""
temperature: float
"""Type f32 in degC, within [10 degC, 25 degC]."""
semantic: SemanticTc | None = None
"""The telecommand as Stellar Control sent it: identifier, target, link, environment."""
@classmethod
def from_tc(cls, tc: SemanticTc) -> CameraSetDetectorSetpoint:
"""The typed arguments of a telecommand received from Stellar Control."""
return cls(
temperature=float(tc["temperature"]),
semantic=tc,
)Samples. A class per component builds the raw samples of its measures, typed by the raw type of a calibrated measure (Stellar Control applies the calibration), with the instance for a multi-instance component and an optional on-board time:
class CameraMeasures:
"""Samples of the measures of `camera`, as the driver decodes them: raw values, before
calibration. The HSC-100 camera, CSP address 6."""
@staticmethod
def detector_temperature(
value: int,
*,
onboard_time: TimeLike | None = None,
) -> RawSample:
"""Detector temperature, regulated by the TEC. Raw i16, calibrated by Stellar Control into f32 in
degC."""
return RawSample(
"camera",
"detector_temperature",
value,
onboard_time=onboard_time,
)Base class. <Package>DriverBase builds the Driver of the SDK with the catalogue and the
coverage, reads each telecommand into its class and dispatches it to its abstract
encode_<component>_<telecommand>(tc, context); decode(frame, context) is abstract too. Its
constructor takes the software name and version, and passes other options (instance, codec,
output, params_schema) to the Driver. run() runs the driver until SIGINT or SIGTERM.
Echoes, chunks and listings. When a telecommand of the catalogue verifies its echo
(verify: [echo]), the base also declares the abstract echo(tc, frame) (True a conforming
echo, False a non-conforming one, None not its echo) and wires it to the Driver. When files
are read in chunks (transfer.read), it declares and wires chunks(frame), the FileChunks a
frame carries. For an on-board directory, FilesListing builds the samples of a listing, typed
and named as Stellar Control expects them, one instance per file id:
samples += [
FilesListing.file_type(FilesFileType.LTTM, file_id=7),
FilesListing.size(4096, file_id=7),
FilesListing.checksum(bytes.fromhex("1c291ca3"), file_id=7),
FilesListing.generation(2, file_id=7),
]driver.py gets their placeholders, and test_driver.py a test of the echo and of the chunks.
driver.py and test_driver.py#
The generator writes driver.py with one placeholder per telecommand:
class Hsc100Driver(Hsc100DriverBase):
"""Encodes the telecommands of hsc-100@1.0.0 and decodes its frames."""
def encode_camera_ping(
self,
tc: CameraPing,
context: LinkContext,
) -> bytes | str:
raise NotImplementedError("encode camera.ping")The developer writes the encoding and the decoding from the ICD, on the typed classes. Excerpts of the completed driver of the HSC-100, which builds CSP packets:
class Hsc100Driver(Hsc100DriverBase):
"""Encodes the telecommands of hsc-100@1.0.0 into CSP packets and decodes its replies."""
def _request(self, context: LinkContext, port: int, data: bytes = b"") -> bytes:
address = context.param("csp_address")
if address is None:
raise ValueError("the CSP address of the ground comes from the link (`csp_address`)")
if len(data) > MTU:
raise ValueError(f"{len(data)} octets of data, at most {MTU}")
return Packet(
src=int(address), dst=CAMERA, dport=port, sport=GROUND_PORT, data=data, priority=PRIORITY
).encode()
def encode_camera_set_mode(self, tc: CameraSetMode, context: LinkContext) -> bytes | str:
if tc.mode not in ("STANDBY", "READY"):
raise ValueError(f"mode {tc.mode}: only STANDBY or READY are commanded (ICD §4)")
return self._request(context, PORT_MODE, bytes([MODES[tc.mode]]))
def encode_camera_set_detector_setpoint(
self, tc: CameraSetDetectorSetpoint, context: LinkContext
) -> bytes | str:
return self._request(context, PORT_SETPOINT, struct.pack(">h", round(tc.temperature * 100)))
def decode(self, frame: bytes, context: LinkContext) -> Iterable[RawSample]:
packet = self._reply(frame, context)
if packet is None:
return []
data = packet.data
samples = [CameraMeasures.responding(True)]
match packet.sport:
case 1: # PORT_PING
pass
case 10: # PORT_HOUSEKEEPING
samples += self._housekeeping(data)
case 11: # PORT_MODE
status, mode = _fields(">BB", data, "mode reply")
samples += [CameraMeasures.last_status(status), CameraMeasures.mode(mode)]def main() -> None:
Hsc100Driver("hsc-100-csp", "1.0.0").run()test_driver.py is written with one test per telecommand, its arguments set to their default,
the low end of their range, or zero; the developer replaces the generated assertion with the
frame of the ICD. The tests run in the context of a link of the topology that uses the driver
(else of a target of the catalogue), its parameters included, so a driver that reads one finds
it; without such a link, a target <package>-1 and the link nominal:
CONTEXT = LinkContext(target="cam-em-1", link="can", params={"csp_address": 10})
DRIVER = Hsc100Driver("hsc-100-csp", "1.0.0")
def test_camera_set_detector_setpoint() -> None:
frame = DRIVER.encode_camera_set_detector_setpoint(
CameraSetDetectorSetpoint(temperature=10.0),
CONTEXT,
)
# The frame of the ICD for these arguments.
assert isinstance(frame, bytes | str)In the Payload integration repository, the same test compares the frame with the ICD:
DRIVER = Hsc100Driver("hsc-100-csp", "1.0.0")
def test_setpoint_in_hundredths_of_a_degree() -> None:
frame = DRIVER.encode_camera_set_detector_setpoint(
CameraSetDetectorSetpoint(temperature=18.25), CONTEXT
)
assert frame == bytes.fromhex("9463e000 0721") # 1825Run the driver with python -m hsc_100.driver from drivers/, and its tests with
pytest drivers/hsc_100.
A new version of the catalogue#
Generate the package again: _generated.py follows the catalogue, driver.py and
test_driver.py are kept. A telecommand added to the catalogue is a new abstract method, which a
type checker (mypy) and the instantiation of the driver report until it is written; a
telecommand renamed or removed leaves an encode_… method that no longer overrides anything.
stellar generate client#
stellar generate client hsc-100-ops --repository . -o hsc_100_opsThe package has two files, both the generator's: _generated.py and an __init__.py that
re-exports it. In the Payload integration repository, hsc_100_ops has the functions of
« First light », « Release cover » and « Download quicklook ».
For each procedure of the library, the module has two functions, named after the procedure in
snake case (First light → first_light, Download quicklook → download_quicklook):
| Function | Returns | Does |
|---|---|---|
<procedure>(client, *, <roles>, <inputs>, environment, on_ask=None, on_event=None) | RunResult | Launches the procedure and follows the run to its end (Run.wait) |
launch_<procedure>(client, *, <roles>, <inputs>, environment) | Run | Launches it and returns once Stellar Control accepted it |
The procedures still run in the executor of Stellar Control, with its leases, confirmations, log and
validated versions: a function only builds the run request, with library set to the library,
and calls Client.launch. For « TVAC cycle » of the
Test bench automation use case, a procedure with three
roles and two inputs (stellar generate client tvac-ops --repository . -o tvac_ops):
async def launch_tvac_cycle(
client: Client,
*,
chamber: str,
psu: str,
dut: str,
hot: float | str,
cold: float | str,
environment: Literal["SIM", "LAB"],
) -> Run:
"""Launches `TVAC cycle` and returns once Stellar Control accepted it: follow it with `Run.events()`
or `Run.wait()`. Two thermal cycles under vacuum of the unit under test, a functional check
on each plateau.
Roles: `chamber` a target of tvac-chamber, `psu` a target of lab-psu, `dut` a target of
hsc-100. Inputs: `hot` a number in degC, or a quantity with its unit (`"<value> degC"`);
`cold` a number in degC, or a quantity with its unit (`"<value> degC"`). Allowed in SIM, LAB.
Lasts at most 85807s. Sends hazardous telecommands: each waits for its confirmation,
answered through the run returned (`Run.wait`)."""
return await client.launch(
"TVAC cycle",
library=LIBRARY,
environment=environment,
targets={
"chamber": chamber,
"psu": psu,
"dut": dut,
},
inputs={
"hot": _quantity(hot, "degC"),
"cold": _quantity(cold, "degC"),
},
)Parameters. Every role and input is a keyword parameter, named after it (a Python keyword
or a clash with client, environment, on_ask or on_event gets a trailing _):
| Role or input | Python type | Sent as |
|---|---|---|
| Role | str | The target of the role |
bool | bool | As is |
Number with a unit (f32 degC) | float or str | 50.0 becomes "50.0 degC"; a quantity such as "50 degC" is sent as written and converted by Stellar Control |
| Number without unit | int or float | As is |
| Enum of a platform | an enum.StrEnum of the module (EpsChannel for eps_channel) | Its value |
bytes | bytes | Hexadecimal |
| Duration, instant | str | As written ("30 s") |
file_id of <type> | int or str | The on-board file identifier |
file | bytes or str | Bytes are uploaded first with Client.upload; a string is the hash of a content already stored |
environment is a Literal of the environments of allowed in when the procedure declares
them, a str otherwise. Each enum used by an input becomes a class, named after the enum, or
after its platform and the enum when two platforms have an enum of that name. The docstrings say
the roles, inputs, environments, the maximum duration of the procedure and whether it sends
hazardous telecommands, with its description.
Use. A script runs « First light » on the simulated camera cam-sim-1:
from hsc_100_ops import first_light
from stellar_control import Client
async with Client(args.api, token=args.token) as control:
result = await first_light(
control,
cam="cam-sim-1",
environment="SIM", # Literal["SIM", "BENCH"]
on_ask=confirm,
on_event=show,
)The same functions, called from pytest against an environment with the configuration and its
simulated targets, test procedures end to end from a test bench.
Stellar Control still checks everything at launch: a wrong type caught by the type checker is a
convenience, not a guarantee, and an input out of range or a target of the wrong platform is
refused by the API (ApiError, see Error Codes).
In CI#
Keep the generator's files in the repository of the code that uses them, and check them against the configuration in CI: a new version of the catalogue or of the library then fails the build until the package is generated again.
# GitHub Actions, in the repository of the driver and of the scripts
- run: stellar generate driver hsc-100 --repository config -o hsc_100 --software hsc-100-csp --check
- run: stellar generate client hsc-100-ops --repository config -o hsc_100_ops --check
- run: uv run mypy . && uv run pytest--check compares only the generator's files: driver.py, test_driver.py and the
__init__.py of a driver are the developer's and never checked.
See also Writing a Driver, Python SDK and CLI Reference.