Skip to content

Commit d14e274

Browse files
Add comprehensive API documentation
- Create `docs/` directory structure - Add detailed documentation for: - Clients (FiveMClient, FlashForgeClient) - Models and Interfaces - Control Modules - TCP and HTTP Protocols - Error Handling - Advanced Topics (AD5X multi-color, G-code) - Add main README in docs/ with navigation
1 parent dce6cc0 commit d14e274

7 files changed

Lines changed: 585 additions & 0 deletions

File tree

docs/README.md

Lines changed: 77 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,77 @@
1+
# FlashForge API Documentation
2+
3+
Welcome to the comprehensive documentation for the FlashForge API. This library provides a robust interface for interacting with FlashForge 3D printers, supporting both legacy TCP-based communication and the newer HTTP API used by 5M, 5M Pro, and Adventurer 5X (AD5X) series printers.
4+
5+
## Table of Contents
6+
7+
1. [Getting Started](#getting-started)
8+
2. [Architecture Overview](#architecture-overview)
9+
3. [Client Documentation](clients.md)
10+
4. [Models & Interfaces](models.md)
11+
5. [Modules & Namespaces](modules.md)
12+
6. [Protocols](protocols.md)
13+
7. [Error Handling](errors.md)
14+
8. [Advanced Topics](advanced.md)
15+
16+
## Getting Started
17+
18+
### Installation
19+
20+
```bash
21+
npm install @ghosttypes/ff-api
22+
```
23+
24+
### Discovery
25+
26+
To start interacting with a printer, you first need to discover it on your local network.
27+
28+
```typescript
29+
import { FlashForgePrinterDiscovery } from '@ghosttypes/ff-api';
30+
31+
const discovery = new FlashForgePrinterDiscovery();
32+
const printers = await discovery.discoverPrintersAsync();
33+
34+
printers.forEach(printer => {
35+
console.log(`Found printer: ${printer.name} at ${printer.ipAddress}`);
36+
});
37+
```
38+
39+
### connecting to a Printer
40+
41+
Once you have the printer's IP address, serial number, and check code (usually provided by the discovery or known beforehand), you can instantiate a client.
42+
43+
**For newer printers (5M, 5M Pro, AD5X):**
44+
45+
```typescript
46+
import { FiveMClient } from '@ghosttypes/ff-api';
47+
48+
const client = new FiveMClient("192.168.1.100", "SERIAL123", "CHECKCODE123");
49+
const connected = await client.initialize();
50+
51+
if (connected) {
52+
console.log("Connected!");
53+
await client.initControl(); // Initialize control connection
54+
}
55+
```
56+
57+
**For legacy printers (Adventurer 3/4, etc.):**
58+
59+
```typescript
60+
import { FlashForgeClient } from '@ghosttypes/ff-api';
61+
62+
const client = new FlashForgeClient("192.168.1.100");
63+
const connected = await client.initControl();
64+
65+
if (connected) {
66+
console.log("Connected to legacy printer!");
67+
}
68+
```
69+
70+
## Architecture Overview
71+
72+
The library is built around two main client classes:
73+
74+
- **`FiveMClient`**: Designed for the Adventurer 5M series and AD5X. It primarily uses an HTTP API for state management, file operations, and job control, while falling back to TCP for specific real-time commands.
75+
- **`FlashForgeClient`**: A TCP-based client that communicates using FlashForge's G-code/M-code protocol. This is used for legacy printers and is also wrapped by `FiveMClient` for low-level operations.
76+
77+
For detailed API usage, refer to the [Client Documentation](clients.md).

docs/advanced.md

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
# Advanced Topics
2+
3+
## Multi-Color Printing (AD5X)
4+
5+
The Adventurer 5X (AD5X) supports multi-material printing via its Intelligent Filament Station (IFS). The API allows you to map tools (extruders) in your G-code to specific slots in the IFS.
6+
7+
### Material Mapping
8+
9+
To start a multi-color print, you need to define `AD5XMaterialMapping` objects.
10+
11+
```typescript
12+
import { AD5XMaterialMapping } from '@ghosttypes/ff-api';
13+
14+
const mappings: AD5XMaterialMapping[] = [
15+
{
16+
toolId: 0, // The first tool in the G-code
17+
slotId: 1, // Use filament from Slot 1
18+
materialName: "PLA",
19+
toolMaterialColor: "#FF0000", // Color defined in slicer
20+
slotMaterialColor: "#FF0000" // Actual color in slot
21+
},
22+
{
23+
toolId: 1,
24+
slotId: 2,
25+
materialName: "PLA",
26+
toolMaterialColor: "#0000FF",
27+
slotMaterialColor: "#0000FF"
28+
}
29+
];
30+
```
31+
32+
### Starting a Job
33+
34+
You can start a job with these mappings using `startAD5XMultiColorJob` (for local files) or `uploadFileAD5X` (for new uploads).
35+
36+
```typescript
37+
await client.jobControl.startAD5XMultiColorJob({
38+
fileName: "multi_color_model.gcode",
39+
levelingBeforePrint: true,
40+
materialMappings: mappings
41+
});
42+
```
43+
44+
## Direct G-Code Control
45+
46+
For advanced users, you may need to send raw G-code commands that aren't exposed by the high-level API. You can access the underlying `FlashForgeClient` via `client.tcpClient`.
47+
48+
```typescript
49+
// Send a raw G-code command
50+
const response = await client.tcpClient.sendRawCmd("~G1 X100 Y100 F3000");
51+
console.log(response); // Output from printer
52+
```
53+
54+
*Note: Use raw commands with caution. Incorrect G-code can damage the printer.*
55+
56+
## Image Preview Handling
57+
58+
The API allows retrieving thumbnail previews for G-code files. This is useful for building UI applications.
59+
60+
```typescript
61+
const thumbnailBuffer = await client.files.getGCodeThumbnail("model.gcode");
62+
63+
if (thumbnailBuffer) {
64+
// Save to file
65+
fs.writeFileSync("preview.png", thumbnailBuffer);
66+
67+
// Or convert to base64 for web display
68+
const base64Image = thumbnailBuffer.toString('base64');
69+
const imgSrc = `data:image/png;base64,${base64Image}`;
70+
}
71+
```
72+
73+
## Firmware Version Handling
74+
75+
The library automatically detects the printer's firmware version. Some features (especially file uploads and print starting) have different payload requirements for newer firmware versions (>= 3.1.3). The `JobControl` class handles this logic internally, so you generally don't need to worry about it. However, if you encounter issues with a specific firmware version, check `client.firmVer`.

docs/clients.md

Lines changed: 144 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,144 @@
1+
# Client Documentation
2+
3+
This section documents the primary client classes used to interact with FlashForge printers.
4+
5+
## FiveMClient
6+
7+
The `FiveMClient` is the modern interface for Adventurer 5M, 5M Pro, and Adventurer 5X (AD5X) printers. It combines HTTP API calls with a TCP connection for comprehensive control.
8+
9+
### Constructor
10+
11+
```typescript
12+
constructor(ipAddress: string, serialNumber: string, checkCode: string)
13+
```
14+
15+
- **`ipAddress`** (`string`): The local IP address of the printer.
16+
- **`serialNumber`** (`string`): The printer's serial number (required for authentication).
17+
- **`checkCode`** (`string`): The check code for authentication.
18+
19+
### Properties
20+
21+
- **`control`** (`Control`): Interface for general printer controls (home, fans, LEDs, etc.).
22+
- **`jobControl`** (`JobControl`): Interface for managing print jobs (start, stop, pause, file upload).
23+
- **`info`** (`Info`): Interface for retrieving machine status and details.
24+
- **`files`** (`Files`): Interface for file management (list files, get thumbnails).
25+
- **`tempControl`** (`TempControl`): Interface for temperature management.
26+
- **`tcpClient`** (`FlashForgeClient`): The underlying TCP client instance.
27+
- **`printerName`** (`string`): The configured name of the printer.
28+
- **`isPro`** (`boolean`): True if the printer is a Pro model.
29+
- **`isAD5X`** (`boolean`): True if the printer is an AD5X model.
30+
- **`firmwareVersion`** (`string`): The full firmware version string.
31+
- **`ledControl`** (`boolean`): True if LED control is available/enabled.
32+
- **`filtrationControl`** (`boolean`): True if filtration control is available/enabled.
33+
34+
### Key Methods
35+
36+
#### `initialize()`
37+
38+
```typescript
39+
public async initialize(): Promise<boolean>
40+
```
41+
42+
Initializes the client by verifying the connection to the printer. Returns `true` if successful.
43+
44+
#### `initControl()`
45+
46+
```typescript
47+
public async initControl(): Promise<boolean>
48+
```
49+
50+
Fully initializes control capabilities by authenticating via the product command and establishing the TCP connection. Must be called before performing control actions.
51+
52+
#### `verifyConnection()`
53+
54+
```typescript
55+
public async verifyConnection(): Promise<boolean>
56+
```
57+
58+
Checks connectivity by attempting to fetch printer details. Updates cached machine info.
59+
60+
#### `dispose()`
61+
62+
```typescript
63+
public async dispose(): Promise<void>
64+
```
65+
66+
Cleanly closes connections and stops background keep-alive processes.
67+
68+
---
69+
70+
## FlashForgeClient
71+
72+
The `FlashForgeClient` is a TCP-based client for legacy printers or low-level G-code operations. It extends `FlashForgeTcpClient`.
73+
74+
### Constructor
75+
76+
```typescript
77+
constructor(hostname: string)
78+
```
79+
80+
- **`hostname`** (`string`): The IP address or hostname of the printer.
81+
82+
### Key Methods
83+
84+
#### `initControl()`
85+
86+
```typescript
87+
public async initControl(): Promise<boolean>
88+
```
89+
90+
Establishes the TCP connection, logs in, and starts the keep-alive loop.
91+
92+
#### `getPrinterInfo()`
93+
94+
```typescript
95+
public async getPrinterInfo(): Promise<PrinterInfo | null>
96+
```
97+
98+
Retrieves basic printer information (firmware, machine type, etc.).
99+
100+
#### `getTempInfo()`
101+
102+
```typescript
103+
public async getTempInfo(): Promise<TempInfo | null>
104+
```
105+
106+
Gets current extruder and bed temperatures.
107+
108+
#### `move(x, y, z, feedrate)`
109+
110+
```typescript
111+
public async move(x: number, y: number, z: number, feedrate: number): Promise<boolean>
112+
```
113+
114+
Moves the print head to the specified absolute coordinates.
115+
116+
#### `setExtruderTemp(temp, waitFor)`
117+
118+
```typescript
119+
public async setExtruderTemp(temp: number, waitFor: boolean = false): Promise<boolean>
120+
```
121+
122+
Sets the extruder target temperature.
123+
124+
---
125+
126+
## FlashForgePrinterDiscovery
127+
128+
A utility class for finding printers on the local network.
129+
130+
### Methods
131+
132+
#### `discoverPrintersAsync()`
133+
134+
```typescript
135+
public async discoverPrintersAsync(timeoutMs: number = 10000, idleTimeoutMs: number = 1500, maxRetries: number = 3): Promise<FlashForgePrinter[]>
136+
```
137+
138+
Broadcasts a discovery packet via UDP and listens for responses.
139+
140+
- **`timeoutMs`**: Max time to wait for responses.
141+
- **`idleTimeoutMs`**: Time to wait after the last response before returning.
142+
- **`maxRetries`**: Number of broadcast attempts if no printers are found initially.
143+
144+
**Returns:** An array of `FlashForgePrinter` objects containing IP, Serial, and Name.

docs/errors.md

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Error Handling
2+
3+
The library uses a combination of return values and exceptions to handle errors.
4+
5+
## Connection Errors
6+
7+
- **Initialization Failure**: `initialize()` or `initControl()` methods will return `false` if the connection cannot be established or verified.
8+
- **Network Errors**: Lower-level network issues (timeouts, unreachable host) are often caught and logged to the console, with the method returning `null` or `false`.
9+
- **Keep-Alive Failures**: The TCP client maintains a keep-alive loop. If it fails repeatedly, the connection is considered lost, and the client may attempt to reconnect or stop the keep-alive process.
10+
11+
## API Errors
12+
13+
- **HTTP Status Codes**: The `FiveMClient` checks HTTP status codes. Non-200 responses are treated as failures.
14+
- **Printer Error Codes**: The `FFMachineInfo` object contains an `ErrorCode` property. This string comes directly from the printer and indicates internal hardware or firmware errors (e.g., "File Error", "Sensor Error").
15+
16+
## Best Practices
17+
18+
1. **Check Return Values**: Most control methods return a `boolean` indicating success or failure. Always check this result.
19+
```typescript
20+
if (!await client.control.setLedOn()) {
21+
console.error("Failed to turn on LED");
22+
}
23+
```
24+
25+
2. **Handle Nulls**: Data retrieval methods (like `info.get()`) may return `null` if the request fails.
26+
```typescript
27+
const status = await client.info.get();
28+
if (status) {
29+
console.log(status.Status);
30+
} else {
31+
console.log("Could not retrieve status");
32+
}
33+
```
34+
35+
3. **Verify Connection**: Before performing critical operations, you can use `client.verifyConnection()` to ensure the printer is still reachable.
36+
37+
4. **Try-Catch**: When using methods that perform file I/O (like `uploadFile`), wrap calls in a `try-catch` block to handle file system errors.

0 commit comments

Comments
 (0)