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.
Example usage:
import (
"fmt"
"log"
"github.com/gonzalop/bambulan" // Assuming this is how the package is imported
)
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 with a status update callback
client := bambulan.NewClient(hostname, accessCode, serial, func(status *bambulan.PrinterStatus) {
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
- type AMS
- type AMSEntry
- type CameraClient
- type Client
- type FileClient
- func (f *FileClient) Delete(remotePath string) error
- func (f *FileClient) Download(remotePath string) (io.ReadCloser, error)
- func (f *FileClient) DownloadFile(remotePath, localPath string, onProgress func(int64, int64)) error
- func (f *FileClient) GetFiles(dir string, extension string) ([]string, error)
- func (f *FileClient) ListFiles(dir string) ([]*ftp.Entry, error)
- func (f *FileClient) MakeDirectory(path string) error
- func (f *FileClient) RemoveAll(path string) error
- func (f *FileClient) Rename(source, dest string) error
- func (f *FileClient) Upload(remotePath string, content io.Reader, onProgress func(int64, int64)) error
- func (f *FileClient) UploadFile(localPath, remotePath string, onProgress func(int64, int64)) error
- type IPCam
- type InfoMessage
- type LightsReport
- type MQTTClient
- func (m *MQTTClient) DumpInfo() (string, error)
- func (m *MQTTClient) GetPrinterStatus() *PrinterStatus
- func (m *MQTTClient) GetVersion() (string, error)
- func (m *MQTTClient) LoadFilament(target int) (string, error)
- func (m *MQTTClient) PausePrint() (string, error)
- func (m *MQTTClient) Publish(command any) error
- func (m *MQTTClient) ResumePrint() (string, error)
- func (m *MQTTClient) SendAMSControlCommand(param string) (string, error)
- func (m *MQTTClient) SendGCode(gcode string) (string, error)
- func (m *MQTTClient) SetAMSFilament(amsID, trayID int, filamentID, settingID, color, filamentType string, ...) (string, error)
- func (m *MQTTClient) SetAMSUserSetting(amsID int, startupReadOption, trayReadOption, calibrateRemainFlag bool) (string, error)
- func (m *MQTTClient) SetBedTemperature(temp int) (string, error)
- func (m *MQTTClient) SetBuildPlateMarkerDetector(enabled bool) (string, error)
- func (m *MQTTClient) SetChamberLight(on bool) (string, error)
- func (m *MQTTClient) SetFanSpeed(fan string, percent int) (string, error)
- func (m *MQTTClient) SetNozzleDetails(diameter float64, typeString string) (string, error)
- func (m *MQTTClient) SetNozzleTemperature(temp int) (string, error)
- func (m *MQTTClient) SetPrintOption(option string, enabled bool) (string, error)
- func (m *MQTTClient) SetSpeedProfile(level string) (string, error)
- func (m *MQTTClient) SetSpoolKFactor(trayID int, kValue float64, nCoef float64) (string, error)
- func (m *MQTTClient) SkipObjects(objects []int) (string, error)
- func (m *MQTTClient) Start() error
- func (m *MQTTClient) StartPrint(filename string, opts PrintOptions) (string, error)
- func (m *MQTTClient) Stop()
- func (m *MQTTClient) StopPrint() (string, error)
- func (m *MQTTClient) UnloadFilament() (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).
)
Variables ¶
This section is empty.
Functions ¶
This section is empty.
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 5 is driest)
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
// OnUpdate is a callback invoked whenever a new status message is received from the printer.
OnUpdate func(*PrinterStatus)
}
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 ¶
func NewClient(hostname, accessCode, serial string, onUpdate func(*PrinterStatus)) *Client
NewClient creates a new BambuLAN Client instance.
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.
- onUpdate: A callback function invoked whenever a status update is received via MQTT. Can be nil if monitoring is not required.
Example:
client := bambulan.NewClient("192.168.1.50", "12345678", "01S00A...", func(status *bambulan.PrinterStatus) {
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.
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
}
FileClient handles file operations (listing, uploading, downloading) over FTPS.
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) Delete ¶ added in v0.3.0
func (f *FileClient) Delete(remotePath string) error
Delete deletes a file from the printer.
Parameters:
- 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(remotePath string) (io.ReadCloser, error)
Download streams a file from the printer. The caller is responsible for closing the returned `io.ReadCloser`.
Parameters:
- 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) DownloadFile ¶
func (f *FileClient) DownloadFile(remotePath, localPath string, onProgress func(int64, int64)) error
DownloadFile downloads a file from the printer to a local path.
Parameters:
- 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.
func (*FileClient) GetFiles ¶
func (f *FileClient) GetFiles(dir string, extension string) ([]string, error)
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:
- 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 ¶
func (f *FileClient) ListFiles(dir string) ([]*ftp.Entry, error)
ListFiles returns a detailed list of files in the specified directory.
Parameters:
- dir: The remote directory path to list (e.g., "/timelapse").
Returns:
- A slice of `*ftp.Entry`, each containing file/directory information.
func (*FileClient) MakeDirectory ¶ added in v0.3.0
func (f *FileClient) MakeDirectory(path string) error
MakeDirectory creates a new directory on the printer.
Parameters:
- 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(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:
- 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(source, dest string) error
Rename renames or moves a file/directory on the printer.
Parameters:
- 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(remotePath string, content io.Reader, onProgress func(int64, int64)) error
Upload streams content to the printer.
Parameters:
- 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(localPath, remotePath string, onProgress func(int64, int64)) error
UploadFile uploads a local file to the printer.
Parameters:
- 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.
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"`
}
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
// OnUpdate is called whenever a new status report is received from the printer.
OnUpdate func(*PrinterStatus)
// 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, onUpdate func(*PrinterStatus)) *MQTTClient
NewMQTTClient creates a new MQTTClient.
Parameters:
- hostname: Printer IP/hostname.
- accessCode: Printer access code (password).
- serial: Printer serial number.
- onUpdate: Callback for status updates.
func (*MQTTClient) DumpInfo ¶
func (m *MQTTClient) DumpInfo() (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() (string, error)
GetVersion requests the printer version info (firmware, model, etc).
func (*MQTTClient) LoadFilament ¶ added in v0.3.0
func (m *MQTTClient) LoadFilament(target int) (string, error)
LoadFilament sends a command to load filament from a specific AMS slot.
Parameters:
- 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() (string, error)
PausePrint pauses the current print job.
func (*MQTTClient) Publish ¶
func (m *MQTTClient) Publish(command any) error
Publish sends a JSON command to the printer request topic.
func (*MQTTClient) ResumePrint ¶
func (m *MQTTClient) ResumePrint() (string, error)
ResumePrint resumes a paused print job.
func (*MQTTClient) SendAMSControlCommand ¶ added in v0.3.0
func (m *MQTTClient) SendAMSControlCommand(param string) (string, error)
SendAMSControlCommand sends an AMS control command.
Parameters:
- 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 ¶
func (m *MQTTClient) SendGCode(gcode string) (string, error)
SendGCode sends a single line of G-Code to the printer. Returns the sequence ID of the request.
Example:
client.MQTT.SendGCode("G28") // Auto-home
func (*MQTTClient) SetAMSFilament ¶ added in v0.2.0
func (m *MQTTClient) SetAMSFilament(amsID, trayID int, filamentID, settingID, color, filamentType string, minTemp, maxTemp int) (string, error)
SetAMSFilament updates the filament properties for a specific AMS slot.
Parameters:
- 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(amsID int, startupReadOption, trayReadOption, calibrateRemainFlag bool) (string, error)
SetAMSUserSetting updates AMS user settings for a specific unit.
Parameters:
- 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
func (m *MQTTClient) SetBedTemperature(temp int) (string, error)
SetBedTemperature sets the target bed temperature using M140 G-code.
Parameters:
- temp: The target temperature in Celsius.
Returns:
- The sequence ID of the G-code command.
- An error if the command could not be sent.
func (*MQTTClient) SetBuildPlateMarkerDetector ¶ added in v0.3.0
func (m *MQTTClient) SetBuildPlateMarkerDetector(enabled bool) (string, error)
SetBuildPlateMarkerDetector enables or disables the AI build plate marker detector (ArUco).
Parameters:
- 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 ¶
func (m *MQTTClient) SetChamberLight(on bool) (string, error)
SetChamberLight turns the chamber light on or off.
func (*MQTTClient) SetFanSpeed ¶ added in v0.3.0
func (m *MQTTClient) SetFanSpeed(fan string, percent int) (string, error)
SetFanSpeed sets the speed of the specified fan(s). It sends the appropriate M106 G-code command.
Parameters:
- 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.
func (*MQTTClient) SetNozzleDetails ¶ added in v0.3.0
func (m *MQTTClient) SetNozzleDetails(diameter float64, typeString string) (string, error)
SetNozzleDetails configures the printer's nozzle settings.
Parameters:
- 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(temp int) (string, error)
SetNozzleTemperature sets the target nozzle (tool) temperature using M104 G-code.
Parameters:
- temp: The target temperature in Celsius.
Returns:
- The sequence ID of the G-code command.
- An error if the command could not be sent.
func (*MQTTClient) SetPrintOption ¶ added in v0.3.0
func (m *MQTTClient) SetPrintOption(option string, enabled bool) (string, error)
SetPrintOption enables or disables specific printer options.
Parameters:
- 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 ¶
func (m *MQTTClient) SetSpeedProfile(level string) (string, error)
SetSpeedProfile sets the print speed profile. Supported levels are defined by Speed* constants in models.go.
func (*MQTTClient) SetSpoolKFactor ¶ added in v0.3.0
SetSpoolKFactor sets the linear advance K-factor for a specific spool (tray).
Parameters:
- 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
func (m *MQTTClient) SkipObjects(objects []int) (string, error)
SkipObjects skips specific objects during a multi-object print.
Parameters:
- 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(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., "Metadata/plate_1.gcode" or "model.gcode"). Note: You usually need to upload the file via FTPS first.
Returns the sequence ID of the request.
func (*MQTTClient) StopPrint ¶
func (m *MQTTClient) StopPrint() (string, error)
StopPrint cancels and stops the current print job.
func (*MQTTClient) UnloadFilament ¶ added in v0.3.0
func (m *MQTTClient) UnloadFilament() (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 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 is the human-readable name of the printer (e.g., "Bambu Lab X1 Carbon").
DisplayName string `json:"display_name"`
// MaxNozzleTemp is the maximum safe temperature for the nozzle in degrees Celsius.
MaxNozzleTemp int `json:"max_nozzle_temp"`
// MaxBedTemp is the maximum safe temperature for the heatbed in degrees Celsius.
MaxBedTemp int `json:"max_bed_temp"`
// HasChamberFan indicates whether the printer model is equipped with a chamber ventilation fan.
HasChamberFan bool `json:"has_chamber_fan"`
// HasAuxFan indicates whether the printer model supports an auxiliary part cooling fan.
HasAuxFan bool `json:"has_aux_fan"`
// HasAMSHumidity indicates whether the printer supports reporting AMS humidity levels.
HasAMSHumidity bool `json:"has_ams_humidity"`
// HasTimelapse indicates whether the printer supports internal timelapse recording.
HasTimelapse bool `json:"has_timelapse"`
// HasBedLeveling indicates whether the printer supports automatic bed leveling.
HasBedLeveling bool `json:"has_bed_leveling"`
}
PrinterCapability defines the supported features and limitations for a specific printer model. This structure is populated from the embedded printer_capabilities.json file, which is generated from the official Bambu Lab printer definitions.
func GetPrinterCapabilities ¶ added in v0.4.0
func GetPrinterCapabilities(modelID string) PrinterCapability
GetPrinterCapabilities returns the capabilities for the given printer model ID (e.g., "BL-P001", "C11"). The model ID is typically reported by the printer in its MQTT status messages.
If the model ID is unknown or not found in the embedded database, this function returns an empty PrinterCapability struct. Callers should check if DisplayName is empty to determine if a valid capability set was returned.
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"`
// 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"`
// 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 []any `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 (p *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())
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.

