foxglove-sdk 0.16.3__pp311-pypy311_pp73-manylinux_2_17_ppc64le.manylinux2014_ppc64le.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.

Potentially problematic release.


This version of foxglove-sdk might be problematic. Click here for more details.

foxglove/__init__.py ADDED
@@ -0,0 +1,245 @@
1
+ """
2
+ This module provides interfaces for logging messages to Foxglove.
3
+
4
+ See :py:mod:`foxglove.schemas` and :py:mod:`foxglove.channels` for working with well-known Foxglove
5
+ schemas.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import atexit
11
+ import logging
12
+ from typing import TYPE_CHECKING
13
+
14
+ from . import _foxglove_py as _foxglove
15
+
16
+ # Re-export these imports
17
+ from ._foxglove_py import (
18
+ ChannelDescriptor,
19
+ Context,
20
+ Schema,
21
+ SinkChannelFilter,
22
+ open_mcap,
23
+ )
24
+ from .channel import Channel, log
25
+
26
+ # Deprecated. Use foxglove.mcap.MCAPWriter instead.
27
+ from .mcap import MCAPWriter
28
+
29
+ if TYPE_CHECKING:
30
+ from .notebook.notebook_buffer import NotebookBuffer
31
+
32
+ atexit.register(_foxglove.shutdown)
33
+
34
+
35
+ try:
36
+ from ._foxglove_py.cloud import CloudSink
37
+
38
+ # from ._foxglove_py.cloud import start_cloud_sink as _start_cloud_sink
39
+ from .cloud import CloudSinkListener
40
+ from .websocket import (
41
+ AssetHandler,
42
+ Capability,
43
+ ServerListener,
44
+ Service,
45
+ WebSocketServer,
46
+ )
47
+
48
+ def start_server(
49
+ *,
50
+ name: str | None = None,
51
+ host: str | None = "127.0.0.1",
52
+ port: int | None = 8765,
53
+ capabilities: list[Capability] | None = None,
54
+ server_listener: ServerListener | None = None,
55
+ supported_encodings: list[str] | None = None,
56
+ services: list[Service] | None = None,
57
+ asset_handler: AssetHandler | None = None,
58
+ context: Context | None = None,
59
+ session_id: str | None = None,
60
+ channel_filter: SinkChannelFilter | None = None,
61
+ playback_time_range: tuple[int, int] | None = None,
62
+ ) -> WebSocketServer:
63
+ """
64
+ Start a websocket server for live visualization.
65
+
66
+ :param name: The name of the server.
67
+ :param host: The host to bind to.
68
+ :param port: The port to bind to.
69
+ :param capabilities: A list of capabilities to advertise to clients.
70
+ :param server_listener: A Python object that implements the
71
+ :py:class:`websocket.ServerListener` protocol.
72
+ :param supported_encodings: A list of encodings to advertise to clients.
73
+ :param services: A list of services to advertise to clients.
74
+ :param asset_handler: A callback function that returns the asset for a given URI, or None if
75
+ it doesn't exist.
76
+ :param context: The context to use for logging. If None, the global context is used.
77
+ :param session_id: An ID which allows the client to understand if the connection is a
78
+ re-connection or a new server instance. If None, then an ID is generated based on the
79
+ current time.
80
+ :param channel_filter: A `Callable` that determines whether a channel should be logged to.
81
+ Return `True` to log the channel, or `False` to skip it. By default, all channels
82
+ will be logged.
83
+ :param playback_time_range: Time range of data being played back, in absolute nanoseconds.
84
+ Implies `Capability.RangedPlayback` if set.
85
+ """
86
+ return _foxglove.start_server(
87
+ name=name,
88
+ host=host,
89
+ port=port,
90
+ capabilities=capabilities,
91
+ server_listener=server_listener,
92
+ supported_encodings=supported_encodings,
93
+ services=services,
94
+ asset_handler=asset_handler,
95
+ context=context,
96
+ session_id=session_id,
97
+ channel_filter=channel_filter,
98
+ playback_time_range=playback_time_range,
99
+ )
100
+
101
+ def start_cloud_sink(
102
+ *,
103
+ listener: CloudSinkListener | None = None,
104
+ supported_encodings: list[str] | None = None,
105
+ context: Context | None = None,
106
+ session_id: str | None = None,
107
+ ) -> CloudSink:
108
+ """
109
+ Connect to Foxglove Agent for live visualization and teleop.
110
+
111
+ Foxglove Agent must be running on the same host for this to work.
112
+
113
+ :param capabilities: A list of capabilities to advertise to the agent.
114
+ :param listener: A Python object that implements the
115
+ :py:class:`cloud.CloudSinkListener` protocol.
116
+ :param supported_encodings: A list of encodings to advertise to the agent.
117
+ :param context: The context to use for logging. If None, the global context is used.
118
+ :param session_id: An ID which allows the agent to understand if the connection is a
119
+ re-connection or a new connection instance. If None, then an ID is generated based on
120
+ the current time.
121
+ """
122
+ return _foxglove.start_cloud_sink(
123
+ listener=listener,
124
+ supported_encodings=supported_encodings,
125
+ context=context,
126
+ session_id=session_id,
127
+ )
128
+
129
+ except ImportError:
130
+ pass
131
+
132
+
133
+ def set_log_level(level: int | str = "INFO") -> None:
134
+ """
135
+ Enable SDK logging.
136
+
137
+ This function will call logging.basicConfig() for convenience in scripts, but in general you
138
+ should configure logging yourself before calling this function:
139
+ https://docs.python.org/3/library/logging.html
140
+
141
+ :param level: The logging level to set. This accepts the same values as `logging.setLevel` and
142
+ defaults to "INFO". The SDK will not log at levels "CRITICAL" or higher.
143
+ """
144
+ # This will raise a ValueError for invalid levels if the user has not already configured
145
+ logging.basicConfig(level=level, format="%(asctime)s [%(levelname)s] %(message)s")
146
+
147
+ if isinstance(level, str):
148
+ level_map = (
149
+ logging.getLevelNamesMapping()
150
+ if hasattr(logging, "getLevelNamesMapping")
151
+ else _level_names()
152
+ )
153
+ try:
154
+ level = level_map[level]
155
+ except KeyError:
156
+ raise ValueError(f"Unknown log level: {level}")
157
+ else:
158
+ level = max(0, min(2**32 - 1, level))
159
+
160
+ _foxglove.enable_logging(level)
161
+
162
+
163
+ def _level_names() -> dict[str, int]:
164
+ # Fallback for Python <3.11; no support for custom levels
165
+ return {
166
+ "CRITICAL": logging.CRITICAL,
167
+ "FATAL": logging.FATAL,
168
+ "ERROR": logging.ERROR,
169
+ "WARN": logging.WARNING,
170
+ "WARNING": logging.WARNING,
171
+ "INFO": logging.INFO,
172
+ "DEBUG": logging.DEBUG,
173
+ "NOTSET": logging.NOTSET,
174
+ }
175
+
176
+
177
+ def init_notebook_buffer(context: Context | None = None) -> NotebookBuffer:
178
+ """
179
+ Create a NotebookBuffer object to manage data buffering and visualization in Jupyter
180
+ notebooks.
181
+
182
+ The NotebookBuffer object will buffer all data logged to the provided context. When you
183
+ are ready to visualize the data, you can call the :meth:`show` method to display an embedded
184
+ Foxglove visualization widget. The widget provides a fully-featured Foxglove interface
185
+ directly within your Jupyter notebook, allowing you to explore multi-modal robotics data
186
+ including 3D scenes, plots, images, and more.
187
+
188
+ Args:
189
+ context: The Context used to log the messages. If no Context is provided, the global
190
+ context will be used. Logged messages will be buffered.
191
+
192
+ Returns:
193
+ NotebookBuffer: A NotebookBuffer object that can be used to manage the data buffering
194
+ and visualization.
195
+
196
+ Raises:
197
+ Exception: If the notebook extra package is not installed. Install it
198
+ with `pip install foxglove-sdk[notebook]`.
199
+
200
+ Note:
201
+ This function is only available when the `notebook` extra package
202
+ is installed. Install it with `pip install foxglove-sdk[notebook]`.
203
+
204
+ Example:
205
+ >>> import foxglove
206
+ >>>
207
+ >>> # Create a basic viewer using the default context
208
+ >>> nb_buffer = foxglove.init_notebook_buffer()
209
+ >>>
210
+ >>> # Or use a specific context
211
+ >>> nb_buffer = foxglove.init_notebook_buffer(context=my_ctx)
212
+ >>>
213
+ >>> # ... log data as usual ...
214
+ >>>
215
+ >>> # Display the widget in the notebook
216
+ >>> nb_buffer.show()
217
+ """
218
+ try:
219
+ from .notebook.notebook_buffer import NotebookBuffer
220
+
221
+ except ImportError:
222
+ raise Exception(
223
+ "NotebookBuffer is not installed. "
224
+ 'Please install it with `pip install "foxglove-sdk[notebook]"`'
225
+ )
226
+
227
+ return NotebookBuffer(context=context)
228
+
229
+
230
+ __all__ = [
231
+ "Channel",
232
+ "ChannelDescriptor",
233
+ "Context",
234
+ "MCAPWriter",
235
+ "Schema",
236
+ "SinkChannelFilter",
237
+ "CloudSink",
238
+ "CloudSinkListener",
239
+ "start_cloud_sink",
240
+ "log",
241
+ "open_mcap",
242
+ "set_log_level",
243
+ "start_server",
244
+ "init_notebook_buffer",
245
+ ]
@@ -0,0 +1,233 @@
1
+ from pathlib import Path
2
+ from typing import Any, BinaryIO, Callable, Protocol
3
+
4
+ from foxglove.websocket import AssetHandler
5
+
6
+ class McapWritable(Protocol):
7
+ """A writable and seekable file-like object.
8
+
9
+ This protocol defines the minimal interface required for writing MCAP data.
10
+ """
11
+
12
+ def write(self, data: bytes | bytearray) -> int:
13
+ """Write data and return the number of bytes written."""
14
+ ...
15
+
16
+ def seek(self, offset: int, whence: int = 0) -> int:
17
+ """Seek to position and return the new absolute position."""
18
+ ...
19
+
20
+ def flush(self) -> None:
21
+ """Flush any buffered data."""
22
+ ...
23
+
24
+ from .cloud import CloudSink
25
+ from .mcap import MCAPWriteOptions, MCAPWriter
26
+ from .websocket import Capability, Service, WebSocketServer
27
+
28
+ class BaseChannel:
29
+ """
30
+ A channel for logging messages.
31
+ """
32
+
33
+ def __init__(
34
+ self,
35
+ topic: str,
36
+ message_encoding: str,
37
+ schema: "Schema" | None = None,
38
+ metadata: dict[str, str] | None = None,
39
+ ) -> None: ...
40
+ def id(self) -> int:
41
+ """The unique ID of the channel"""
42
+ ...
43
+
44
+ def topic(self) -> str:
45
+ """The topic name of the channel"""
46
+ ...
47
+
48
+ @property
49
+ def message_encoding(self) -> str:
50
+ """The message encoding for the channel"""
51
+ ...
52
+
53
+ def metadata(self) -> dict[str, str]:
54
+ """
55
+ Returns a copy of the channel's metadata.
56
+
57
+ Note that changes made to the returned dictionary will not be applied to
58
+ the channel's metadata.
59
+ """
60
+ ...
61
+
62
+ def schema(self) -> "Schema" | None:
63
+ """
64
+ Returns a copy of the channel's schema.
65
+
66
+ Note that changes made to the returned object will not be applied to
67
+ the channel's schema.
68
+ """
69
+ ...
70
+
71
+ def schema_name(self) -> str | None:
72
+ """The name of the schema for the channel"""
73
+ ...
74
+
75
+ def has_sinks(self) -> bool:
76
+ """Returns true if at least one sink is subscribed to this channel"""
77
+ ...
78
+
79
+ def log(
80
+ self,
81
+ msg: bytes,
82
+ log_time: int | None = None,
83
+ sink_id: int | None = None,
84
+ ) -> None:
85
+ """
86
+ Log a message to the channel.
87
+
88
+ :param msg: The message to log.
89
+ :param log_time: The optional time the message was logged.
90
+ :param sink_id: The sink ID to log the message to. If not provided, the message will be
91
+ sent to all sinks.
92
+ """
93
+ ...
94
+
95
+ def close(self) -> None: ...
96
+
97
+ class Schema:
98
+ """
99
+ A schema for a message or service call.
100
+ """
101
+
102
+ name: str
103
+ encoding: str
104
+ data: bytes
105
+
106
+ def __init__(
107
+ self,
108
+ *,
109
+ name: str,
110
+ encoding: str,
111
+ data: bytes,
112
+ ) -> None: ...
113
+
114
+ class Context:
115
+ """
116
+ A context for logging messages.
117
+
118
+ A context is the binding between channels and sinks. By default, the SDK will use a single
119
+ global context for logging, but you can create multiple contexts in order to log to different
120
+ topics to different sinks or servers. To do so, associate the context by passing it to the
121
+ channel constructor and to :py:func:`open_mcap` or :py:func:`start_server`.
122
+ """
123
+
124
+ def __init__(self) -> None: ...
125
+ def _create_channel(
126
+ self,
127
+ topic: str,
128
+ message_encoding: str,
129
+ schema: Schema | None = None,
130
+ metadata: list[tuple[str, str]] | None = None,
131
+ ) -> "BaseChannel":
132
+ """
133
+ Instead of calling this method, pass a context to a channel constructor.
134
+ """
135
+ ...
136
+
137
+ @staticmethod
138
+ def default() -> "Context":
139
+ """
140
+ Returns the default context.
141
+ """
142
+ ...
143
+
144
+ class ChannelDescriptor:
145
+ """
146
+ Information about a channel
147
+ """
148
+
149
+ id: int
150
+ topic: str
151
+ message_encoding: str
152
+ metadata: dict[str, str]
153
+ schema: "Schema" | None
154
+
155
+ SinkChannelFilter = Callable[[ChannelDescriptor], bool]
156
+
157
+ def start_server(
158
+ *,
159
+ name: str | None = None,
160
+ host: str | None = "127.0.0.1",
161
+ port: int | None = 8765,
162
+ capabilities: list[Capability] | None = None,
163
+ server_listener: Any = None,
164
+ supported_encodings: list[str] | None = None,
165
+ services: list[Service] | None = None,
166
+ asset_handler: AssetHandler | None = None,
167
+ context: Context | None = None,
168
+ session_id: str | None = None,
169
+ channel_filter: SinkChannelFilter | None = None,
170
+ playback_time_range: tuple[int, int] | None = None,
171
+ ) -> WebSocketServer:
172
+ """
173
+ Start a websocket server for live visualization.
174
+ """
175
+ ...
176
+
177
+ def start_cloud_sink(
178
+ *,
179
+ listener: Any = None,
180
+ supported_encodings: list[str] | None = None,
181
+ context: Context | None = None,
182
+ session_id: str | None = None,
183
+ ) -> CloudSink:
184
+ """
185
+ Connect to Foxglove Agent for remote visualization and teleop.
186
+ """
187
+ ...
188
+
189
+ def enable_logging(level: int) -> None:
190
+ """
191
+ Forward SDK logs to python's logging facility.
192
+ """
193
+ ...
194
+
195
+ def disable_logging() -> None:
196
+ """
197
+ Stop forwarding SDK logs.
198
+ """
199
+ ...
200
+
201
+ def shutdown() -> None:
202
+ """
203
+ Shutdown the running websocket server.
204
+ """
205
+ ...
206
+
207
+ def open_mcap(
208
+ path: str | Path | BinaryIO | McapWritable,
209
+ *,
210
+ allow_overwrite: bool = False,
211
+ context: Context | None = None,
212
+ channel_filter: SinkChannelFilter | None = None,
213
+ writer_options: MCAPWriteOptions | None = None,
214
+ ) -> MCAPWriter:
215
+ """
216
+ Open an MCAP writer for recording.
217
+
218
+ If a path is provided, the file will be created and must not already exist (unless
219
+ allow_overwrite is True). If a file-like object is provided, it must support write(),
220
+ seek(), and flush() methods; the allow_overwrite parameter is ignored.
221
+
222
+ If a context is provided, the MCAP file will be associated with that context. Otherwise, the
223
+ global context will be used.
224
+
225
+ You must close the writer with close() or the with statement to ensure the file is correctly finished.
226
+ """
227
+ ...
228
+
229
+ def get_channel_for_topic(topic: str) -> BaseChannel | None:
230
+ """
231
+ Get a previously-registered channel.
232
+ """
233
+ ...