Documentation
¶
Overview ¶
Package bambulan provides a client library for interacting with Bambu Lab 3D printers over the local area network (LAN).
It supports: - MQTT for status monitoring and command control (printing, lights, speed). - FTPS for file management (listing, uploading, downloading). - Camera access for frame capture. - Home Assistant integration via MQTT Discovery.
Example usage:
import (
"fmt"
"log"
"github.com/gonzalop/bambulan"
)
func main() {
hostname := "192.168.1.100" // Printer's IP address or hostname
accessCode := "your_access_code" // Found in printer settings
serial := "your_printer_serial" // Printer's serial number
// Initialize the client
client := bambulan.NewClient(hostname, accessCode, serial)
// Subscribe to status updates
sub := client.Subscribe()
defer sub.Cancel()
go func() {
for status := range sub.C {
fmt.Printf("Nozzle: %.1f°C | Bed: %.1f°C | Progress: %d%%\n",
status.NozzleTemp, status.BedTemp, status.McPercent)
}
}()
// Start the client (connects to MQTT broker)
if err := client.Start(); err != nil {
log.Fatalf("Failed to connect to printer: %v", err)
}
defer client.Stop() // Ensure connection is closed when main exits
// Example: Turn on chamber light
if _, err := client.MQTT.SetChamberLight(true); err != nil {
log.Printf("Error setting chamber light: %v", err)
} else {
fmt.Println("Chamber light turned on.")
}
// Keep running to receive updates (or perform other operations)
select {}
}
Index ¶
- Constants
- func FormatHMSCode(code, attr uint32) string
- func InferModelFromSerial(serial string) string
- func LookupHMS(code, attr uint32) (string, bool)
- type AMS
- type AMSEntry
- type CameraClient
- type Client
- type EventSubscription
- type FileClient
- func (f *FileClient) Close() error
- func (f *FileClient) Delete(ctx context.Context, remotePath string) error
- func (f *FileClient) Download(ctx context.Context, remotePath string) (io.ReadCloser, error)
- func (f *FileClient) DownloadDirectory(ctx context.Context, remoteDir, localDir string, recursive bool, ...) error
- func (f *FileClient) DownloadFile(ctx context.Context, remotePath, localPath string, ...) error
- func (f *FileClient) GetFiles(ctx context.Context, dir string, extension string) ([]string, error)
- func (f *FileClient) ListFiles(ctx context.Context, dir string) ([]*ftp.Entry, error)
- func (f *FileClient) MakeDirectory(ctx context.Context, path string) error
- func (f *FileClient) RemoveAll(ctx context.Context, path string) error
- func (f *FileClient) Rename(ctx context.Context, source, dest string) error
- func (f *FileClient) Upload(ctx context.Context, remotePath string, content io.Reader, ...) error
- func (f *FileClient) UploadFile(ctx context.Context, localPath, remotePath string, ...) error
- type HMSEvent
- type IPCam
- type InfoMessage
- type LightsReport
- type MQTTClient
- func (m *MQTTClient) DumpInfo(ctx context.Context) (string, error)
- func (m *MQTTClient) GetPrinterStatus() *PrinterStatus
- func (m *MQTTClient) GetVersion(ctx context.Context) (string, error)
- func (m *MQTTClient) IsConnected() bool
- func (m *MQTTClient) LoadFilament(ctx context.Context, target int) (string, error)
- func (m *MQTTClient) PausePrint(ctx context.Context) (string, error)
- func (m *MQTTClient) Publish(ctx context.Context, command any) error
- func (m *MQTTClient) ResumePrint(ctx context.Context) (string, error)
- func (m *MQTTClient) SendAMSControlCommand(ctx context.Context, param string) (string, error)
- func (m *MQTTClient) SendGCode(ctx context.Context, gcode string) (string, error)
- func (m *MQTTClient) SetAMSFilament(ctx context.Context, amsID, trayID int, ...) (string, error)
- func (m *MQTTClient) SetAMSUserSetting(ctx context.Context, amsID int, ...) (string, error)
- func (m *MQTTClient) SetBedTemperature(ctx context.Context, temp int) (string, error)
- func (m *MQTTClient) SetBuildPlateMarkerDetector(ctx context.Context, enabled bool) (string, error)
- func (m *MQTTClient) SetChamberLight(ctx context.Context, on bool) (string, error)
- func (m *MQTTClient) SetChamberTemperature(ctx context.Context, temp int) (string, error)
- func (m *MQTTClient) SetFanSpeed(ctx context.Context, fan string, percent int) (string, error)
- func (m *MQTTClient) SetNozzleDetails(ctx context.Context, diameter float64, typeString string) (string, error)
- func (m *MQTTClient) SetNozzleTemperature(ctx context.Context, temp int, toolIdx int) (string, error)
- func (m *MQTTClient) SetPrintOption(ctx context.Context, option string, enabled bool) (string, error)
- func (m *MQTTClient) SetSpeedProfile(ctx context.Context, level string) (string, error)
- func (m *MQTTClient) SetSpoolKFactor(ctx context.Context, trayID int, kValue float64, nCoef float64) (string, error)
- func (m *MQTTClient) SkipObjects(ctx context.Context, objects []int) (string, error)
- func (m *MQTTClient) Start() error
- func (m *MQTTClient) StartPrint(ctx context.Context, filename string, opts PrintOptions) (string, error)
- func (m *MQTTClient) Stop()
- func (m *MQTTClient) StopPrint(ctx context.Context) (string, error)
- func (m *MQTTClient) Subscribe() *EventSubscription
- func (m *MQTTClient) UnloadFilament(ctx context.Context) (string, error)
- type ModuleInfo
- type Online
- type PrintOptions
- type PrinterCapability
- type PrinterStatus
- type UpgradeState
- type Upload
- type VTTray
Constants ¶
const ( SpeedSilent = "1" SpeedStandard = "2" SpeedSport = "3" SpeedLudicrous = "4" )
Speed Profile Constants
const (
BambuQoS = 0 // Anything else either blocks (for subscriptions) or is ignored (for publications).
)
BambuQoS is the Quality of Service level used for Bambu Lab MQTT communication.
Variables ¶
This section is empty.
Functions ¶
func FormatHMSCode ¶ added in v0.9.0
FormatHMSCode returns the dash-separated hex string for a given code and attribute.
func InferModelFromSerial ¶ added in v0.9.2
InferModelFromSerial returns the model ID (e.g. "C12", "BL-P001") based on the 3-character serial number prefix.
Types ¶
type AMS ¶
type AMS struct {
Ams []*AMSEntry `json:"ams"`
AmsExistBits string `json:"ams_exist_bits"`
AmsExistBitsRaw string `json:"ams_exist_bits_raw"`
TrayExistBits string `json:"tray_exist_bits"`
TrayIsBblBits string `json:"tray_is_bbl_bits"` // Bitmask for Bambu Lab rfid trays
TrayTar string `json:"tray_tar"` // Target tray being loaded
TrayNow string `json:"tray_now"` // Currently loaded tray
TrayPre string `json:"tray_pre"`
TrayReadDoneBits string `json:"tray_read_done_bits"`
TrayReadingBits string `json:"tray_reading_bits"`
Version int `json:"version"`
InsertFlag bool `json:"insert_flag"` // True if filament is detected in the hub
PowerOnFlag bool `json:"power_on_flag"`
}
AMS conveys the state of the AMS (Automatic Material System). A printer can have up to 4 AMS units chained together.
type AMSEntry ¶
type AMSEntry struct {
Humidity string `json:"humidity"` // Humidity level (1-5, where 1 is driest)
HumidityRaw string `json:"humidity_raw"` // Raw humidity value (10-100)
ID string `json:"id"` // AMS Unit ID (0-3)
Temp string `json:"temp"` // Temperature inside AMS
Tray []*VTTray `json:"tray"` // List of up to 4 trays
}
AMSEntry represents a single AMS unit, which can hold up to 4 trays.
type CameraClient ¶
type CameraClient struct {
// Hostname is the IP or hostname of the printer's camera stream.
Hostname string
// AccessCode is the password for the camera stream authentication.
AccessCode string
// Port is the TCP/TLS port for the camera stream (default 6000).
Port int
// Username is the username for camera stream authentication (default "bblp").
Username string
// contains filtered or unexported fields
}
CameraClient handles the MJPEG camera stream connection over TCP/TLS.
func NewCameraClient ¶
func NewCameraClient(hostname, accessCode string) *CameraClient
NewCameraClient creates a new CameraClient.
Parameters:
- hostname: The IP address or hostname of the printer.
- accessCode: The printer's access code.
func (*CameraClient) CaptureFrame ¶
func (c *CameraClient) CaptureFrame() ([]byte, error)
CaptureFrame connects to the camera via the "Bambu Tunnel" protocol (port 6000), captures a single JPEG frame, and then closes the connection.
Compatibility: - P1 / A1 Series: Primary method for fetching snapshots in LAN mode. - X1 Series: Supported (typically lower resolution than RTSP).
This is a blocking call that will return once a frame is received or a timeout occurs.
Returns:
- A byte slice containing the JPEG image data.
Example:
imgData, err := client.Camera.CaptureFrame()
if err != nil {
log.Println("Error capturing frame:", err)
} else {
err = os.WriteFile("frame.jpg", imgData, 0644)
if err != nil {
log.Println("Error saving frame:", err)
}
}
func (*CameraClient) GetRTSPURL ¶ added in v0.4.0
func (c *CameraClient) GetRTSPURL(reportedURL string) string
GetRTSPURL returns the authenticated RTSPS URL for the printer's camera stream. It accepts an optional `reportedURL` (e.g., from PrinterStatus.IPCam.RTSPURL).
If `reportedURL` is provided (non-empty), it injects the authentication credentials into it. If `reportedURL` is empty, it logs a warning and generates a default URL which might not work on all models.
Format: rtsps://bblp:<access_code>@<hostname>:322/streaming/live/1
Example:
status := client.GetPrinterStatus()
var url string
if status.IPCam != nil {
// Use the URL reported by the printer (recommended)
url = client.Camera.GetRTSPURL(status.IPCam.RTSPURL)
} else {
// Fallback to default guess (logs a warning)
url = client.Camera.GetRTSPURL("")
}
func (*CameraClient) StartStream ¶
func (c *CameraClient) StartStream(onImage func([]byte)) error
StartStream connects to the camera via the "Bambu Tunnel" protocol (port 6000) and continuously sends new JPEG frames to the onImage callback.
Compatibility:
- P1 / A1 Series: This is the primary method for streaming in LAN mode.
- X1 Series: Supported as a standard fallback. For higher quality (1080p/30fps), consider using GetRTSPURL() if supported by the network configuration.
This method runs in a new goroutine and will continue until StopStream is called or an error occurs.
Parameters:
- onImage: A callback function `func(imageData []byte)` which is invoked for each received JPEG frame.
Example:
err := client.Camera.StartStream(func(imgData []byte) {
fmt.Printf("Received JPEG frame of %d bytes\n", len(imgData))
// Process or save image data
})
if err != nil {
log.Println("Error starting stream:", err)
}
func (*CameraClient) StopStream ¶
func (c *CameraClient) StopStream()
StopStream stops the camera stream if it is running.
type Client ¶
type Client struct {
// MQTT client for control and status updates.
MQTT *MQTTClient
// Camera client for video and image access.
Camera *CameraClient
// File client for FTPS operations.
File *FileClient
}
Client is the main entry point for the BambuLAN library. It acts as a central hub, coordinating interaction with the printer through three specialized clients:
- MQTT: For real-time status monitoring and sending commands (movement, temperature, print jobs).
- Camera: For fetching live video streams or capturing static images.
- File: For managing files on the printer's SD card (upload, download, list) via FTPS.
func NewClient ¶
NewClient creates a new BambuLAN Client instance.
It initializes the three sub-clients (MQTT, Camera, File) but does not immediately connect. Call Start() to establish the MQTT connection.
Parameters:
- hostname: The IP address or hostname of the printer (e.g., "192.168.1.50").
- accessCode: The printer's access code, found in the Network settings on the printer's screen.
- serial: The printer's serial number (e.g., "01S00A..."), used for MQTT topic subscription.
Example:
client := bambulan.NewClient("192.168.1.50", "12345678", "01S00A...")
sub := client.Subscribe()
defer sub.Cancel()
go func() {
for status := range sub.C {
fmt.Printf("Current nozzle temp: %.1f\n", status.NozzleTemp)
}
}()
func (*Client) GetPrinterStatus ¶
func (c *Client) GetPrinterStatus() *PrinterStatus
GetPrinterStatus returns the most recently received printer status. It returns nil if no status has been received yet.
func (*Client) Start ¶
Start initiates the MQTT connection and subscribes to the printer's report topic. It returns an error if the connection cannot be established or subscription fails.
func (*Client) Stop ¶
func (c *Client) Stop()
Stop gracefully shuts down the MQTT connection and stops any active camera streams.
func (*Client) Subscribe ¶ added in v0.6.0
func (c *Client) Subscribe() *EventSubscription
Subscribe creates a new subscription to receive real-time printer status updates. The returned EventSubscription contains a channel (C) that will receive updates. Make sure to call Cancel() on the subscription when it's no longer needed to free resources.
type EventSubscription ¶ added in v0.6.0
type EventSubscription struct {
C <-chan *PrinterStatus
// contains filtered or unexported fields
}
EventSubscription represents a subscription to printer status updates.
func (*EventSubscription) Cancel ¶ added in v0.6.0
func (s *EventSubscription) Cancel()
Cancel unsubscribes from the updates and cleans up resources.
type FileClient ¶
type FileClient struct {
// Hostname is the IP or hostname of the printer's FTPS server.
Hostname string
// AccessCode is the password for the FTPS connection.
AccessCode string
// contains filtered or unexported fields
}
FileClient handles file operations (listing, uploading, downloading) over FTPS. It maintains a persistent connection to the printer.
func NewFileClient ¶
func NewFileClient(hostname, accessCode string) *FileClient
NewFileClient creates a new FileClient.
Parameters:
- hostname: The IP address or hostname of the printer's FTPS server.
- accessCode: The printer's access code, usually found in the Network settings.
func (*FileClient) Close ¶ added in v0.5.0
func (f *FileClient) Close() error
Close closes the active FTP connection if it exists.
func (*FileClient) Delete ¶ added in v0.3.0
func (f *FileClient) Delete(ctx context.Context, remotePath string) error
Delete deletes a file from the printer.
Parameters:
- ctx: Context for cancellation.
- remotePath: The full absolute path to the file on the printer (e.g., "/timelapse/video.mp4").
Returns:
- An error if the file could not be deleted (e.g., file not found, permission denied).
func (*FileClient) Download ¶
func (f *FileClient) Download(ctx context.Context, remotePath string) (io.ReadCloser, error)
Download streams a file from the printer. The caller is responsible for closing the returned `io.ReadCloser`. If ctx is cancelled, the dedicated download connection is closed and the reader will return an error.
Parameters:
- ctx: Context for cancellation. Cancellation closes the underlying connection.
- remotePath: The full path to the file on the printer (e.g., "/timelapse/video.mp4").
Returns:
- An `io.ReadCloser` from which the file content can be read.
func (*FileClient) DownloadDirectory ¶ added in v0.6.0
func (f *FileClient) DownloadDirectory(ctx context.Context, remoteDir, localDir string, recursive bool, onProgress func(string, int64, int64)) error
DownloadDirectory downloads a remote directory to a local directory.
Parameters:
- ctx: Context for cancellation. Checked between files; an in-progress file download will be cancelled too.
- remoteDir: The remote directory path to download.
- localDir: The local directory path where files should be saved.
- recursive: If true, downloads subdirectories recursively.
- onProgress: An optional callback function `func(filename string, current, total int64)` that reports progress for each file.
func (*FileClient) DownloadFile ¶
func (f *FileClient) DownloadFile(ctx context.Context, remotePath, localPath string, onProgress func(int64, int64)) error
DownloadFile downloads a file from the printer to a local path.
Parameters:
- ctx: Context for cancellation.
- remotePath: The full path to the file on the printer.
- localPath: The local file system path where the file should be saved.
- onProgress: An optional callback function `func(currentBytes, totalBytes int64)` that reports the current download progress. `totalBytes` will be 0 if unknown.
Example:
err := client.File.DownloadFile(ctx, "/timelapse/video.mp4", "./video.mp4", func(current, total int64) {
if total > 0 {
fmt.Printf("Downloading: %.1f%%\r", float64(current)/float64(total)*100)
}
})
func (*FileClient) GetFiles ¶
GetFiles returns a list of file names in the specified directory that match the given extension. Note: The Bambu printer's FTPS server does not support globbing, so this method filters results client-side.
Parameters:
- ctx: Context for cancellation.
- dir: The remote directory path to search (e.g., "/timelapse").
- extension: The file extension to match (e.g., ".3mf", ".mp4").
Returns:
- A slice of strings, where each string is the name of a matching file.
func (*FileClient) ListFiles ¶
ListFiles returns a detailed list of files in the specified directory.
Parameters:
- ctx: Context for cancellation. If cancelled, the FTP connection is closed.
- dir: The remote directory path to list (e.g., "/timelapse").
Returns:
- A slice of `*ftp.Entry`, each containing file/directory information.
Example:
entries, err := client.File.ListFiles(ctx, "/timelapse")
if err != nil {
log.Fatal(err)
}
for _, entry := range entries {
fmt.Printf("%s: %d bytes\n", entry.Name, entry.Size)
}
func (*FileClient) MakeDirectory ¶ added in v0.3.0
func (f *FileClient) MakeDirectory(ctx context.Context, path string) error
MakeDirectory creates a new directory on the printer.
Parameters:
- ctx: Context for cancellation.
- path: The full absolute path of the directory to create.
Returns:
- An error if the directory could not be created.
func (*FileClient) RemoveAll ¶ added in v0.3.0
func (f *FileClient) RemoveAll(ctx context.Context, path string) error
RemoveAll recursively deletes a file or directory. If the path is a directory, it deletes all its contents before deleting the directory itself.
Parameters:
- ctx: Context for cancellation.
- path: The full absolute path to remove.
Returns:
- An error if any deletion step failed.
func (*FileClient) Rename ¶ added in v0.3.0
func (f *FileClient) Rename(ctx context.Context, source, dest string) error
Rename renames or moves a file/directory on the printer.
Parameters:
- ctx: Context for cancellation.
- source: The current full path of the file or directory.
- dest: The new full path (including name) for the file or directory.
Returns:
- An error if the operation failed.
func (*FileClient) Upload ¶
func (f *FileClient) Upload(ctx context.Context, remotePath string, content io.Reader, onProgress func(int64, int64)) error
Upload streams content to the printer.
Parameters:
- ctx: Context for cancellation.
- remotePath: The full path where the file should be saved on the printer.
- content: An `io.Reader` providing the content to upload.
- onProgress: An optional callback function `func(currentBytes, totalBytes int64)` that reports the current upload progress.
func (*FileClient) UploadFile ¶
func (f *FileClient) UploadFile(ctx context.Context, localPath, remotePath string, onProgress func(int64, int64)) error
UploadFile uploads a local file to the printer.
Parameters:
- ctx: Context for cancellation.
- localPath: The local file system path of the file to upload.
- remotePath: The full path where the file should be saved on the printer.
- onProgress: An optional callback function `func(currentBytes, totalBytes int64)` that reports the current upload progress.
Example:
err := client.File.UploadFile(ctx, "./model.gcode.3mf", "/model.gcode.3mf", nil)
type HMSEvent ¶ added in v0.9.0
HMSEvent represents a Health Management System event reported by the printer.
type IPCam ¶
type IPCam struct {
AgoraService string `json:"agora_service"`
IPCamDev string `json:"ipcam_dev"`
IPCamRecord string `json:"ipcam_record"`
Timelapse string `json:"timelapse"`
Resolution string `json:"resolution"` // e.g., "1080p", "720p"
TutkServer string `json:"tutk_server"`
ModeBits int `json:"mode_bits"`
RTSPURL string `json:"rtsp_url"` // rtsp:// or rtsps:// URL for live stream
}
IPCam contains information about the printer's camera stream.
type InfoMessage ¶ added in v0.3.0
type InfoMessage struct {
Command string `json:"command"`
SequenceID string `json:"sequence_id"`
Module []ModuleInfo `json:"module"`
Result string `json:"result"`
Reason string `json:"reason"`
}
InfoMessage represents a message containing system information or responses from the printer.
type LightsReport ¶
type LightsReport struct {
Node string `json:"node"` // e.g., "chamber_light", "work_light"
Mode string `json:"mode"` // "on", "off", "flashing"
}
LightsReport contains the status of the printer's lighting.
type MQTTClient ¶
type MQTTClient struct {
// Hostname is the IP or hostname of the printer's MQTT broker.
Hostname string
// AccessCode is the password for the MQTT connection.
AccessCode string
// Serial is the printer's serial number, used to construct topic strings (device/<serial>/...).
Serial string
OnConnect func()
OnDisconnect func(error)
// contains filtered or unexported fields
}
MQTTClient handles the MQTT connection to the printer for control and monitoring. It manages the connection lifecycle, subscription to status topics, and publishing of commands.
func NewMQTTClient ¶
func NewMQTTClient(hostname, accessCode, serial string) *MQTTClient
NewMQTTClient creates a new MQTTClient.
Parameters:
- hostname: Printer IP/hostname.
- accessCode: Printer access code (password).
- serial: Printer serial number.
func (*MQTTClient) DumpInfo ¶
func (m *MQTTClient) DumpInfo(ctx context.Context) (string, error)
DumpInfo requests a full status push from the printer. It sends a "pushall" command. The printer will respond by publishing a full status report to the report topic. Returns the sequence ID of the request, which can be used to correlate the response.
func (*MQTTClient) GetPrinterStatus ¶
func (m *MQTTClient) GetPrinterStatus() *PrinterStatus
GetPrinterStatus returns the current status pointer.
func (*MQTTClient) GetVersion ¶ added in v0.3.0
func (m *MQTTClient) GetVersion(ctx context.Context) (string, error)
GetVersion requests the printer version info (firmware, model, etc).
func (*MQTTClient) IsConnected ¶ added in v0.8.0
func (m *MQTTClient) IsConnected() bool
IsConnected returns true if the client is currently connected to the printer.
func (*MQTTClient) LoadFilament ¶ added in v0.3.0
LoadFilament sends a command to load filament from a specific AMS slot.
Parameters:
- ctx: Context for cancellation.
- target: The slot ID to load from. 0-15 correspond to the 4 slots in up to 4 AMS units. 254 typically represents the external spool holder.
Returns:
- The sequence ID of the command.
- An error if the command could not be published.
func (*MQTTClient) PausePrint ¶
func (m *MQTTClient) PausePrint(ctx context.Context) (string, error)
PausePrint pauses the current print job.
func (*MQTTClient) Publish ¶
func (m *MQTTClient) Publish(ctx context.Context, command any) error
Publish sends a JSON command to the printer request topic.
func (*MQTTClient) ResumePrint ¶
func (m *MQTTClient) ResumePrint(ctx context.Context) (string, error)
ResumePrint resumes a paused print job.
func (*MQTTClient) SendAMSControlCommand ¶ added in v0.3.0
SendAMSControlCommand sends an AMS control command.
Parameters:
- ctx: Context for cancellation.
- param: The control parameter, one of "resume", "pause", or "reset".
Returns:
- The sequence ID of the command.
- An error if the command could not be published.
func (*MQTTClient) SendGCode ¶
SendGCode sends a single line of G-Code to the printer. Returns the sequence ID of the request.
Example:
client.MQTT.SendGCode(ctx, "G28") // Auto-home
func (*MQTTClient) SetAMSFilament ¶ added in v0.2.0
func (m *MQTTClient) SetAMSFilament(ctx context.Context, amsID, trayID int, filamentID, settingID, color, filamentType string, minTemp, maxTemp int) (string, error)
SetAMSFilament updates the filament properties for a specific AMS slot.
Parameters:
- ctx: Context for cancellation.
- amsID: AMS unit ID (0-3).
- trayID: Slot ID (0-3).
- filamentID: Filament ID (e.g., "GFA00").
- settingID: Setting ID (e.g., "GFA00_1.75_PLA...").
- color: RGBA hex color (e.g., "FFFFFFFF").
- filamentType: Filament type (e.g., "PLA Basic").
- minTemp: Min nozzle temp (e.g., 190).
- maxTemp: Max nozzle temp (e.g., 220).
func (*MQTTClient) SetAMSUserSetting ¶ added in v0.3.0
func (m *MQTTClient) SetAMSUserSetting(ctx context.Context, amsID int, startupReadOption, trayReadOption, calibrateRemainFlag bool) (string, error)
SetAMSUserSetting updates AMS user settings for a specific unit.
Parameters:
- ctx: Context for cancellation.
- amsID: The ID of the AMS unit (0-3).
- startupReadOption: If true, the AMS will read the RFID on startup.
- trayReadOption: If true, the AMS will read the RFID when a tray is inserted.
- calibrateRemainFlag: If true, the AMS will calibrate the remaining filament on startup.
Returns:
- The sequence ID of the command.
- An error if the command could not be published.
func (*MQTTClient) SetBedTemperature ¶ added in v0.3.0
SetBedTemperature sets the target bed temperature using M140 G-code.
Parameters:
- ctx: Context for cancellation.
- temp: The target temperature in Celsius.
Returns:
- The sequence ID of the G-code command.
- An error if the command could not be sent.
Example:
client.MQTT.SetBedTemperature(ctx, 60) // Set bed to 60°C
func (*MQTTClient) SetBuildPlateMarkerDetector ¶ added in v0.3.0
SetBuildPlateMarkerDetector enables or disables the AI build plate marker detector (ArUco).
Parameters:
- ctx: Context for cancellation.
- enabled: If true, enables the detector.
Returns:
- The sequence ID of the command.
- An error if the command could not be published.
func (*MQTTClient) SetChamberLight ¶
SetChamberLight turns the chamber light on or off.
Example:
// Turn light on client.MQTT.SetChamberLight(ctx, true)
func (*MQTTClient) SetChamberTemperature ¶ added in v0.7.0
SetChamberTemperature sets the target chamber temperature using M191 G-code.
Parameters:
- ctx: Context for cancellation.
- temp: The target temperature in Celsius.
Returns:
- The sequence ID of the G-code command.
- An error if the command could not be sent.
Example:
client.MQTT.SetChamberTemperature(ctx, 50) // Set chamber to 50°C
func (*MQTTClient) SetFanSpeed ¶ added in v0.3.0
SetFanSpeed sets the speed of the specified fan(s). It sends the appropriate M106 G-code command.
Parameters:
- ctx: Context for cancellation.
- fan: The fan to control. One of "part" (P1), "aux" (P2), "chamber" (P3), or "all".
- percent: The target speed percentage (0-100).
Returns:
- The sequence ID of the G-code command.
- An error if the command could not be sent or the fan type is invalid.
Example:
client.MQTT.SetFanSpeed(ctx, "aux", 100) // Set auxiliary fan to 100%
func (*MQTTClient) SetNozzleDetails ¶ added in v0.3.0
func (m *MQTTClient) SetNozzleDetails(ctx context.Context, diameter float64, typeString string) (string, error)
SetNozzleDetails configures the printer's nozzle settings.
Parameters:
- ctx: Context for cancellation.
- diameter: The nozzle diameter in mm (e.g., 0.4).
- typeString: The nozzle type (e.g., "hardened_steel", "stainless_steel").
Returns:
- The sequence ID of the command.
- An error if the command could not be published.
func (*MQTTClient) SetNozzleTemperature ¶ added in v0.3.0
func (m *MQTTClient) SetNozzleTemperature(ctx context.Context, temp int, toolIdx int) (string, error)
SetNozzleTemperature sets the target nozzle (tool) temperature using M104 G-code.
Parameters:
- ctx: Context for cancellation.
- temp: The target temperature in Celsius.
- toolIdx: The index of the tool (extruder) to set (optional, use 0 for single).
Returns:
- The sequence ID of the G-code command.
- An error if the command could not be sent.
Example:
client.MQTT.SetNozzleTemperature(ctx, 220, 0) // Set nozzle 1 to 220°C
func (*MQTTClient) SetPrintOption ¶ added in v0.3.0
func (m *MQTTClient) SetPrintOption(ctx context.Context, option string, enabled bool) (string, error)
SetPrintOption enables or disables specific printer options.
Parameters:
- ctx: Context for cancellation.
- option: The option name. Common options include: "auto_recovery", "auto_switch_filament", "filament_tangle_detect", "sound_enable".
- enabled: The desired state of the option.
Returns:
- The sequence ID of the command.
- An error if the command could not be published.
func (*MQTTClient) SetSpeedProfile ¶
SetSpeedProfile sets the print speed profile. Supported levels are defined by Speed* constants in models.go.
func (*MQTTClient) SetSpoolKFactor ¶ added in v0.3.0
func (m *MQTTClient) SetSpoolKFactor(ctx context.Context, trayID int, kValue float64, nCoef float64) (string, error)
SetSpoolKFactor sets the linear advance K-factor for a specific spool (tray).
Parameters:
- ctx: Context for cancellation.
- trayID: The ID of the tray (0-15 or 254).
- kValue: The K-factor value.
- nCoef: The N coefficient (typically 1.4).
Returns:
- The sequence ID of the command.
- An error if the command could not be published.
func (*MQTTClient) SkipObjects ¶ added in v0.3.0
SkipObjects skips specific objects during a multi-object print.
Parameters:
- ctx: Context for cancellation.
- objects: A list of object IDs to skip.
Returns:
- The sequence ID of the command.
- An error if the command could not be published.
func (*MQTTClient) Start ¶
func (m *MQTTClient) Start() error
Start connects to the MQTT broker and subscribes to report topics.
func (*MQTTClient) StartPrint ¶
func (m *MQTTClient) StartPrint(ctx context.Context, filename string, opts PrintOptions) (string, error)
StartPrint starts a print job for a file already on the printer (SD card). The filename specifies the path to the file on the printer (e.g., "model.gcode.3mf"). Note: You usually need to upload the file via FTPS first.
Returns the sequence ID of the request.
Example:
// 1. Upload file first (see FileClient.UploadFile)
// err := client.File.UploadFile(ctx, "local.3mf", "my-model.gcode.3mf", nil)
// 2. Start Print
opts := bambulan.PrintOptions{
BedType: "textured_plate",
BedLeveling: true,
FlowCalibration: true,
}
seqID, err := client.MQTT.StartPrint(ctx, "my-model.gcode.3mf", opts)
func (*MQTTClient) StopPrint ¶
func (m *MQTTClient) StopPrint(ctx context.Context) (string, error)
StopPrint cancels and stops the current print job.
func (*MQTTClient) Subscribe ¶ added in v0.6.0
func (m *MQTTClient) Subscribe() *EventSubscription
Subscribe creates a new subscription for printer status updates. The returned EventSubscription contains a channel that will receive updates. Call Cancel() on the subscription when done to free resources.
func (*MQTTClient) UnloadFilament ¶ added in v0.3.0
func (m *MQTTClient) UnloadFilament(ctx context.Context) (string, error)
UnloadFilament sends a command to the printer to unload the current filament. This triggers the "unload_filament" printer command.
Returns:
- The sequence ID of the command.
- An error if the command could not be published.
type ModuleInfo ¶ added in v0.3.0
type ModuleInfo struct {
Name string `json:"name"`
Project string `json:"project_name"` // e.g. "C11", "C12" (This is often the model!)
SwVer string `json:"sw_ver"`
HwVer string `json:"hw_ver"`
Sn string `json:"sn"`
}
ModuleInfo contains identification and version information for printer components.
type Online ¶
type Online struct {
Ahb bool `json:"ahb"` // Automatic Hub Board
Ext bool `json:"ext"` // Extruder Board
Rfid bool `json:"rfid"` // AMS RFID Reader
Version int `json:"version"` // Protocol version
}
Online indicates the connection status of various printer modules.
type PrintOptions ¶
type PrintOptions struct {
BedType string
Timelapse bool
BedLeveling bool
FlowCalibration bool
VibrationCalibration bool
LayerInspection bool
UseAMS bool
}
PrintOptions configures the parameters for starting a print job.
type PrinterCapability ¶ added in v0.4.0
type PrinterCapability struct {
DisplayName string `json:"display_name"`
MaxNozzleTemp int `json:"max_nozzle_temp"`
MaxBedTemp int `json:"max_bed_temp"`
HasChamberFan bool `json:"has_chamber_fan"`
HasAuxFan bool `json:"has_aux_fan"`
HasAMSHumidity bool `json:"has_ams_humidity"`
HasAMSCapacityReporting bool `json:"has_ams_capacity_reporting"`
HasTimelapse bool `json:"has_timelapse"`
HasBedLeveling bool `json:"has_bed_leveling"`
HasChamberHeater bool `json:"has_chamber_heater"`
HasChamberTemp bool `json:"has_chamber_temp"`
MinChamberTemp int `json:"min_chamber_temp"`
MaxChamberTemp int `json:"max_chamber_temp"`
NumExtruders int `json:"num_extruders"`
}
PrinterCapability defines the supported features and limitations for a specific printer model.
func GetPrinterCapabilities ¶ added in v0.4.0
func GetPrinterCapabilities(modelID string) PrinterCapability
GetPrinterCapabilities returns the capabilities for the given printer model ID, model name, or serial number.
If the model ID is unknown or empty, this function returns a default PrinterCapability struct with common enclosed printer capabilities (enabling fan and temp controls).
type PrinterStatus ¶
type PrinterStatus struct {
// Upload contains status information about current file uploads (FTPS).
Upload *Upload `json:"upload,omitempty"`
// DeviceModel is the printer's model ID (e.g., "BL-P001", "C11"). Use this with GetPrinterCapabilities.
DeviceModel string `json:"device_model,omitempty"`
// DevName is the user-defined nickname of the printer.
DevName string `json:"dev_name,omitempty"`
// Modules lists the hardware and software versions of printer components.
Modules []ModuleInfo `json:"modules,omitempty"`
// BedTempLimit is the hardware-enforced maximum temperature for the heatbed.
BedTempLimit int `json:"bed_temp_limit,omitempty"`
// NozzleTempLimit is the hardware-enforced maximum temperature for the nozzle.
NozzleTempLimit int `json:"nozzle_temp_limit,omitempty"`
// NozzleTemp is the current actual nozzle temperature in Celsius.
NozzleTemp float64 `json:"nozzle_temper"`
// NozzleTargetTemp is the target nozzle temperature in Celsius.
NozzleTargetTemp float64 `json:"nozzle_target_temper"`
// BedTemp is the current actual bed temperature in Celsius.
BedTemp float64 `json:"bed_temper"`
// BedTargetTemp is the target bed temperature in Celsius.
BedTargetTemp float64 `json:"bed_target_temper"`
// ChamberTemp is the current actual chamber temperature in Celsius.
// Note: Not all printers have a chamber temperature sensor.
ChamberTemp float64 `json:"chamber_temper"`
// ChamberTargetTemp is the target chamber temperature in Celsius (for printers with heaters).
ChamberTargetTemp float64 `json:"chamber_target_temper"`
// McPrintStage is the internal numeric code for the current print stage.
// Use GetPrintStageName() to get a human-readable description.
McPrintStage string `json:"mc_print_stage"`
// PrintStageDesc is a human-readable description of the print stage, if available.
PrintStageDesc string `json:"print_stage_desc,omitempty"`
// HeatbreakFanSpeed is the speed of the heatbreak fan (percentage string or numeric string).
HeatbreakFanSpeed string `json:"heatbreak_fan_speed"`
// CoolingFanSpeed is the speed of the part cooling fan (percentage string or numeric string).
CoolingFanSpeed string `json:"cooling_fan_speed"`
// BigFan1Speed is the speed of the auxiliary fan (percentage string or numeric string).
BigFan1Speed string `json:"big_fan1_speed"`
// BigFan2Speed is the speed of the chamber fan (percentage string or numeric string).
BigFan2Speed string `json:"big_fan2_speed"`
// McPercent is the integer percentage of print progress (0-100).
McPercent int `json:"mc_percent"`
// McRemainingTime is the estimated remaining print time in minutes.
McRemainingTime int `json:"mc_remaining_time"`
// AMSStatus represents the global status of the AMS system (if connected).
AMSStatus int `json:"ams_status"`
// AMSRFIDStatus represents the status of RFID reading in the AMS.
AMSRFIDStatus int `json:"ams_rfid_status"`
// HwSwitchState is a bitmask representing various hardware switch states.
HwSwitchState int `json:"hw_switch_state"`
// SpdMag is the speed multiplier magnitude (e.g., 100 for Standard).
SpdMag int `json:"spd_mag"`
// SpdLvl is the current speed profile level:
// 1=Silent, 2=Standard, 3=Sport, 4=Ludicrous.
SpdLvl int `json:"spd_lvl"`
// PrintError contains the error code if the print has failed or encountered an issue.
PrintError int `json:"print_error"`
// Lifecycle indicates the high-level state of the printer (e.g., "printing", "idle").
Lifecycle string `json:"lifecycle"`
// WifiSignal represents the WiFi signal strength in dBm.
WifiSignal string `json:"wifi_signal"`
// GcodeState indicates the G-code execution state (e.g., "RUNNING", "PAUSE", "IDLE", "FINISH").
GcodeState string `json:"gcode_state"`
// GcodeFilePreparePercent is the progress of processing the G-code file before printing.
GcodeFilePreparePercent string `json:"gcode_file_prepare_percent"`
// QueueNumber serves to identify the print job in the queue.
QueueNumber int `json:"queue_number"`
QueueTotal int `json:"queue_total"`
QueueEst int `json:"queue_est"`
QueueSts int `json:"queue_sts"`
// ProjectID identifies the cloud project associated with the print.
ProjectID string `json:"project_id"`
ProfileID string `json:"profile_id"`
TaskID string `json:"task_id"`
// SubtaskID identifies the specific print job (subtask).
SubtaskID string `json:"subtask_id"`
// SubtaskName is the name of the file or job being printed.
SubtaskName string `json:"subtask_name"`
// GcodeFile is the path to the G-code file being printed.
GcodeFile string `json:"gcode_file"`
Stg []any `json:"stg"`
StgCur int `json:"stg_cur"`
PrintType string `json:"print_type"`
HomeFlag int `json:"home_flag"`
McPrintLineNumber string `json:"mc_print_line_number"`
McPrintSubStage int `json:"mc_print_sub_stage"`
// Sdcard indicates if an SD card is inserted.
Sdcard bool `json:"sdcard"`
ForceUpgrade bool `json:"force_upgrade"`
MessProductionState string `json:"mess_production_state"`
// LayerNum is the current layer being printed.
LayerNum int `json:"layer_num"`
// TotalLayerNum is the total number of layers in the G-code file.
TotalLayerNum int `json:"total_layer_num"`
SObj []any `json:"s_obj"`
FanGear int `json:"fan_gear"`
Hms []HMSEvent `json:"hms"`
Online *Online `json:"online,omitempty"`
Ams *AMS `json:"ams,omitempty"`
IPCam *IPCam `json:"ipcam,omitempty"`
VtTray *VTTray `json:"vt_tray,omitempty"`
LightsReport []*LightsReport `json:"lights_report,omitempty"`
UpgradeState *UpgradeState `json:"upgrade_state,omitempty"`
Command string `json:"command"`
Msg int `json:"msg"`
SequenceID string `json:"sequence_id"`
Result string `json:"result"`
Reason string `json:"reason"`
}
PrinterStatus contains the detailed status of the printer components. It is the primary data structure returned by the printer via MQTT.
func (*PrinterStatus) GetPrintStageName ¶
func (ps *PrinterStatus) GetPrintStageName() string
GetPrintStageName converts the internal `mc_print_stage` code and `gcode_state` into a human-readable string representing the current activity of the printer.
Example:
status := client.GetPrinterStatus()
fmt.Println("Printer stage:", status.GetPrintStageName())
func (*PrinterStatus) HMSDescription ¶ added in v0.9.0
func (ps *PrinterStatus) HMSDescription() string
HMSDescription returns the human-readable description for the first HMS event, if any.
func (*PrinterStatus) HMSMessage ¶ added in v0.9.0
func (ps *PrinterStatus) HMSMessage() string
HMSMessage returns a formatted string containing the dash-separated HMS code and its human-readable description (if available).
func (*PrinterStatus) WikiURLs ¶ added in v0.9.0
func (ps *PrinterStatus) WikiURLs() []string
WikiURLs returns a list of troubleshooting Wiki URLs for all active HMS events.
type UpgradeState ¶
type UpgradeState struct {
SequenceID int `json:"sequence_id"`
Progress string `json:"progress"` // 0-100 percentage string
Status string `json:"status"` // "IDLE", "DOWNLOADING", "FLASHING", "SUCCESS", "FAILED"
ConsistencyRequest bool `json:"consistency_request"`
DisState int `json:"dis_state"`
ErrCode int `json:"err_code"`
ForceUpgrade bool `json:"force_upgrade"`
Message string `json:"message"`
Module string `json:"module"` // The component being upgraded
NewVersionState int `json:"new_version_state"`
NewVerList []any `json:"new_ver_list"`
CurStateCode int `json:"cur_state_code"`
AhbNewVersionNumber string `json:"ahb_new_version_number"`
AmsNewVersionNumber string `json:"ams_new_version_number"`
ExtNewVersionNumber string `json:"ext_new_version_number"`
Idx int `json:"idx"`
Idx1 int `json:"idx1"`
LowerLimit string `json:"lower_limit"`
OtaNewVersionNumber string `json:"ota_new_version_number"`
Sn string `json:"sn"`
}
UpgradeState tracks the firmware upgrade process.
type Upload ¶
type Upload struct {
FileSize int `json:"file_size"`
FinishSize int `json:"finish_size"`
Status string `json:"status"` // e.g., "idle", "running", "success"
Progress int `json:"progress"` // Percentage 0-100
Message string `json:"message"`
OSSURL string `json:"oss_url"`
SequenceID string `json:"sequence_id"`
Speed int `json:"speed"` // Upload speed in bytes/sec
TaskID string `json:"task_id"`
TimeRemaining int `json:"time_remaining"` // Estimated seconds remaining
TroubleID string `json:"trouble_id"`
}
Upload represents the progress and status of a file upload to the printer via FTPS.
type VTTray ¶
type VTTray struct {
ID string `json:"id"` // Tray ID (0-3)
TagUID string `json:"tag_uid"` // RFID Tag UID
TrayIDName string `json:"tray_id_name"` // User-assigned name
TrayInfoIdx string `json:"tray_info_idx"` // Filament profile ID (e.g. "GFA00")
TrayType string `json:"tray_type"` // Filament type (e.g. "PLA Basic")
TraySubBrands string `json:"tray_sub_brands"`
TrayColor string `json:"tray_color"` // Color in RGBA hex (e.g. "FFFFFFFF")
TrayWeight string `json:"tray_weight"` // Estimated weight in grams
TrayDiameter string `json:"tray_diameter"` // Firmware estimate of diameter
TrayTemp string `json:"tray_temp"` // Recommended temperature range
TrayTime string `json:"tray_time"` // Usage time?
BedTempType string `json:"bed_temp_type"`
BedTemp string `json:"bed_temp"` // Recommended bed temp
NozzleTempMax string `json:"nozzle_temp_max"`
NozzleTempMin string `json:"nozzle_temp_min"`
XcamInfo string `json:"xcam_info"`
TrayUUID string `json:"tray_uuid"`
Remain int `json:"remain"` // Remaining percentage estimate
K float64 `json:"k"` // Flow calibration K-factor
N int `json:"n"` // Flow calibration N-coefficient
CaliIdx int `json:"cali_idx"`
Cols []string `json:"cols"`
Ctype int `json:"ctype"`
DryingTemp string `json:"drying_temp"`
DryingTime string `json:"drying_time"`
}
VTTray represents a single filament tray in the AMS.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
cmd
|
|
|
bambulan
command
|
|
|
gen-capabilities
command
|
|
|
internal
|
|
|
hms
Code generated by scrape_hms.py; DO NOT EDIT.
|
Code generated by scrape_hms.py; DO NOT EDIT. |


