API Reference¶
Version: 0.15.2
Note
The notebook integration classes and functions are only available when the notebook extra package is installed. Install it with pip install foxglove-sdk[notebook].
foxglove¶
This module provides interfaces for logging messages to Foxglove.
See foxglove.schemas and foxglove.channels for working with well-known Foxglove
schemas.
- class foxglove.Channel(topic, *, schema=None, message_encoding=None, context=None, metadata=None)¶
A channel that can be used to log binary messages or JSON messages.
- 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.CloudSink¶
A handle to the CloudSink connection.
This handle can safely be dropped and the connection will run forever.
- stop()¶
Gracefully disconnect from the agent.
If the agent has already been disconnected, this has no effect.
- class foxglove.CloudSinkListener(*args, **kwargs)¶
A mechanism to register callbacks for handling client message events.
- on_client_advertise(client, channel)¶
Called 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 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_message_data(client, client_channel_id, data)¶
Called 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_subscribe(client, channel)¶
Called 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 when a client unsubscribes from a channel or disconnects.
- 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.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().- static default()¶
Returns the default context.
- class foxglove.Schema(*, name, encoding, data)¶
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.
- data¶
Schema data.
- encoding¶
The encoding of the schema.
- name¶
The name of the 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.
- 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 schemas 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,CompressedImage,CompressedVideo,CubePrimitive,CylinderPrimitive,Duration,FrameTransform,FrameTransforms,GeoJson,Grid,ImageAnnotations,KeyValuePair,LaserScan,LinePrimitive,LocationFix,LocationFixes,Log,ModelPrimitive,PackedElementField,Point2,Point3,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 a new mcap file for recording.
- Parameters:
path (str | Path) – The path to the MCAP file. This file will be created and must not already exist.
allow_overwrite (Optional[bool]) – Set this flag in order to overwrite an existing file at this path.
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')¶
Enable SDK logging.
This function will call logging.basicConfig() for convenience in scripts, but in general you should configure logging yourself before calling this function: https://docs.python.org/3/library/logging.html
- 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_cloud_sink(*, listener=None, supported_encodings=None, context=None, session_id=None)¶
Connect to Foxglove Agent for live visualization and teleop.
Foxglove Agent must be running on the same host for this to work.
- Parameters:
capabilities – A list of capabilities to advertise to the agent.
listener (
CloudSinkListener|None(default:None)) – A Python object that implements thecloud.CloudSinkListenerprotocol.supported_encodings (
list[str] |None(default:None)) – A list of encodings to advertise to the agent.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 agent to understand if the connection is a re-connection or a new connection instance. If None, then an ID is generated based on the current time.
- Return type:
- 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)¶
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 (
Callable[[str],bytes|None] |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)) – 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.
- Return type:
Notebook Integration¶
Functions and classes for integrating with Jupyter notebooks and creating interactive visualizations.
- foxglove.init_notebook_buffer(context: Context | None = None) NotebookBuffer¶
Create a NotebookBuffer object to manage data buffering and visualization in Jupyter notebooks.
- Parameters:
context – The Context used to log the messages. If no Context is provided, the global context will be used. Logged messages will be buffered.
- Returns:
A NotebookBuffer object that can be used to manage the data buffering and visualization.
- Raises:
Exception – If the notebook extra package is not installed. Install it with pip install “foxglove-sdk[notebook]””.
Note
This function is only available when the notebook extra package is installed. Install it with pip install “foxglove-sdk[notebook]””.
Notebook Classes¶
- class foxglove.NotebookBuffer¶
A NotebookBuffer object to manage data buffering and visualization in Jupyter notebooks.
Obtain an instance by calling
foxglove.init_notebook_buffer().The NotebookBuffer object will buffer all data logged to the provided context. When you are ready to visualize the data, you can call the
NotebookBuffer.show()method to display an embedded Foxglove visualization widget. The widget provides a fully-featured Foxglove interface directly within your Jupyter notebook, allowing you to explore multi-modal robotics data including 3D scenes, plots, images, and more.- show(layout_storage_key: str, width: int | Literal['full'] | None = None, height: int | None = None) FoxgloveWidget¶
Show the Foxglove viewer. Call this method as the last step of a notebook cell to display the viewer.
- clear() None¶
Clear the buffered data.
- class foxglove.FoxgloveWidget¶
A widget that displays a Foxglove viewer in a notebook.
Obtain an instance by calling
NotebookBuffer.show().- refresh() None¶
Refresh the widget by reading the latest data from the buffer used to created the widget and sending it to the widget.
Schemas¶
ArrowPrimitiveCameraCalibrationCircleAnnotationColorCompressedImageCompressedVideoCubePrimitiveCylinderPrimitiveDurationFrameTransformFrameTransformsGeoJsonGridImageAnnotationsKeyValuePairLaserScanLinePrimitiveLinePrimitiveLineTypeLocationFixLocationFixPositionCovarianceTypeLocationFixesLogLogLevelModelPrimitivePackedElementFieldPackedElementFieldNumericTypePoint2Point3PointCloudPointsAnnotationPointsAnnotationTypePosePoseInFramePosesInFrameQuaternionRawAudioRawImageSceneEntitySceneEntityDeletionSceneEntityDeletionTypeSceneUpdateSpherePrimitiveTextAnnotationTextPrimitiveTimestampTriangleListPrimitiveVector2Vector3VoxelGrid
Channels¶
ArrowPrimitiveChannelCameraCalibrationChannelCircleAnnotationChannelColorChannelCompressedImageChannelCompressedVideoChannelCubePrimitiveChannelCylinderPrimitiveChannelFrameTransformChannelFrameTransformsChannelGeoJsonChannelGridChannelImageAnnotationsChannelKeyValuePairChannelLaserScanChannelLinePrimitiveChannelLocationFixChannelLocationFixesChannelLogChannelModelPrimitiveChannelPackedElementFieldChannelPoint2ChannelPoint3ChannelPointCloudChannelPointsAnnotationChannelPoseChannelPoseInFrameChannelPosesInFrameChannelQuaternionChannelRawAudioChannelRawImageChannelSceneEntityChannelSceneEntityDeletionChannelSceneUpdateChannelSpherePrimitiveChannelTextAnnotationChannelTextPrimitiveChannelTriangleListPrimitiveChannelVector2ChannelVector3ChannelVoxelGridChannel
Parameters¶
Used with the parameter service during live visualization. Requires the websocket.Capability.Parameters capability.
- class foxglove.websocket.ParameterType¶
A parameter type.
- 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.
- class foxglove.websocket.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.
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.
foxglove.mcap¶
- class foxglove.mcap.MCAPWriteOptions(*, compression=None, profile=None, chunk_size=None, use_chunks=False, emit_statistics=True, emit_summary_offsets=True, emit_message_indexes=True, emit_chunk_indexes=True, repeat_channels=True, repeat_schemas=True, calculate_chunk_crcs=True, calculate_data_section_crc=True, calculate_summary_section_crc=True)¶
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) – Specifies the target uncompressed size of each chunk.
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.
- 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.
- 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.
- 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.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.
- 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.MessageSchema(*, encoding, schema)¶
A service request or response schema.
- Parameters:
encoding (str) – The encoding of the message.
schema (
foxglove.Schema) – The message schema.
- encoding¶
The encoding of the message.
- schema¶
The message schema.
- class foxglove.websocket.Parameter(name, *, value=None, **kwargs)¶
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.
- 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.websocket.ServerListener(*args, **kwargs)¶
A mechanism to register callbacks for handling client message events.
- 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.
- Return type:
None
- on_connection_graph_unsubscribe()¶
Called by the server when the last client unsubscribes from the connection graph.
- Return type:
None
- 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.
- 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.Service(name, *, schema, handler)¶
A websocket service.
The handler must be a callback function which takes the
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.
- class foxglove.websocket.ServiceRequest¶
A websocket 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.websocket.ServiceSchema(name, *, request=None, response=None)¶
A service schema.
- Parameters:
name (str) – The name of the service.
request (
MessageSchema| None) – The request schema.response (
MessageSchema| None) – The response schema.
- name¶
The name of the service.
- request¶
The request schema.
- response¶
The response schema.
- class foxglove.websocket.WebSocketServer¶
A live visualization 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.- Parameters:
services – 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 (default:
None) – An optional layout ID to include in the URL.open_in_desktop (default:
False) – 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 – 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 (default:
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.
- Parameters:
graph – 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 – The message to send.
level – The level of the status message.
id (default:
None) – An optional id for the status message.
- remove_services(names)¶
Removes services that were previously advertised.
- Parameters:
names – 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.
- 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.
- 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.
- enum foxglove.websocket.StatusLevel¶
A level for
WebSocketServer.publish_status().- Info¶
- Warning¶
- Error¶