RPC
plantimager.commons.RPC Link
Remote Procedure Call (RPC) Framework.
This module provides a lightweight RPC framework built on top of ZeroMQ. It supports method execution (both JSON-serializable and binary buffers), property proxying, and a publish-subscribe signaling mechanism.
Classes:
| Name | Description |
|---|---|
NoResult |
Represents an operation failure with error details. |
RPCSignal |
Lightweight publish-subscribe signal implementation. |
RPCProperty |
RPC-enabled property descriptor for proxying attribute access. |
RPCClient |
Abstract client class for connecting to and interacting with an RPC server. |
RPCServer |
Server class that exposes methods, properties, and signals over the network. |
NoResult Link
NoResult(error, traceback)
Represents an outcome with no result, typically used to indicate an operation failure along with associated error details.
This class encapsulates the error message and traceback information to provide a structured representation of operation failures, useful for logging or debugging purposes.
This class is Falsey
Attributes:
| Name | Type | Description |
|---|---|---|
error |
str
|
A string containing the error message describing the nature of the failure. |
traceback |
str
|
A string containing the traceback or detailed information about where and why the failure occurred. |
Source code in plantimager/commons/RPC.py
85 86 87 | |
RPCClient Link
RPCClient(context, url, timeout=1000)
Abstract base class for RPC clients.
This class sets up a ZeroMQ REQ socket to communicate with an RPCServer.
To use this, create a subclass that inherits from both a target interface
and this class, and decorate it with @RPCClient.register_interface.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
Context
|
The ZeroMQ context used for networking. |
required |
url
|
str
|
The URL of the target RPC server to connect to. |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
own_address |
str
|
The local IP address of the client. |
peer_address |
str
|
The IP address of the connected RPC server. |
name |
str
|
The designated name of the connected RPC server. |
Source code in plantimager/commons/RPC.py
491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 | |
execute Link
execute(method_name, params)
Execute a remote method on the RPC server.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method_name
|
str
|
The name of the method to execute. |
required |
params
|
dict
|
A dictionary containing the |
required |
Returns:
| Type | Description |
|---|---|
tuple
|
A 2-tuple |
Raises:
| Type | Description |
|---|---|
TimeoutError
|
If the server does not respond within the configured timeout. |
Source code in plantimager/commons/RPC.py
663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 | |
register_interface
classmethod
Link
register_interface(interface)
Class decorator to bind an interface to an RPCClient subclass.
This decorator inspects the provided interface and dynamically
proxies its methods and properties so that calls are forwarded
over the network to the RPC server.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
interface
|
type
|
The interface class defining the methods and properties to proxy. |
required |
Returns:
| Type | Description |
|---|---|
callable
|
A class decorator that applies the proxy logic. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
If the decorated class does not inherit from both |
Source code in plantimager/commons/RPC.py
555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 | |
stop_server Link
stop_server()
Request the connected RPC server to shut down.
Sends a non-blocking STOP_SERVER event to the remote server.
If the server responds, it logs the reply.
Source code in plantimager/commons/RPC.py
718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 | |
RPCEvents Link
Bases: StrEnum
Enumeration of valid RPC event types used for communication between clients and servers.
RPCProperty Link
RPCProperty(fget=None, fset=None, fdel=None, doc=None, notify=None, auto_notify=False)
Bases: property
RPC-enabled property descriptor.
This subclass of :class:property adds optional notification support
via an :class:RPCSignal. When a property created with RPCProperty
is assigned a new value, the supplied notify signal (if provided)
can be emitted to inform remote listeners of the change. The class is
typically used as a decorator on a getter function; the optional
notify argument is stored on the resulting property object and can
be accessed by custom setter implementations.
The setter must explicitly emit the ''notify'' signal if a change occurred.
Attributes:
| Name | Type | Description |
|---|---|---|
_notifier |
RPCSignal or None
|
Signal that will be emitted when the property's value changes.
It is initialized from the |
_auto_notify |
bool
|
When True, when the setter of the property is called and the value is modified, the _notifier is emitted. |
Initialize the property with optional RPC notification.
This subclass of property adds support for emitting an RPC signal
when the property value changes. If auto_notify is True the
signal provided via notify is emitted automatically after a successful
set operation; otherwise the caller must trigger the notification
manually.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fget
|
callable
|
Getter function that receives the instance and returns the attribute value. |
None
|
fset
|
callable
|
Setter function that receives the instance and the value to assign. |
None
|
fdel
|
callable
|
Deleter function that receives the instance and removes the attribute. |
None
|
doc
|
str
|
Documentation string for the property. |
None
|
notify
|
RPCSignal
|
RPC signal emitted when the property value is changed. |
None
|
auto_notify
|
bool
|
When |
``False``
|
See Also
property
Built‑in property class that this class extends.
Source code in plantimager/commons/RPC.py
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 | |
__set__ Link
__set__(obj, value)
Set the property on obj and emit the _notifier signal if the
observable value actually changes.
The logic is:
1. Retrieve the old value via the getter (if any).
2. Call the original setter.
3. Retrieve the new value via the getter.
4. If old != new and a notifier exists, emit the signal with the
new value.
Source code in plantimager/commons/RPC.py
341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 | |
RPCServer Link
RPCServer(context, url, alive_timeout=60)
RPCServer to use in combination with RPCClient.
The server holds the concrete implementation of an interface that is made available on the network.
To create an RPCServer create a class inheriting from an interface and RPCServer. Callable
methods must be decorated using RPCServer.register_method_buffer or RPCServer.register_method_json.
The server is also capable of sending signals defined by the RPCSignal class and proxying properties
defined with RPCProperty.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
Context
|
ZMQ context used to make the various sockets necessary for communicating with the client. |
required |
url
|
str
|
Url where the RPCServer should listen. It should be of the form "tcp:// |
required |
alive_timeout
|
int
|
Time in seconds after which the device_registry will consider this service dead or unreachable. |
60
|
Attributes:
| Name | Type | Description |
|---|---|---|
context |
Context
|
ZMQ context used to make the various sockets necessary for communicating with the client. |
url |
str
|
Url where the RPCServer is opened. The url should include the port in the form
|
name |
str
|
Name of the RPCServer as given by the deviceregistry once registered |
uuid |
str
|
Unique identifier of this RPCServer given by the registry once registered.. |
peer_addr |
str
|
Ip address of the client once connected. |
Source code in plantimager/commons/RPC.py
741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 | |
register_method_buffer
staticmethod
Link
register_method_buffer(timeout=10000)
Registers this method as remote callable procedure which will transmit its output as a buffer-like object as well as a buffer_info dictionary.
method may take any input which will be serialized via json and must output a 2-tuple:
(memoryview or bytes, dict).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
int | None
|
Specifies how much time in ms a client is expected to wait for the method to finish. If None, waits indefinitely. |
10000
|
Returns:
| Name | Type | Description |
|---|---|---|
decorator |
Callable[Callable[..., tuple[memoryview | bytes, dict]], Callable[..., tuple[memoryview | bytes, dict]]]
|
|
Source code in plantimager/commons/RPC.py
939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 | |
register_method_json
staticmethod
Link
register_method_json(timeout=10000)
Registers this method as remote callable procedure which will transmit its output via json. It is advised to only send basic types and containers as output (int, float, str, bool, list, tuple, dict, ...) Arguments are also serialized via json.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
timeout
|
int | None
|
Specifies how much time in ms a client is expected to wait for the method to finish. If None, waits indefinitely. |
10000
|
Returns:
| Name | Type | Description |
|---|---|---|
decorator |
Callable[Callable[..., Any], Callable[..., Any]]
|
|
Source code in plantimager/commons/RPC.py
912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 | |
register_to_registry Link
register_to_registry(type_, name, registry_url, overwrite=True)
Register this RPCServer to the registry at registry_address as a device of type type_ and name name.
Note: The name not be accepted as is and may be modified by the registry to avoid duplicate. This method returns the accepted name of this device.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
type_
|
str
|
Name of the device type. |
required |
name
|
str
|
Proposed name of the device. |
required |
registry_url
|
str
|
Url of the device registry. Must have the form "tcp:// |
required |
overwrite
|
Wether or not this device should take preference for the use of this name and overwrite other conflicting devices. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
accepted_name |
str
|
Name of this device as accepted by the registry. |
Source code in plantimager/commons/RPC.py
866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 | |
serve_forever Link
serve_forever()
Serve the RPC server indefinitely, handling incoming requests until a stop signal is received.
The method enters a loop that repeatedly notifies the watchdog, checks the server's
liveness, waits for a request, and dispatches the request based on its event field.
Supported events include peer discovery, inventory retrieval, signal handling
initialization, method invocation, property access, and server shutdown. Upon receiving
a STOP_SERVER event the loop terminates, sockets are closed, and a log entry is
written.
If registered to the registry and the check_alive fails, exits the loop
Returns:
| Type | Description |
|---|---|
None
|
The server runs until it is stopped; no value is returned. |
Notes
- The private attribute
_stopcontrols the loop termination. It is set toTrueonly when aSTOP_SERVERrequest is processed. _socketand_signal_socketare closed during cleanup; if either attribute isNonethe correspondingclosecall is skipped.notify_watchdogand_alive_checkare called on every iteration to maintain server health monitoring.- The method assumes that
_wait_for_requestreturns a mapping with aneventkey; a falsy return value causes the loop to continue without processing.
See Also
RPCEvents : Enum defining the possible request events. _handle_find_peer_address, _handle_get_inventory, _handle_init_signal_handling, _handle_method_call, _handle_property_get, _handle_property_set : Private helper methods that implement the handling logic for each event type.
Source code in plantimager/commons/RPC.py
1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 | |
stop_server Link
stop_server()
Stop the server and unregister the device if it has been registered.
The method sets the internal stop flag, optionally calls
:func:unregister_device to remove the device from a remote registry,
clears the identifying attributes (name, uuid, registry_addr),
and resets the corresponding entries in _cleanup_state to None.
This prevents a second unregister attempt during cleanup.
Raises:
| Type | Description |
|---|---|
Exception
|
Propagates any exception raised by :func: |
Notes
- The device is only unregistered when all three attributes
self.name,self.registry_addrandself.uuidevaluate toTrue. If any of them is falsy, the function simply sets the stop flag and returns. self._cleanup_stateis updated after a successful unregister to avoid duplicate cleanup actions later in the object's lifecycle.
See Also
unregister_device : Function that removes a device from the registry.
Source code in plantimager/commons/RPC.py
1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 | |
RPCSignal Link
RPCSignal(*arg_types)
RPCSignal
Lightweight publish‑subscribe signal implementation that stores either strong or weak references to callables and invokes them with supplied arguments.
Instances are created with a variable number of type specifications that
describe the expected arguments for the signal. These specifications are
stored unchanged in the :attr:args attribute; they are not validated at
runtime but may be used by callers for documentation or static checking.
Connections are added via :meth:connect and removed via :meth:disconnect.
When the signal is emitted with :meth:emit, each stored connection is called
in the order it was added. Weak references that have been garbage‑collected
are silently ignored.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*arg_types
|
tuple
|
Positional argument type specifications supplied at construction time. The contents are opaque to the implementation – they are kept only for external introspection. |
()
|
Attributes:
| Name | Type | Description |
|---|---|---|
arg_types |
tuple
|
The positional argument type specifications supplied to |
connections |
list
|
Mutable list of connected callables or weak references. Each entry is
either a callable object or a :class: |
See Also
weakref.WeakMethod : Standard library class used to store weak references to bound methods.
Initialize a new RPCSignal instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*arg_types
|
tuple
|
Positional argument type specifications. The values are stored in
:attr: |
()
|
Notes
arg_types can be any hashable objects (e.g., int, str,
numpy.ndarray) that the user wishes to document as the expected
argument types for the signal.
Source code in plantimager/commons/RPC.py
132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 | |
connect Link
connect(conn)
Connect a callable (or weak reference) to the signal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conn
|
Callable or WeakMethod
|
The function, bound method, or weak reference that should be called when the signal is emitted. |
required |
Raises:
| Type | Description |
|---|---|
TypeError
|
If |
Notes
The same conn is added only once; duplicate connections are ignored.
Source code in plantimager/commons/RPC.py
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 | |
disconnect Link
disconnect(conn=None)
Remove a previously connected callable or clear all connections.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
conn
|
Callable
|
The specific callable or weak reference to remove. If omitted (or
|
None
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Notes
After a successful call, the target is no longer invoked by future
:meth:emit calls.
Source code in plantimager/commons/RPC.py
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 | |
emit Link
emit(*args)
Emit the signal, invoking all connected callables.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
tuple
|
Positional arguments that will be forwarded to each connected
callable. The number and type of arguments should match the
specifications stored in :attr: |
()
|
Notes
- Weak references stored as :class:
weakref.WeakMethodare dereferenced before the call; if the underlying object has been garbage‑collected, the entry is simply skipped. - Any exception raised by a connected callable propagates to the caller
of :meth:
emit. The method does not catch or suppress errors.
Source code in plantimager/commons/RPC.py
153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 | |
validate_args Link
validate_args(*args, coerce=False)
Validates and coerces input arguments based on expected types.
This method validates the provided args against the expected types specified
in self.arg_types. If coerce is set to True, it attempts to coerce the
arguments to the expected types when a mismatch occurs. If validation or coercion
fails, the method raises appropriate exceptions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
*args
|
Positional arguments to be validated against |
()
|
|
coerce
|
bool
|
If |
False
|
Returns:
| Type | Description |
|---|---|
tuple
|
A tuple of validated (or coerced) arguments in the same order as the input. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
Raised if the number of provided arguments does not match the number of
expected types in |
TypeError
|
Raised if an argument type mismatch occurs and |
See Also
coerce_to_generic : Function used to coerce arguments to generic types. is_instance_of_generic : Function to check whether an argument matches an expected type.
Source code in plantimager/commons/RPC.py
180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 | |
RPCSignalReceiver Link
RPCSignalReceiver(context, url, signals)
Bases: Thread
Background thread that listens for and dispatches RPC signals from the server.
This thread binds a ZeroMQ REP socket to a random port and continuously
polls for incoming signal events. When a signal is received, it emits the
corresponding proxy signal on the client side.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
context
|
Context
|
The ZeroMQ context used to create the socket. |
required |
url
|
str
|
The base URL to bind the receiver socket (e.g., "tcp://127.0.0.1"). |
required |
signals
|
dict of str to RPCSignal
|
A dictionary mapping signal names to their corresponding |
required |
Attributes:
| Name | Type | Description |
|---|---|---|
port |
int
|
The randomly selected port number this receiver is bound to. |
Source code in plantimager/commons/RPC.py
407 408 409 410 411 412 413 414 415 | |
run Link
run()
Continuously processes incoming socket requests to emit signals.
This method runs an event loop that listens for incoming JSON requests via
a ZeroMQ socket. Requests are expected to contain an event key and
associated data such as signals and arguments. If a request matches the
expected event type (RPCEvents.EMIT_SIGNAL), a corresponding signal
is emitted. The loop runs until the _stop_flag is set to True.
Notes
- If the
"blocking"flag in the request isTrue, the signal emission is performed before sending back a success response. Otherwise, the success response is sent immediately, and the signal emission happens afterward.
Raises:
| Type | Description |
|---|---|
KeyError
|
If the incoming request JSON does not contain the required keys. |
ZMQError
|
If there is an issue receiving or sending data via the ZeroMQ socket. |
RuntimeError
|
If an error occurs while emitting a signal. |
Source code in plantimager/commons/RPC.py
417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 | |
stop Link
stop()
Signal the receiver thread to stop polling and shut down.
Source code in plantimager/commons/RPC.py
460 461 462 463 464 | |