This document provides a comprehensive reference for the FlashForge Python API, including all classes, methods, and data models.
For recommended modern entry points, use FlashForgeClient and PrinterDiscovery. FlashForgePrinterDiscovery remains available as a compatibility wrapper.
Main client for interacting with a FlashForge 3D printer. Orchestrates both HTTP and TCP communication layers.
FlashForgeClient(ip_address: str, serial_number: str, check_code: str)Parameters:
ip_address(str): IP address of the printerserial_number(str): Serial number of the printer (required for HTTP API)check_code(str): Per-printer authentication check code (not returned by discovery)
Connection Management:
-
async initialize() -> bool
Initializes connection and verifies printer. ReturnsTrueif successful. -
async init_control() -> bool
Initializes control interface (required for some operations). ReturnsTrueif successful. -
async dispose() -> None
Cleans up resources, stops keep-alive, closes connections.
Status & Information:
-
async get_printer_status() -> Optional[FFMachineInfo]
Gets current printer status and information. -
async get_temperatures() -> Optional[TempInfo]
Gets current temperature readings from TCP client.
Control Operations:
-
async home_all_axes() -> bool
Homes all axes (X, Y, Z). -
async emergency_stop() -> bool
Performs emergency stop. -
async pause_print() -> bool
Pauses current print job. -
async resume_print() -> bool
Resumes paused print job. -
async cancel_print() -> bool
Cancels current print job.
is_ad5x: bool- True if printer is AD5X modelprinter_name: str- Cached printer nameis_pro: bool- True if Pro modelfirmware_version: str- Firmware version stringmac_address: str- MAC addresscamera_stream_url: str- Runtime OEM camera stream URL reported by the printerled_control: bool- True if LED control availablefiltration_control: bool- True if filtration control available
control: Control- General machine controljob_control: JobControl- Print job managementfiles: Files- File operationsinfo: Info- Information retrievaltemp_control: TempControl- Temperature managementtcp_client: FlashForgeTcpClient- Low-level TCP client
async with FlashForgeClient(ip, serial, check_code) as client:
# Use client...
# Automatic cleanupTyped UDP discovery API for modern and legacy FlashForge models.
async discover(options: DiscoveryOptions | None = None) -> list[DiscoveredPrinter]monitor(options: DiscoveryOptions | None = None) -> DiscoveryMonitor
Backward-compatible wrapper around PrinterDiscovery.
async discover_printers_async(timeout_ms: int = 10000, idle_timeout_ms: int = 1500, max_retries: int = 3) -> List[FlashForgePrinter]
Discovers printers on the network. Returns list of discovered printers.
Parameters:
timeout_ms(int): Total discovery timeout in milliseconds (default: 10000)idle_timeout_ms(int): Idle timeout between responses (default: 1500)max_retries(int): Maximum retry attempts (default: 3)
Data class representing a discovered printer.
Properties:
name: str- Printer nameserial_number: str- Serial numberip_address: str- IP address
General machine control operations.
-
async home_axes() -> bool
Homes X, Y, and Z axes. -
async home_axes_rapid() -> bool
Performs rapid homing of all axes.
-
async set_led_on() -> bool
Turns on LED lights (requiresled_controlcapability). -
async set_led_off() -> bool
Turns off LED lights.
Note: For printers with aftermarket LEDs or when the led_control capability flag is incorrectly False, you can use the TCP-based LED control methods via client.tcp_client.led_on() and client.tcp_client.led_off(). See Advanced Usage for examples.
-
async set_external_filtration_on() -> bool
Turns on external filtration system. -
async set_internal_filtration_on() -> bool
Turns on internal filtration system. -
async set_filtration_off() -> bool
Turns off all filtration systems.
-
async turn_camera_on() -> bool
Sends the OEM camera enable command for Pro models. -
async turn_camera_off() -> bool
Sends the OEM camera disable command for Pro models.
-
async set_chamber_fan_speed(speed: int) -> bool
Sets chamber fan speed percentage (0-100). -
async set_cooling_fan_speed(speed: int) -> bool
Sets cooling fan speed percentage (0-100).
-
async set_speed_override(speed: int) -> bool
Sets print speed override percentage. -
async set_z_axis_override(offset: float) -> bool
Sets Z-axis offset override.
-
async turn_runout_sensor_on() -> bool
Enables filament runout sensor. -
async turn_runout_sensor_off() -> bool
Disables filament runout sensor.
Print job management and file operations.
-
async pause_print_job() -> bool
Pauses current print job. -
async resume_print_job() -> bool
Resumes paused print job. -
async cancel_print_job() -> bool
Cancels current print job. -
async clear_platform() -> bool
Sends command to clear build platform.
async upload_file(file_path: str, start_print: bool = True, level_before_print: bool = True) -> bool
Uploads G-code/3MF file and optionally starts printing.
Parameters:
-
file_path(str): Path to file to upload -
start_print(bool): Start printing after upload (default: True) -
level_before_print(bool): Perform bed leveling before print (default: True) -
async print_local_file(file_name: str, leveling_before_print: bool = True) -> bool
Starts printing a file already stored on the printer.
Parameters:
file_name(str): Name of file on printerleveling_before_print(bool): Perform bed leveling (default: True)
-
async upload_file_ad5x(params: AD5XUploadParams) -> bool
Uploads file to AD5X printer with material station support. -
async start_ad5x_multi_color_job(params: AD5XLocalJobParams) -> bool
Starts multi-color print job with material mappings. -
async start_ad5x_single_color_job(params: AD5XSingleColorJobParams) -> bool
Starts single-color print job on AD5X printer.
-
async upload_file_creator5(params: Creator5UploadParams) -> bool
Uploads a file to a Creator 5 / Creator 5 Pro, with material mappings whenstart_printis true. -
async start_creator5_job(params: Creator5JobParams) -> bool
Starts a file already on a Creator 5 / Creator 5 Pro, with per-tool material mappings.
To build the mappings for these methods, parse the 3MF first. See Sliced 3MF Parsing.
These rules apply to upload_file, upload_file_ad5x, and upload_file_creator5 (since 1.6.0):
- The methods open and measure the local file in a worker thread, so they do not block the event loop.
- The methods use
flashforge.api.controls.job_control.UPLOAD_TIMEOUT. It has no total time limit, a 30-second connect limit, and a 300-second read limit. A large upload over slow Wi-Fi can take as long as it needs. - If
file_pathdoes not exist or is not a regular file (for example, a directory), the method returnsFalse.
Reads a sliced .3mf file and returns what a client needs before upload: the filaments (tools) the print uses, their material and color, estimates, the thumbnail, and slicer warnings. The Creator 5 series does not report which tools a stored file uses, so this is the only way to build correct material mappings for that family.
parse_3mf(source: str | os.PathLike[str] | IO[bytes], *, file_name: str | None = None) -> ThreeMFFileParameters:
source: A path to the file, or a binary file object open for readingfile_name(str | None): The name to report inThreeMFFile.file_name. Defaults to the base name of a path source, or"unknown.3mf"for a file object
Returns: ThreeMFFile (see Data Models)
Raises:
FileNotFoundError: The path does not existThreeMFFormatError: The file is not a valid ZIP archive, has a corrupt entry, or has malformed or oversized slice metadataThreeMFNotSlicedError: The file holds no sliced plate G-code (a project file)ThreeMFMultiplePlatesError: The file holds more than one sliced plate
Rules:
- The parser accepts one sliced plate only. Nobody knows which plate the printer prints from a multi-plate file, so export a single plate from the slicer.
filamentslists only the filaments the plate uses. Each one keeps its slicer number: a file that uses only filament 3 gives one entry withfilament_id3 andtool_id2.- Data comes from
Metadata/slice_info.configin the archive. If that file lists no filaments, the parser reads the comments at the start of the plate G-code instead. - The parser reads only small parts of the archive and never decompresses the whole G-code.
- The call is synchronous. In asyncio code, run it in a worker thread:
await asyncio.to_thread(parse_3mf, path).
Tested with output from Orca-FlashForge, OrcaSlicer, Flash Studio, and Snapmaker Orca.
printer_family_from_model_id(model_id: str | None) -> PrinterFamily | NoneMaps a slicer printer-model id (for example Flashforge-AD5X or Flashforge-Creator-5-Pro) to a PrinterFamily. The comparison ignores case, spaces, hyphens, and underscores. Returns None for an unknown or missing id. ThreeMFFile.printer_family calls this for you.
translate_warning(key: str) -> strTurns a raw slicer warning key (for example bed_temperature_too_high_than_filament) into readable text. An unknown key falls back to a readable form of the key. An empty key gives an empty string. The parser already fills ThreeMFWarning.message with this text.
The parser stops reading at these limits, all importable from flashforge.threemf:
| Constant | Value | Part of the archive |
|---|---|---|
MAX_SLICE_INFO_BYTES |
4 MB | Slice metadata (slice_info.config) |
MAX_THUMBNAIL_BYTES |
8 MB | Plate thumbnail |
MAX_GCODE_HEADER_BYTES |
1 MB | Start of the plate G-code |
Oversized slice metadata raises ThreeMFFormatError. An oversized thumbnail gives thumbnail_png = None.
| Exception | Parent | Meaning |
|---|---|---|
ThreeMFError |
FlashForgeError |
Base class for all 3MF errors |
ThreeMFFormatError |
ThreeMFError |
Not a readable archive, corrupt entry, or bad slice metadata |
ThreeMFNotSlicedError |
ThreeMFError |
No sliced plate G-code in the file |
ThreeMFMultiplePlatesError |
ThreeMFError |
More than one sliced plate; has plate_count |
parse_3mf, ThreeMFFile, ThreeMFFilament, ThreeMFWarning, PrinterFamily, and the four exceptions are available from flashforge. printer_family_from_model_id, translate_warning, and the size limits are available from flashforge.threemf.
Temperature control for extruders and print bed.
async set_extruder_temp(temperature: int, wait_for: bool = False) -> bool
Sets extruder target temperature in Celsius.
Parameters:
-
temperature(int): Target temperature -
wait_for(bool): Wait for temperature to be reached (default: False) -
async set_bed_temp(temperature: int, wait_for: bool = False) -> bool
Sets bed target temperature in Celsius.
Parameters:
temperature(int): Target temperaturewait_for(bool): Wait for temperature to be reached (default: False)
-
async cancel_extruder_temp() -> bool
Cancels extruder heating (sets target to 0). -
async cancel_bed_temp() -> bool
Cancels bed heating (sets target to 0).
async wait_for_part_cool(target_temp: float = 50.0, timeout_seconds: int = 1800) -> bool
Waits for components to cool to safe temperature.
Parameters:
target_temp(float): Target temperature in Celsius (default: 50.0)timeout_seconds(int): Maximum wait time in seconds (default: 1800)
File operations and thumbnail retrieval.
-
async get_file_list() -> List[str]
Gets list of files stored locally on printer (via TCP). -
async get_local_file_list() -> List[str]
Alias forget_file_list(). -
async get_recent_file_list() -> List[FFGcodeFileEntry]
Gets list of 10 most recently printed files with metadata (via HTTP).
async get_gcode_thumbnail(file_name: str) -> Optional[bytes]
Retrieves thumbnail image for a G-code file as PNG bytes.
Parameters:
file_name(str): Name of the G-code file
Information retrieval and status checking.
-
async get() -> Optional[FFMachineInfo]
Gets comprehensive machine information. -
async get_detail_response() -> Optional[DetailResponse]
Gets raw detailed response from printer.
-
async is_printing() -> bool
Checks if printer is currently printing. -
async get_status() -> Optional[str]
Gets raw status string (e.g., "ready", "printing"). -
async get_machine_state() -> Optional[MachineState]
Gets machine state as enum value.
Low-level TCP client for G-code commands and real-time status.
async send_command_async(cmd: str) -> Optional[str]
Sends raw G-code command and returns response.
async get_file_list_async() -> List[str]
Gets list of files on printer.
-
async get_printer_info() -> Optional[PrinterInfo]
Gets printer hardware information. -
async get_temp_info() -> Optional[TempInfo]
Gets temperature readings. -
async get_location_info() -> Optional[LocationInfo]
Gets current axis positions. -
async get_endstop_status() -> Optional[EndstopStatus]
Gets machine status, endstops, and movement mode. -
async get_print_status() -> Optional[PrintStatus]
Gets print progress information. -
async get_thumbnail(file_name: str) -> Optional[ThumbnailInfo]
Gets thumbnail with metadata.
-
async is_printer_ready() -> bool
Checks if printer is ready. -
async get_current_print_file() -> Optional[str]
Gets name of currently loaded file. -
async get_print_progress() -> Tuple[float, float, int]
Returns (layer_percent, sd_percent, current_layer). -
async check_machine_state() -> str
Gets machine state string.
-
async set_extruder_temp(temperature: int, wait_for: bool = False) -> bool
Sets extruder temperature via TCP. -
async set_bed_temp(temperature: int, wait_for: bool = False) -> bool
Sets bed temperature via TCP. -
async cancel_extruder_temp() -> bool
Cancels extruder heating. -
async cancel_bed_temp() -> bool
Cancels bed heating. -
async wait_for_part_cool(target_temp: float = 50.0, timeout_seconds: int = 1800) -> bool
Waits for cooling.
The TCP client provides direct G-code-based LED control using the M146 command. This is useful for:
-
Printers with aftermarket LED installations not detected by the HTTP API
-
Cases where the
led_controlcapability flag is incorrectlyFalse -
Direct TCP-only connections without HTTP API access
-
async led_on() -> bool
Turns on LED lights using M146 G-code command (~M146 r255 g255 b255 F0). -
async led_off() -> bool
Turns off LED lights using M146 G-code command (~M146 r0 g0 b0 F0).
Note: The M146 command uses RGB parameters but only supports binary on/off control (255,255,255 for on, 0,0,0 for off). See the LED Control example for usage patterns.
Structured printer status and information.
Key Properties:
name: str- Printer namemachine_state: MachineState- Current state enumstatus: str- Raw status stringis_pro: bool- Pro model flagis_ad5x: bool- AD5X model flagfirmware_version: str- Firmware versionip_address: str- IP addressmac_address: str- MAC addresscamera_stream_url: str- OEM camera stream URL, or empty when the printer is not reporting oneprint_file_name: str- Current print fileprint_progress: float- Print progress (0.0-100.0)current_print_layer: int- Current layer numbertotal_print_layers: int- Total layersprint_duration: int- Print time in secondsextruder: Temperature- Extruder temperaturesprint_bed: Temperature- Bed temperatureslights_on: bool- LED statusdoor_open: bool- Door statuserror_code: str- Error code if any
Temperature readings for a component.
Properties:
current: float- Current temperature in Celsiusset: float- Target temperature in Celsius
Enum for printer operational states.
Values:
READY- Printer is readyBUSY- Printer is busyPRINTING- Actively printingPAUSED- Print is pausedCOMPLETED- Print completedERROR- Error stateHEATING- Heating componentsCALIBRATING- Performing calibrationCANCELLED- Print cancelledUNKNOWN- Unknown state
Raw printer detail response from API. Contains all raw fields from the printer's HTTP API.
The result types of parse_3mf. See Sliced 3MF Models for every field.
Printer hardware information from TCP.
Properties:
type_name: str- Printer typefirmware_name: str- Firmware namex_size: int- Build volume X (mm)y_size: int- Build volume Y (mm)z_size: int- Build volume Z (mm)
Temperature information from TCP.
Methods:
get_extruder_temp() -> Optional[Temperature]- Get extruder temperaturesget_bed_temp() -> Optional[Temperature]- Get bed temperatures
Current axis positions.
Properties:
x_pos: float- X position (mm)y_pos: float- Y position (mm)z_pos: float- Z position (mm)
Machine status and endstop information.
Properties:
machine_status: MachineStatus- Machine status enummove_mode: MoveMode- Movement mode enumled_enabled: bool- LED statuscurrent_file: Optional[str]- Currently loaded fileendstop: Optional[Endstop]- Endstop states
Methods:
is_printing() -> bool- Check if printingis_ready() -> bool- Check if readyis_paused() -> bool- Check if pausedis_print_complete() -> bool- Check if print complete
Print progress information.
Methods:
get_layer_progress() -> str- Layer progress stringget_print_percent() -> float- Layer progress percentageget_sd_progress() -> str- SD card progress stringget_sd_percent() -> float- SD card progress percentageis_complete() -> bool- Check if print complete
Thumbnail image data and metadata.
Methods:
has_image_data() -> bool- Check if thumbnail existsget_image_size() -> Tuple[int, int]- Get (width, height)get_image_bytes() -> Optional[bytes]- Get raw PNG bytesto_base64_data_url() -> Optional[str]- Get base64 data URLsave_to_file_sync(path: str) -> bool- Save to file
from flashforge import FlashForgeClient
async with FlashForgeClient("192.168.1.100", "SERIAL", "CHECK_CODE") as client:
status = await client.get_printer_status()
if status:
print(f"Printer: {status.name}, State: {status.machine_state.value}")from flashforge import PrinterDiscovery
discovery = PrinterDiscovery()
printers = await discovery.discover()
for printer in printers:
print(f"{printer.name} at {printer.ip_address}")# Set temperatures
await client.temp_control.set_extruder_temp(200)
await client.temp_control.set_bed_temp(60)
# Wait for heating
await client.temp_control.set_extruder_temp(200, wait_for=True)
# Cool down
await client.temp_control.wait_for_part_cool(target_temp=50.0)# List files
files = await client.files.get_file_list()
print(f"Found {len(files)} files")
# Get thumbnail
thumbnail_bytes = await client.files.get_gcode_thumbnail("model.gcode")
if thumbnail_bytes:
with open("thumbnail.png", "wb") as f:
f.write(thumbnail_bytes)# Upload and print
await client.job_control.upload_file("model.gcode", start_print=True)
# Control print
await client.job_control.pause_print_job()
await client.job_control.resume_print_job()
await client.job_control.cancel_print_job()import asyncio
from flashforge import AD5XMaterialMapping, ThreeMFError, parse_3mf
from flashforge.models import Creator5JobParams, Creator5UploadParams
try:
info = await asyncio.to_thread(parse_3mf, "model.3mf")
except ThreeMFError as err:
print(f"Cannot use this file: {err}")
raise
mappings = [
AD5XMaterialMapping(
tool_id=filament.tool_id,
slot_id=filament.tool_id + 1, # pick the slot from the printer's reported slots
material_name=filament.material_name,
tool_material_color=filament.color or "#FFFFFF",
slot_material_color=filament.color or "#FFFFFF",
)
for filament in info.filaments
]
await client.job_control.upload_file_creator5(
Creator5UploadParams(
file_path="model.3mf",
start_print=False,
leveling_before_print=True,
use_matl_station=True,
gcode_tool_cnt=max(info.tool_count, 1),
)
)
await client.job_control.start_creator5_job(
Creator5JobParams(
file_name=info.file_name,
leveling_before_print=True,
material_mappings=mappings,
)
)