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) 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) Upload(remotePath string, content io.Reader) error
- func (f *FileClient) UploadFile(localPath, remotePath string, onProgress func(int64, int64)) error
- type IPCam
- type LightsReport
- type MQTTClient
- func (m *MQTTClient) DumpInfo() (string, error)
- func (m *MQTTClient) GetPrinterStatus() *PrinterStatus
- func (m *MQTTClient) PausePrint() (string, error)
- func (m *MQTTClient) Publish(command any) error
- func (m *MQTTClient) ResumePrint() (string, error)
- func (m *MQTTClient) SendGCode(gcode string) (string, error)
- func (m *MQTTClient) SetAMSFilament(amsID, trayID int, color, filamentType string) (string, error)
- func (m *MQTTClient) SetChamberLight(on bool) (string, error)
- func (m *MQTTClient) SetSpeedProfile(level string) (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)
- type Online
- type PrintOptions
- 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"`
TrayTar string `json:"tray_tar"`
TrayNow string `json:"tray_now"`
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"`
PowerOnFlag bool `json:"power_on_flag"`
}
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, captures a single JPEG frame, and then closes the connection. 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) StartStream ¶
func (c *CameraClient) StartStream(onImage func([]byte)) error
StartStream connects to the camera and continuously sends new JPEG frames to the onImage callback. 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 *MQTTClient
Camera *CameraClient
File *FileClient
// OnUpdate is a callback for status updates. It delegates to MQTT.OnUpdate.
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, usually 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 underlying printer status.
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) 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) Upload ¶
func (f *FileClient) Upload(remotePath string, content io.Reader) 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.
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"`
TutkServer string `json:"tutk_server"`
ModeBits int `json:"mode_bits"`
RTSPURL string `json:"rtsp_url"`
}
type LightsReport ¶
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) 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) 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, color, filamentType string) (string, error)
SetAMSFilament updates the filament properties (color and type) for a specific AMS slot.
NOTE: This command is tricky and often doesn't work correctly with the printer's current firmware.
Parameters:
- amsID: The ID of the AMS unit (0-indexed, typically 0 for the first AMS).
- trayID: The ID of the tray within the AMS unit (0-indexed, 0-3 for each AMS).
- color: The filament color in RRGGBBAA hex format (e.g., "FF0000FF" for opaque red).
- filamentType: The filament material type identifier (e.g., "PLA Basic", "PETG", "ABS").
Returns the sequence ID of the request.
func (*MQTTClient) SetChamberLight ¶
func (m *MQTTClient) SetChamberLight(on bool) (string, error)
SetChamberLight turns the chamber light on or off.
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) 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.
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 PrinterStatus ¶
type PrinterStatus struct {
Upload *Upload `json:"upload,omitempty"`
NozzleTemp float64 `json:"nozzle_temper"` // Actual nozzle temperature in Celsius.
NozzleTargetTemp float64 `json:"nozzle_target_temper"` // Target nozzle temperature in Celsius.
BedTemp float64 `json:"bed_temper"` // Actual bed temperature in Celsius.
BedTargetTemp float64 `json:"bed_target_temper"` // Target bed temperature in Celsius.
ChamberTemp float64 `json:"chamber_temper"` // Actual chamber temperature in Celsius.
McPrintStage string `json:"mc_print_stage"` // Internal code for the current mechanical print stage (see GetPrintStageName).
HeatbreakFanSpeed string `json:"heatbreak_fan_speed"` // Speed of the heatbreak fan.
CoolingFanSpeed string `json:"cooling_fan_speed"` // Speed of the part cooling fan.
BigFan1Speed string `json:"big_fan1_speed"` // Speed of the auxiliary fan.
BigFan2Speed string `json:"big_fan2_speed"` // Speed of the chamber fan.
McPercent int `json:"mc_percent"` // Print progress percentage (0-100).
McRemainingTime int `json:"mc_remaining_time"` // Estimated remaining print time in minutes.
AMSStatus int `json:"ams_status"` // AMS status code.
AMSRFIDStatus int `json:"ams_rfid_status"` // AMS RFID status code.
HwSwitchState int `json:"hw_switch_state"` // Hardware switch state.
SpdMag int `json:"spd_mag"` // Speed multiplier magnitude (e.g., 50, 100, 125, 166).
SpdLvl int `json:"spd_lvl"` // Current speed profile level (1=Silent, 2=Standard, 3=Sport, 4=Ludicrous).
PrintError int `json:"print_error"` // Error code if a print error occurred.
Lifecycle string `json:"lifecycle"` // Printer lifecycle state (e.g., "printing", "idle").
WifiSignal string `json:"wifi_signal"` // WiFi signal strength.
GcodeState string `json:"gcode_state"` // Current G-code execution state (e.g., "RUNNING", "PAUSE", "IDLE", "FINISH").
GcodeFilePreparePercent string `json:"gcode_file_prepare_percent"`
QueueNumber int `json:"queue_number"`
QueueTotal int `json:"queue_total"`
QueueEst int `json:"queue_est"`
QueueSts int `json:"queue_sts"`
ProjectID string `json:"project_id"`
ProfileID string `json:"profile_id"`
TaskID string `json:"task_id"`
SubtaskID string `json:"subtask_id"`
SubtaskName string `json:"subtask_name"`
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 bool `json:"sdcard"`
ForceUpgrade bool `json:"force_upgrade"`
MessProductionState string `json:"mess_production_state"`
LayerNum int `json:"layer_num"` // Current layer number.
TotalLayerNum int `json:"total_layer_num"` // Total number of layers.
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"` // Sequence ID of the last command, for correlating responses.
Result string `json:"result"` // Result of the last command (e.g., "success").
Reason string `json:"reason"` // Reason for command failure, if any.
}
PrinterStatus contains the detailed status of the printer components.
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"`
Status string `json:"status"`
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"`
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"`
}
type Upload ¶
type Upload struct {
FileSize int `json:"file_size"`
FinishSize int `json:"finish_size"`
Status string `json:"status"`
Progress int `json:"progress"`
Message string `json:"message"`
OSSURL string `json:"oss_url"`
SequenceID string `json:"sequence_id"`
Speed int `json:"speed"`
TaskID string `json:"task_id"`
TimeRemaining int `json:"time_remaining"`
TroubleID string `json:"trouble_id"`
}
type VTTray ¶
type VTTray struct {
Id string `json:"id"`
TagUid string `json:"tag_uid"`
TrayIdName string `json:"tray_id_name"`
TrayInfoIdx string `json:"tray_info_idx"`
TrayType string `json:"tray_type"`
TraySubBrands string `json:"tray_sub_brands"`
TrayColor string `json:"tray_color"`
TrayWeight string `json:"tray_weight"`
TrayDiameter string `json:"tray_diameter"`
TrayTemp string `json:"tray_temp"`
TrayTime string `json:"tray_time"`
BedTempType string `json:"bed_temp_type"`
BedTemp string `json:"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"`
K float64 `json:"k"`
N int `json:"n"`
CaliIdx int `json:"cali_idx"`
Cols []string `json:"cols"`
Ctype int `json:"ctype"`
DryingTemp string `json:"drying_temp"`
DryingTime string `json:"drying_time"`
}

