BaseCsc

class lsst.ts.salobj.BaseCsc(name: str, index: int | None = None, check_if_duplicate: bool = False, initial_state: State = State.STANDBY, override: str = '', simulation_mode: int = 0, allow_missing_callbacks: bool = False)

Bases: Controller

Base class for a Commandable SAL Component (CSC)

To implement a CSC in Python define a subclass of this class.

Parameters
namestr

Name of SAL component.

indexint or None

SAL component index, or 0 or None if the component is not indexed.

check_if_duplicatebool, optional

Check for heartbeat events from the same SAL name and index at startup (before starting the heartbeat loop)? Defaults to False in order to speed up unit tests, but amain sets it true.

initial_stateState or int, optional

Initial state for this CSC. Typically State.STANDBY (or State.OFFLINE for an externally commandable CSC) but can also be State.DISABLED, or State.ENABLED, in which case you may also want to specify override for a configurable CSC.

overridestr, optional

Configuration override file to apply if initial_state is State.DISABLED or State.ENABLED. Ignored if the CSC is not configurable.

simulation_modeint, optional

Simulation mode. The default is 0: do not simulate.

allow_missing_callbacksbool, optional

Allow missing do_<name> callback methods? Missing method will be replaced with one that raises salobj.ExpectedError. This is intended for mock controllers, which may only support a subset of commands.

Raises
ValueError

If initial_state is invalid.

salobj.ExpectedError

If simulation_mode is invalid. Note: you will only see this error if you await start_task.

RuntimeError

If class variable version is not defined, or class variable valid_simulation_modes is None.

TypeError

If one or more do_{command} methods is present that has no corresponding command, or if do_callbacks true, allow_missing_callbacks false, and one or more do_{command} methods is missing.

Notes

Constructor

The constructor does the following, beyond the parent class constructor:

  • For each command defined for the component, find a do_<name> method (which must be present) and add it as a callback to the cmd_<name> attribute.

  • The base class provides asynchronous do_<name> methods for the standard CSC commands. The default implementation is as follows (if any step fails then the remaining steps are not performed):

    • Check for validity of the requested state change; if the change is valid then:

    • Call begin_<name>. This is a no-op in the base class, and is available for the subclass to override. If this fails, then log an error and acknowledge the command as failed.

    • Change self.summary_state.

    • Call end_<name>. Again, this is a no-op in the base class, and is available for the subclass to override. If this fails then revert self.summary_state, log an error, and acknowledge the command as failed.

    • Call handle_summary_state to handle the new summary state. If this fails then leave the summary state updated (since the new value may have been reported), but acknowledge the command as failed.

    • Acknowledge the command as complete.

  • Set the summary state.

  • Run start asynchronously.

Attributes
default_initial_stateState

A class attribute. Default initial state. Leave at State.STANDBY for most CSCs; set to State.OFFLINE for externally commandable CSCs.

enable_cmdline_stateState

A class attribute. If True then add --state and (if a subclass of ConfigurableCsc) --override command-line arguments. The default is False because CSCs should start in default_initial_state unless we have good reason to do otherwise.

valid_simulation_modeslist [int]

A class attribute. Valid simulation modes; defaults to [0], meaning no simulation. The default simulation mode will be 0 if that is a valid value (and it certainly should be). Otherwise the default value will be the first entry.

simulation_helpstr or None

A class attribute. Help for the –simulate command, or None (the default value) for the default help. None is fine for the usual case of valid_simulation_modes = (0, 1). Ignored if simulation is not supported.

versionstr

A class attribute. Used to set the cscVersion attribute of the softwareVersions event. You should almost always set this to your package’s __version__ attribute.

check_if_duplicatebool

Check for heartbeat events from the same SAL name and index at startup (before starting the heartbeat loop)?

heartbeat_intervalfloat

Interval between heartbeat events, in seconds.

Attributes Summary

default_initial_state

disabled_or_enabled

Return True if the summary state is State.DISABLED or State.ENABLED.

domain

enable_cmdline_state

simulation_help

simulation_mode

Get the current simulation mode.

summary_state

Get the summary state as a State enum.

valid_simulation_modes

Methods Summary

add_arguments(parser)

Add arguments to the parser created by make_from_cmd_line.

add_kwargs_from_args(args, kwargs)

Add constructor keyword arguments based on parsed arguments.

amain(index, **kwargs)

Make a CSC from command-line arguments and run it.

assert_enabled([action])

Assert that an action that requires ENABLED state can be run.

begin_disable(data)

Begin do_disable; called before state changes.

begin_enable(data)

Begin do_enable; called before state changes.

begin_exitControl(data)

Begin do_exitControl; called before state changes.

begin_standby(data)

Begin do_standby; called before the state changes.

begin_start(data)

Begin do_start; called before state changes.

check_for_duplicate_heartbeat([num_messages])

Monitor heartbeat events and return True if any have a different private_origin.

close([exception, cancel_start])

Shut down, clean up resources and set done_task done.

close_tasks()

Shut down pending tasks.

do_disable(data)

Transition from State.ENABLED to State.DISABLED.

do_enable(data)

Transition from State.DISABLED to State.ENABLED.

do_exitControl(data)

Transition from State.STANDBY to State.OFFLINE and quit.

do_setAuthList(data)

Update the authorization list.

do_setLogLevel(data)

Set logging level.

do_standby(data)

Transition from State.DISABLED or State.FAULT to State.STANDBY.

do_start(data)

Transition from State.STANDBY to State.DISABLED.

end_disable(data)

End do_disable; called after state changes but before command acknowledged.

end_enable(data)

End do_enable; called after state changes but before command acknowledged.

end_exitControl(data)

End do_exitControl; called after state changes but before command acknowledged.

end_standby(data)

End do_standby; called after state changes but before command acknowledged.

end_start(data)

End do_start; called after state changes but before command acknowledged.

fault(code, report[, traceback])

Enter the fault state and output the errorCode event.

handle_summary_state()

Called when the summary state has changed.

implement_simulation_mode(simulation_mode)

Implement going into or out of simulation mode.

make_from_cmd_line(index[, check_if_duplicate])

Construct a CSC from command line arguments.

put_log_level()

Output the logLevel event.

set_simulation_mode(simulation_mode)

Set the simulation mode.

start()

Finish constructing the CSC.

start_phase2()

Handle the initial state.

Attributes Documentation

default_initial_state: State = 5
disabled_or_enabled

Return True if the summary state is State.DISABLED or State.ENABLED.

This is useful in handle_summary_state to determine if you should start or stop a telemetry loop, and connect to or disconnect from an external controller

domain
enable_cmdline_state = False
simulation_help: str | None = None
simulation_mode

Get the current simulation mode.

0 means normal operation (no simulation).

Raises
ExpectedError

If the new simulation mode is not a supported value.

summary_state

Get the summary state as a State enum.

valid_simulation_modes: Sequence[int] = (0,)

Methods Documentation

classmethod add_arguments(parser: ArgumentParser) None

Add arguments to the parser created by make_from_cmd_line.

Parameters
parserargparse.ArgumentParser

The argument parser.

Notes

If you override this method then you should almost certainly override add_kwargs_from_args as well.

classmethod add_kwargs_from_args(args: Namespace, kwargs: dict[str, Any]) None

Add constructor keyword arguments based on parsed arguments.

Parameters
argsargparse.Namespace

Parsed command.

kwargsdict

Keyword argument dict for the constructor. Update this based on args. The index argument will already be present if relevant.

Notes

If you override this method then you should almost certainly override add_arguments as well.

async classmethod amain(index: int | enum.IntEnum | bool | None, **kwargs: Any) None

Make a CSC from command-line arguments and run it.

Parameters
indexint, enum.IntEnum, True, or None

If the CSC is indexed, do one of the following:

  • Specify True to make index a required command-line argument that accepts any nonzero index.

  • Specify an enum.IntEnum class to make index a required command-line argument that only accepts the enum values.

  • Specify a non-zero integer to use that index. This is rare; if the CSC is indexed then the user should usually be allowed to specify the index.

If the CSC is not indexed, specify None or 0.

**kwargsdict, optional

Additional keyword arguments for your CSC’s constructor.

assert_enabled(action: str = '') None

Assert that an action that requires ENABLED state can be run.

Parameters
actionstr, optional

Action attempted. Not needed if this is called at the beginning of a do_... method, since the user will know what command was called.

async begin_disable(data: BaseMsgType) None

Begin do_disable; called before state changes.

Parameters
dataDataType

Command data

async begin_enable(data: BaseMsgType) None

Begin do_enable; called before state changes.

Parameters
dataDataType

Command data

async begin_exitControl(data: BaseMsgType) None

Begin do_exitControl; called before state changes.

Parameters
dataDataType

Command data

async begin_standby(data: BaseMsgType) None

Begin do_standby; called before the state changes.

Parameters
dataDataType

Command data

async begin_start(data: BaseMsgType) None

Begin do_start; called before state changes.

Parameters
dataDataType

Command data

async check_for_duplicate_heartbeat(num_messages: int = 5) int

Monitor heartbeat events and return True if any have a different private_origin.

Intended for use by check_if_duplicate.

The heartbeat loop should be running before this is called. This avoids the issue that if 2 CSCs are started at the same time then neither will see the other one’s heartbeat. This code also assumes that will be true; it will likely raise asyncio.TimeoutError if not.

Parameters
num_messagesfloat

The number of heartbeat messages to read.

Returns
originint

private_origin field of duplicate heartbeat, or 0 if none detected.

Raises
asyncio.TimeoutError

If no heartbeat seen within the specified time.

async close(exception: Exception | None = None, cancel_start: bool = True) None

Shut down, clean up resources and set done_task done.

May be called multiple times. The first call closes the Controller; subsequent calls wait until the Controller is closed.

Subclasses should override close_tasks instead of close, unless you have a good reason to do otherwise.

Parameters
exceptionException, optional

The exception that caused stopping, if any, in which case the self.done_task exception is set to this value. Specify None for a normal exit, in which case the self.done_task result is set to None.

cancel_startbool, optional

Cancel the start task? Leave this true unless calling this from the start task.

Notes

Removes the SAL log handler, calls close_tasks to stop all background tasks, pauses briefly to allow final SAL messages to be sent, then closes the dds domain.

async close_tasks() None

Shut down pending tasks. Called by close.

async do_disable(data: BaseMsgType) None

Transition from State.ENABLED to State.DISABLED.

Parameters
datacmd_disable.DataType

Command data

async do_enable(data: BaseMsgType) None

Transition from State.DISABLED to State.ENABLED.

Parameters
datacmd_enable.DataType

Command data

async do_exitControl(data: BaseMsgType) None

Transition from State.STANDBY to State.OFFLINE and quit.

Parameters
datacmd_exitControl.DataType

Command data

async do_setAuthList(data: BaseMsgType) None

Update the authorization list.

Parameters
datacmd_setAuthList.DataType

Authorization lists.

Notes

Add items if the data string starts with “+”, ignoring duplicates (both with respect to the existing items and within the data string). Remove items if the data string starts with “-”, ignoring missing items (items specified for removal that do not exist). Ignore whitespace after each comma and after the +/- prefix.

async do_setLogLevel(data: BaseMsgType) None

Set logging level.

Parameters
datacmd_setLogLevel.DataType

Logging level.

async do_standby(data: BaseMsgType) None

Transition from State.DISABLED or State.FAULT to State.STANDBY.

Parameters
datacmd_standby.DataType

Command data

async do_start(data: BaseMsgType) None

Transition from State.STANDBY to State.DISABLED.

Parameters
datacmd_start.DataType

Command data

async end_disable(data: BaseMsgType) None

End do_disable; called after state changes but before command acknowledged.

Parameters
dataDataType

Command data

async end_enable(data: BaseMsgType) None

End do_enable; called after state changes but before command acknowledged.

Parameters
dataDataType

Command data

async end_exitControl(data: BaseMsgType) None

End do_exitControl; called after state changes but before command acknowledged.

Parameters
dataDataType

Command data

async end_standby(data: BaseMsgType) None

End do_standby; called after state changes but before command acknowledged.

Parameters
dataDataType

Command data

async end_start(data: BaseMsgType) None

End do_start; called after state changes but before command acknowledged.

Parameters
dataDataType

Command data

async fault(code: int | None, report: str, traceback: str = '') None

Enter the fault state and output the errorCode event.

Parameters
codeint

Error code for the errorCode event. If None then errorCode is not output and you should output it yourself. Specifying None is deprecated; please always specify an integer error code.

reportstr

Description of the error.

tracebackstr, optional

Description of the traceback, if any.

async handle_summary_state() None

Called when the summary state has changed.

Override to perform tasks such as starting and stopping telemetry (example).

Notes

The versions in BaseCsc and ConfigurableCsc do nothing, so if you subclass one of those you do not need to call await super().handle_summary_state().

async implement_simulation_mode(simulation_mode: int) None

Implement going into or out of simulation mode.

Deprecated. See simulation mode for details.

Parameters
simulation_modeint

Requested simulation mode; 0 for normal operation.

Raises
ExpectedError

If simulation_mode is not a supported value.

classmethod make_from_cmd_line(index: int | enum.IntEnum | bool | None, check_if_duplicate: bool = False, **kwargs: Any) BaseCsc

Construct a CSC from command line arguments.

Parameters
indexint, enum.IntEnum, True, or None

If the CSC is indexed, do one of the following:

  • Specify True to make index a required command-line argument that accepts any nonzero index.

  • Specify an enum.IntEnum class to make index a required command-line argument that only accepts the enum values.

  • Specify a non-zero integer to use that index. This is rare; if the CSC is indexed then the user should usually be allowed to specify the index.

If the CSC is not indexed, specify None or 0.

check_if_duplicatebool, optional

Check for heartbeat events from the same SAL name and index at startup (before starting the heartbeat loop)? The default is False, to match the BaseCsc default. Note: handled by setting the attribute directly instead of as a constructor argument, because CSCs may not all support the constructor argument.

**kwargsdict, optional

Additional keyword arguments for your CSC’s constructor.

Returns
csccls

The CSC.

Notes

To add additional command-line arguments, override add_arguments and add_kwargs_from_args.

async put_log_level() None

Output the logLevel event.

async set_simulation_mode(simulation_mode: int) None

Set the simulation mode.

Await implement_simulation_mode, update the simulation mode property and report the new value.

Parameters
simulation_modeint

Requested simulation mode; 0 for normal operation.

async start() None

Finish constructing the CSC.

async start_phase2() None

Handle the initial state.

Called after start.