UniteLabs
Tutorial

Controls

Triggering actions on a device.

Controls are always SiLA Commands. They impact the state of the connector and the attached hardware or software by triggering a discrete action on the target system of the connector, e.g. to change configuration settings, or start a parameterized process.

A control allows input parameters for execution and optionally either returns just a single response (UnobservableCommand) or a stream of responses consisting of intermediate responses and a final response (ObservableCommand).

Control actions may also have additional metadata attached, such as progress information, time remaining, and execution state. Unlike properties, there are no prefixes for commands.

Intermediate Responses

During a long-running processes observable commands may wish to provide users with intermediate responses as well as status updates. The return of intermediate responses requires status: sila.Status and intermediate: sila.Intermediate[ T ] to be passed as parameters, where T is a valid SiLA data type.

Intermediate Response types cannot be inferred and must be annotated in the intermediate parameter. The IntermediateResponses of an observable command can be annotated with a Yields section in the docstring.

src/unitelabs/tutorial/features/sila_endpoints.py
@sila.ObservableCommand()
async def iterative_method(
    self,
    seed: int,
    iterations: int,
    *,
    status: sila.Status,
    intermediate: sila.Intermediate[int],
) -> float:
    """
    Create a random number based on a `seed` after `iterations`.

    Args:
      Seed: Number used to initialize the pseudorandom number generator.
      NumberOfIterations: How many times to iterate before number generation.

    Yields:
      CurrentIteration: The current iteration.

    Returns:
      RandomNumber: A random number.
    """

    import asyncio
    import random

    random.seed(seed)

    total = iterations + 1
    for x in range(1, total):
        intermediate.send(x)
        status.update(progress=(x / total))
        await asyncio.sleep(1)

    return random.random()

Intermediate response inner types must be valid SiLA Data Types.

Implementation Example

Continuing with our example of a ClockController, let's implement some Controls.

Unobservable Command

Unobservable commands can be used to modify the state of a device or controller. For our ClockController, which is initialized with no default timezone, we can create a method that allows the user to update the currently set timezone.

src/unitelabs/tutorial/features/clock_controller.py
@sila.UnobservableCommand()
async def set_timezone(self, hours: int) -> None:
    """
    Set the timezone of the current location.

    This will update the underlying clock to use the given timezone offset.

    Args:
      Hours: The offset of the timezone in hours.
    """

    return await self.protocol.set_timezone(hours=hours)

Inside the Clock class, this method sets the current timezone. Now calls to our UnobservableProperty get_current_timestamp returns a timestamp produced using the user-defined timezone.

Observable Command

An observable command for our ClockController could be a timer functionality.

We will allow the user to set a timer with a desired timeout and give feedback to the user as the timer winds down before finally reporting that the timer is over.

src/unitelabs/tutorial/features/clock_controller.py
def __init__(self) -> None:
    ...
    self.timer_time_remaining = Publisher[int](self.protocol.get_time_remaining, interval=1)

@sila.ObservableCommand()
async def set_timer(
    self,
    wait_time: datetime.time,
    *,
    status: sila.Status,
    intermediate: sila.Intermediate[int],
) -> None:
    """
    Start a timer.

    Args:
      WaitTime: The amount of time for the timer to run.

    Yields:
      SecondsRemaining: The amount of seconds left before the alarm goes off.
    """

    timer_task = asyncio.create_task(self.protocol.set_timer(wait_time))
    try:
        with self.timer_time_remaining as sub:
            async for value in sub:
                if value == 0:
                    status.update(progress=1.0)
                    return
                status.update(
                    progress=((self.protocol.timer_total - value) / self.protocol.timer_total),
                    remaining_time=datetime.timedelta(seconds=value),
                )
                intermediate.send(value)
    finally:
        if not timer_task.done():
            timer_task.cancel()
        with contextlib.suppress(asyncio.CancelledError):
            await timer_task

Here we start our timer task by delegating it to our protocol. We monitor the progress of the timer by creating an automated subscription to the Clock.get_time_remaining, which is called every 1 second. The time remaining is then fed back to the user in the form of both a sila.Status update and a sila.Intermediate value which also sends the time remaining. Normally we would not send such redundant data with the intermediate response, this is done here only to offer a full-fledged implementation example.

Last updated