-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #3 from pymeasure/add-core
Core elements added.
- Loading branch information
Showing
12 changed files
with
1,020 additions
and
5 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,31 @@ | ||
# | ||
# This file is part of the PyLECO package. | ||
# | ||
# Copyright (c) 2023-2023 PyLECO Developers | ||
# | ||
# Permission is hereby granted, free of charge, to any person obtaining a copy | ||
# of this software and associated documentation files (the "Software"), to deal | ||
# in the Software without restriction, including without limitation the rights | ||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
# copies of the Software, and to permit persons to whom the Software is | ||
# furnished to do so, subject to the following conditions: | ||
# | ||
# The above copyright notice and this permission notice shall be included in | ||
# all copies or substantial portions of the Software. | ||
# | ||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
# THE SOFTWARE. | ||
# | ||
|
||
""" | ||
Core - Essential modules for pyleco. | ||
""" | ||
|
||
# Current protocol version | ||
VERSION: int = 0 | ||
VERSION_B: bytes = VERSION.to_bytes(1, "big") |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,76 @@ | ||
# | ||
# This file is part of the PyLECO package. | ||
# | ||
# Copyright (c) 2023-2023 PyLECO Developers | ||
# | ||
# Permission is hereby granted, free of charge, to any person obtaining a copy | ||
# of this software and associated documentation files (the "Software"), to deal | ||
# in the Software without restriction, including without limitation the rights | ||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
# copies of the Software, and to permit persons to whom the Software is | ||
# furnished to do so, subject to the following conditions: | ||
# | ||
# The above copyright notice and this permission notice shall be included in | ||
# all copies or substantial portions of the Software. | ||
# | ||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
# THE SOFTWARE. | ||
# | ||
|
||
""" | ||
These classes show pyleco's internal API of tools that talk with the LECO protocol. | ||
They are not defined by LECO itself as it does not touch the message transfer. | ||
Any Component could use these tools in order to send and read messsages. | ||
For example a Director might use these tools to direct an Actor. | ||
""" | ||
|
||
from typing import Any, Optional, Protocol | ||
|
||
from .leco_protocols import ComponentProtocol | ||
from .message import Message | ||
from .rpc_generator import RPCGenerator | ||
|
||
|
||
class CommunicatorProtocol(ComponentProtocol, Protocol): | ||
"""A helper class for a Component, to communicate via the LECO protocol. | ||
For example a Director might use such a class to send/read messages to/from an Actor. | ||
""" | ||
|
||
name: str | ||
namespace: Optional[str] = None | ||
rpc_generator: RPCGenerator | ||
|
||
def sign_in(self) -> None: ... | ||
|
||
def sign_out(self) -> None: ... | ||
|
||
def send(self, | ||
receiver: str | bytes, | ||
conversation_id: Optional[bytes] = None, | ||
data: Optional[Any] = None, | ||
**kwargs) -> None: | ||
"""Send a message based on kwargs.""" | ||
self.send_message(message=Message( | ||
receiver=receiver, conversation_id=conversation_id, data=data, **kwargs | ||
)) | ||
|
||
def send_message(self, message: Message) -> None: ... | ||
|
||
def ask(self, receiver: bytes | str, conversation_id: Optional[bytes] = None, | ||
data: Optional[Any] = None, | ||
**kwargs) -> Message: | ||
"""Send a message based on kwargs and retrieve the response.""" | ||
return self.ask_message(message=Message( | ||
receiver=receiver, conversation_id=conversation_id, data=data, **kwargs)) | ||
|
||
def ask_message(self, message: Message) -> Message: ... | ||
|
||
def close(self) -> None: ... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,135 @@ | ||
# | ||
# This file is part of the PyLECO package. | ||
# | ||
# Copyright (c) 2023-2023 PyLECO Developers | ||
# | ||
# Permission is hereby granted, free of charge, to any person obtaining a copy | ||
# of this software and associated documentation files (the "Software"), to deal | ||
# in the Software without restriction, including without limitation the rights | ||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
# copies of the Software, and to permit persons to whom the Software is | ||
# furnished to do so, subject to the following conditions: | ||
# | ||
# The above copyright notice and this permission notice shall be included in | ||
# all copies or substantial portions of the Software. | ||
# | ||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
# THE SOFTWARE. | ||
# | ||
|
||
""" | ||
These classes show which methods have to be available via RPC in order to comply with LECO message | ||
definitions. | ||
A combination of type checking and unit tests can test the compliance with LECO definitions. | ||
For example, if you want to verify, that the class `Actor` fulfills the requirements for a | ||
Component, for an Actor which supports Polling and setting the log level, you may use the following | ||
tests. | ||
For a static test, that all the methods are present with the correct types, the following works: | ||
.. code:: | ||
class ExtendedActorProtocol(ExtendedComponentProtocol, PollingActorProtocol, Protocol): | ||
"Combine all required Protocols for the class under test." | ||
pass | ||
def static_test_methods_are_present(): | ||
def testing(component: ExtendedActorProtocol): | ||
pass | ||
testing(Actor(name="test", cls=FantasyInstrument)) | ||
For unit test, that all the necessary methods are reachable via RPC, the following works: | ||
.. code:: | ||
protocol_methods = [m for m in dir(ExtendedActorProtocol) if not m.startswith("_")] | ||
@pytest.fixture | ||
def component_methods(actor: Actor): | ||
response = actor.rpc.process_request( | ||
'{"id": 1, "method": "rpc.discover", "jsonrpc": "2.0"}') | ||
result = actor.rpc_generator.get_result_from_response(response) # type: ignore | ||
return result.get('methods') | ||
@pytest.mark.parametrize("method", protocol_methods) | ||
def test_method_is_available(component_methods, method): | ||
for m in component_methods: | ||
if m.get('name') == method: | ||
return | ||
raise AssertionError(f"Method {method} is not available.") | ||
""" | ||
|
||
from typing import Any, Optional, Protocol, Union | ||
|
||
|
||
class ComponentProtocol(Protocol): | ||
"""Any Component of the LECO protocol.""" | ||
|
||
def pong(self) -> None: | ||
"""Respond to any request.""" | ||
return # always succeeds. | ||
|
||
|
||
class ExtendedComponentProtocol(ComponentProtocol, Protocol): | ||
"""A Component which supports more features.""" | ||
|
||
def set_log_level(self, level: int) -> None: ... | ||
|
||
def shut_down(self) -> None: ... | ||
|
||
|
||
class CoordinatorProtocol(ComponentProtocol, Protocol): | ||
"""A command protocol Coordinator""" | ||
|
||
def sign_in(self) -> None: ... | ||
|
||
def sign_out(self) -> None: ... | ||
|
||
def coordinator_sign_in(self) -> None: ... | ||
|
||
def coordinator_sign_out(self) -> None: ... | ||
|
||
def set_nodes(self, nodes: dict[str, str]) -> None: ... | ||
|
||
def compose_global_directory(self) -> dict: ... | ||
|
||
def compose_local_directory(self) -> dict: ... | ||
|
||
|
||
class ActorProtocol(ComponentProtocol, Protocol): | ||
"""An Actor Component.""" | ||
|
||
def get_parameters(self, parameters: Union[list[str], tuple[str, ...]]) -> dict[str, Any]: ... | ||
|
||
def set_parameters(self, parameters: dict[str, Any]) -> None: ... | ||
|
||
def call_action(self, action: str, _args: Optional[list | tuple] = None, **kwargs) -> Any: ... | ||
|
||
|
||
class PollingActorProtocol(ActorProtocol, Protocol): | ||
"""An Actor which allows regular polling.""" | ||
|
||
def start_polling(self, polling_interval: Optional[float]) -> None: ... | ||
|
||
def set_polling_interval(self, polling_interval: float) -> None: ... | ||
|
||
def get_polling_interval(self) -> float: ... | ||
|
||
def stop_polling(self) -> None: ... | ||
|
||
|
||
class LockingActorProtocol(ActorProtocol, Protocol): | ||
"""An Actor which allows to lock the device or channels of the device.""" | ||
|
||
def lock(self, resource: Optional[str] = None) -> bool: ... | ||
|
||
def unlock(self, resource: Optional[str] = None) -> None: ... | ||
|
||
def force_unlock(self, resource: Optional[str] = None) -> None: ... |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,148 @@ | ||
# | ||
# This file is part of the PyLECO package. | ||
# | ||
# Copyright (c) 2023-2023 PyLECO Developers | ||
# | ||
# Permission is hereby granted, free of charge, to any person obtaining a copy | ||
# of this software and associated documentation files (the "Software"), to deal | ||
# in the Software without restriction, including without limitation the rights | ||
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell | ||
# copies of the Software, and to permit persons to whom the Software is | ||
# furnished to do so, subject to the following conditions: | ||
# | ||
# The above copyright notice and this permission notice shall be included in | ||
# all copies or substantial portions of the Software. | ||
# | ||
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | ||
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | ||
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | ||
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER | ||
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, | ||
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN | ||
# THE SOFTWARE. | ||
# | ||
|
||
from json import JSONDecodeError | ||
from typing import Any, Optional, Self | ||
|
||
|
||
from . import VERSION_B | ||
from .serialization import (create_header_frame, serialize_data, interpret_header, split_name, | ||
deserialize_data, FullName, Header | ||
) | ||
|
||
|
||
# Control transfer protocol | ||
class Message: | ||
"""A message in LECO protocol. | ||
It consists of the following bytes frames, for which each an attribute exists: | ||
- `version` | ||
- `receiver` | ||
- `sender` | ||
- `header` | ||
- 0 or more `payload` frames | ||
If you do not specify a sender, the sending program shall add it itself. | ||
The :attr:`data` attribute is the content of the first :attr:`payload` frame. It can be set with | ||
the corresponding argument. | ||
All attributes, except the official frames, are for convenience. | ||
""" | ||
|
||
version: bytes = VERSION_B | ||
receiver: bytes | ||
sender: bytes | ||
header: bytes | ||
payload: list[bytes] | ||
|
||
def __init__(self, receiver: bytes | str, sender: bytes | str = b"", | ||
data: Optional[bytes | str | Any] = None, | ||
header: Optional[bytes] = None, | ||
conversation_id: Optional[bytes] = None, | ||
message_id: Optional[bytes] = None, | ||
message_type: Optional[bytes] = None, | ||
) -> None: | ||
self.receiver = receiver if isinstance(receiver, bytes) else receiver.encode() | ||
self.sender = sender if isinstance(sender, bytes) else sender.encode() | ||
if header and (conversation_id or message_id or message_type): | ||
raise ValueError( | ||
"You may not specify the header and some header element at the same time!") | ||
self.header = (create_header_frame(conversation_id=conversation_id, message_id=message_id, | ||
message_type=message_type) | ||
if header is None else header) | ||
if isinstance(data, bytes): | ||
self.payload = [data] | ||
elif isinstance(data, str): | ||
self.payload = [data.encode()] | ||
elif data is None: | ||
self.payload = [] | ||
else: | ||
self.payload = [serialize_data(data)] | ||
|
||
@classmethod | ||
def from_frames(cls, version: bytes, receiver: bytes, sender: bytes, header: bytes, | ||
*payload: bytes) -> Self: | ||
"""Create a message from a frames list, for example after reading from a socket. | ||
.. code:: | ||
frames = socket.recv_multipart() | ||
message = Message.from_frames(*frames) | ||
""" | ||
inst = cls(receiver, sender, header=header) | ||
inst.version = version | ||
inst.payload = list(payload) | ||
return inst | ||
|
||
def to_frames(self) -> list[bytes]: | ||
"""Get a list representation of the message, ready for sending it.""" | ||
if not self.sender: | ||
raise ValueError("Empty sender frame not allowed to send.") | ||
return self._to_frames_without_sender_check() | ||
|
||
def _to_frames_without_sender_check(self) -> list[bytes]: | ||
return [self.version, self.receiver, self.sender, self.header] + self.payload | ||
|
||
# Convenience methods to access elements | ||
@property | ||
def receiver_elements(self) -> FullName: | ||
return split_name(self.receiver) | ||
|
||
@property | ||
def sender_elements(self) -> FullName: | ||
return split_name(self.sender) | ||
|
||
@property | ||
def header_elements(self) -> Header: | ||
return interpret_header(self.header) | ||
|
||
@property | ||
def conversation_id(self) -> bytes: | ||
return self.header_elements.conversation_id | ||
|
||
@property | ||
def data(self) -> object: | ||
return deserialize_data(self.payload[0]) if self.payload else None | ||
|
||
def __eq__(self, other: Any) -> bool: | ||
if not isinstance(other, Message): | ||
return NotImplemented | ||
partial_comparison = ( | ||
self.version == other.version | ||
and self.receiver == other.receiver | ||
and self.sender == other.sender | ||
and self.header == other.header | ||
) | ||
try: | ||
# Try to compare the data (python objects) instead of their bytes representation. | ||
my_data = self.data | ||
other_data = other.data | ||
except JSONDecodeError: | ||
# Maybe the payload is binary, compare the raw payload | ||
return partial_comparison and self.payload == other.payload | ||
else: | ||
return (partial_comparison and my_data == other_data | ||
and self.payload[1:] == other.payload[1:]) | ||
|
||
def __repr__(self) -> str: | ||
return f"Message.from_frames({self._to_frames_without_sender_check()})" |
Oops, something went wrong.