All docsStellar ControlMission control · by Stellar Systems v1.1.0

Tools

Code Generators

stellar generate: the typed skeleton of a Python driver from a catalogue, typed Python functions launching the procedures of a library, and the simulation of a platform.

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:

CommandFromWrites
stellar generate driver <catalogue>A catalogue packageThe 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 proceduresOne pair of functions per procedure, launching it through the API client with its roles, inputs and environments typed
stellar generate simulation <catalogue>A catalogue packageThe 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:

OwnerWrittenMeaning
The generatorEvery timeSays what the configuration says; never edited by hand, generated again with each version of the catalogue or library
The developerOnly when missingWritten 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#

text
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 optionDefaultMeaning
CATALOGUEdriver: the catalogue package (hsc-100), or hsc-100@1.0.0 to pick one of several versions; the highest version of the repository otherwise
LIBRARYclient: the library of steps and procedures (hsc-100-ops)
-o, --output <DIR>requiredOutput directory, a Python package; created when missing
--software <NAME>the catalogue packagedriver: the software name the driver registers with
--version <VERSION>0.1.0driver: the version of the driver software
--repository <DIR>.Configuration repository
--langpythonLanguage of the SDK; Python only for now
--checkoffWrite nothing; fail when the generator's files of the output directory do not match the configuration (CI)
--config <FILE>STELLAR_CONFIGGlobal 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 codeMeaning
0Generated; with --check, up to date (`drivers/hsc_100` is up to date)
1The 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)
2The command could not run: unknown catalogue or library (the message lists those of the repository), a directory that cannot be written

stellar generate driver#

Shell
stellar generate driver hsc-100 --repository . -o drivers/hsc_100 \
    --software hsc-100-csp --version 1.0.0

At 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:

FileOwnerContent
_generated.pythe generatorWhat 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__.pythe developerThe package
driver.pythe developerThe concrete driver: one encode_… method per telecommand and decode, as placeholders raising NotImplementedError, and main()
test_driver.pythe developerOne 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:

Python
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."""
  • CATALOGUE is 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.
  • TELECOMMANDS lists every telecommand of the catalogue, those of files included; MEASURES the measures the driver decodes, without those of files and stream, which Stellar Control produces itself.
  • Each enum of the catalogue is an enum.StrEnum (CameraMode.STANDBY), those of files included (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:

Python
@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:

Python
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:

Python
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:

Python
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:

Python
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)]
Python
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:

Python
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:

Python
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")  # 1825

Run 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#

Shell
stellar generate client hsc-100-ops --repository . -o hsc_100_ops

The 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):

FunctionReturnsDoes
<procedure>(client, *, <roles>, <inputs>, environment, on_ask=None, on_event=None)RunResultLaunches the procedure and follows the run to its end (Run.wait)
launch_<procedure>(client, *, <roles>, <inputs>, environment)RunLaunches 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):

Python
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 inputPython typeSent as
RolestrThe target of the role
boolboolAs is
Number with a unit (f32 degC)float or str50.0 becomes "50.0 degC"; a quantity such as "50 degC" is sent as written and converted by Stellar Control
Number without unitint or floatAs is
Enum of a platforman enum.StrEnum of the module (EpsChannel for eps_channel)Its value
bytesbytesHexadecimal
Duration, instantstrAs written ("30 s")
file_id of <type>int or strThe on-board file identifier
filebytes or strBytes 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:

Python
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.

YAML
# 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.

↑↓ to moveEnter to open