ezmsg-peripheraldevice 0.1.0__py3-none-any.whl

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.
@@ -0,0 +1,23 @@
1
+ from .__version__ import __version__ as __version__
2
+ from .mouse import (
3
+ MouseListener,
4
+ MouseListenerProducer,
5
+ MouseListenerSettings,
6
+ MouseListenerState,
7
+ MousePoller,
8
+ MousePollerSettings,
9
+ MousePollerState,
10
+ MousePollerTransformer,
11
+ )
12
+
13
+ __all__ = [
14
+ "__version__",
15
+ "MouseListenerProducer",
16
+ "MouseListenerSettings",
17
+ "MouseListenerState",
18
+ "MouseListener",
19
+ "MousePollerSettings",
20
+ "MousePollerState",
21
+ "MousePollerTransformer",
22
+ "MousePoller",
23
+ ]
@@ -0,0 +1,34 @@
1
+ # file generated by setuptools-scm
2
+ # don't change, don't track in version control
3
+
4
+ __all__ = [
5
+ "__version__",
6
+ "__version_tuple__",
7
+ "version",
8
+ "version_tuple",
9
+ "__commit_id__",
10
+ "commit_id",
11
+ ]
12
+
13
+ TYPE_CHECKING = False
14
+ if TYPE_CHECKING:
15
+ from typing import Tuple
16
+ from typing import Union
17
+
18
+ VERSION_TUPLE = Tuple[Union[int, str], ...]
19
+ COMMIT_ID = Union[str, None]
20
+ else:
21
+ VERSION_TUPLE = object
22
+ COMMIT_ID = object
23
+
24
+ version: str
25
+ __version__: str
26
+ __version_tuple__: VERSION_TUPLE
27
+ version_tuple: VERSION_TUPLE
28
+ commit_id: COMMIT_ID
29
+ __commit_id__: COMMIT_ID
30
+
31
+ __version__ = version = '0.1.0'
32
+ __version_tuple__ = version_tuple = (0, 1, 0)
33
+
34
+ __commit_id__ = commit_id = None
@@ -0,0 +1,263 @@
1
+ """Mouse input via pynput."""
2
+
3
+ import queue
4
+ import time
5
+
6
+ import ezmsg.core as ez
7
+ import numpy as np
8
+ from ezmsg.baseproc import (
9
+ BaseProducerUnit,
10
+ BaseStatefulProducer,
11
+ BaseStatefulTransformer,
12
+ BaseTransformerUnit,
13
+ processor_state,
14
+ )
15
+ from ezmsg.util.messages.axisarray import AxisArray, replace
16
+ from pynput.mouse import Controller, Listener
17
+
18
+ # =============================================================================
19
+ # Polled Mouse Transformer (takes LinearAxis from Clock, like Counter)
20
+ # =============================================================================
21
+
22
+
23
+ class MousePollerSettings(ez.Settings):
24
+ """Settings for MousePollerTransformer."""
25
+
26
+ pass
27
+
28
+
29
+ @processor_state
30
+ class MousePollerState:
31
+ """State for MousePollerTransformer."""
32
+
33
+ controller: Controller | None = None
34
+ template: AxisArray | None = None
35
+
36
+
37
+ class MousePollerTransformer(
38
+ BaseStatefulTransformer[
39
+ MousePollerSettings,
40
+ AxisArray.LinearAxis,
41
+ AxisArray,
42
+ MousePollerState,
43
+ ]
44
+ ):
45
+ """
46
+ Reads current mouse position when triggered by clock tick.
47
+
48
+ Takes LinearAxis input (from Clock) and outputs the current mouse position
49
+ as a single sample with the clock's timestamp.
50
+
51
+ Input: LinearAxis (from Clock - provides timing info)
52
+ Output: AxisArray with shape (1, 2) - single sample with x, y channels
53
+ """
54
+
55
+ def _reset_state(self, message: AxisArray.LinearAxis) -> None:
56
+ """Initialize mouse controller."""
57
+ self._state.controller = Controller()
58
+
59
+ # Pre-construct template AxisArray
60
+ self._state.template = AxisArray(
61
+ data=np.zeros((1, 2), dtype=np.float64),
62
+ dims=["time", "ch"],
63
+ axes={
64
+ "time": AxisArray.CoordinateAxis(
65
+ data=np.array([message.offset]),
66
+ dims=["time"],
67
+ unit="s",
68
+ ),
69
+ "ch": AxisArray.CoordinateAxis(
70
+ data=np.array(["x", "y"]),
71
+ dims=["ch"],
72
+ ),
73
+ },
74
+ key="mouse",
75
+ )
76
+
77
+ def _process(self, message: AxisArray.LinearAxis) -> AxisArray:
78
+ """Read current mouse position and return as AxisArray."""
79
+ pos = self._state.controller.position
80
+
81
+ # Create output with single sample
82
+ data = np.array([[pos[0], pos[1]]], dtype=np.float64)
83
+ time_axis = replace(
84
+ self._state.template.axes["time"],
85
+ data=np.array([message.offset]),
86
+ )
87
+
88
+ return replace(
89
+ self._state.template,
90
+ data=data,
91
+ axes={"time": time_axis, "ch": self._state.template.axes["ch"]},
92
+ )
93
+
94
+
95
+ class MousePoller(
96
+ BaseTransformerUnit[
97
+ MousePollerSettings,
98
+ AxisArray.LinearAxis,
99
+ AxisArray,
100
+ MousePollerTransformer,
101
+ ]
102
+ ):
103
+ """
104
+ Unit for reading mouse position from Clock input.
105
+
106
+ Receives LinearAxis from Clock and outputs current mouse position.
107
+ """
108
+
109
+ SETTINGS = MousePollerSettings
110
+
111
+
112
+ # =============================================================================
113
+ # Event-driven Mouse Listener Producer
114
+ # =============================================================================
115
+
116
+
117
+ class MouseListenerSettings(ez.Settings):
118
+ """Settings for MouseListenerProducer."""
119
+
120
+ pass
121
+
122
+
123
+ @processor_state
124
+ class MouseListenerState:
125
+ """State for MouseListenerProducer."""
126
+
127
+ listener: Listener | None = None
128
+ event_queue: queue.Queue | None = None
129
+ template: AxisArray | None = None
130
+
131
+
132
+ class MouseListenerProducer(BaseStatefulProducer[MouseListenerSettings, AxisArray, MouseListenerState]):
133
+ """
134
+ Produces mouse position events as they occur.
135
+
136
+ Uses pynput.mouse.Listener to capture mouse move events with timestamps.
137
+ Events are queued and emitted as AxisArray messages with irregular
138
+ CoordinateAxis timestamps.
139
+
140
+ Output: AxisArray with shape (n_events, 2) where n_events varies,
141
+ time axis is CoordinateAxis with actual event timestamps.
142
+ """
143
+
144
+ def _reset_state(self) -> None:
145
+ """Initialize listener and queue."""
146
+ self._state.event_queue = queue.Queue()
147
+
148
+ def on_move(x: int, y: int) -> None:
149
+ """Callback for mouse movement events."""
150
+ print(f"on_move called: ({x}, {y})") # DEBUG
151
+ self._state.event_queue.put((x, y, time.monotonic()))
152
+
153
+ # def on_click(x, y, button, pressed):
154
+ # print(f"{'Pressed' if pressed else 'Released'} at {(x, y)}")
155
+ # if not pressed:
156
+ # # Stop listener
157
+ # return False
158
+
159
+ self._state.listener = Listener(
160
+ on_move=on_move,
161
+ # on_click=on_click
162
+ )
163
+ self._state.listener.start()
164
+
165
+ # Check if process is trusted for input monitoring (macOS)
166
+ if hasattr(Listener, "IS_TRUSTED"):
167
+ if not Listener.IS_TRUSTED:
168
+ import warnings
169
+
170
+ warnings.warn(
171
+ "Process is not trusted for input monitoring. "
172
+ "On macOS, add your terminal to Accessibility clients: "
173
+ "System Settings > Privacy & Security > Accessibility. "
174
+ "Then fully restart your terminal (Cmd+Q).",
175
+ RuntimeWarning,
176
+ stacklevel=2,
177
+ )
178
+
179
+ # Pre-construct template AxisArray
180
+ self._state.template = AxisArray(
181
+ data=np.zeros((0, 2), dtype=np.float64),
182
+ dims=["time", "ch"],
183
+ axes={
184
+ "time": AxisArray.CoordinateAxis(
185
+ data=np.array([], dtype=np.float64),
186
+ dims=["time"],
187
+ unit="s",
188
+ ),
189
+ "ch": AxisArray.CoordinateAxis(
190
+ data=np.array(["x", "y"]),
191
+ dims=["ch"],
192
+ ),
193
+ },
194
+ key="mouse",
195
+ )
196
+
197
+ def _hash_message(self) -> int:
198
+ # Return constant - state persists across calls
199
+ return 0
200
+
201
+ def _drain_queue(self) -> tuple[list[float], list[float], list[float]]:
202
+ """Drain all events from queue."""
203
+ x_vals: list[float] = []
204
+ y_vals: list[float] = []
205
+ timestamps: list[float] = []
206
+
207
+ while True:
208
+ try:
209
+ x, y, t = self._state.event_queue.get_nowait()
210
+ x_vals.append(float(x))
211
+ y_vals.append(float(y))
212
+ timestamps.append(t)
213
+ except queue.Empty:
214
+ break
215
+
216
+ return x_vals, y_vals, timestamps
217
+
218
+ def _build_output(self, x_vals: list[float], y_vals: list[float], timestamps: list[float]) -> AxisArray | None:
219
+ """Build output AxisArray from collected events."""
220
+ if not timestamps:
221
+ return None
222
+
223
+ data = np.column_stack([x_vals, y_vals])
224
+ time_axis = replace(
225
+ self._state.template.axes["time"],
226
+ data=np.array(timestamps, dtype=np.float64),
227
+ )
228
+
229
+ return replace(
230
+ self._state.template,
231
+ data=data,
232
+ axes={"time": time_axis, "ch": self._state.template.axes["ch"]},
233
+ )
234
+
235
+ def __call__(self) -> AxisArray | None:
236
+ """Synchronous production - drain queue and return events."""
237
+ if self._hash == -1:
238
+ self._reset_state()
239
+ self._hash = 0
240
+
241
+ x_vals, y_vals, timestamps = self._drain_queue()
242
+ return self._build_output(x_vals, y_vals, timestamps)
243
+
244
+ async def _produce(self) -> AxisArray | None:
245
+ """Async production - drain queue and return events."""
246
+ x_vals, y_vals, timestamps = self._drain_queue()
247
+ return self._build_output(x_vals, y_vals, timestamps)
248
+
249
+ def __del__(self) -> None:
250
+ """Clean up listener on destruction."""
251
+ if hasattr(self, "_state") and self._state.listener is not None:
252
+ self._state.listener.stop()
253
+
254
+
255
+ class MouseListener(BaseProducerUnit[MouseListenerSettings, AxisArray, MouseListenerProducer]):
256
+ """
257
+ Unit for event-driven mouse position capture.
258
+
259
+ Produces AxisArray messages with mouse positions and their timestamps
260
+ as events occur. Time axis is an irregular CoordinateAxis.
261
+ """
262
+
263
+ SETTINGS = MouseListenerSettings
@@ -0,0 +1,71 @@
1
+ Metadata-Version: 2.4
2
+ Name: ezmsg-peripheraldevice
3
+ Version: 0.1.0
4
+ Summary: Modules to stream data from peripheral devices into ezmsg
5
+ Author-email: Chadwick Boulay <chadwick.boulay@gmail.com>
6
+ License-Expression: MIT
7
+ License-File: LICENSE
8
+ Requires-Python: >=3.10
9
+ Requires-Dist: ezmsg-baseproc>=1.1.0
10
+ Requires-Dist: ezmsg>=3.6.0
11
+ Requires-Dist: numpy>=1.26.0
12
+ Requires-Dist: pynput>=1.8.1
13
+ Description-Content-Type: text/markdown
14
+
15
+ # ezmsg-peripheraldevice
16
+
17
+ Short description of your ezmsg package.
18
+
19
+ ## Installation
20
+
21
+ ```bash
22
+ pip install ezmsg-peripheraldevice
23
+ ```
24
+
25
+ ## Dependencies
26
+
27
+ - `ezmsg`
28
+ - `ezmsg-baseproc`
29
+ - `numpy`
30
+ - `pynput`
31
+
32
+ ## Usage
33
+
34
+ ### Mouse Examples
35
+
36
+ **Event-driven mouse listener** - captures every mouse movement event:
37
+
38
+ ```bash
39
+ python examples/mouse_listen.py
40
+ ```
41
+
42
+ **Polling mouse position** - reads mouse position at a fixed rate:
43
+
44
+ ```bash
45
+ python examples/mouse_poll.py --rate 60
46
+ ```
47
+
48
+ ### Programmatic Usage
49
+
50
+ ```python
51
+ import ezmsg.core as ez
52
+ from ezmsg.peripheraldevice import MouseListener, MouseListenerSettings
53
+ from ezmsg.peripheraldevice import MousePoller, MousePollerSettings
54
+ ```
55
+
56
+ > Note: MouseListener requires extra permissions.
57
+
58
+ ## Development
59
+
60
+ We use [`uv`](https://docs.astral.sh/uv/getting-started/installation/) for development.
61
+
62
+ 1. Install [`uv`](https://docs.astral.sh/uv/getting-started/installation/) if not already installed.
63
+ 2. Fork this repository and clone your fork locally.
64
+ 3. Open a terminal and `cd` to the cloned folder.
65
+ 4. Run `uv sync` to create a `.venv` and install dependencies.
66
+ 5. (Optional) Install pre-commit hooks: `uv run pre-commit install`
67
+ 6. After making changes, run the test suite: `uv run pytest tests`
68
+
69
+ ## License
70
+
71
+ MIT License - see [LICENSE](LICENSE) for details.
@@ -0,0 +1,7 @@
1
+ ezmsg/peripheraldevice/__init__.py,sha256=i9V3KAYGZqZ3VZ_O80CfNsG2pB-kKtI72Zs5iFMwBq0,503
2
+ ezmsg/peripheraldevice/__version__.py,sha256=5jwwVncvCiTnhOedfkzzxmxsggwmTBORdFL_4wq0ZeY,704
3
+ ezmsg/peripheraldevice/mouse.py,sha256=1pbuJomunUrytbhwHwbl-gBivcc5n-ttLMj-rT7Otto,8262
4
+ ezmsg_peripheraldevice-0.1.0.dist-info/METADATA,sha256=fVBj1ReplmRpseEUiKlyyr-mG0kGNLjSQ934Vbah2e0,1718
5
+ ezmsg_peripheraldevice-0.1.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
6
+ ezmsg_peripheraldevice-0.1.0.dist-info/licenses/LICENSE,sha256=BDD8rfac1Ur7mp0_3izEdr6fHgSA3Or6U1Kb0ZAWsow,1066
7
+ ezmsg_peripheraldevice-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.28.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 ezmsg-org
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.