asmagic 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.
asmagic/__init__.py ADDED
@@ -0,0 +1,31 @@
1
+ """
2
+ asmagic - Read Daya from asMagic App
3
+
4
+ A Python library for subscribing to AR sensor data streams.
5
+
6
+ Example - Simple and clean:
7
+ >>> from asmagic import ARDataSubscriber
8
+ >>>
9
+ >>> sub = ARDataSubscriber("192.168.1.100")
10
+ >>>
11
+ >>> # Get data - super simple!
12
+ >>> data = sub.get()
13
+ >>> if data:
14
+ ... print(data.timestamp)
15
+ ... print(data.velocity)
16
+ ... print(data.local_pose)
17
+ >>>
18
+ >>> sub.close()
19
+ """
20
+
21
+ __version__ = "0.1.0"
22
+ __author__ = "ASMagic Team"
23
+
24
+ # Main exports - keep it simple, no need to expose ARFrame
25
+ from .subscriber import ARDataSubscriber
26
+
27
+ __all__ = [
28
+ "ARDataSubscriber",
29
+ "__version__",
30
+ ]
31
+
asmagic/data_types.py ADDED
@@ -0,0 +1,236 @@
1
+ """
2
+ Data types for AR data subscription.
3
+
4
+ This module defines the data structures returned by ARDataSubscriber.
5
+ Easy to extend and maintain when new data types are added.
6
+ """
7
+
8
+ from dataclasses import dataclass, field
9
+ from typing import Optional
10
+ import numpy as np
11
+
12
+ # 延迟导入图像处理库,避免强制依赖
13
+ _cv2 = None
14
+ _Image = None
15
+ _io = None
16
+
17
+ def _ensure_image_libs():
18
+ """Ensure image processing libraries are imported"""
19
+ global _cv2, _Image, _io
20
+ if _cv2 is None:
21
+ try:
22
+ import cv2
23
+ _cv2 = cv2
24
+ except ImportError:
25
+ raise ImportError("opencv-python is required for image display: pip install opencv-python")
26
+
27
+ if _Image is None:
28
+ try:
29
+ from PIL import Image
30
+ import io
31
+ _Image = Image
32
+ _io = io
33
+ except ImportError:
34
+ raise ImportError("Pillow is required for image processing: pip install Pillow")
35
+
36
+
37
+ @dataclass
38
+ class ARFrame:
39
+ """
40
+ A single frame of AR data containing all sensor readings.
41
+
42
+ Attributes:
43
+ timestamp: Unix timestamp of the frame
44
+ color_img: Raw bytes of the color image (JPEG/PNG encoded)
45
+ depth_img: Raw bytes of the depth image (uint16 format)
46
+ depth_width: Width of the depth image in pixels
47
+ depth_height: Height of the depth image in pixels
48
+ local_pose: 4x4 local transformation matrix as numpy array
49
+ global_pose: 4x4 global transformation matrix as numpy array
50
+ velocity: Velocity vector as numpy array
51
+ camera_intrinsics: Camera intrinsic parameters as numpy array
52
+ """
53
+ timestamp: float = 0.0
54
+ color_img: bytes = b""
55
+ depth_img: bytes = b""
56
+ depth_width: int = 0
57
+ depth_height: int = 0
58
+ local_pose: np.ndarray = field(default_factory=lambda: np.array([]))
59
+ global_pose: np.ndarray = field(default_factory=lambda: np.array([]))
60
+ velocity: np.ndarray = field(default_factory=lambda: np.array([]))
61
+ camera_intrinsics: np.ndarray = field(default_factory=lambda: np.array([]))
62
+
63
+ @property
64
+ def has_color_image(self) -> bool:
65
+ """Check if color image data is available."""
66
+ return len(self.color_img) > 0
67
+
68
+ @property
69
+ def has_depth_image(self) -> bool:
70
+ """Check if depth image data is available."""
71
+ return len(self.depth_img) > 0 and self.depth_width > 0 and self.depth_height > 0
72
+
73
+ @property
74
+ def has_pose(self) -> bool:
75
+ """Check if pose data is available."""
76
+ return len(self.local_pose) > 0 or len(self.global_pose) > 0
77
+
78
+ def get_depth_array(self) -> Optional[np.ndarray]:
79
+ """
80
+ Convert depth bytes to numpy array with proper shape.
81
+
82
+ Returns:
83
+ Depth image as uint16 numpy array with shape (height, width),
84
+ or None if no depth data available.
85
+ """
86
+ if not self.has_depth_image:
87
+ return None
88
+ depth_array = np.frombuffer(self.depth_img, dtype=np.uint16)
89
+ return depth_array.reshape(self.depth_height, self.depth_width)
90
+
91
+ def get_local_pose_matrix(self) -> Optional[np.ndarray]:
92
+ """
93
+ Get local pose as 4x4 transformation matrix.
94
+
95
+ Returns:
96
+ 4x4 numpy array or None if pose data is insufficient.
97
+ """
98
+ if len(self.local_pose) == 16:
99
+ return self.local_pose.reshape(4, 4)
100
+ return None
101
+
102
+ def get_global_pose_matrix(self) -> Optional[np.ndarray]:
103
+ """
104
+ Get global pose as 4x4 transformation matrix.
105
+
106
+ Returns:
107
+ 4x4 numpy array or None if pose data is insufficient.
108
+ """
109
+ if len(self.global_pose) == 16:
110
+ return self.global_pose.reshape(4, 4)
111
+ return None
112
+
113
+ def show_color(self, window_name: str = "Color Image") -> bool:
114
+ """
115
+ Display color image if available.
116
+
117
+ Args:
118
+ window_name: OpenCV window name, default "Color Image"
119
+
120
+ Returns:
121
+ True if displayed successfully, False if no image data
122
+
123
+ Example:
124
+ >>> data = sub.get()
125
+ >>> if data:
126
+ ... data.show_color()
127
+ ... cv2.waitKey(1)
128
+ """
129
+ if not self.has_color_image:
130
+ return False
131
+
132
+ _ensure_image_libs()
133
+
134
+ try:
135
+ # Convert bytes to PIL image
136
+ pil_image = _Image.open(_io.BytesIO(self.color_img))
137
+ color_array = np.array(pil_image)
138
+
139
+ # Convert color format from RGB to BGR (OpenCV format)
140
+ if len(color_array.shape) == 3 and color_array.shape[2] == 3:
141
+ color_bgr = _cv2.cvtColor(color_array, _cv2.COLOR_RGB2BGR)
142
+ else:
143
+ color_bgr = color_array
144
+
145
+ # Display image
146
+ _cv2.imshow(window_name, color_bgr)
147
+ return True
148
+ except Exception as e:
149
+ print(f"Error displaying color image: {e}")
150
+ return False
151
+
152
+ def show_depth(self, window_name: str = "Depth Image", colormap: int = None) -> bool:
153
+ """
154
+ Display depth image if available, with automatic normalization and colormap.
155
+
156
+ Args:
157
+ window_name: OpenCV window name, default "Depth Image"
158
+ colormap: OpenCV colormap, default cv2.COLORMAP_JET
159
+ Options: COLORMAP_JET, COLORMAP_HOT, COLORMAP_VIRIDIS, etc.
160
+
161
+ Returns:
162
+ True if displayed successfully, False if no depth data
163
+
164
+ Example:
165
+ >>> data = sub.get()
166
+ >>> if data:
167
+ ... data.show_depth()
168
+ ... cv2.waitKey(1)
169
+ """
170
+ if not self.has_depth_image:
171
+ return False
172
+
173
+ _ensure_image_libs()
174
+
175
+ try:
176
+ # Get depth array
177
+ depth_array = self.get_depth_array()
178
+ if depth_array is None:
179
+ return False
180
+
181
+ # Normalize to 0-255
182
+ if depth_array.max() > depth_array.min():
183
+ depth_normalized = ((depth_array - depth_array.min()) /
184
+ (depth_array.max() - depth_array.min()) * 255).astype(np.uint8)
185
+ else:
186
+ depth_normalized = np.zeros(depth_array.shape, dtype=np.uint8)
187
+
188
+ # Apply colormap
189
+ if colormap is None:
190
+ colormap = _cv2.COLORMAP_JET
191
+ depth_colored = _cv2.applyColorMap(depth_normalized, colormap)
192
+
193
+ # Display image
194
+ _cv2.imshow(window_name, depth_colored)
195
+ return True
196
+ except Exception as e:
197
+ print(f"Error displaying depth image: {e}")
198
+ return False
199
+
200
+ def show_images(self,
201
+ show_color: bool = True,
202
+ show_depth: bool = True,
203
+ color_window: str = "Color Image",
204
+ depth_window: str = "Depth Image") -> tuple:
205
+ """
206
+ Display both color and depth images.
207
+
208
+ Args:
209
+ show_color: Whether to show color image, default True
210
+ show_depth: Whether to show depth image, default True
211
+ color_window: Color image window name
212
+ depth_window: Depth image window name
213
+
214
+ Returns:
215
+ (color_shown, depth_shown) - Two booleans indicating display success
216
+
217
+ Example:
218
+ >>> data = sub.get()
219
+ >>> if data:
220
+ ... data.show_images()
221
+ ... cv2.waitKey(1)
222
+
223
+ >>> # Show only depth
224
+ >>> data.show_images(show_color=False, show_depth=True)
225
+ """
226
+ color_shown = False
227
+ depth_shown = False
228
+
229
+ if show_color:
230
+ color_shown = self.show_color(color_window)
231
+
232
+ if show_depth:
233
+ depth_shown = self.show_depth(depth_window)
234
+
235
+ return (color_shown, depth_shown)
236
+
@@ -0,0 +1,2 @@
1
+ # Proto package
2
+
@@ -0,0 +1,37 @@
1
+ # -*- coding: utf-8 -*-
2
+ # Generated by the protocol buffer compiler. DO NOT EDIT!
3
+ # NO CHECKED-IN PROTOBUF GENCODE
4
+ # source: phone_msg.proto
5
+ # Protobuf Python Version: 5.29.3
6
+ """Generated protocol buffer code."""
7
+ from google.protobuf import descriptor as _descriptor
8
+ from google.protobuf import descriptor_pool as _descriptor_pool
9
+ from google.protobuf import runtime_version as _runtime_version
10
+ from google.protobuf import symbol_database as _symbol_database
11
+ from google.protobuf.internal import builder as _builder
12
+ _runtime_version.ValidateProtobufRuntimeVersion(
13
+ _runtime_version.Domain.PUBLIC,
14
+ 5,
15
+ 29,
16
+ 3,
17
+ '',
18
+ 'phone_msg.proto'
19
+ )
20
+ # @@protoc_insertion_point(imports)
21
+
22
+ _sym_db = _symbol_database.Default()
23
+
24
+
25
+
26
+
27
+ DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0fphone_msg.proto\x12\x05Phone\"\xc0\x01\n\x05Phone\x12\x11\n\ttimestamp\x18\x01 \x01(\x01\x12\x11\n\tcolor_img\x18\x02 \x01(\x0c\x12\x11\n\tdepth_img\x18\x03 \x01(\x0c\x12\x13\n\x0b\x64\x65pth_width\x18\x04 \x01(\x05\x12\x14\n\x0c\x64\x65pth_height\x18\x05 \x01(\x05\x12\x12\n\nlocal_pose\x18\x06 \x03(\x02\x12\x13\n\x0bglobal_pose\x18\x07 \x03(\x02\x12\x10\n\x08velocity\x18\x08 \x03(\x02\x12\x18\n\x10\x63\x61mersIntrinsics\x18\t \x03(\x02\x62\x06proto3')
28
+
29
+ _globals = globals()
30
+ _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)
31
+ _builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'phone_msg_pb2', _globals)
32
+ if not _descriptor._USE_C_DESCRIPTORS:
33
+ DESCRIPTOR._loaded_options = None
34
+ _globals['_PHONE']._serialized_start=27
35
+ _globals['_PHONE']._serialized_end=219
36
+ # @@protoc_insertion_point(module_scope)
37
+
asmagic/py.typed ADDED
@@ -0,0 +1,2 @@
1
+ # Marker file for PEP 561 - this package supports type hints
2
+
asmagic/subscriber.py ADDED
@@ -0,0 +1,330 @@
1
+ """
2
+ AR Data Subscriber module.
3
+
4
+ Provides ARDataSubscriber class for receiving AR sensor data via ZMQ.
5
+ """
6
+
7
+ import zmq
8
+ import numpy as np
9
+ from typing import Optional, Callable, Any, TYPE_CHECKING
10
+ from contextlib import contextmanager
11
+
12
+ if TYPE_CHECKING:
13
+ from .data_types import ARFrame
14
+ else:
15
+ from .data_types import ARFrame
16
+
17
+ from .proto import phone_msg_pb2
18
+
19
+
20
+ # Default configuration
21
+ DEFAULT_PORT = 8000
22
+ DEFAULT_HWM = 1
23
+ DEFAULT_TIMEOUT = 1000 # milliseconds
24
+
25
+
26
+ class ARDataSubscriber:
27
+ """
28
+ A subscriber for AR data streams.
29
+
30
+ This class provides a simple interface to receive AR data including
31
+ images, depth maps, poses, and other sensor readings.
32
+
33
+ Example:
34
+ >>> from asmagic import ARDataSubscriber
35
+ >>>
36
+ >>> # Simple usage with context manager
37
+ >>> with ARDataSubscriber("192.168.1.100") as subscriber:
38
+ ... frame = subscriber.get_frame()
39
+ ... if frame:
40
+ ... print(f"Timestamp: {frame.timestamp}")
41
+ ... print(f"Has color: {frame.has_color_image}")
42
+ >>>
43
+ >>> # Or manual management
44
+ >>> subscriber = ARDataSubscriber("192.168.1.100")
45
+ >>> frame = subscriber.get_frame()
46
+ >>> subscriber.close()
47
+ """
48
+
49
+ def __init__(
50
+ self,
51
+ ip: str,
52
+ port: int = DEFAULT_PORT,
53
+ hwm: int = DEFAULT_HWM,
54
+ conflate: bool = True,
55
+ verbose: bool = False
56
+ ) -> None:
57
+ """
58
+ Initialize the AR data subscriber.
59
+
60
+ Args:
61
+ ip: IP address of the AR device
62
+ port: Port number (default: 8000)
63
+ hwm: High water mark for ZMQ socket (default: 1)
64
+ conflate: Whether to keep only the latest message (default: True)
65
+ verbose: Print connection info (default: False)
66
+ """
67
+ self._ip = ip
68
+ self._port = port
69
+ self._address = f"tcp://{ip}:{port}"
70
+ self._connected = False
71
+
72
+ if verbose:
73
+ print(f"[ARDataSubscriber] Connecting to {self._address}")
74
+
75
+ # Create ZMQ context and socket
76
+ self._context = zmq.Context()
77
+ self._socket = self._context.socket(zmq.SUB)
78
+ self._socket.set_hwm(hwm)
79
+ self._socket.setsockopt(zmq.CONFLATE, conflate)
80
+ self._socket.connect(self._address)
81
+ self._socket.setsockopt_string(zmq.SUBSCRIBE, "")
82
+
83
+ # Set up poller for non-blocking receives
84
+ self._poller = zmq.Poller()
85
+ self._poller.register(self._socket, zmq.POLLIN)
86
+
87
+ # Reusable protobuf message
88
+ self._proto_msg = phone_msg_pb2.Phone()
89
+ self._connected = True
90
+
91
+ if verbose:
92
+ print(f"[ARDataSubscriber] Connected successfully")
93
+
94
+ def __enter__(self) -> "ARDataSubscriber":
95
+ """Context manager entry."""
96
+ return self
97
+
98
+ def __exit__(self, exc_type, exc_val, exc_tb) -> None:
99
+ """Context manager exit."""
100
+ self.close()
101
+
102
+ @property
103
+ def is_connected(self) -> bool:
104
+ """Check if subscriber is connected."""
105
+ return self._connected
106
+
107
+ @property
108
+ def address(self) -> str:
109
+ """Get the connection address."""
110
+ return self._address
111
+
112
+ def get_frame(self, timeout: int = DEFAULT_TIMEOUT) -> Optional[ARFrame]:
113
+ """
114
+ Get a single frame of AR data.
115
+
116
+ Args:
117
+ timeout: Timeout in milliseconds (default: 100)
118
+
119
+ Returns:
120
+ ARFrame object containing all sensor data, or None if timeout
121
+ """
122
+ if not self._connected:
123
+ return None
124
+
125
+ socks = dict(self._poller.poll(timeout))
126
+ if self._socket not in socks or socks[self._socket] != zmq.POLLIN:
127
+ return None
128
+
129
+ try:
130
+ data = self._socket.recv(zmq.DONTWAIT)
131
+ self._proto_msg.ParseFromString(data)
132
+
133
+ return ARFrame(
134
+ timestamp=self._proto_msg.timestamp,
135
+ color_img=self._proto_msg.color_img,
136
+ depth_img=self._proto_msg.depth_img,
137
+ depth_width=self._proto_msg.depth_width,
138
+ depth_height=self._proto_msg.depth_height,
139
+ local_pose=np.array(self._proto_msg.local_pose, dtype=np.float32),
140
+ global_pose=np.array(self._proto_msg.global_pose, dtype=np.float32),
141
+ velocity=np.array(self._proto_msg.velocity, dtype=np.float32),
142
+ camera_intrinsics=np.array(self._proto_msg.camersIntrinsics, dtype=np.float32)
143
+ )
144
+ except zmq.Again:
145
+ return None
146
+ except Exception as e:
147
+ raise RuntimeError(f"Failed to receive AR data: {e}")
148
+
149
+ def get(self, timeout: int = DEFAULT_TIMEOUT) -> Optional[ARFrame]:
150
+ """
151
+ Get the latest AR data - Recommended method!
152
+
153
+ Returns a data object with properties for accessing various sensor data.
154
+
155
+ Returns:
156
+ Data object with the following properties:
157
+ - timestamp: Unix timestamp
158
+ - velocity: Velocity vector
159
+ - local_pose: Local pose array
160
+ - global_pose: Global pose array
161
+ - camera_intrinsics: Camera intrinsic parameters
162
+ - color_img: Color image bytes
163
+ - depth_img: Depth image bytes
164
+ - depth_width, depth_height: Depth image dimensions
165
+
166
+ Returns None if no data available
167
+
168
+ Example:
169
+ >>> data = sub.get()
170
+ >>> if data:
171
+ ... print(data.timestamp)
172
+ ... print(data.velocity)
173
+ ... print(data.local_pose)
174
+ ...
175
+ ... # Get depth image as numpy array
176
+ ... depth_array = data.get_depth_array()
177
+ """
178
+ return self.get_frame(timeout)
179
+
180
+ def get_all_data(self, timeout: int = DEFAULT_TIMEOUT) -> Optional[tuple]:
181
+ """
182
+ Get all data at once (returns tuple, requires manual unpacking).
183
+
184
+ ⚠️ Recommend using get() method instead for cleaner API!
185
+
186
+ Returns:
187
+ Tuple of (timestamp, color_img, depth_img, depth_width, depth_height,
188
+ local_pose, global_pose, velocity, camera_intrinsics)
189
+ or None if no data available.
190
+ """
191
+ frame = self.get_frame(timeout)
192
+ if frame is None:
193
+ return None
194
+
195
+ return (
196
+ frame.timestamp,
197
+ frame.color_img,
198
+ frame.depth_img,
199
+ frame.depth_width,
200
+ frame.depth_height,
201
+ frame.local_pose,
202
+ frame.global_pose,
203
+ frame.velocity,
204
+ frame.camera_intrinsics
205
+ )
206
+
207
+ def get_timestamp(self, timeout: int = DEFAULT_TIMEOUT) -> Optional[float]:
208
+ """Get only the timestamp from the latest frame."""
209
+ frame = self.get_frame(timeout)
210
+ return frame.timestamp if frame else None
211
+
212
+ def get_color_image(self, timeout: int = DEFAULT_TIMEOUT) -> Optional[bytes]:
213
+ """Get only the color image bytes from the latest frame."""
214
+ frame = self.get_frame(timeout)
215
+ return frame.color_img if frame and frame.has_color_image else None
216
+
217
+ def get_depth_image(self, timeout: int = DEFAULT_TIMEOUT) -> Optional[np.ndarray]:
218
+ """
219
+ Get the depth image as a numpy array.
220
+
221
+ Returns:
222
+ Depth image as uint16 numpy array with shape (height, width),
223
+ or None if no data available.
224
+ """
225
+ frame = self.get_frame(timeout)
226
+ return frame.get_depth_array() if frame else None
227
+
228
+ def get_depth_raw(self, timeout: int = DEFAULT_TIMEOUT) -> Optional[tuple]:
229
+ """
230
+ Get raw depth data with dimensions.
231
+
232
+ Returns:
233
+ Tuple of (depth_bytes, width, height) or None if no data.
234
+ """
235
+ frame = self.get_frame(timeout)
236
+ if frame and frame.has_depth_image:
237
+ return (frame.depth_img, frame.depth_width, frame.depth_height)
238
+ return None
239
+
240
+ def get_local_pose(self, timeout: int = DEFAULT_TIMEOUT) -> Optional[np.ndarray]:
241
+ """Get the local pose array from the latest frame."""
242
+ frame = self.get_frame(timeout)
243
+ return frame.local_pose if frame and len(frame.local_pose) > 0 else None
244
+
245
+ def get_global_pose(self, timeout: int = DEFAULT_TIMEOUT) -> Optional[np.ndarray]:
246
+ """Get the global pose array from the latest frame."""
247
+ frame = self.get_frame(timeout)
248
+ return frame.global_pose if frame and len(frame.global_pose) > 0 else None
249
+
250
+ def get_velocity(self, timeout: int = DEFAULT_TIMEOUT) -> Optional[np.ndarray]:
251
+ """Get the velocity array from the latest frame."""
252
+ frame = self.get_frame(timeout)
253
+ return frame.velocity if frame and len(frame.velocity) > 0 else None
254
+
255
+ def get_camera_intrinsics(self, timeout: int = DEFAULT_TIMEOUT) -> Optional[np.ndarray]:
256
+ """Get the camera intrinsics array from the latest frame."""
257
+ frame = self.get_frame(timeout)
258
+ return frame.camera_intrinsics if frame and len(frame.camera_intrinsics) > 0 else None
259
+
260
+ def stream(
261
+ self,
262
+ timeout: int = DEFAULT_TIMEOUT,
263
+ on_frame: Optional[Callable[[ARFrame], Any]] = None
264
+ ):
265
+ """
266
+ Generator that yields frames continuously.
267
+
268
+ Args:
269
+ timeout: Timeout for each frame in milliseconds
270
+ on_frame: Optional callback function called for each frame
271
+
272
+ Yields:
273
+ ARFrame objects as they arrive
274
+
275
+ Example:
276
+ >>> for frame in subscriber.stream():
277
+ ... print(frame.timestamp)
278
+ """
279
+ while self._connected:
280
+ frame = self.get_frame(timeout)
281
+ if frame:
282
+ if on_frame:
283
+ on_frame(frame)
284
+ yield frame
285
+
286
+ def close(self) -> None:
287
+ """
288
+ Close the subscriber connection.
289
+
290
+ This method is idempotent and safe to call multiple times.
291
+ """
292
+ if not self._connected:
293
+ return
294
+
295
+ self._connected = False
296
+
297
+ if hasattr(self, '_socket') and self._socket:
298
+ try:
299
+ self._socket.close()
300
+ except:
301
+ pass
302
+
303
+ if hasattr(self, '_context') and self._context:
304
+ try:
305
+ self._context.term()
306
+ except:
307
+ pass
308
+
309
+ def __del__(self):
310
+ """Destructor to ensure resources are cleaned up."""
311
+ self.close()
312
+
313
+
314
+ # Convenience function for quick access
315
+ @contextmanager
316
+ def connect(ip: str, port: int = DEFAULT_PORT, **kwargs):
317
+ """
318
+ Context manager for quick AR data access.
319
+
320
+ Example:
321
+ >>> from asmagic import connect
322
+ >>> with connect("192.168.1.100") as sub:
323
+ ... frame = sub.get_frame()
324
+ """
325
+ subscriber = ARDataSubscriber(ip, port, **kwargs)
326
+ try:
327
+ yield subscriber
328
+ finally:
329
+ subscriber.close()
330
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Shenzhen AncoraSpring Robotics Technology Co., Ltd.
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.
@@ -0,0 +1,219 @@
1
+ Metadata-Version: 2.1
2
+ Name: asmagic
3
+ Version: 0.1.0
4
+ Summary: AR Sensor Data Magic Library - Subscribe to AR sensor data streams
5
+ Author: ASMagic Team
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/asmagic/asmagic
8
+ Project-URL: Documentation, https://github.com/asmagic/asmagic#readme
9
+ Project-URL: Repository, https://github.com/asmagic/asmagic
10
+ Project-URL: Issues, https://github.com/asmagic/asmagic/issues
11
+ Keywords: ar,sensor,zmq,protobuf,streaming
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.8
18
+ Classifier: Programming Language :: Python :: 3.9
19
+ Classifier: Programming Language :: Python :: 3.10
20
+ Classifier: Programming Language :: Python :: 3.11
21
+ Classifier: Programming Language :: Python :: 3.12
22
+ Classifier: Topic :: Scientific/Engineering
23
+ Requires-Python: >=3.8
24
+ Description-Content-Type: text/markdown
25
+ License-File: LICENSE
26
+ Requires-Dist: numpy>=1.20.0
27
+ Requires-Dist: pyzmq>=22.0.0
28
+ Requires-Dist: protobuf>=4.0.0
29
+ Provides-Extra: all
30
+ Requires-Dist: opencv-python>=4.5.0; extra == "all"
31
+ Requires-Dist: Pillow>=8.0.0; extra == "all"
32
+ Provides-Extra: dev
33
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
34
+ Requires-Dist: black>=22.0.0; extra == "dev"
35
+ Requires-Dist: mypy>=0.990; extra == "dev"
36
+ Provides-Extra: image
37
+ Requires-Dist: opencv-python>=4.5.0; extra == "image"
38
+ Requires-Dist: Pillow>=8.0.0; extra == "image"
39
+
40
+ # asmagic
41
+
42
+ A lightweight Python library for subscribing to AR sensor data streams via ZeroMQ.
43
+
44
+ ## Installation
45
+
46
+ ```bash
47
+ pip install asmagic
48
+ ```
49
+
50
+ For image display support:
51
+
52
+ ```bash
53
+ pip install asmagic[image]
54
+ ```
55
+
56
+ ## Quick Start
57
+
58
+ ```python
59
+ from asmagic import ARDataSubscriber
60
+
61
+ # Create subscriber
62
+ sub = ARDataSubscriber("192.168.1.100")
63
+
64
+ # Get data frame
65
+ data = sub.get()
66
+ if data:
67
+ print(data.timestamp)
68
+ print(data.velocity)
69
+ print(data.local_pose)
70
+ print(data.camera_intrinsics)
71
+
72
+ sub.close()
73
+ ```
74
+
75
+ ## Usage
76
+
77
+ ### Continuous Data Streaming
78
+
79
+ ```python
80
+ from asmagic import ARDataSubscriber
81
+
82
+ sub = ARDataSubscriber("192.168.1.100")
83
+
84
+ try:
85
+ while True:
86
+ data = sub.get()
87
+ if data:
88
+ print(f"Velocity: {data.velocity}")
89
+ print(f"Local pose: {data.local_pose}")
90
+ print(f"Timestamp: {data.timestamp}")
91
+ except KeyboardInterrupt:
92
+ pass
93
+ finally:
94
+ sub.close()
95
+ ```
96
+
97
+ ### Image Display
98
+
99
+ Requires `opencv-python` and `Pillow`:
100
+
101
+ ```bash
102
+ pip install asmagic[image]
103
+ ```
104
+
105
+ ```python
106
+ from asmagic import ARDataSubscriber
107
+ import cv2
108
+
109
+ sub = ARDataSubscriber("192.168.1.100")
110
+
111
+ try:
112
+ while True:
113
+ data = sub.get()
114
+ if data:
115
+ # Display both color and depth images
116
+ data.show_images()
117
+
118
+ # Or display individually
119
+ # data.show_color()
120
+ # data.show_depth()
121
+
122
+ if cv2.waitKey(1) == 27: # ESC to exit
123
+ break
124
+ finally:
125
+ sub.close()
126
+ cv2.destroyAllWindows()
127
+ ```
128
+
129
+ ### Accessing Individual Fields
130
+
131
+ ```python
132
+ from asmagic import ARDataSubscriber
133
+
134
+ sub = ARDataSubscriber("192.168.1.100")
135
+
136
+ # Get specific data
137
+ velocity = sub.get_velocity()
138
+ pose = sub.get_local_pose()
139
+ timestamp = sub.get_timestamp()
140
+
141
+ sub.close()
142
+ ```
143
+
144
+ ## API Reference
145
+
146
+ ### ARDataSubscriber
147
+
148
+ **Constructor:**
149
+
150
+ ```python
151
+ ARDataSubscriber(ip, port=8000, hwm=1, conflate=True, verbose=False)
152
+ ```
153
+
154
+ **Parameters:**
155
+
156
+ - `ip` (str): IP address of the AR device
157
+ - `port` (int): Port number (default: 8000)
158
+ - `hwm` (int): High water mark for ZMQ socket (default: 1)
159
+ - `conflate` (bool): Enable message conflation (default: True)
160
+ - `verbose` (bool): Print connection info (default: False)
161
+
162
+ **Methods:**
163
+
164
+ | Method | Returns | Description |
165
+ | ------------------------------------- | ---------------------- | --------------------- |
166
+ | `get(timeout=1000)` | `ARFrame` or `None` | Get latest data frame |
167
+ | `get_timestamp(timeout=1000)` | `float` or `None` | Get timestamp |
168
+ | `get_velocity(timeout=1000)` | `np.ndarray` or `None` | Get velocity |
169
+ | `get_local_pose(timeout=1000)` | `np.ndarray` or `None` | Get local pose |
170
+ | `get_global_pose(timeout=1000)` | `np.ndarray` or `None` | Get global pose |
171
+ | `get_camera_intrinsics(timeout=1000)` | `np.ndarray` or `None` | Get camera intrinsics |
172
+ | `get_color_image(timeout=1000)` | `bytes` or `None` | Get color image bytes |
173
+ | `get_depth_image(timeout=1000)` | `np.ndarray` or `None` | Get depth image array |
174
+ | `close()` | `None` | Close connection |
175
+
176
+ ### ARFrame
177
+
178
+ Data object returned by `get()`:
179
+
180
+ **Properties:**
181
+
182
+ | Property | Type | Description |
183
+ | ------------------- | ------------ | -------------------------------- |
184
+ | `timestamp` | `float` | Frame timestamp |
185
+ | `velocity` | `np.ndarray` | Velocity vector |
186
+ | `local_pose` | `np.ndarray` | Local pose matrix |
187
+ | `global_pose` | `np.ndarray` | Global pose matrix |
188
+ | `camera_intrinsics` | `np.ndarray` | Camera intrinsic parameters |
189
+ | `color_img` | `bytes` | Color image bytes (JPEG/PNG) |
190
+ | `depth_img` | `bytes` | Raw depth image bytes |
191
+ | `depth_width` | `int` | Depth image width |
192
+ | `depth_height` | `int` | Depth image height |
193
+ | `has_color_image` | `bool` | Whether color image is available |
194
+ | `has_depth_image` | `bool` | Whether depth image is available |
195
+
196
+ **Methods:**
197
+
198
+ | Method | Returns | Description |
199
+ | ------------------------------------- | ------------ | --------------------------------- |
200
+ | `get_depth_array()` | `np.ndarray` | Get depth as numpy array (uint16) |
201
+ | `show_color(window_name)` | `bool` | Display color image |
202
+ | `show_depth(window_name, colormap)` | `bool` | Display depth image |
203
+ | `show_images(show_color, show_depth)` | `tuple` | Display both images |
204
+
205
+ ## Requirements
206
+
207
+ - Python >= 3.8
208
+ - numpy >= 1.20.0
209
+ - pyzmq >= 22.0.0
210
+ - protobuf >= 4.0.0
211
+
212
+ Optional (for image display):
213
+
214
+ - opencv-python >= 4.5.0
215
+ - Pillow >= 8.0.0
216
+
217
+ ## License
218
+
219
+ MIT License
@@ -0,0 +1,11 @@
1
+ asmagic/__init__.py,sha256=GcibC9w027DeAQnF-drumkFviZeG-IRsls0gR4MKRds,665
2
+ asmagic/data_types.py,sha256=TUm2Ra8I2_V6G4SY3OR6LTbgL3Ngkd20PIqQpreNEhI,8022
3
+ asmagic/py.typed,sha256=D584YO_PYScRnMsh1Bs-wbAGfuub66Gxgi_7Y4cd1Vc,62
4
+ asmagic/subscriber.py,sha256=gOpRvr4kV4RLSV036uztSowEHZJER78GYnzHOwhjzJw,11139
5
+ asmagic/proto/__init__.py,sha256=hW9BjIovmiHpIsg5aSuq5dmOlwKablgt3xthmSVnrnU,17
6
+ asmagic/proto/phone_msg_pb2.py,sha256=LDeGvLQgVYY5cvsgEUfGClwBw7i5IpMbWavkj7cA_oc,1620
7
+ asmagic-0.1.0.dist-info/LICENSE,sha256=42t9f9iKXW42N3pJb-uAY5Y-v6dCi1U35lsqPkXRKdk,1108
8
+ asmagic-0.1.0.dist-info/METADATA,sha256=vTA5COn7HuS-gPX3FtGYYEgAm4RUkyrnHXMT1Ug1zZY,6547
9
+ asmagic-0.1.0.dist-info/WHEEL,sha256=iAkIy5fosb7FzIOwONchHf19Qu7_1wCWyFNR5gu9nU0,91
10
+ asmagic-0.1.0.dist-info/top_level.txt,sha256=jBWbeHDTZiSTTaHPEiHB5TX1puwNE8N5MdCYS9RwB3M,8
11
+ asmagic-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.3.2)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ asmagic