API Reference¶
Version: 0.32.1
foxglove¶
This module provides interfaces for logging messages to Foxglove.
See foxglove.messages and foxglove.channels for working with well-known Foxglove
message types.
- class foxglove.Channel¶
A channel that can be used to log binary messages or JSON messages.
- __init__(topic, *, schema=None, message_encoding=None, context=None, metadata=None)¶
Create a new channel for logging messages on a topic.
- Parameters:
topic (
str) – The topic name. You should choose a unique topic name per channel.message_encoding (
str|None(default:None)) – The message encoding. Optional ifschemais a dictionary, in which case the message encoding is presumed to be “json”.schema (
dict[str,Any] |Schema|None(default:None)) – A definition of your schema. Pass aSchemafor full control. If a dictionary is passed, it will be treated as a JSON schema.metadata (
dict[str,str] |None(default:None)) – A dictionary of key/value strings to add to the channel. A type error is raised if any key or value is not a string.
If both message_encoding and schema are None, then the channel will use JSON encoding, and allow any dict to be logged.
- close()¶
Close the channel.
You can use this to explicitly unadvertise the channel to sinks that subscribe to channels dynamically, such as the
foxglove.websocket.WebSocketServer.Attempts to log on a closed channel will elicit a throttled warning message.
- Return type:
None
- has_sinks()¶
Returns true if at least one sink is subscribed to this channel
- Return type:
bool
- id()¶
The unique ID of the channel
- Return type:
int
- log(msg, *, log_time=None, sink_id=None)¶
Log a message on the channel.
- Parameters:
msg (
dict[str,Any] |list[Any] |bytes|str) – the message to log. If the channel uses JSON encoding, you may pass a dictionary or list. Otherwise, you are responsible for serializing the message.log_time (
int|None(default:None)) – The optional time the message was logged.
- Return type:
None
- property message_encoding: str¶
The message encoding for the channel
- metadata()¶
Returns a copy of the channel’s metadata.
Note that changes made to the returned dictionary will not be applied to the channel’s metadata.
- Return type:
dict[str,str]
- schema()¶
Returns a copy of the channel’s metadata.
Note that changes made to the returned object will not be applied to the channel’s schema.
- Return type:
Schema|None
- schema_name()¶
The name of the schema for the channel
- Return type:
str|None
- topic()¶
The topic name of the channel
- Return type:
str
- class foxglove.ChannelDescriptor¶
Information about a Channel.
- id¶
Returns the channel ID.
- message_encoding¶
Returns the message encoding for this channel.
- metadata¶
Returns the metadata for this channel.
- schema¶
Returns the schema for this channel.
- topic¶
Returns the channel topic.
- class foxglove.ConnectionGraph¶
A connection graph.
- __new__(**kwargs)¶
- set_advertised_service(service, provider_ids)¶
Set an advertised service and its associated provider IDs. Overwrites any existing service with the same name.
- Parameters:
service – The service name.
provider_ids – The set of provider IDs.
- set_published_topic(topic, publisher_ids)¶
Set a published topic and its associated publisher IDs. Overwrites any existing topic with the same name.
- Parameters:
topic – The topic name.
publisher_ids – The set of publisher IDs.
- set_subscribed_topic(topic, subscriber_ids)¶
Set a subscribed topic and its associated subscriber IDs. Overwrites any existing topic with the same name.
- Parameters:
topic – The topic name.
subscriber_ids – The set of subscriber IDs.
- class foxglove.Context¶
A context for logging messages.
A context is the binding between channels and sinks. By default, the SDK will use a single global context for logging, but you can create multiple contexts in order to log to different topics to different sinks or servers. To do so, associate the context by passing it to the channel constructor and to
open_mcap()orstart_server().- __new__(**kwargs)¶
- static default()¶
Returns the default context.
- class foxglove.MessageSchema¶
A service request or response schema.
- Parameters:
encoding (str) – The encoding of the message.
schema (
foxglove.Schema) – The message schema.
- __new__(**kwargs)¶
- encoding¶
The encoding of the message.
- schema¶
The message schema.
- class foxglove.Parameter¶
A parameter which can be sent to a client.
- Parameters:
name (str) – The parameter name.
value (None|bool|float|str|bytes|list|dict|ParameterValue) – Optional value, represented as a native python object, or a ParameterValue.
type (ParameterType|None) – Optional parameter type. This is automatically derived when passing a native python object as the value.
- __new__(**kwargs)¶
- get_value()¶
Returns the parameter value as a native python object.
- Return type:
None|bool|float|str|bytes|list|dict
- name¶
The name of the parameter.
- type¶
The parameter type.
- value¶
The parameter value.
- class foxglove.Schema¶
A Schema is a description of the data format of messages or service calls.
- Parameters:
name (str) – The name of the schema.
encoding (str) – The encoding of the schema.
data (bytes) – Schema data.
- __new__(**kwargs)¶
- data¶
Schema data.
- encoding¶
The encoding of the schema.
- name¶
The name of the schema.
- class foxglove.Service¶
A service.
The handler must be a callback function which takes the
foxglove.ServiceRequestas its argument, and returns bytes as a response. If the handler raises an exception, the stringified exception message will be returned to the client as an error.- __new__(**kwargs)¶
- class foxglove.ServiceRequest¶
A service request.
- call_id¶
The call ID that uniquely identifies this request for this client.
- client_id¶
The client ID.
- encoding¶
The request encoding.
- payload¶
The request payload.
- service_name¶
The service name.
- class foxglove.ServiceSchema¶
A service schema.
- Parameters:
name (str) – The name of the service.
request (
foxglove.MessageSchema| None) – The request schema.response (
foxglove.MessageSchema| None) – The response schema.
- __new__(**kwargs)¶
- name¶
The name of the service.
- request¶
The request schema.
- response¶
The response schema.
- class foxglove.SinkChannelFilter¶
A filter for channels that can be used to subscribe to or unsubscribe from channels.
This can be used to omit one or more channels from a sink, but still log all channels to another sink in the same context.
Return
Trueto log the channel, orFalseto skip it. If the callback errors, then the channel will be skipped.
- class foxglove.SystemInfoPublisher¶
A handle to a running system info publisher.
The publisher is started by
foxglove.start_sysinfo_publisher()and runs in the background untilstop()is called. Seefoxglove.start_sysinfo_publisher()for the list of metrics published on the channel.- stop()¶
Stop the publisher.
Aborts the background task. Subsequent calls to
stopare no-ops.
- foxglove.log(topic, message, *, log_time=None, sink_id=None)¶
Log a message on a topic.
Creates a new channel the first time called for a given topic. For Foxglove types in the messages module, this creates a typed channel (see
foxglove.channelsfor supported types). For bytes and str, this creates a simple schemaless channel and logs the bytes as-is. For dict and list, this creates a schemaless json channel.The type of the message must be kept consistent for each topic or an error will be raised. This can be avoided by creating and using the channels directly instead of using this function.
Note: this raises an error if a channel with the same topic was created by other means. This limitation may be lifted in the future.
- Parameters:
topic (
str) – The topic name.message (
Union[dict[str,Any],list[Any],bytes,str,ArrowPrimitive,CameraCalibration,CircleAnnotation,Color,CompressedAudio,CompressedImage,CompressedPointCloud,CompressedVideo,CubePrimitive,CylinderPrimitive,Duration,Event,FrameTransform,FrameTransforms,GeoJson,Grid,ImageAnnotations,JointState,JointStates,KeyValuePair,LaserScan,LinePrimitive,LocationFix,LocationFixes,Log,ModelPrimitive,Odometry,PackedElementField,Point2,Point3,Point3InFrame,PointCloud,PointsAnnotation,Pose,PoseInFrame,PosesInFrame,Quaternion,RawAudio,RawImage,SceneEntity,SceneEntityDeletion,SceneUpdate,SpherePrimitive,TextAnnotation,TextPrimitive,Timestamp,TriangleListPrimitive,Vector2,Vector3,VoxelGrid]) – The message to log.log_time (
int|None(default:None)) – The optional time the message was logged.
- Return type:
None
- foxglove.open_mcap(path, *, allow_overwrite=False, context=None, channel_filter=None, writer_options=None)¶
Open an MCAP writer for recording.
- Parameters:
path (str | Path | BinaryIO) – The destination to write the MCAP to. If it is a path, the file will be created and must not already exist unless allow_overwrite is True. If it is a file-like object, it must support write(), seek(), and flush() methods.
allow_overwrite (Optional[bool]) – Set this flag in order to overwrite an existing file at this path. Ignored when a file-like object is provided.
context (
Context) – The context to use for logging. If None, the global context is used.channel_filter (Optional[Callable[[ChannelDescriptor], bool]]) – A Callable that determines whether a channel should be logged to. Return True to log the channel, or False to skip it. By default, all channels will be logged.
writer_options (
mcap.MCAPWriteOptions) – Options for the MCAP writer.
- Return type:
- foxglove.set_log_level(level='INFO')¶
Sets the global log level for the Foxglove SDK and initializes logging.
If FOXGLOVE_LOG_LEVEL is set, that’s used instead of the passed level.
This function should be called before other Foxglove initialization to capture output from all components. Calling this after starting a sink (e.g. server, gateway, or mcap) will have no effect. Only the first call to this function will have an effect. Thread-safe.
This calls logging.basicConfig to setup a global logger if one is not already configured. Set up your logging before calling this function to avoid that.
- Parameters:
level (
int|str(default:'INFO')) – The logging level to set. This accepts the same values as logging.setLevel and defaults to “INFO”. The SDK will not log at levels “CRITICAL” or higher.- Return type:
None
- foxglove.start_gateway(*, name=None, device_token=None, capabilities=None, listener=None, supported_encodings=None, services=None, asset_handler=None, context=None, channel_filter=None, qos_classifier=None, suppress_video_transcode=None, message_backlog_size=None, foxglove_api_url=None, foxglove_api_timeout=None, video_encoder=None, point_cloud_compression=None)¶
Start a remote access gateway for live visualization and teleop in Foxglove.
- Parameters:
name (str | None (default:
None)) – The name of the server. If not set, the device name from the Foxglove platform is used.device_token (str | None (default:
None)) – The device token for authenticating with the Foxglove platform. If not set, theFOXGLOVE_DEVICE_TOKENenvironment variable is used.capabilities (list[RemoteAccessCapability] | None (default:
None)) – A list of capabilities to advertise to clients.listener (RemoteAccessListener | None (default:
None)) – A Python object that implements thefoxglove.remote_access.RemoteAccessListenerprotocol.supported_encodings (list[str] | None (default:
None)) – A list of encodings to advertise to clients.services (list[Service] | None (default:
None)) – A list of services to advertise to clients.asset_handler (AssetHandler | None (default:
None)) – A callback function that returns the asset for a given URI, or None if it doesn’t exist.context (Context | None (default:
None)) – The context to use for logging. If None, the global context is used.channel_filter (SinkChannelFilter | None (default:
None)) – ACallablethat determines whether a channel should be logged to. ReturnTrueto log the channel, orFalseto skip it. By default, all channels will be logged.qos_classifier (Callable[[ChannelDescriptor], QosProfile] | None (default:
None)) – ACallablethat returns thefoxglove.remote_access.QosProfileto use for a given channel. If not set, all channels use the default lossy profile.suppress_video_transcode (Callable[[ChannelDescriptor], bool] | None (default:
None)) – ACallablethat returnsTrueto deliver a given channel as data rather than transcoding it to video. Required for compressed depth maps. If not set, all video-capable channels are transcoded.message_backlog_size (int | None (default:
None)) – The maximum number of messages to buffer before disconnecting the slow client. Defaults to 1024.foxglove_api_url (str | None (default:
None)) – Override the Foxglove API base URL.foxglove_api_timeout (float | None (default:
None)) – Timeout for Foxglove API requests, in seconds.video_encoder (VideoEncoderBackend | None (default:
None)) – Preferred backend for encoding published video tracks. If not set, or set toAuto, the SDK chooses (honoring theFOXGLOVE_VIDEO_ENCODERenvironment variable). If the requested backend is unavailable, the SDK falls back to another compatible encoder.point_cloud_compression (Callable[[ChannelDescriptor], DracoEncodeOptions | bool | None] | None (default:
None)) –A per-channel policy for transparent point-cloud compression. When a channel is compressed, it is advertised as
foxglove.CompressedPointCloudand each logged point cloud is compressed in a background task before delivery. TheCallableis invoked for each compressible Lossy point-cloud channel (protobuf-, JSON-, or FlatBuffer-encodedfoxglove.PointCloud, CDR-encoded ROS 2sensor_msgs/msg/PointCloud2, or ROS 1sensor_msgs/PointCloud2); return aDracoEncodeOptionsto compress that channel with those settings,Trueto compress with the default settings, orFalse(orNone) to deliver it unmodified. If the callable raises an exception, the error is logged and the default settings are applied. The default ofNone(no policy) defers to the SDK, which currently compresses every such channel with default settings; note that the defaults are lossy (kd-tree encoding with positions quantized to 12 bits). Channels classified as Reliable skip compression and deliver the raw point cloud on the control bytestream; the policy is not consulted for them.Compressed clouds are conditioned before encoding: per-point fields that carry no value on a remote viewer (timestamps, ranges and angles derivable from the positions, and per-point indices, matched by exact (name, type) tuple) are dropped; packed
rgb/rgbacolor fields declaredfloat32are reinterpreted asuint32;float64fields are narrowed tofloat32(about seven significant digits); and points containing a non-finite value in any float field are removed. A cloud the encoder still cannot compress (for example, fewer than two ofx/y/zpresent) is dropped, not delivered uncompressed — a throttled warning is sent to the device log and to viewers. To deliver clouds untouched, returnFalsefor that channel frompoint_cloud_compression.
- Return type:
RemoteAccessGateway
- foxglove.start_server(*, name=None, host='127.0.0.1', port=8765, capabilities=None, server_listener=None, supported_encodings=None, services=None, asset_handler=None, context=None, session_id=None, channel_filter=None, playback_time_range=None, message_backlog_size=None, tls_cert=None, tls_key=None)¶
Start a WebSocket server for live visualization.
- Parameters:
name (str | None (default:
None)) – The name of the server.host (str | None (default:
'127.0.0.1')) – The host to bind to.port (int | None (default:
8765)) – The port to bind to.capabilities (list[Capability] | None (default:
None)) – A list of capabilities to advertise to clients.server_listener (ServerListener | None (default:
None)) – A Python object that implements thewebsocket.ServerListenerprotocol.supported_encodings (list[str] | None (default:
None)) – A list of encodings to advertise to clients.services (list[Service] | None (default:
None)) – A list of services to advertise to clients.asset_handler (AssetHandler | None (default:
None)) – A callback function that returns the asset for a given URI, or None if it doesn’t exist.context (Context | None (default:
None)) – The context to use for logging. If None, the global context is used.session_id (str | None (default:
None)) – An ID which allows the client to understand if the connection is a re-connection or a new server instance. If None, then an ID is generated based on the current time.channel_filter (SinkChannelFilter | None (default:
None)) – ACallablethat determines whether a channel should be logged to. ReturnTrueto log the channel, orFalseto skip it. By default, all channels will be logged.playback_time_range (tuple[int, int] | None (default:
None)) – Time range of data being played back, in absolute nanoseconds. ImpliesCapability.PlaybackControlif set.message_backlog_size (int | None (default:
None)) – The maximum number of outgoing messages to buffer per client. The oldest data-plane message is dropped when the buffer fills. The control-plane queue is the same size; if it fills, the slow client is disconnected. Defaults to 1024.tls_cert (bytes | None (default:
None)) – A PEM-encoded X.509 certificate for the server. Must be provided together withtls_key. When set, the server only acceptswss://connections.tls_key (bytes | None (default:
None)) – A PEM-encoded PKCS#8 private key matchingtls_cert.
- Return type:
WebSocketServer
- foxglove.start_sysinfo_publisher(*, topic=None, refresh_interval=None, context=None)¶
Start the system info publisher.
Periodically publishes a
SystemInfomessage to a channel containing process and system statistics (memory, CPU, OS info).Published metrics
Each message is a JSON object with a JSON Schema attached to the channel. The following fields are published:
process_memory(number): Resident memory used by the SDK process, in bytes.process_virtual_memory(number): Virtual memory used by the SDK process, in bytes.process_cpu_percent(number): CPU usage for the SDK process, as a percent of total system CPU capacity (0.0 to 100.0).process_cpu_cores(number): CPU usage for the SDK process, expressed in core-equivalents (0.0 tonum_cpus). 1.0 means a single logical CPU is fully utilized.total_cpu_percent(number): Total CPU usage across all logical CPUs on the system, as a percent (0.0 to 100.0).total_cpu_cores(number): Total CPU usage across the system, expressed in core-equivalents (0.0 tonum_cpus). 1.0 means one logical CPU’s worth of work is being done.num_cpus(integer): Number of logical CPUs on the system.total_memory(number): Total physical memory on the system, in bytes.used_memory(number): Used physical memory on the system, in bytes.total_swap(number): Total swap space on the system, in bytes.used_swap(number): Used swap space on the system, in bytes.kernel_version(string): Kernel version string, or empty if unknown.os_version(string): OS version string, or empty if unknown.
CPU usage values are computed from the difference between consecutive samples, so they reflect activity over the most recent refresh interval.
The caller is responsible for calling stop() on the returned handle when done; dropping the handle does not stop the background task.
- Parameters:
topic (
str|None(default:None)) – The channel topic name. Defaults to/sysinfo.refresh_interval (
float|None(default:None)) – How often to publish, in seconds. Defaults to0.5. Clamped to a minimum of 0.2s.context (
Context|None(default:None)) – The context on which the publisher creates its channel. Defaults to the global default context.
- Return type:
- Returns:
A handle that can be used to stop the publisher.
Message Types¶
ArrowPrimitiveCameraCalibrationCircleAnnotationColorCompressedAudioCompressedImageCompressedPointCloudCompressedVideoCubePrimitiveCylinderPrimitiveDurationEventFrameTransformFrameTransformsGeoJsonGridImageAnnotationsJointStateJointStatesKeyValuePairLaserScanLinePrimitiveLinePrimitiveLineTypeLocationFixLocationFixPositionCovarianceTypeLocationFixesLogLogLevelModelPrimitiveOdometryPackedElementFieldPackedElementFieldNumericTypePoint2Point3Point3InFramePointCloudPointsAnnotationPointsAnnotationTypePosePoseInFramePosesInFrameQuaternionRawAudioRawImageSceneEntitySceneEntityDeletionSceneEntityDeletionTypeSceneUpdateSpherePrimitiveTextAnnotationTextPrimitiveTimestampTriangleListPrimitiveVector2Vector3VoxelGrid
Channels¶
ArrowPrimitiveChannelCameraCalibrationChannelCircleAnnotationChannelColorChannelCompressedAudioChannelCompressedImageChannelCompressedPointCloudChannelCompressedVideoChannelCubePrimitiveChannelCylinderPrimitiveChannelEventChannelFrameTransformChannelFrameTransformsChannelGeoJsonChannelGridChannelImageAnnotationsChannelJointStateChannelJointStatesChannelKeyValuePairChannelLaserScanChannelLinePrimitiveChannelLocationFixChannelLocationFixesChannelLogChannelModelPrimitiveChannelOdometryChannelPackedElementFieldChannelPoint2ChannelPoint3ChannelPoint3InFrameChannelPointCloudChannelPointsAnnotationChannelPoseChannelPoseInFrameChannelPosesInFrameChannelQuaternionChannelRawAudioChannelRawImageChannelSceneEntityChannelSceneEntityDeletionChannelSceneUpdateChannelSpherePrimitiveChannelTextAnnotationChannelTextPrimitiveChannelTriangleListPrimitiveChannelVector2ChannelVector3ChannelVoxelGridChannel
Parameters¶
Used with the parameter service. Requires the Capability.Parameters capability.
- class foxglove.ParameterType¶
An optional type hint for a
Parameter, used to disambiguate values whose intended type cannot be inferred from the wire representation alone.A parameter’s type is typically derived directly from its value: integers, booleans, strings, dicts, and homogeneous arrays of these are unambiguous on the wire. This enum only enumerates the cases that need an explicit hint:
ParameterType.ByteArray: a byte array is transmitted as a base64-encoded string, so without a type hint it would be indistinguishable from an ordinary string.ParameterType.Float64: a whole-valued float (e.g.1.0) may be indistinguishable from an integer on the wire; the hint preserves the intended floating-point type.ParameterType.Float64Array: same rationale asFloat64, for arrays.
Parameters of other types (integer, bool, string, dict, arrays of these) leave
Parameter.typeset toNone.- ByteArray¶
A byte array.
- Float64¶
A floating-point value that can be represented as a 64-bit floating point number.
- Float64Array¶
An array of floating-point values that can be represented as 64-bit floating point numbers.
- __init__()¶
- __new__(**kwargs)¶
- class foxglove.ParameterValue¶
A parameter value.
- class Float64(value: float)¶
A floating-point value.
- class Integer(value: int)¶
An integer value.
- class Bool(value: bool)¶
A boolean value.
- class String(value: str)¶
A string value.
For parameters of type
ParameterType.ByteArray, this is a base64 encoding of the byte array.
- class Array(value: list[ParameterValue])¶
An array of parameter values.
- class Dict(value: dict[str, ParameterValue])¶
An associative map of parameter values.
- __init__()¶
- __new__(**kwargs)¶
Asset handling¶
You can provide an optional AssetHandler to start_server() to serve assets such
as URDFs for live visualization. The asset handler is a Callable that returns the asset
for a given URI, or None if it doesn’t exist.
Foxglove assets will be requested with the package:// scheme. See https://docs.foxglove.dev/docs/visualization/panels/3d#resolution-of-urdf-assets-with-package-urls
This handler will be run on a separate thread; a typical implementation will load the asset from disk and return its contents.
See the Asset Server example for more information.
- foxglove.AssetHandler¶
alias of Callable[[str], bytes | None]
- class foxglove.MCAPCompression¶
Deprecated. Use
mcap.MCAPCompressioninstead.
Enums¶
foxglove.mcap¶
- class foxglove.mcap.MCAPWriteOptions¶
Options for the MCAP writer.
All parameters are optional.
- Parameters:
compression (MCAPCompression) – Specifies the compression that should be used on chunks. Defaults to Zstd. Pass None to disable compression.
profile (str) – Specifies the profile that should be written to the MCAP Header record.
chunk_size (int | None) – Specifies the target uncompressed size of each chunk. Pass None to disable the chunk size limit.
use_chunks (bool) – Specifies whether to use chunks for storing messages.
emit_statistics (bool) – Specifies whether to write a statistics record in the summary section.
emit_summary_offsets (bool) – Specifies whether to write summary offset records.
emit_message_indexes (bool) – Specifies whether to write message index records after each chunk.
emit_chunk_indexes (bool) – Specifies whether to write chunk index records in the summary section.
repeat_channels (bool) – Specifies whether to repeat each channel record from the data section in the summary section.
repeat_schemas (bool) – Specifies whether to repeat each schema record from the data section in the summary section.
calculate_chunk_crcs (bool) – Specifies whether to calculate and write CRCs for chunk records.
calculate_data_section_crc (bool) – Specifies whether to calculate and write a data section CRC into the DataEnd record.
calculate_summary_section_crc (bool) – Specifies whether to calculate and write a summary section CRC into the Footer record.
calculate_attachment_crcs (bool) – Specifies whether to calculate and write CRCs for attachment records.
compression_level (int) – Specifies the compression level to use. 0 means use the compressor default.
compression_threads (int | None) – Specifies how many threads to use for zstd compression. None uses the number of physical CPUs. 0 disables multithreaded compression.
- __new__(**kwargs)¶
- class foxglove.mcap.MCAPWriter¶
A writer for logging messages to an MCAP file.
Obtain an instance by calling
foxglove.open_mcap().This class may be used as a context manager, in which case the writer will be closed when you exit the context.
If the writer is not closed by the time it is garbage collected, it will be closed automatically, and any errors will be logged.
- attach(*, log_time, create_time, name, media_type, data)¶
Write an attachment to the MCAP file.
Attachments are arbitrary binary data that can be stored alongside messages. Common uses include storing configuration files, calibration data, or other reference material related to the recording.
- Parameters:
log_time – Time at which the attachment was logged, in nanoseconds since epoch.
create_time – Time at which the attachment data was created, in nanoseconds since epoch.
name – Name of the attachment (e.g., “config.json”).
media_type – MIME type of the attachment (e.g., “application/json”).
data – Binary content of the attachment.
- close()¶
Close the MCAP writer.
You may call this to explicitly close the writer. Note that the writer will be automatically closed for you when it is garbage collected, or when exiting the context manager.
- flush()¶
Finishes the current chunk (if any) and flushes the underlying writer.
Note that compression ratios tend to improve over the lifetime of a chunk, so flushing frequently with chunked output may reduce overall compression.
- write_metadata(name, metadata)¶
Write metadata to the MCAP file.
Metadata consists of key-value string pairs associated with a name. If the metadata dictionary is empty, this method does nothing.
foxglove.remote_access¶
- class foxglove.remote_access.Client¶
A client connected to a running remote access gateway.
- class foxglove.remote_access.ConnectionGraph¶
A connection graph.
- __new__(**kwargs)¶
- set_advertised_service(service, provider_ids)¶
Set an advertised service and its associated provider IDs. Overwrites any existing service with the same name.
- Parameters:
service – The service name.
provider_ids – The set of provider IDs.
- set_published_topic(topic, publisher_ids)¶
Set a published topic and its associated publisher IDs. Overwrites any existing topic with the same name.
- Parameters:
topic – The topic name.
publisher_ids – The set of publisher IDs.
- set_subscribed_topic(topic, subscriber_ids)¶
Set a subscribed topic and its associated subscriber IDs. Overwrites any existing topic with the same name.
- Parameters:
topic – The topic name.
subscriber_ids – The set of subscriber IDs.
- class foxglove.remote_access.DracoEncodeOptions¶
Options for Draco point-cloud encoding.
- Parameters:
quantization_bits (int) – Quantization bits for positions and float32 fields; must be between 1 and 30 inclusive, or a
ValueErroris raised. To disable compression for a channel, returnFalsefrom thepoint_cloud_compressionpolicy rather than passing0. Defaults to 12.method (
DracoMethod) – The encoding method. Defaults toKdTree.
- __new__(**kwargs)¶
- class foxglove.remote_access.QosProfile¶
Quality-of-service profile for a channel.
- __new__(**kwargs)¶
- class foxglove.remote_access.Reliability¶
The reliability policy for a channel’s data delivery.
- class foxglove.remote_access.RemoteAccessGateway¶
A handle to a running remote access gateway.
Obtain an instance by calling
foxglove.start_gateway().- add_services(services)¶
Advertises support for the provided services.
These services will be available for clients to use until they are removed with
remove_services().This method will fail if the server was not configured with
Capability.Services, if a service name is not unique, or if a service has no request encoding and the server has no supported encodings.- Parameters:
services (list[Service]) – Services to add.
- connection_status()¶
Returns the current connection status.
- publish_connection_graph(graph)¶
Publishes a connection graph update to all subscribed clients. An update is published to clients as a difference from the current graph to the replacement graph. When a client first subscribes to connection graph updates, it receives the current graph.
Raises an error if the gateway wasn’t started with Capability.ConnectionGraph.
- Parameters:
graph (ConnectionGraph) – The connection graph to publish.
- publish_parameter_values(parameters)¶
Publishes parameter values to all subscribed clients.
- Parameters:
parameters (list[Parameter]) – The parameters to publish.
- publish_status(message, level, id=None)¶
Send a status message to all connected participants.
- Parameters:
message (str) – The message to send.
level (StatusLevel) – The level of the status message.
id (str | None) – An optional ID for the status message.
- remove_services(names)¶
Removes services that were previously advertised.
- Parameters:
names (list[str]) – Names of services to remove.
- remove_status(ids)¶
Remove status messages by ID from all connected participants.
- Parameters:
ids (list[str]) – The IDs of the status messages to remove.
- send_status(client_id, message, level, id=None)¶
Send a status message to a single connected participant. If the client is unknown or has disconnected, or there is no active session, this has no effect.
This method may be called from within
RemoteAccessListenercallbacks.- Parameters:
client_id (int) – The
idof aClientpassed to a listener callback.message (str) – The message to send.
level (StatusLevel) – The level of the status message.
id (str | None) – An optional ID for the status message.
- stop()¶
Gracefully disconnect from the remote access gateway.
- class foxglove.remote_access.RemoteAccessListener¶
A mechanism to register callbacks for handling remote access client events.
- __init__(*args, **kwargs)¶
- on_client_advertise(client, channel)¶
Called when a client advertises a channel.
- Parameters:
client (
Client) – The client that advertised the channel.channel (
ChannelDescriptor) – The channel that was advertised.
- Return type:
None
- on_client_unadvertise(client, channel)¶
Called when a client unadvertises a channel.
- Parameters:
client (
Client) – The client that unadvertised the channel.channel (
ChannelDescriptor) – The channel that was unadvertised.
- Return type:
None
- on_connection_graph_subscribe()¶
Called when the first client subscribes to the connection graph.
Requires
Capability.ConnectionGraph. :rtype:NoneWarning
Do not call
publish_connection_graph()from within this callback; doing so will deadlock.
- on_connection_graph_unsubscribe()¶
Called when the last client unsubscribes from the connection graph.
Requires
Capability.ConnectionGraph. :rtype:NoneWarning
Do not call
publish_connection_graph()from within this callback; doing so will deadlock.
- on_connection_status_changed(status)¶
Called when the gateway connection status changes.
- Parameters:
status (
RemoteAccessConnectionStatus) – The new connection status.- Return type:
None
- on_get_parameters(client, param_names, request_id=None)¶
Called when a client requests parameters.
Requires
Capability.Parameters.
- on_message_data(client, channel, data)¶
Called when a message is received from a client.
- Parameters:
client (
Client) – The client that sent the message.channel (
ChannelDescriptor) – The channel the message was sent on.data (
bytes) – The message data.
- Return type:
None
- on_parameters_subscribe(param_names)¶
Called when a client subscribes to one or more parameters for the first time.
Requires
Capability.Parameters.- Parameters:
param_names (
list[str]) – The names of the parameters to subscribe to.- Return type:
None
- on_parameters_unsubscribe(param_names)¶
Called when the last client subscription to one or more parameters has been removed.
Requires
Capability.Parameters.- Parameters:
param_names (
list[str]) – The names of the parameters to unsubscribe from.- Return type:
None
- on_set_parameters(client, parameters, request_id=None)¶
Called when a client sets parameters.
Requires
Capability.Parameters.
- on_subscribe(client, channel)¶
Called when a client subscribes to a channel.
- Parameters:
client (
Client) – The client that subscribed.channel (
ChannelDescriptor) – The channel that was subscribed to.
- Return type:
None
- on_unsubscribe(client, channel)¶
Called when a client unsubscribes from a channel or disconnects. Also called when a subscribed channel is removed from the
Context.- Parameters:
client (
Client) – The client that unsubscribed.channel (
ChannelDescriptor) – The channel that was unsubscribed from.
- Return type:
None
Enums¶
- enum foxglove.remote_access.Capability¶
An enumeration of capabilities that the remote access gateway can advertise to its clients.
Specify the capabilities you support when calling
foxglove.start_gateway().- ClientPublish¶
Allow clients to advertise channels to send data messages to the server.
- ConnectionGraph¶
Allow clients to subscribe to connection graph updates.
- Parameters¶
Allow clients to get, set, and subscribe to parameter updates.
- Services¶
Allow clients to call services.
- enum foxglove.remote_access.RemoteAccessConnectionStatus¶
The status of the remote access gateway connection.
- Connecting¶
The gateway is attempting to establish or re-establish a connection.
- Connected¶
The gateway is connected and handling events.
- ShuttingDown¶
The gateway is shutting down. Listener callbacks may still be in progress.
- Shutdown¶
The gateway has been shut down. No further listener callbacks will be invoked.
- enum foxglove.remote_access.VideoEncoderBackend¶
The preferred backend for encoding published video tracks.
This is a gateway-wide preference applied to every published video track. If the requested backend is unavailable on the host, the SDK falls back to another compatible encoder.
- Auto¶
Let the SDK choose the encoder backend (honoring
FOXGLOVE_VIDEO_ENCODER). The default.
- Software¶
Prefer a software encoder.
- Hardware¶
Prefer any available hardware encoder.
- Nvenc¶
Prefer NVIDIA NVENC when available.
- Vaapi¶
Prefer VAAPI when available.
- VideoToolbox¶
Prefer VideoToolbox on Apple platforms when available.
- enum foxglove.remote_access.DracoMethod¶
Draco point-cloud encoding method, selected with
DracoEncodeOptions. Quantization applies to positions and every float32 field under both methods, and integer fields are copied losslessly under both; the methods differ in point order and compression ratio.- KdTree¶
kd-tree encoding: the best compression ratios, but points are reordered. The default.
- Sequential¶
Sequential encoding: preserves point order, at a lower compression ratio.
foxglove.websocket¶
- class foxglove.websocket.ChannelView¶
Information about a channel.
- class foxglove.websocket.Client¶
A client connected to a running WebSocket server.
- id¶
A client identifier that is unique within the scope of this server.
- class foxglove.websocket.ClientChannel¶
Information about a client channel.
- class foxglove.websocket.ConnectionGraph¶
A connection graph.
- __new__(**kwargs)¶
- set_advertised_service(service, provider_ids)¶
Set an advertised service and its associated provider IDs. Overwrites any existing service with the same name.
- Parameters:
service – The service name.
provider_ids – The set of provider IDs.
- set_published_topic(topic, publisher_ids)¶
Set a published topic and its associated publisher IDs. Overwrites any existing topic with the same name.
- Parameters:
topic – The topic name.
publisher_ids – The set of publisher IDs.
- set_subscribed_topic(topic, subscriber_ids)¶
Set a subscribed topic and its associated subscriber IDs. Overwrites any existing topic with the same name.
- Parameters:
topic – The topic name.
subscriber_ids – The set of subscriber IDs.
- class foxglove.websocket.PlaybackControlRequest¶
A request to control playback from the Foxglove app
- class foxglove.websocket.PlaybackState¶
The status playback of data that the server is providing
- __new__(**kwargs)¶
- current_time¶
The current time of playback, in absolute nanoseconds
- did_seek¶
Whether a seek forward or backward in time triggered this message to be emitted
- playback_speed¶
The speed of playback, as a factor of realtime
- request_id¶
If this message is being emitted in response to a PlaybackControlRequest message, the request_id from that message. Set this to None if the state of playback has been changed by any other condition.
- status¶
The status of server data playback
- class foxglove.websocket.ServerListener¶
A mechanism to register callbacks for handling client message events.
- __init__(*args, **kwargs)¶
- on_client_advertise(client, channel)¶
Called by the server when a client advertises a channel.
- Parameters:
client (
Client) – The client (id) that sent the message.channel (
ClientChannel) – The client channel that is being advertised.
- Return type:
None
- on_client_unadvertise(client, client_channel_id)¶
Called by the server when a client unadvertises a channel.
- Parameters:
client (
Client) – The client (id) that is unadvertising the channel.client_channel_id (
int) – The client channel ID that is being unadvertised.
- Return type:
None
- on_connection_graph_subscribe()¶
Called by the server when the first client subscribes to the connection graph.
Requires
Capability.ConnectionGraph. :rtype:NoneWarning
Do not call
publish_connection_graph()from within this callback; doing so will deadlock.
- on_connection_graph_unsubscribe()¶
Called by the server when the last client unsubscribes from the connection graph.
Requires
Capability.ConnectionGraph. :rtype:NoneWarning
Do not call
publish_connection_graph()from within this callback; doing so will deadlock.
- on_get_parameters(client, param_names, request_id=None)¶
Called by the server when a client requests parameters.
Requires
Capability.Parameters.
- on_message_data(client, client_channel_id, data)¶
Called by the server when a message is received from a client.
- Parameters:
client (
Client) – The client (id) that sent the message.client_channel_id (
int) – The client channel ID that the message was sent on.data (
bytes) – The message data.
- Return type:
None
- on_parameters_subscribe(param_names)¶
Called by the server when a client subscribes to one or more parameters for the first time.
Requires
Capability.Parameters.- Parameters:
param_names (
list[str]) – The names of the parameters to subscribe to.- Return type:
None
- on_parameters_unsubscribe(param_names)¶
Called by the server when the last client subscription to one or more parameters has been removed.
Requires
Capability.Parameters.- Parameters:
param_names (
list[str]) – The names of the parameters to unsubscribe from.- Return type:
None
- on_set_parameters(client, parameters, request_id=None)¶
Called by the server when a client sets parameters. Note that only parameters which have changed are included in the callback, but the return value must include all parameters. If a parameter that is unset is included in the return value, it will not be published to clients.
Requires
Capability.Parameters.
- on_subscribe(client, channel)¶
Called by the server when a client subscribes to a channel.
- Parameters:
client (
Client) – The client (id) that sent the message.channel (
ChannelView) – The channel (id, topic) that the message was sent on.
- Return type:
None
- on_unsubscribe(client, channel)¶
Called by the server when a client unsubscribes from a channel or disconnects. Also called when a subscribed channel is removed from the server.
- Parameters:
client (
Client) – The client (id) that sent the message.channel (
ChannelView) – The channel (id, topic) that the message was sent on.
- Return type:
None
- class foxglove.websocket.WebSocketServer¶
A WebSocket server. Obtain an instance by calling
foxglove.start_server().- add_services(services)¶
Advertises support for the provided services.
These services will be available for clients to use until they are removed with
remove_services().This method will fail if the server was not configured with
Capability.Services, if a service name is not unique, or if a service has no request encoding and the server has no supported encodings.- Parameters:
services (list[Service]) – Services to add.
- app_url(*, layout_id=None, open_in_desktop=False)¶
Returns an app URL to open the WebSocket as a data source.
Returns None if the server has been stopped.
- Parameters:
layout_id (str | None) – An optional layout ID to include in the URL.
open_in_desktop (bool) – Opens the foxglove desktop app.
- broadcast_time(timestamp_nanos)¶
Publishes the current server timestamp to all clients. If the server has been stopped, this has no effect.
- Parameters:
timestamp_nanos (int) – The timestamp to broadcast, in nanoseconds.
- clear_session(session_id=None)¶
Sets a new session ID and notifies all clients, causing them to reset their state. If no session ID is provided, generates a new one based on the current timestamp. If the server has been stopped, this has no effect.
- Parameters:
session_id (str | None) – An optional session ID.
- port¶
Get the port on which the server is listening.
- publish_connection_graph(graph)¶
Publishes a connection graph update to all subscribed clients. An update is published to clients as a difference from the current graph to the replacement graph. When a client first subscribes to connection graph updates, it receives the current graph.
Raises an error if the server wasn’t started with Capability.ConnectionGraph.
- Parameters:
graph (ConnectionGraph) – The connection graph to publish.
- publish_parameter_values(parameters)¶
Publishes parameter values to all subscribed clients.
- Parameters:
parameters (list[Parameter]) – The parameters to publish.
- publish_status(message, level, id=None)¶
Send a status message to all clients. If the server has been stopped, this has no effect.
- Parameters:
message (str) – The message to send.
level (StatusLevel) – The level of the status message.
id (str | None) – An optional ID for the status message.
- remove_services(names)¶
Removes services that were previously advertised.
- Parameters:
names (list[str]) – Names of services to remove.
- remove_status(status_ids)¶
Remove status messages by ID from all clients. If the server has been stopped, this has no effect.
- Parameters:
status_ids (list[str]) – The IDs of the status messages to remove.
- send_status(client_id, message, level, id=None)¶
Send a status message to a single client. If the client is unknown or has disconnected, or the server has been stopped, this has no effect.
This method may be called from within
ServerListenercallbacks.- Parameters:
client_id (int) – The ID of the client, from
Client.id.message (str) – The message to send.
level (StatusLevel) – The level of the status message.
id (str | None) – An optional ID for the status message.
- stop()¶
Explicitly stop the server.
Enums¶
- enum foxglove.websocket.Capability¶
An enumeration of capabilities that you may choose to support for live visualization.
Specify the capabilities you support when calling
foxglove.start_server(). These will be advertised to the Foxglove app when connected as a WebSocket client.- ClientPublish¶
Allow clients to advertise channels to send data messages to the server.
- ConnectionGraph¶
Allow clients to subscribe to connection graph updates.
- Parameters¶
Allow clients to get & set parameters.
- Services¶
Allow clients to call services.
- Time¶
Inform clients about the latest server time.
This allows accelerated, slowed, or stepped control over the progress of time. If the server publishes time data, then timestamps of published messages must originate from the same time source.
- PlaybackControl¶
Indicates that the server is capable of responding to playback control requests from controls in the Foxglove app.
Playback control¶
Used with the playback control feature during live visualization. Requires the
Capability.PlaybackControl capability.
- enum foxglove.websocket.PlaybackCommand¶
The command for playback requested by the client player.
- Play¶
Start or continue playback.
- Pause¶
Pause playback.
- enum foxglove.websocket.PlaybackStatus¶
The status of server data playback.
- Playing¶
Playing at the requested playback speed.
- Paused¶
Playback paused.
- Buffering¶
Server is not yet playing back data because it is performing a prerequisite required operation.
- Ended¶
The end of the available data has been reached.
foxglove.datasets¶
Topic-filtered episode readers for optional Ray and PyTorch integrations.
For a short script that reads a dataset, see the Datasets quickstart.
- class foxglove.datasets.DatasetSplit¶
Assign whole recording groups to train, validation, and test sets.
Episodes connected by a shared recording form one group. Each group is assigned according to a hash of its smallest custom group ID, or its smallest recording ID when
groupsis omitted, together withseedand the configured probabilities. Membership is reproducible for a committed dataset version and configuration, independent of API order, framework, source, epoch, ranks, and workers. A draft’s episodes can change until the draft is committed, and its membership can change with them.- Parameters:
train (
float(default:0.8)) – Optional. Probability that a group is assigned to the training set. The three proportions must be finite, nonnegative, and sum to one.validation (
float(default:0.1)) – Optional. Probability that a group is assigned to the validation set.test (
float(default:0.1)) – Optional. Probability that a group is assigned to the test set.seed (
int(default:0)) – Optional. Seed for the assignment hash. Independent of epoch shuffling.groups (
Mapping[str,str] |Sequence[Sequence[str]] |None(default:None)) – Optional. Maps every episode ID to a session, site, or other group ID, and must cover exactly the episodes of the dataset version. These constraints are added to recording grouping, so shared recordings always stay together. The mapping is snapshotted as sorted, immutable episode/group pairs; these pairs are also accepted as sequences when restoring fromdataclasses.asdictor JSON.
- Raises:
ValueError – If a proportion is not a finite, nonnegative number, the proportions do not sum to one,
seedis not an integer, orgroupsis not a mapping or sequence of episode/group pairs of nonempty strings with unique episode IDs.
Example:
from foxglove.datasets import DatasetSplit, inspect_splits split = DatasetSplit(train=0.8, validation=0.1, test=0.1) summaries = inspect_splits( "dset_123", version=2, split_config=split )
- class foxglove.datasets.EpisodeReader¶
An episode scoped to the topics selected by
read_dataset.Instances are supplied to the user’s
read_episodecallback. The SDK closes an instance when that callback’s iterator finishes or is closed. Message tuples are the client’s(schema, channel, message, decoded_message)values. Create custom message decoders inside the callback and pass them toiter_messages().- property end_time: datetime¶
End of the episode’s time window.
- property id: str¶
Episode ID.
- iter_messages(*, decoder_factories=None, topics=None, lookback=datetime.timedelta(0))¶
Stream the selected topics in log-time order without buffering the episode.
Each invocation opens a new stream on first iteration. Repeated invocations redownload data. Active streams are closed when the callback ends. Message context and stream order are preserved for stateful processing.
- Parameters:
decoder_factories (
Sequence[DecoderFactory] |None(default:None)) – Optional. MCAP decoder factories used for message deserialization.Noneuses the client’s default decoders; an explicit list replaces them. Construct factories inside the callback so their state stays local to the worker and episode.topics (
Sequence[str] |None(default:None)) – Optional. Nonempty subset of the dataset topics;Nonestreams all of them. Filtering happens on the server or through MCAP indexes for object storage; separate calls open separate downloads.lookback (
timedelta(default:datetime.timedelta(0))) – Optional. Additional history to request before the episode start, for stateful media decoding. Must be nonnegative. The history is read from the recordings attached to the episode. Consumers must exclude lookback messages, which are logged beforestart_time, from their training samples.
- Return type:
Generator[tuple[Schema|None,Channel,Message,Any],None,None]- Returns:
Tuples of schema (possibly
None), channel, raw MCAP message, and decoded message payload.- Raises:
ValueError – On first iteration, if
lookbackis negative, ortopicsis empty or not a subset of the dataset topics.RuntimeError – On first iteration, if the callback that received this reader has ended.
mcap.exceptions.DecoderNotFoundError – If no decoder factory handles the encoding of a message.
Example:
def read_episode(episode): for _, channel, message, _ in episode.iter_messages(): yield { "topic": channel.topic, "log_time": message.log_time, }
- property properties: Mapping[str, Any]¶
Read-only properties of the episode version pinned by the dataset version.
Requires
include_properties=Trueinread_dataset. Empty if the episode has no properties.- Raises:
RuntimeError – If properties were not requested.
- property start_time: datetime¶
Start of the episode’s time window.
- class foxglove.datasets.ObjectLocation¶
Location of an original recording in customer-managed storage.
-
azure_storage_account_name:
str|None= None¶ For Azure, the storage account of the container.
-
bucket:
str¶ Bucket that holds the object. For Azure, the container.
-
path:
str¶ Full object key, not the recording’s display filename.
-
scheme:
str|None= None¶ Cloud provider:
s3,gs, orazfor built-in storage access. Custom stores may also accept other or absent schemes.
-
azure_storage_account_name:
- class foxglove.datasets.ObjectStore¶
Worker-local storage access using the customer’s credentials.
Implementations may use PyArrow, fsspec, or another random-access filesystem. Any object with a matching
openmethod satisfies this protocol.- open(location)¶
Open a fresh seekable binary file; the SDK owns and closes this handle.
The handle must support
readintoas well asreadandseek. The SDK buffers small reads in 64 KiB blocks. Use range reads and bounded caching, not a whole-object download. Files must remain immutable for the duration of a dataset read.- Parameters:
location (
ObjectLocation) – Required. The recording to open.- Return type:
IO[bytes]- Returns:
A seekable binary file handle for the object.
Example:
class LocalStore: def open(self, location): path = f"/mnt/{location.bucket}/{location.path}" return open(path, "rb")
- class foxglove.datasets.SplitSummary¶
Metadata counts for one split, before rank or worker partitioning.
-
episode_count:
int¶ Number of episodes in the split.
-
group_count:
int¶ Number of connected recording groups in the split, including custom grouping constraints.
-
episode_count:
- foxglove.datasets.inspect_splits(dataset_id, *, version, split_config, client_factory=None)¶
Inspect train, validation, and test sizes using episode metadata only.
Uses the same assignment as the PyTorch and Ray readers, without downloading messages or requiring either framework. Counts cover the whole dataset version, before worker/rank partitioning. Proportions are probabilities per connected group.
- Parameters:
dataset_id (
str) – Required. ID of the dataset.version (
int) – Required. Number of the dataset version to inspect: a committed version or the dataset’s draft.split_config (
DatasetSplit) – Required. Split configuration to inspect.client_factory (
Callable[[],_Client] |None(default:None)) – Optional. Callable that returns the API client, for custom authentication or endpoints, as withread_dataset. The default client usesFOXGLOVE_API_TOKEN.
- Return type:
dict[Literal['train','validation','test'],SplitSummary]- Returns:
The
SplitSummaryof each split, keyed by"train","validation", and"test".- Raises:
ValueError – If an argument is invalid,
FOXGLOVE_API_TOKENis not set and noclient_factoryis given, the version contains missing recordings, an episode has no recording IDs, orsplit_config.groupsdoes not cover exactly the version’s episodes.
Example:
from foxglove.datasets import DatasetSplit, inspect_splits summaries = inspect_splits( "dset_123", version=2, split_config=DatasetSplit() ) print(summaries["train"].episode_count)
foxglove.datasets.ray¶
Load dataset versions with Ray Data; requires foxglove-sdk[ray].
- foxglove.datasets.ray.read_dataset(dataset_id, *, version, topics, read_episode, source='foxglove', split_config=None, split=None, include_properties=False, client_factory=None, object_store_factory=None, concurrency=None)¶
Return a native Ray dataset of callback-produced sample mappings.
Planning fetches only the episode list (ids, time windows, and, for object storage, recording locations). Workers stream selected topics and execute
read_episode. Factories and callbacks must be serializable and their dependencies available on every worker.- Parameters:
dataset_id (
str) – Required. ID of the dataset.version (
int) – Required. Number of the dataset version to read: a committed version or the dataset’s draft. The episode list is read once, during this call. A draft’s episodes can change until the draft is committed, so separate calls can read different episode lists. Every call for a committed version reads the same list, so split membership is reproducible.topics (
Sequence[str]) – Required. Topics to stream. Must be nonempty.read_episode (
Callable[[EpisodeReader],Iterable[Mapping[str,Any]]]) – Required. Callback that receives eachEpisodeReaderand yields sample mappings. Mappings (including TypedDict samples) are materialized as dictionaries for Ray. Use consistent column types containing scalars, NumPy arrays, or other Arrow-compatible values. Read task retries rerun callbacks, so callbacks should not perform external side effects.source (
Literal['foxglove','object_storage'] (default:'foxglove')) – Optional."foxglove"downloads messages through Foxglove."object_storage"reads indexed MCAPs directly from S3, GCS, or Azure. The SDK selects the filesystem from recording locations and uses each worker’s cloud credentials. Each MCAP file must have a summary. A file needs chunk indexes unless its summary reports zero messages, and every chunk that contains messages needs message indexes. Missing locations, unsupported schemes, and access failures raise errors.split_config (
DatasetSplit|None(default:None)) – Optional. Together withsplit, selects a recording-safe train, validation, or test pool before task partitioning. Seefoxglove.datasets.DatasetSplit.split (
Optional[Literal['train','validation','test']] (default:None)) – Optional. The pool to read:"train","validation", or"test". Requiressplit_config.include_properties (
bool(default:False)) – Optional.Truefetches each episode’s properties from its pinned version forEpisodeReader.properties. They are not fetched by default.client_factory (
Callable[[],_Client] |None(default:None)) – Optional. Callable that returns the API client, overriding API authentication or endpoints. The default client usesFOXGLOVE_API_TOKEN. For object storage the API client factory is only used during planning and is not serialized.object_store_factory (
Callable[[],ObjectStore] |None(default:None)) – Optional. Callable that returns anObjectStore, overriding built-in storage. Requiressource="object_storage". Factories used by workers must be serializable. No storage clients or open files are serialized in the read tasks.concurrency (
int|None(default:None)) – Optional. Caps concurrent read tasks. By default, Ray decides.
- Return type:
Dataset- Returns:
A Ray dataset whose rows are the mappings that
read_episodeyields. Block construction follows Ray’sDataContext.target_max_block_size. Ray can combine blocks and buffer multiple episodes before delivering output. Settingtarget_max_block_sizetoNoneallows an entire task to be buffered.- Raises:
ValueError – If an argument is invalid,
FOXGLOVE_API_TOKENis not set and noclient_factoryis given, the version contains missing recordings,split_config.groupsdoes not cover exactly the version’s episodes, an episode has no recording IDs whensplit_configis given, or, for object storage, a recording has no supported location.RuntimeError – When the dataset is executed, if
read_episodeor a message stream raises, orread_episodeyields a value that is not a mapping. The message names the episode, dataset, and version. Ray reports it as aRayTaskErrorthat is also aRuntimeErrorand whose message contains the original traceback.
Example:
from foxglove.datasets.ray import read_dataset from foxglove.datasets.video import decode_h264 ds = read_dataset("dset_123", version=2, topics=["/camera"], read_episode=decode_h264)
foxglove.datasets.torch¶
Load dataset versions with PyTorch; requires foxglove-sdk[torch].
- class foxglove.datasets.torch.TorchDataset¶
Bases:
IterableDataset[_T]An episode iterable created by
read_dataset().Call
set_epoch()before each new DataLoader pass to select its episode order. Epoch updates are shared with spawned and persistent loader workers.- set_epoch(epoch)¶
Select the epoch for the next iteration (initially zero).
Set it in every rank before starting the next DataLoader iteration, after completing the previous pass. Active iterators retain the order they started with. For a dataset created with
shuffle=True, the epoch selects the episode order.- Parameters:
epoch (
int) – Required. A nonnegative signed 64-bit integer.- Raises:
TypeError – If
epochis not an integer.ValueError – If
epochis negative or greater than2**63 - 1.
- Return type:
None
Example:
from torch.utils.data import DataLoader for epoch in range(3): ds.set_epoch(epoch) for batch in DataLoader(ds, batch_size=8): ...
- foxglove.datasets.torch.read_dataset(dataset_id, *, version, topics, read_episode, source='foxglove', split_config=None, split=None, include_properties=False, client_factory=None, object_store_factory=None, rank=None, world_size=None, shuffle=False, seed=None)¶
Return a
TorchDatasetover a dataset version.Planning fetches only the episode list (ids, time windows, and, for object storage, recording locations). Messages are downloaded during iteration, and each new iteration rereads data. Factories and callbacks used by workers must be pickleable.
- Parameters:
dataset_id (
str) – Required. ID of the dataset.version (
int) – Required. Number of the dataset version to read: a committed version or the dataset’s draft. The episode list is read once, during this call. A draft’s episodes can change until the draft is committed, so separate calls, including the calls that different ranks make, can read different episode lists. Every call for a committed version reads the same list, so the shuffle order, split membership, and division of episodes among ranks are reproducible.topics (
Sequence[str]) – Required. Topics to stream. Must be nonempty.read_episode (
Callable[[EpisodeReader],Iterable[TypeVar(_T)]]) – Required. Callback that receives eachEpisodeReaderand yields samples, such as tensors, tuples, or dictionaries. Use DataLoader’scollate_fnfor custom sample types.source (
Literal['foxglove','object_storage'] (default:'foxglove')) – Optional."foxglove"downloads messages through Foxglove."object_storage"reads indexed MCAPs from S3, GCS, or Azure using recording locations and the worker’s cloud credentials. No filesystem configuration is needed. Each MCAP file must have a summary. A file needs chunk indexes unless its summary reports zero messages, and every chunk that contains messages needs message indexes. Missing locations, unsupported schemes, and access failures raise errors. Use DataLoader’sspawnmultiprocessing context with cloud storage.split_config (
DatasetSplit|None(default:None)) – Optional. Together withsplit, selects a recording-safe train, validation, or test pool before worker partitioning. Seefoxglove.datasets.DatasetSplit.split (
Optional[Literal['train','validation','test']] (default:None)) – Optional. The pool to read:"train","validation", or"test". Requiressplit_config.include_properties (
bool(default:False)) – Optional.Truefetches each episode’s properties from its pinned version forEpisodeReader.properties. They are not fetched by default.client_factory (
Callable[[],_Client] |None(default:None)) – Optional. Callable that returns the API client, for custom authentication or endpoints. The default client readsFOXGLOVE_API_TOKENfrom the environment. Withsource="object_storage", the factory runs only during planning and is not serialized. Withsource="foxglove", it also runs in each consuming process, so it must be pickleable.object_store_factory (
Callable[[],ObjectStore] |None(default:None)) – Optional. Callable that returns anObjectStore, overriding built-in storage. Requiressource="object_storage".rank (
int|None(default:None)) – Optional. Distributed rank of this process. Supply together withworld_size. If both are omitted, they are captured here fromtorch.distributed, before DataLoader workers start. Iftorch.distributedis not initialized, rank 0 and world size 1 are used.world_size (
int|None(default:None)) – Optional. Number of distributed ranks. Episodes are divided among ranks, then among each rank’s DataLoader workers, so each episode of a committed version is read once per pass.read_datasetalready splits episodes by rank, so do not add aDistributedSampler. Ranks can get different numbers of batches, because each rank reads whole episodes and episodes differ in length. Before the forward pass of each training step, calltorch.distributed.all_reducewithReduceOp.MINon a tensor that is 1 if the rank has a batch and 0 if it does not, and stop the epoch on every rank when the result is 0. Every rank then takes the same number of optimizer steps.shuffle (
bool(default:False)) – Optional.Truepermutes episode metadata usingseed + epochbefore partitioning ranks and workers. The same seed, epoch, and episode list produce the same permutation; all ranks must use the same seed and epoch. CallTorchDataset.set_epoch()between completed passes (initial epoch zero). Without shuffling, episodes retain sorted ID order. Samples within each episode keep callback order. Shuffling uses O(number of episodes) metadata references, without buffering message payloads. The dataset orders and partitions episodes itself, so leave DataLoader’sshuffleandsampleroptions unset.seed (
int|None(default:None)) – Optional. Shuffle seed. Must be a nonnegative integer and requiresshuffle=Truewhen supplied. If omitted orNone, shuffling uses seed zero.
- Return type:
TorchDataset[TypeVar(_T)]- Returns:
An iterable dataset of the samples that
read_episodeyields.- Raises:
TypeError – If
shuffleis not a bool orseedis not an integer.ValueError – If an argument is invalid,
FOXGLOVE_API_TOKENis not set and noclient_factoryis given, the version contains missing recordings,split_config.groupsdoes not cover exactly the version’s episodes, an episode has no recording IDs whensplit_configis given, or, for object storage, a recording has no supported location.RuntimeError – While iterating, if
read_episodeor a message stream raises. The message names the episode, dataset, and version, and the original exception is its__cause__. DataLoader worker processes report the error to the main process as a newRuntimeErrorwhose message contains the original traceback.
Example:
from foxglove.datasets.torch import read_dataset from foxglove.datasets.video import decode_h264 ds = read_dataset("dset_123", version=2, topics=["/camera"], read_episode=decode_h264)
- foxglove.datasets.torch.to_image_tensor(frame)¶
Convert channels-last images to a contiguous channels-first tensor.
- Parameters:
frame (
Mapping[str,Any]) – Required. A sample or batch whoseimageis a NumPy array or Tensor shaped[..., H, W, 3].- Return type:
Tensor- Returns:
The image shaped
[..., 3, H, W]. Preserves dtype and device.- Raises:
KeyError – If
framehas no"image"entry.ValueError – If
imageis not shaped[..., H, W, 3].
Example:
import torch from foxglove.datasets.torch import to_image_tensor batch = {"image": torch.zeros(8, 4, 8, 3)} images = to_image_tensor(batch)
foxglove.datasets.video¶
CPU H.264 decoding for dataset callbacks; requires foxglove-sdk[video].
- exception foxglove.datasets.video.VideoDecodeError¶
Bases:
ValueErrorVideo data cannot be decoded completely and safely.
- class foxglove.datasets.video.VideoSample¶
Bases:
TypedDictAn RGB image and the metadata of its original compressed message.
All timestamps are integer nanoseconds since the Unix epoch.
-
channel_id:
int¶ ID of the MCAP channel of the compressed message.
-
frame_id:
str¶ The camera’s coordinate frame, not a sequence number.
-
image:
ndarray¶ Writable, contiguous uint8 NumPy array of shape
[H, W, 3].
-
log_time_ns:
int¶ Log time of the compressed message. Determines episode membership.
-
publish_time_ns:
int¶ Publish time of the compressed message.
-
timestamp_ns:
int¶ The video’s capture timestamp.
-
topic:
str¶ Topic of the compressed message.
-
channel_id:
- foxglove.datasets.video.decode_h264(episode, *, topic=None, lookback=datetime.timedelta(seconds=5), decoder_factories=None)¶
Yield RGB frames from an episode. Requires
foxglove-sdk[video].Iteration opens the episode’s message sources and maintains independent decoder state per MCAP channel. The returned generator closes them when exhausted or closed.
A frame can depend on every message on its channel since the latest keyframe. If one of those messages is missing, decoding raises VideoDecodeError or yields frames that can be corrupt until the next keyframe.
- Parameters:
episode (
EpisodeReader) – Required. Supplies the inclusive MCAP log-time window for output frames.topic (
str|None(default:None)) – Optional. One selected dataset topic, or None for all selected topics. Non-video schemas are ignored only when topic is None.lookback (
timedelta(default:datetime.timedelta(seconds=5))) – Optional. Nonnegative history budget, default five seconds. The history is read from the recordings attached to the episode and decoded from its latest self-contained keyframe. Missing initialization history raises VideoDecodeError.decoder_factories (
Sequence[DecoderFactory] |None(default:None)) – Optional. MCAP deserializers created in the callback. None uses the client’s defaults.
- Return type:
Generator[VideoSample,None,None]- Returns:
VideoSample dictionaries, ordered per channel. Consume to exhaustion to receive buffered frames.
- Raises:
VideoDecodeError – Unsupported or invalid video, or incomplete decoding. Supports CompressedVideo H.264 Annex B, one image per message, no B-frames, with an initial IDR keyframe containing SPS/PPS.
ValueError – On first iteration, if
lookbackis negative ortopicis not one of the dataset topics.RuntimeError – If the callback that received
episodehas ended.
Example:
from foxglove.datasets.torch import read_dataset from foxglove.datasets.video import decode_h264 ds = read_dataset("dset_123", version=2, topics=["/camera"], read_episode=decode_h264)
foxglove.client (foxglove-client package)¶
foxglove.client is the Python client for the Foxglove API. It is published separately from the
SDK, as the foxglove-client package.