auto-trainer-api 0.12.0__tar.gz → 1.0.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/PKG-INFO +28 -6
  2. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/README.md +26 -5
  3. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/pyproject.toml +1 -0
  4. auto_trainer_api-1.0.0/src/autotrainer/api/__init__.py +24 -0
  5. auto_trainer_api-1.0.0/src/autotrainer/api/api_event_plugin.py +54 -0
  6. auto_trainer_api-1.0.0/src/autotrainer/api/api_service.py +16 -0
  7. auto_trainer_api-1.0.0/src/autotrainer/api/api_system_status.py +13 -0
  8. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/command/api_command.py +10 -10
  9. auto_trainer_api-1.0.0/src/autotrainer/api/event/__init__.py +12 -0
  10. auto_trainer_api-1.0.0/src/autotrainer/api/event/api_event.py +21 -0
  11. auto_trainer_api-1.0.0/src/autotrainer/api/event/api_event_kind.py +5 -0
  12. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/rpc_service.py +5 -4
  13. auto_trainer_api-1.0.0/tests/test_api_event_plugin.py +96 -0
  14. auto_trainer_api-1.0.0/tests/test_legacy_names.py +59 -0
  15. auto_trainer_api-1.0.0/tests/test_rpc_send_event.py +33 -0
  16. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/tests/test_util.py +1 -1
  17. auto_trainer_api-0.12.0/src/autotrainer/api/__init__.py +0 -31
  18. auto_trainer_api-0.12.0/src/autotrainer/api/api_alarm_kind.py +0 -28
  19. auto_trainer_api-0.12.0/src/autotrainer/api/api_application_mode.py +0 -10
  20. auto_trainer_api-0.12.0/src/autotrainer/api/api_detector_kind.py +0 -38
  21. auto_trainer_api-0.12.0/src/autotrainer/api/api_emergency_stop.py +0 -17
  22. auto_trainer_api-0.12.0/src/autotrainer/api/api_system_status.py +0 -115
  23. auto_trainer_api-0.12.0/src/autotrainer/api/api_training_mode.py +0 -8
  24. auto_trainer_api-0.12.0/src/autotrainer/api/event/__init__.py +0 -18
  25. auto_trainer_api-0.12.0/src/autotrainer/api/event/api_event.py +0 -71
  26. auto_trainer_api-0.12.0/src/autotrainer/api/event/api_event_kind.py +0 -540
  27. auto_trainer_api-0.12.0/src/autotrainer/api/event/api_event_payloads.py +0 -705
  28. auto_trainer_api-0.12.0/src/autotrainer/api/event/build_event.py +0 -301
  29. auto_trainer_api-0.12.0/tests/test_api_event.py +0 -42
  30. auto_trainer_api-0.12.0/tests/test_build_event.py +0 -151
  31. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/.gitignore +0 -0
  32. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/publish-testpypi.py +0 -0
  33. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/api_options.py +0 -0
  34. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/api_system_configuration.py +0 -0
  35. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/bridge/__init__.py +0 -0
  36. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/bridge/__main__.py +0 -0
  37. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/bridge/bridge_app.py +0 -0
  38. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/bridge/bridge_service.py +0 -0
  39. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/command/__init__.py +0 -0
  40. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/command/api_command_request.py +0 -0
  41. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/command/api_command_request_response.py +0 -0
  42. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/command/api_command_request_result.py +0 -0
  43. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/command/command_request_delegate.py +0 -0
  44. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/telemetry/__init__.py +0 -0
  45. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/telemetry/open_telemetry_service.py +0 -0
  46. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/util.py +0 -0
  47. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/zeromq/__init__.py +0 -0
  48. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/zeromq/zeromq_api_service.py +0 -0
  49. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/tests/test_api_basics.py +0 -0
  50. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/tests/test_bridge_service.py +0 -0
  51. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/tests/test_resolve_enum.py +0 -0
  52. {auto_trainer_api-0.12.0 → auto_trainer_api-1.0.0}/uv.lock +0 -0
@@ -1,11 +1,12 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: auto-trainer-api
3
- Version: 0.12.0
3
+ Version: 1.0.0
4
4
  Summary: API for interfacing with the core acquisition process via platform and language agnostic message queues.
5
5
  License: AGPL-3.0-only
6
6
  Classifier: Operating System :: OS Independent
7
7
  Classifier: Programming Language :: Python :: 3
8
8
  Requires-Python: >=3.8
9
+ Requires-Dist: auto-trainer-core<2.3,>=2.2.0
9
10
  Requires-Dist: pyhumps==3.8.0
10
11
  Requires-Dist: pyzmq==26.4
11
12
  Requires-Dist: typing-extensions>=3.11
@@ -51,17 +52,38 @@ started.
51
52
  Events are published through the `send_event_dict(message)` or `send_event(message)` methods on the `RpcService`
52
53
  instance.
53
54
 
54
- `send_event_dict` accepts a dictionary with the following entries:
55
- * `kind` - an `ApiEventKind` value
55
+ The event vocabulary (`EventKind`, the payload and status types, `EventInfo` and `build_event`) lives in
56
+ `autotrainer.core.event`. The old `Api*` names remain importable from `autotrainer.api` for now.
57
+
58
+ `send_event` accepts an `EventInfo` from `autotrainer.core.event`, usually built with `build_event(kind, payload)`.
59
+ It has the following fields:
60
+ * `kind` - an `EventKind` value
56
61
  * `when` - a wall-clock value of time
57
62
  * `index` - monotonically increasing timestamp w/units of nanoseconds (typically `time.perf_counter_ns()`)
58
- * `context` - an object whose contents depend on the `ApiEventKind`; may be None for some event kinds
63
+ * `context` - an object whose contents depend on the `EventKind`; may be None for some event kinds
64
+ * `repeat` - the number of additional times the event has repeated (0 when it has not)
59
65
 
60
- `send_event` accepts an `ApiEvent` dataclass instance with the same fields.
66
+ `send_event_dict` accepts an `ApiEventDict`, the wire shape of an event: a dictionary with the same entries, in which
67
+ `repeat` is optional. The bridge and clients that build events by hand use it.
61
68
 
62
- Emergency events (`ApiEventKind.emergencyStop`, `ApiEventKind.emergencyResume`) are automatically published on both
69
+ Emergency events (`EventKind.emergencyStop`, `EventKind.emergencyResume`) are automatically published on both
63
70
  the standard event channel and a dedicated emergency channel for subscribers that only monitor critical events.
64
71
 
72
+ ### Publishing Through the Event Manager
73
+ An application that posts events to core's `EventManager` publishes them through an `ApiEventPlugin`, which it
74
+ constructs and registers itself:
75
+
76
+ ```python
77
+ from autotrainer.api import ApiEventPlugin, create_default_api_options
78
+ from autotrainer.core.event import EventManager
79
+
80
+ plugin = ApiEventPlugin(create_default_api_options())
81
+ plugin.set_enable(True) # creates and starts the RpcService
82
+ EventManager.default().register_plugin(plugin)
83
+ ```
84
+
85
+ `plugin.service` is the running `RpcService`, for example to set its `command_request_delegate`.
86
+
65
87
  ### Commands
66
88
  Commands from external sources are supported by registering a `CommandRequestDelegate` with the `RpcService` instance
67
89
  via the `command_request_delegate` property. The delegate receives an instance of `ApiCommandRequest` and must return
@@ -26,17 +26,38 @@ started.
26
26
  Events are published through the `send_event_dict(message)` or `send_event(message)` methods on the `RpcService`
27
27
  instance.
28
28
 
29
- `send_event_dict` accepts a dictionary with the following entries:
30
- * `kind` - an `ApiEventKind` value
29
+ The event vocabulary (`EventKind`, the payload and status types, `EventInfo` and `build_event`) lives in
30
+ `autotrainer.core.event`. The old `Api*` names remain importable from `autotrainer.api` for now.
31
+
32
+ `send_event` accepts an `EventInfo` from `autotrainer.core.event`, usually built with `build_event(kind, payload)`.
33
+ It has the following fields:
34
+ * `kind` - an `EventKind` value
31
35
  * `when` - a wall-clock value of time
32
36
  * `index` - monotonically increasing timestamp w/units of nanoseconds (typically `time.perf_counter_ns()`)
33
- * `context` - an object whose contents depend on the `ApiEventKind`; may be None for some event kinds
37
+ * `context` - an object whose contents depend on the `EventKind`; may be None for some event kinds
38
+ * `repeat` - the number of additional times the event has repeated (0 when it has not)
34
39
 
35
- `send_event` accepts an `ApiEvent` dataclass instance with the same fields.
40
+ `send_event_dict` accepts an `ApiEventDict`, the wire shape of an event: a dictionary with the same entries, in which
41
+ `repeat` is optional. The bridge and clients that build events by hand use it.
36
42
 
37
- Emergency events (`ApiEventKind.emergencyStop`, `ApiEventKind.emergencyResume`) are automatically published on both
43
+ Emergency events (`EventKind.emergencyStop`, `EventKind.emergencyResume`) are automatically published on both
38
44
  the standard event channel and a dedicated emergency channel for subscribers that only monitor critical events.
39
45
 
46
+ ### Publishing Through the Event Manager
47
+ An application that posts events to core's `EventManager` publishes them through an `ApiEventPlugin`, which it
48
+ constructs and registers itself:
49
+
50
+ ```python
51
+ from autotrainer.api import ApiEventPlugin, create_default_api_options
52
+ from autotrainer.core.event import EventManager
53
+
54
+ plugin = ApiEventPlugin(create_default_api_options())
55
+ plugin.set_enable(True) # creates and starts the RpcService
56
+ EventManager.default().register_plugin(plugin)
57
+ ```
58
+
59
+ `plugin.service` is the running `RpcService`, for example to set its `command_request_delegate`.
60
+
40
61
  ### Commands
41
62
  Commands from external sources are supported by registering a `CommandRequestDelegate` with the `RpcService` instance
42
63
  via the `command_request_delegate` property. The delegate receives an instance of `ApiCommandRequest` and must return
@@ -28,6 +28,7 @@ classifiers = [
28
28
  "Operating System :: OS Independent"
29
29
  ]
30
30
  dependencies = [
31
+ "auto-trainer-core >= 2.2.0, < 2.3",
31
32
  "pyhumps==3.8.0",
32
33
  "pyzmq==26.4",
33
34
  "typing_extensions>=3.11"
@@ -0,0 +1,24 @@
1
+ """
2
+ API Service functionality for Autotrainer.
3
+ """
4
+ from autotrainer.core.event import (AlarmKind, AppTrainingMode, ApplicationMode, DetectorKind,
5
+ EmergencyResumeReason, EmergencyStopReason)
6
+
7
+ from .api_event_plugin import ApiEventPlugin
8
+ from .api_options import ApiOptions, create_default_api_options
9
+ from .api_service import create_api_service
10
+ from .api_system_configuration import ApiSystemConfiguration
11
+ from .api_system_status import ApiSystemStatus, ApiPelletDeviceStatus, ApiTunnelDeviceStatus, \
12
+ ApiDetectorStatus, ApiAlarmStatus, ApiProjectStatus, ApiAnimalStatus
13
+ from .command import ApiCommand, ApiCommandRequestResponse, ApiCommandRequestResult, ApiCommandRequest
14
+ from .event import ApiEvent, ApiEventDict, ApiEventKind, ApiPelletShiftSource, build_event
15
+ from .rpc_service import ApiTopic, ApiCommandRequestErrorKind, RpcService
16
+ from .util import resolve_enum
17
+
18
+ # Pre-rename names, kept importable for a release or two (the rest are in .event and .api_system_status).
19
+ ApiAlarmKind = AlarmKind
20
+ ApiDetectorKind = DetectorKind
21
+ ApiApplicationMode = ApplicationMode
22
+ ApiTrainingMode = AppTrainingMode
23
+ ApiEmergencyStopReason = EmergencyStopReason
24
+ ApiEmergencyResumeReason = EmergencyResumeReason
@@ -0,0 +1,54 @@
1
+ from dataclasses import replace
2
+ from typing import Optional
3
+
4
+ from autotrainer.core import ProjectInfo
5
+ from autotrainer.core.event import EventInfo, EventManagerPlugin
6
+
7
+ from .api_options import ApiOptions
8
+ from .api_service import create_api_service
9
+ from .rpc_service import RpcService
10
+
11
+
12
+ class ApiEventPlugin(EventManagerPlugin):
13
+ """
14
+ An EventManager plugin that sends events to the auto-trainer-api facilities.
15
+
16
+ See auto-trainer-api for additional details.
17
+ """
18
+
19
+ def __init__(self, options: ApiOptions):
20
+ self._options = options
21
+ self._service: Optional[RpcService] = None
22
+
23
+ @property
24
+ def service(self) -> Optional[RpcService]:
25
+ return self._service
26
+
27
+ def set_project(self, project: Optional[ProjectInfo]) -> None:
28
+ pass
29
+
30
+ def set_enable(self, enable: bool) -> None:
31
+ svc = self._service
32
+ if enable and svc is None:
33
+ svc = self._service = create_api_service(self._options)
34
+ if svc is not None:
35
+ svc.start()
36
+ elif not enable and svc is not None:
37
+ svc.stop()
38
+ self._service = None
39
+
40
+ def process_event(self, info: EventInfo, repeat_count: int) -> None:
41
+ svc = self._service
42
+ if svc is not None:
43
+ if repeat_count:
44
+ info = replace(info, repeat=repeat_count)
45
+ svc.send_event(info)
46
+
47
+ def flush(self) -> None:
48
+ pass
49
+
50
+ def close(self) -> None:
51
+ svc = self._service
52
+ if svc is not None:
53
+ svc.stop()
54
+ self._service = None
@@ -0,0 +1,16 @@
1
+ from typing import Optional
2
+
3
+ from .api_options import ApiOptions
4
+ from .rpc_service import RpcService
5
+
6
+
7
+ def create_api_service(options: ApiOptions) -> Optional[RpcService]:
8
+ from .zeromq import ZeroMQApiService
9
+
10
+ # TODO Enable when ready
11
+ # configure_telemetry(options.telemetry)
12
+
13
+ if options.rpc is not None and options.rpc.enable:
14
+ return ZeroMQApiService(options.rpc)
15
+ else:
16
+ return None
@@ -0,0 +1,13 @@
1
+ from autotrainer.core.event import (AlarmStatus, AnimalStatus, BehaviorStatus, DetectorStatus, PelletDeviceStatus,
2
+ ProjectStatus, ReachStatus, SystemStatus, TunnelDeviceStatus)
3
+
4
+ # Pre-rename names, kept importable for a release or two.
5
+ ApiProjectStatus = ProjectStatus
6
+ ApiDetectorStatus = DetectorStatus
7
+ ApiAlarmStatus = AlarmStatus
8
+ ApiTunnelDeviceStatus = TunnelDeviceStatus
9
+ ApiPelletDeviceStatus = PelletDeviceStatus
10
+ ApiReachStatus = ReachStatus
11
+ ApiBehaviorStatus = BehaviorStatus
12
+ ApiAnimalStatus = AnimalStatus
13
+ ApiSystemStatus = SystemStatus
@@ -17,8 +17,8 @@ class ApiCommand(IntEnum):
17
17
  already did), UNAVAILABLE when the receiver cannot change it in its current state, and FAILED when the
18
18
  payload is missing or not a boolean. A non-success response reports the unchanged current value. Most of
19
19
  these settings publish no event when changed in the application, so their commands publish none either;
20
- the exceptions say so. Each is also reported as the like-named `is_*_enabled` field of `ApiBehaviorStatus`
21
- or `ApiPelletDeviceStatus`, so GET_STATUS reads back what these commands set. Values are spaced by ten to
20
+ the exceptions say so. Each is also reported as the like-named `is_*_enabled` field of `BehaviorStatus`
21
+ or `PelletDeviceStatus`, so GET_STATUS reads back what these commands set. Values are spaced by ten to
22
22
  leave room for the sub-settings each one gates.
23
23
  """
24
24
  NONE = 0
@@ -43,25 +43,25 @@ class ApiCommand(IntEnum):
43
43
 
44
44
  SET_APPLICATION_MODE = 120
45
45
  """
46
- Payload: {mode: ApiApplicationMode}
46
+ Payload: {mode: ApplicationMode}
47
47
  The response is application mode after attempting to set. Typically the same as the payload, but if for some reason
48
48
  the mode is invalid in the current context, it should return the actual mode.
49
- Response Payload: {mode: ApiApplicationMode}
49
+ Response Payload: {mode: ApplicationMode}
50
50
 
51
51
  Publishes applicationModeChanged only when the mode actually changes.
52
52
 
53
53
  Result: SUCCESS when the mode was set (or already had that value); UNAVAILABLE when the mode is a valid
54
- ApiApplicationMode the receiver does not support at this time; FAILED when the value is not a valid
55
- ApiApplicationMode at all. In every case the response payload carries the mode actually in effect, so a
54
+ ApplicationMode the receiver does not support at this time; FAILED when the value is not a valid
55
+ ApplicationMode at all. In every case the response payload carries the mode actually in effect, so a
56
56
  non-success response reports the unchanged current mode.
57
57
  """
58
58
 
59
59
  SET_TRAINING_MODE = 130
60
60
  """
61
- Payload: {mode: ApiTrainingMode}
61
+ Payload: {mode: AppTrainingMode}
62
62
  The response is training mode after attempting to set. Typically the same as the payload, but if for some reason
63
63
  the mode is invalid in the current context, it should return the actual mode.
64
- Response Payload: {mode: ApiTrainingMode}
64
+ Response Payload: {mode: AppTrainingMode}
65
65
 
66
66
  Publishes trainingModeChanged only when the mode actually changes.
67
67
 
@@ -89,10 +89,10 @@ class ApiCommand(IntEnum):
89
89
  """Response Payload: ApiSystemConfiguration"""
90
90
 
91
91
  GET_STATUS = 400
92
- """Response Payload: ApiSystemStatus"""
92
+ """Response Payload: SystemStatus"""
93
93
 
94
94
  GET_ANIMALS = 500
95
- """Response Payload: List[ApiAnimalStatus]
95
+ """Response Payload: List[AnimalStatus]
96
96
 
97
97
  The order of the list is not defined. An empty list is a valid result: a receiver with no animal location
98
98
  configured, or one whose location holds no animals, responds SUCCESS with [] rather than failing.
@@ -0,0 +1,12 @@
1
+ """
2
+ The wire shape of an event (:class:`ApiEventDict`) and the pre-rename names of the event vocabulary, which now
3
+ lives in :mod:`autotrainer.core.event`.
4
+ """
5
+ from autotrainer.core.event import build_event, event_payloads
6
+ from autotrainer.core.event.event_payloads import * # noqa: F401,F403 (re-export the *Context payload types)
7
+
8
+ from .api_event import ApiEvent, ApiEventDict
9
+ from .api_event_kind import ApiEventKind, ApiPelletShiftSource
10
+
11
+ __all__ = ["ApiEvent", "ApiEventDict", "ApiEventKind", "ApiPelletShiftSource", "build_event",
12
+ *event_payloads.__all__]
@@ -0,0 +1,21 @@
1
+ from datetime import datetime
2
+ from typing import Any, Mapping, Optional, TypedDict
3
+
4
+ from typing_extensions import NotRequired
5
+
6
+ from autotrainer.core.event import EventInfo, EventKind
7
+
8
+
9
+ class ApiEventDict(TypedDict):
10
+ """An event in its wire shape: what ``RpcService.send_event_dict`` publishes and what the bridge forwards
11
+ from its clients. ``RpcService.send_event`` publishes an ``EventInfo``'s fields, so its events always carry
12
+ ``repeat``; dicts built by hand may leave it out."""
13
+ kind: EventKind
14
+ when: datetime
15
+ index: int
16
+ context: Optional[Mapping[str, Any]]
17
+ repeat: NotRequired[int]
18
+
19
+
20
+ # Pre-rename name, kept importable for a release or two.
21
+ ApiEvent = EventInfo
@@ -0,0 +1,5 @@
1
+ from autotrainer.core.event import EventKind, PelletShiftSource
2
+
3
+ # Pre-rename names, kept importable for a release or two.
4
+ ApiEventKind = EventKind
5
+ ApiPelletShiftSource = PelletShiftSource
@@ -10,7 +10,8 @@ from typing import Optional, Protocol, Any, Mapping
10
10
  import humps
11
11
 
12
12
  from .command import ApiCommand, ApiCommandRequest, ApiCommandRequestResult, ApiCommandRequestResponse
13
- from .event import ApiEventDict, ApiEvent, ApiEventKind
13
+ from autotrainer.core.event import EventInfo, EventKind
14
+ from .event.api_event import ApiEventDict
14
15
  from .api_options import RpcOptions
15
16
  from .command.command_request_delegate import CommandRequestDelegate
16
17
  from .util import prepare_for_serialization
@@ -58,7 +59,7 @@ class ApiCommandRequestErrorKind(IntEnum):
58
59
 
59
60
  ApiCommandRequestSystemErrorSerialization: int = 0
60
61
 
61
- NotificationEventKinds = [ApiEventKind.emergencyStop, ApiEventKind.emergencyResume]
62
+ NotificationEventKinds = [EventKind.emergencyStop, EventKind.emergencyResume]
62
63
 
63
64
 
64
65
  @dataclass(frozen=True)
@@ -130,7 +131,7 @@ class ApiMessageQueueService(Protocol):
130
131
 
131
132
  def send_event_dict(self, message: ApiEventDict) -> bool: ...
132
133
 
133
- def send_event(self, message: ApiEvent) -> bool: ...
134
+ def send_event(self, message: EventInfo) -> bool: ...
134
135
 
135
136
  def send_command_result(self, result: ApiCommandRequestResponse) -> bool: ...
136
137
 
@@ -238,7 +239,7 @@ class RpcService:
238
239
  logger.warning("The RPC service has been terminated. Message not sent.")
239
240
  return False
240
241
 
241
- def send_event(self, message: ApiEvent) -> bool:
242
+ def send_event(self, message: EventInfo) -> bool:
242
243
  if message is None:
243
244
  return False
244
245
 
@@ -0,0 +1,96 @@
1
+ from datetime import datetime
2
+ from typing import List
3
+
4
+ import pytest
5
+
6
+ from autotrainer.api import ApiEventPlugin, create_default_api_options
7
+ from autotrainer.core.event import EventInfo, EventKind, EventManager, build_event
8
+
9
+ import autotrainer.api.api_event_plugin as api_event_plugin
10
+
11
+
12
+ class _FakeService:
13
+ def __init__(self):
14
+ self.started = False
15
+ self.stopped = False
16
+ self.sent: List[EventInfo] = []
17
+
18
+ def start(self):
19
+ self.started = True
20
+
21
+ def stop(self):
22
+ self.stopped = True
23
+
24
+ def send_event(self, info: EventInfo) -> bool:
25
+ self.sent.append(info)
26
+ return True
27
+
28
+
29
+ @pytest.fixture
30
+ def fake_service(monkeypatch) -> _FakeService:
31
+ service = _FakeService()
32
+ monkeypatch.setattr(api_event_plugin, "create_api_service", lambda options: service)
33
+ return service
34
+
35
+
36
+ @pytest.fixture
37
+ def plugin(fake_service) -> ApiEventPlugin:
38
+ return ApiEventPlugin(create_default_api_options())
39
+
40
+
41
+ def _event(kind: EventKind = EventKind.tunnelEnter) -> EventInfo:
42
+ return EventInfo(kind=kind, when=datetime(2024, 1, 1), index=7, context={"a": 1})
43
+
44
+
45
+ def test_enable_starts_service_and_disable_stops_it(plugin, fake_service):
46
+ plugin.set_enable(True)
47
+ assert fake_service.started
48
+ assert plugin.service is fake_service
49
+
50
+ plugin.set_enable(False)
51
+ assert fake_service.stopped
52
+ assert plugin.service is None
53
+
54
+
55
+ def test_close_stops_service(plugin, fake_service):
56
+ plugin.set_enable(True)
57
+ plugin.close()
58
+ assert fake_service.stopped
59
+ assert plugin.service is None
60
+
61
+
62
+ def test_disabled_plugin_drops_events(plugin, fake_service):
63
+ plugin.process_event(_event(), 0)
64
+ assert fake_service.sent == []
65
+
66
+
67
+ def test_event_without_repeat_is_sent_as_is(plugin, fake_service):
68
+ plugin.set_enable(True)
69
+ event = _event()
70
+ plugin.process_event(event, 0)
71
+ assert fake_service.sent == [event]
72
+ assert fake_service.sent[0] is event
73
+
74
+
75
+ def test_repeat_count_is_sent_as_repeat(plugin, fake_service):
76
+ plugin.set_enable(True)
77
+ event = _event()
78
+ plugin.process_event(event, 4)
79
+ sent = fake_service.sent[0]
80
+ assert sent.repeat == 4
81
+ assert (sent.kind, sent.when, sent.index, sent.context) == (event.kind, event.when, event.index, event.context)
82
+
83
+
84
+ def test_repeat_run_reaches_the_service_through_the_event_manager(plugin, fake_service):
85
+ manager = EventManager("EventManagerInstance")
86
+ try:
87
+ plugin.set_enable(True)
88
+ manager.register_plugin(plugin)
89
+ for _ in range(3):
90
+ manager.post_event(build_event(EventKind.tunnelEnter))
91
+ manager.post_event(build_event(EventKind.tunnelExit))
92
+ finally:
93
+ manager.close()
94
+
95
+ assert [(e.kind, e.repeat) for e in fake_service.sent] == [
96
+ (EventKind.tunnelEnter, 0), (EventKind.tunnelEnter, 2), (EventKind.tunnelExit, 0)]
@@ -0,0 +1,59 @@
1
+ import importlib
2
+ from datetime import datetime
3
+
4
+ import pytest
5
+
6
+ import autotrainer.api.event
7
+ import autotrainer.core.event
8
+ from autotrainer.api import ApiEvent, ApiEventKind
9
+ from autotrainer.core.event import EventInfo, event_payloads
10
+
11
+ _ALIASES = [
12
+ ("autotrainer.api", "ApiEvent", "EventInfo"),
13
+ ("autotrainer.api", "ApiEventKind", "EventKind"),
14
+ ("autotrainer.api", "ApiPelletShiftSource", "PelletShiftSource"),
15
+ ("autotrainer.api", "build_event", "build_event"),
16
+ ("autotrainer.api", "ApiApplicationMode", "ApplicationMode"),
17
+ ("autotrainer.api", "ApiTrainingMode", "AppTrainingMode"),
18
+ ("autotrainer.api", "ApiSystemStatus", "SystemStatus"),
19
+ ("autotrainer.api", "ApiPelletDeviceStatus", "PelletDeviceStatus"),
20
+ ("autotrainer.api", "ApiTunnelDeviceStatus", "TunnelDeviceStatus"),
21
+ ("autotrainer.api", "ApiDetectorStatus", "DetectorStatus"),
22
+ ("autotrainer.api", "ApiAlarmStatus", "AlarmStatus"),
23
+ ("autotrainer.api", "ApiProjectStatus", "ProjectStatus"),
24
+ ("autotrainer.api", "ApiAnimalStatus", "AnimalStatus"),
25
+ ("autotrainer.api", "ApiAlarmKind", "AlarmKind"),
26
+ ("autotrainer.api", "ApiDetectorKind", "DetectorKind"),
27
+ ("autotrainer.api", "ApiEmergencyStopReason", "EmergencyStopReason"),
28
+ ("autotrainer.api", "ApiEmergencyResumeReason", "EmergencyResumeReason"),
29
+ ("autotrainer.api.event", "ApiEvent", "EventInfo"),
30
+ ("autotrainer.api.event", "ApiEventKind", "EventKind"),
31
+ ("autotrainer.api.event", "ApiPelletShiftSource", "PelletShiftSource"),
32
+ ("autotrainer.api.event", "build_event", "build_event"),
33
+ ("autotrainer.api.event.api_event_kind", "ApiEventKind", "EventKind"),
34
+ ("autotrainer.api.event.api_event_kind", "ApiPelletShiftSource", "PelletShiftSource"),
35
+ ("autotrainer.api.api_system_status", "ApiProjectStatus", "ProjectStatus"),
36
+ ("autotrainer.api.api_system_status", "ApiDetectorStatus", "DetectorStatus"),
37
+ ("autotrainer.api.api_system_status", "ApiAlarmStatus", "AlarmStatus"),
38
+ ("autotrainer.api.api_system_status", "ApiTunnelDeviceStatus", "TunnelDeviceStatus"),
39
+ ("autotrainer.api.api_system_status", "ApiPelletDeviceStatus", "PelletDeviceStatus"),
40
+ ("autotrainer.api.api_system_status", "ApiReachStatus", "ReachStatus"),
41
+ ("autotrainer.api.api_system_status", "ApiBehaviorStatus", "BehaviorStatus"),
42
+ ("autotrainer.api.api_system_status", "ApiAnimalStatus", "AnimalStatus"),
43
+ ("autotrainer.api.api_system_status", "ApiSystemStatus", "SystemStatus"),
44
+ ]
45
+
46
+
47
+ @pytest.mark.parametrize("module,old_name,new_name", _ALIASES, ids=[f"{m}.{o}" for m, o, _ in _ALIASES])
48
+ def test_old_name_is_the_core_object(module, old_name, new_name):
49
+ assert getattr(importlib.import_module(module), old_name) is getattr(autotrainer.core.event, new_name)
50
+
51
+
52
+ @pytest.mark.parametrize("name", event_payloads.__all__)
53
+ def test_payload_names_are_re_exported(name):
54
+ assert getattr(autotrainer.api.event, name) is getattr(event_payloads, name)
55
+
56
+
57
+ def test_old_constructor_builds_an_event_info():
58
+ event = ApiEvent(kind=ApiEventKind.tunnelEnter, when=datetime.now(), index=1, context=None)
59
+ assert isinstance(event, EventInfo)
@@ -0,0 +1,33 @@
1
+ from dataclasses import asdict
2
+ from datetime import datetime
3
+ from unittest import mock
4
+
5
+ import pytest
6
+
7
+ from autotrainer.api.api_options import RpcOptions
8
+ from autotrainer.api.event.api_event import ApiEventDict
9
+ from autotrainer.api.rpc_service import ApiTopic, RpcService
10
+ from autotrainer.core.event import EventInfo, EventKind
11
+
12
+
13
+ def test_send_event_publishes_all_fields_including_repeat():
14
+ service = RpcService(RpcOptions())
15
+ event = EventInfo(kind=EventKind.tunnelEnter, when=datetime(2024, 1, 1), index=3, context=None, repeat=2)
16
+ with mock.patch.object(service, "send_event_dict", return_value=True) as send_event_dict:
17
+ assert service.send_event(event)
18
+ send_event_dict.assert_called_once_with(asdict(event))
19
+ assert send_event_dict.call_args.args[0]["repeat"] == 2
20
+
21
+
22
+ @pytest.mark.parametrize("kind,topics", [
23
+ (EventKind.emergencyStop, [ApiTopic.EMERGENCY, ApiTopic.EVENT]),
24
+ (EventKind.tunnelEnter, [ApiTopic.EVENT]),
25
+ ])
26
+ def test_send_event_dict_topics(kind, topics):
27
+ service = RpcService(RpcOptions())
28
+ message = ApiEventDict(kind=kind, when=datetime(2024, 1, 1), index=1, context=None)
29
+ with mock.patch.object(service, "_send_dict", return_value=True) as send_dict:
30
+ assert service.send_event_dict(message)
31
+ while not service._queue.empty():
32
+ service._queue.get_nowait()()
33
+ assert [call.args[0] for call in send_dict.call_args_list] == topics
@@ -43,7 +43,7 @@ class TestIntertrialResponseLikeSerialization:
43
43
  def test_like_object_serializes_to_wire_form(self):
44
44
  import collections
45
45
 
46
- from autotrainer.api.event import ReachEventMethodLike, ReachEventOutcomeLike
46
+ from autotrainer.core.event import ReachEventMethodLike, ReachEventOutcomeLike
47
47
 
48
48
  offset3d = collections.namedtuple("Offset3DTuple", "x y z") # stands in for autotrainer.core
49
49
 
@@ -1,31 +0,0 @@
1
- """
2
- API Service functionality for Autotrainer.
3
- """
4
-
5
- from typing import Optional
6
-
7
- from .api_options import ApiOptions, create_default_api_options
8
- from .event import ApiEvent, ApiEventDict, ApiEventKind, ApiPelletShiftSource, build_event
9
- from .api_application_mode import ApiApplicationMode
10
- from .api_training_mode import ApiTrainingMode
11
- from .api_system_status import ApiSystemStatus, ApiPelletDeviceStatus, ApiTunnelDeviceStatus, ApiDetectorStatus, \
12
- ApiAlarmStatus, ApiProjectStatus, ApiAnimalStatus
13
- from .api_alarm_kind import ApiAlarmKind
14
- from .api_detector_kind import ApiDetectorKind
15
- from .api_emergency_stop import ApiEmergencyStopReason, ApiEmergencyResumeReason
16
- from .api_system_configuration import ApiSystemConfiguration
17
- from .command import ApiCommand, ApiCommandRequestResponse, ApiCommandRequestResult, ApiCommandRequest
18
- from .rpc_service import ApiTopic, ApiCommandRequestErrorKind, RpcService
19
- from .util import resolve_enum
20
-
21
-
22
- def create_api_service(options: ApiOptions) -> Optional[RpcService]:
23
- from .zeromq import ZeroMQApiService
24
-
25
- # TODO Enable when ready
26
- # configure_telemetry(options.telemetry)
27
-
28
- if options.rpc is not None and options.rpc.enable:
29
- return ZeroMQApiService(options.rpc)
30
- else:
31
- return None
@@ -1,28 +0,0 @@
1
- from enum import IntEnum
2
-
3
-
4
- class ApiAlarmKind(IntEnum):
5
- # Environmental
6
- externalDoors = 101
7
-
8
- # Animal Emergency
9
- animalMissing = 201
10
- animalImmobile = 210
11
-
12
- # Behavior Emergency
13
- thrashing = 301
14
-
15
- # Device hardware
16
- deviceCommunication = 401
17
-
18
- # Jetson/Computer
19
- systemFault = 501
20
-
21
- # System maintenance
22
- systemMaintenance = 601
23
-
24
- # Training Issues (non-emergency)
25
- animalEvasion = 701
26
-
27
- # Animal Welfare (non-emergency)
28
- animalWelfare = 801
@@ -1,10 +0,0 @@
1
- from enum import IntEnum
2
-
3
-
4
- class ApiApplicationMode(IntEnum):
5
- IDLE = 0
6
- RUNNING = 100
7
- IN_DEVICE = 200
8
- IN_TRAINING = 300
9
- CALIBRATION_DCS = 1000
10
- CALIBRATION_3D = 1100