auto-trainer-api 0.11.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 (53) hide show
  1. {auto_trainer_api-0.11.0 → auto_trainer_api-1.0.0}/PKG-INFO +28 -6
  2. {auto_trainer_api-0.11.0 → auto_trainer_api-1.0.0}/README.md +26 -5
  3. {auto_trainer_api-0.11.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-1.0.0/src/autotrainer/api/command/api_command.py +212 -0
  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.11.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.11.0 → auto_trainer_api-1.0.0}/tests/test_util.py +1 -1
  17. auto_trainer_api-0.11.0/src/autotrainer/api/__init__.py +0 -31
  18. auto_trainer_api-0.11.0/src/autotrainer/api/api_alarm_kind.py +0 -28
  19. auto_trainer_api-0.11.0/src/autotrainer/api/api_application_mode.py +0 -10
  20. auto_trainer_api-0.11.0/src/autotrainer/api/api_detector_kind.py +0 -38
  21. auto_trainer_api-0.11.0/src/autotrainer/api/api_emergency_stop.py +0 -17
  22. auto_trainer_api-0.11.0/src/autotrainer/api/api_system_status.py +0 -101
  23. auto_trainer_api-0.11.0/src/autotrainer/api/api_training_mode.py +0 -8
  24. auto_trainer_api-0.11.0/src/autotrainer/api/command/api_command.py +0 -105
  25. auto_trainer_api-0.11.0/src/autotrainer/api/event/__init__.py +0 -18
  26. auto_trainer_api-0.11.0/src/autotrainer/api/event/api_event.py +0 -71
  27. auto_trainer_api-0.11.0/src/autotrainer/api/event/api_event_kind.py +0 -540
  28. auto_trainer_api-0.11.0/src/autotrainer/api/event/api_event_payloads.py +0 -694
  29. auto_trainer_api-0.11.0/src/autotrainer/api/event/build_event.py +0 -301
  30. auto_trainer_api-0.11.0/tests/test_api_event.py +0 -42
  31. auto_trainer_api-0.11.0/tests/test_build_event.py +0 -151
  32. {auto_trainer_api-0.11.0 → auto_trainer_api-1.0.0}/.gitignore +0 -0
  33. {auto_trainer_api-0.11.0 → auto_trainer_api-1.0.0}/publish-testpypi.py +0 -0
  34. {auto_trainer_api-0.11.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/api_options.py +0 -0
  35. {auto_trainer_api-0.11.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/api_system_configuration.py +0 -0
  36. {auto_trainer_api-0.11.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/bridge/__init__.py +0 -0
  37. {auto_trainer_api-0.11.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/bridge/__main__.py +0 -0
  38. {auto_trainer_api-0.11.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/bridge/bridge_app.py +0 -0
  39. {auto_trainer_api-0.11.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/bridge/bridge_service.py +0 -0
  40. {auto_trainer_api-0.11.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/command/__init__.py +0 -0
  41. {auto_trainer_api-0.11.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/command/api_command_request.py +0 -0
  42. {auto_trainer_api-0.11.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/command/api_command_request_response.py +0 -0
  43. {auto_trainer_api-0.11.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/command/api_command_request_result.py +0 -0
  44. {auto_trainer_api-0.11.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/command/command_request_delegate.py +0 -0
  45. {auto_trainer_api-0.11.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/telemetry/__init__.py +0 -0
  46. {auto_trainer_api-0.11.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/telemetry/open_telemetry_service.py +0 -0
  47. {auto_trainer_api-0.11.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/util.py +0 -0
  48. {auto_trainer_api-0.11.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/zeromq/__init__.py +0 -0
  49. {auto_trainer_api-0.11.0 → auto_trainer_api-1.0.0}/src/autotrainer/api/zeromq/zeromq_api_service.py +0 -0
  50. {auto_trainer_api-0.11.0 → auto_trainer_api-1.0.0}/tests/test_api_basics.py +0 -0
  51. {auto_trainer_api-0.11.0 → auto_trainer_api-1.0.0}/tests/test_bridge_service.py +0 -0
  52. {auto_trainer_api-0.11.0 → auto_trainer_api-1.0.0}/tests/test_resolve_enum.py +0 -0
  53. {auto_trainer_api-0.11.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.11.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
@@ -0,0 +1,212 @@
1
+ from enum import IntEnum
2
+
3
+
4
+ class ApiCommand(IntEnum):
5
+ """
6
+ A command value is required for all command requests.
7
+
8
+ Each member documents its request payload (`data` on the request), its response payload (`data` on the
9
+ `ApiCommandRequestResponse`), and the `ApiCommandRequestResult` a receiver is expected to return. The
10
+ `GET_*` commands are queries: they must not change any state or publish any event. A command that changes
11
+ state is expected to publish the event that a state change of that kind normally publishes, so subscribers
12
+ see the same thing whether the change came from a command or from the application itself.
13
+
14
+ Values 1000-1099 set the behavior settings that appear as the primary toggles of the Behavior preferences.
15
+ They share one shape: `{enabled: bool}` in and out, the response carrying the state actually in effect
16
+ after the attempt. Result is SUCCESS when the setting holds the requested value (including when it
17
+ already did), UNAVAILABLE when the receiver cannot change it in its current state, and FAILED when the
18
+ payload is missing or not a boolean. A non-success response reports the unchanged current value. Most of
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 `BehaviorStatus`
21
+ or `PelletDeviceStatus`, so GET_STATUS reads back what these commands set. Values are spaced by ten to
22
+ leave room for the sub-settings each one gates.
23
+ """
24
+ NONE = 0
25
+ """No command. Can be used to verify connection or that the receiver is configured to receive commands.
26
+
27
+ Changes no state and publishes no event.
28
+ Response Payload: None
29
+ Result: SUCCESS
30
+ """
31
+
32
+ START_ACQUISITION = 50
33
+ """ Obsolete
34
+
35
+ Result: UNRECOGNIZED
36
+ """
37
+
38
+ STOP_ACQUISITION = 55
39
+ """ Obsolete
40
+
41
+ Result: UNRECOGNIZED
42
+ """
43
+
44
+ SET_APPLICATION_MODE = 120
45
+ """
46
+ Payload: {mode: ApplicationMode}
47
+ The response is application mode after attempting to set. Typically the same as the payload, but if for some reason
48
+ the mode is invalid in the current context, it should return the actual mode.
49
+ Response Payload: {mode: ApplicationMode}
50
+
51
+ Publishes applicationModeChanged only when the mode actually changes.
52
+
53
+ Result: SUCCESS when the mode was set (or already had that value); UNAVAILABLE when the mode is a valid
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
+ non-success response reports the unchanged current mode.
57
+ """
58
+
59
+ SET_TRAINING_MODE = 130
60
+ """
61
+ Payload: {mode: AppTrainingMode}
62
+ The response is training mode after attempting to set. Typically the same as the payload, but if for some reason
63
+ the mode is invalid in the current context, it should return the actual mode.
64
+ Response Payload: {mode: AppTrainingMode}
65
+
66
+ Publishes trainingModeChanged only when the mode actually changes.
67
+
68
+ Result: as for SET_APPLICATION_MODE, with the response payload always carrying the mode in effect.
69
+ """
70
+
71
+ EMERGENCY_STOP = 200
72
+ """Response Payload: None
73
+
74
+ Idempotent: a stop received while already stopped is still SUCCESS and still publishes emergencyStop,
75
+ carrying the alarms active at that moment. The event announces the condition rather than a transition, so
76
+ it is not suppressed on a repeat.
77
+
78
+ Result: SUCCESS
79
+ """
80
+
81
+ EMERGENCY_RESUME = 210
82
+ """Response Payload: None
83
+
84
+ Result: SUCCESS when the receiver was stopped, publishing emergencyResume; FAILED when it was not stopped,
85
+ in which case no event is published.
86
+ """
87
+
88
+ GET_CONFIGURATION = 300
89
+ """Response Payload: ApiSystemConfiguration"""
90
+
91
+ GET_STATUS = 400
92
+ """Response Payload: SystemStatus"""
93
+
94
+ GET_ANIMALS = 500
95
+ """Response Payload: List[AnimalStatus]
96
+
97
+ The order of the list is not defined. An empty list is a valid result: a receiver with no animal location
98
+ configured, or one whose location holds no animals, responds SUCCESS with [] rather than failing.
99
+
100
+ Result: SUCCESS
101
+ """
102
+
103
+ SET_LIVE_ANALYSIS_ENABLED = 1000
104
+ """Real-time pose inference during live trials ("Live Analysis").
105
+
106
+ Payload: {enabled: bool}
107
+ Response Payload: {enabled: bool}
108
+
109
+ The gate for most of the other behavior settings: while this is off, the settings that depend on it keep
110
+ their value but have no effect.
111
+ """
112
+
113
+ SET_PELLET_DELIVERY_ENABLED = 1010
114
+ """Pellet load-send-release cycles based on pellet detection and related factors ("Deliver Pellets").
115
+
116
+ Payload: {enabled: bool}
117
+ Response Payload: {enabled: bool}
118
+
119
+ Depends on SET_LIVE_ANALYSIS_ENABLED.
120
+ """
121
+
122
+ SET_PELLET_COVER_ENABLED = 1020
123
+ """Covering the pellet while the animal is out of the tunnel, uncovering with a tone on entry
124
+ ("Cover Pellets").
125
+
126
+ Payload: {enabled: bool}
127
+ Response Payload: {enabled: bool}
128
+
129
+ Depends on SET_PELLET_DELIVERY_ENABLED.
130
+ """
131
+
132
+ SET_INTERTRIAL_PELLET_SHIFT_ENABLED = 1030
133
+ """Adjustment of the pellet delivery position from post-trial reach analysis ("Intertrial Pellet Shift").
134
+
135
+ Payload: {enabled: bool}
136
+ Response Payload: {enabled: bool}
137
+
138
+ Depends on SET_LIVE_ANALYSIS_ENABLED. Does not affect whether intertrialPelletShift events are published:
139
+ a shift that is calculated but not applied is still reported.
140
+ """
141
+
142
+ SET_HOME_ON_EXCESSIVE_DRIFT_ENABLED = 1040
143
+ """Homing the pellet motors when measured drift exceeds the configured threshold
144
+ ("Home On Excessive Drift").
145
+
146
+ Payload: {enabled: bool}
147
+ Response Payload: {enabled: bool}
148
+
149
+ Depends on SET_LIVE_ANALYSIS_ENABLED.
150
+ """
151
+
152
+ SET_TRIANGLE_PELLET_DISTANCE_DETECTION_ENABLED = 1050
153
+ """Detection of an excessive triangle-to-pellet distance
154
+ ("Triangle-pellet distance too far detection").
155
+
156
+ Payload: {enabled: bool}
157
+ Response Payload: {enabled: bool}
158
+
159
+ Depends on SET_LIVE_ANALYSIS_ENABLED.
160
+ """
161
+
162
+ SET_AUTO_CLOSE_GATE_ON_INTERTRIAL_ENABLED = 1060
163
+ """Closing the tunnel gate for the duration of intertrial analysis
164
+ ("Auto-close gate during intertrial analysis").
165
+
166
+ Payload: {enabled: bool}
167
+ Response Payload: {enabled: bool}
168
+ """
169
+
170
+ SET_AUTO_CLAMP_ENABLED = 1070
171
+ """Automatic head-clamp engagement and release ("Auto-Clamp").
172
+
173
+ Payload: {enabled: bool}
174
+ Response Payload: {enabled: bool}
175
+
176
+ Publishes autoClampEnabledChanged only when the value actually changes.
177
+ """
178
+
179
+ SET_TUNNEL_SWEEP_ENABLED = 1080
180
+ """The monitor that sweeps a misplaced pellet out of the tunnel ("Tunnel Sweep").
181
+
182
+ Payload: {enabled: bool}
183
+ Response Payload: {enabled: bool}
184
+
185
+ Enabling starts the monitor and disabling stops it, so the change takes effect immediately rather than at
186
+ the next trial.
187
+ """
188
+
189
+ SET_BATCH_TRIALS_ENABLED = 1090
190
+ """Recording trials in a batch while the animal stays in the tunnel, deferring their analysis to the end
191
+ of the batch ("Batch trials while in tunnel").
192
+
193
+ Payload: {enabled: bool}
194
+ Response Payload: {enabled: bool}
195
+
196
+ Sessions started after this is enabled report is_analysis_deferred and produce the
197
+ batchAnalysisStarted/batchAnalysisEnded bracket; a session already under way is unaffected.
198
+ """
199
+
200
+ USER_DEFINED = 99999
201
+ """A custom command defined between a particular commander and receiver. Additional information can be
202
+ defined in the `data` field.
203
+
204
+ Also the value a request carries when its command is not a member of this enum (see
205
+ `ApiCommandRequest.parse_object`).
206
+
207
+ Result: UNRECOGNIZED unless the receiver defines handling for the specific custom command.
208
+ """
209
+
210
+ @classmethod
211
+ def is_member(cls, value):
212
+ return value in cls._value2member_map_
@@ -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)