Data endpoints
Data endpoints represent the subset of SiLA endpoints which return data to the user. Observable Properties and Unobservable Properties as well as Unobservable Commands may all be used to create Data Endpoints depending on the function being wrapped.
In this context, properties are relatively clear in their data extraction functionality. Unobservable commands, however, could be functions which have input parameters (which are not allowed for SiLA properties) and use those parameters to selectively get information from the device, i.e. extracting a single value from a dictionary based on its key.
The following use case exemplifies the distinction we want to make between data endpoints and controls.
@sila.UnobservableCommand()
async def get_variable_value(self, variable: str) -> str:
"""
Read out the variable value for the currently active configuration.
Args:
VariableName: The name of the variable in the active configuration
to get the value for.
Allowed values can be accessed from `SiLAEndpointTutorialService.get_variables`.
Raises:
UnknownConfigValueError: If the variable name is not in the configuration.
Returns:
Value: The variable value.
"""
if variable not in self.active_config:
raise UnknownConfigValueError.from_config(variable, self.active_config)
return self.active_config[variable]
The above function does not fit into the SiLA definition of a property because it is parameterized, however its functionality more closely matches that of properties conceptually as static information providers.
With this distinction in mind, we will proceed to a real world example and implement some data endpoints.
Implementation
Throughout this and the next tutorial we will use the example of a clock to understand the differences between different SiLA methods. We will implement a SiLA Clock Feature and then create data endpoints for each of the three types. For our underlying clock logic we will rely on the Clock class defined in the io module of our tutorial. This class holds all the logic that we will expose to users through our SiLA ClockController feature.
The feature class
For our feature class we will start by declaring methods that we will later implement on the feature.
import asyncio
from unitelabs.cdk import sila
from unitelabs.cdk.sila import datetime
from unitelabs.cdk.subscriptions import Publisher
from ..io.clock import Clock
class ClockController(sila.Feature):
def __init__(self):
super().__init__(
originator="io.unitelabs",
category="tutorial",
)
self.protocol = Clock()
self.timer_time_remaining = Publisher[int](self.protocol.get_time_remaining, interval=1)
@sila.UnobservableProperty()
async def get_current_timestamp(self) -> datetime.datetime:
"""Get the current time."""
@sila.ObservableProperty(name="Running Clock")
async def subscribe_current_timestamp(self) -> sila.Stream[datetime.datetime]:
"""Subscribe to the current time."""
@sila.UnobservableCommand()
async def get_time_difference(self, future_time: datetime.time) -> int:
"""
Get the difference in seconds between given `FutureTime` and the current time.
Args:
FutureTime: The future time to compare the current time with.
Returns:
TimeDifference: The time difference in seconds.
"""
For each method, we have so far defined:
- name
- method type (Observable vs. Unobservable, Property vs. Command)
- parameters, if any
- return values, if any
- type hints (type of the parameters & return variables)
- documentation (docstring used to specify functionality in a human-readable way)
UnobservableProperty
The first method we will implement is the unobservable property get_current_timestamp. Here is the stub we produced above.
@sila.UnobservableProperty()
async def get_current_timestamp(self) -> datetime.datetime:
"""Get the current time."""
In this case, the structure that has been defined is:
- name: get_current_timestamp
- method type: unobservable property
- parameters: only the required self (properties don't allow input parameters)
- returns: a single return value named "Current Timestamp" (based on the name of the function - "get")
- type hints: the return value is a
datetime.datetime. - documentation: everything within the """ ... """. Additional documentation is inferred from the method name and type hints.
Now to add the logic to make this functional:
@sila.UnobservableProperty()
async def get_current_timestamp(self) -> datetime.datetime:
"""Get the current time."""
return await self.protocol.get_current_timestamp()
Internally our Clock class's _time_zone attribute is used to set the timezone for the returned timestamp. By default the Clock has no timezone, but users will be able to set this with the UnobservableCommand set_timezone which we will define later in the Control tutorial, meaning that our feature holds a particular state which can only be modified through usage of the feature.
ObservableProperty
The observable property we will implement is a method to subscribe to the clock's state, i.e. the current time. Subscribing means retrieving the state and continually receiving the updated state as soon as it changes.
@sila.ObservableProperty(name="Running Clock")
async def subscribe_current_timestamp(self) -> sila.Stream[datetime.datetime]:
"""Subscribe to the current time."""
One important thing to note here is the use of name with the sila.ObservableProperty decorator. Without explicitly setting the name here, this function would have the same identifier as our UnobservableProperty get_current_timestamp. Remember that the "get_" of UnobservableProperties and the "subscribe_" of ObservableProperties are by default stripped from names when creating unique identifiers for methods in a feature. In the case of namespace overlaps such as this, the ObservableProperty would override the UnobservableProperty in the SiLA client. By setting the name explicitly we avoid this namespace collision.
Our implementation might be as follows:
class ClockController(sila.Feature):
def __init__(self):
...
@sila.ObservableProperty(name="Running Clock")
async def subscribe_current_timestamp(self) -> sila.Stream[datetime.datetime]:
"""Subscribe to the current time."""
while True:
yield await self.protocol.get_current_timestamp()
# without any pause this will very quickly send a lot of timestamps
await asyncio.sleep(1)
This example is highly simplified for the purpose of showcasing the structure of an ObservableProperty. For more information about how to create and manage observable data sources, check out our Subscriptions Guideline.
UnobservableCommand
Unobservable commands differ from properties in that they may accept parameters. In this way, they can be used in data endpoints to retrieve information which is modified by the input parameter(s).
@sila.UnobservableCommand()
async def get_time_difference(self, future_time: datetime.time) -> int:
"""
Get the difference in seconds between given `FutureTime` and the current time.
Args:
FutureTime: The future time to compare the current time with.
Returns:
TimeDifference: The time difference in seconds.
"""
return await self.protocol.get_time_difference(future_time=future_time)
Here we provide the command with a datetime.time and ask what the time difference would be in seconds between the given future_time and the current clock time.
Last updated