taro-bluetooth-print 2.3.1 → 2.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/CHANGELOG.md +42 -0
  2. package/README.md +6 -1
  3. package/dist/index.cjs.js +1 -1
  4. package/dist/index.es.js +1 -1
  5. package/dist/index.umd.js +1 -1
  6. package/dist/types/config/PrinterConfigManager.d.ts +206 -0
  7. package/dist/types/config/index.d.ts +8 -0
  8. package/dist/types/device/MultiPrinterManager.d.ts +164 -0
  9. package/dist/types/device/index.d.ts +2 -0
  10. package/dist/types/index.d.ts +5 -1
  11. package/dist/types/services/BatchPrintManager.d.ts +205 -0
  12. package/dist/types/services/PrintHistory.d.ts +142 -0
  13. package/dist/types/services/PrintJobManager.d.ts +28 -4
  14. package/dist/types/services/PrinterStatus.d.ts +97 -0
  15. package/dist/types/services/index.d.ts +3 -0
  16. package/package.json +2 -2
  17. package/src/adapters/AlipayAdapter.ts +1 -0
  18. package/src/adapters/BaiduAdapter.ts +1 -0
  19. package/src/adapters/ByteDanceAdapter.ts +1 -0
  20. package/src/adapters/TaroAdapter.ts +1 -0
  21. package/src/adapters/WebBluetoothAdapter.ts +1 -1
  22. package/src/config/PrinterConfigManager.ts +523 -0
  23. package/src/config/index.ts +15 -0
  24. package/src/device/MultiPrinterManager.ts +470 -0
  25. package/src/device/index.ts +8 -0
  26. package/src/encoding/gbk-lite.ts +81 -76
  27. package/src/encoding/gbk-table.ts +14 -14
  28. package/src/index.ts +12 -1
  29. package/src/services/BatchPrintManager.ts +494 -0
  30. package/src/services/ConnectionManager.ts +4 -1
  31. package/src/services/PrintHistory.ts +338 -0
  32. package/src/services/PrintJobManager.ts +69 -9
  33. package/src/services/PrinterStatus.ts +261 -0
  34. package/src/services/index.ts +25 -0
  35. package/src/template/TemplateEngine.ts +4 -1
@@ -0,0 +1,206 @@
1
+ /**
2
+ * Printer Configuration Manager
3
+ *
4
+ * Manages persistent printer configurations including:
5
+ * - Saved devices and their settings
6
+ * - Default print parameters
7
+ * - User preferences
8
+ *
9
+ * Supports localStorage and file-based storage backends.
10
+ *
11
+ * @example
12
+ * ```typescript
13
+ * const configManager = new PrinterConfigManager();
14
+ *
15
+ * // Save a printer configuration
16
+ * configManager.savePrinter({
17
+ * id: 'my-printer',
18
+ * deviceId: 'XX:XX:XX:XX:XX:XX',
19
+ * name: 'Kitchen Printer',
20
+ * isDefault: true
21
+ * });
22
+ *
23
+ * // Get all saved printers
24
+ * const printers = configManager.getSavedPrinters();
25
+ *
26
+ * // Load configuration for a printer
27
+ * const config = configManager.loadPrinterConfig('my-printer');
28
+ * ```
29
+ */
30
+ /**
31
+ * Print configuration for a device
32
+ */
33
+ export interface PrintConfig {
34
+ /** Encoding (default: 'GBK') */
35
+ encoding?: string;
36
+ /** Chunk size for data transfer */
37
+ chunkSize?: number;
38
+ /** Delay between chunks in ms */
39
+ chunkDelay?: number;
40
+ /** Number of retries */
41
+ retries?: number;
42
+ }
43
+ /**
44
+ * Saved printer configuration
45
+ */
46
+ export interface SavedPrinter {
47
+ /** Unique printer ID */
48
+ id: string;
49
+ /** Bluetooth device ID */
50
+ deviceId: string;
51
+ /** Friendly name */
52
+ name: string;
53
+ /** Printer model/type */
54
+ model?: string;
55
+ /** Whether this is the default printer */
56
+ isDefault?: boolean;
57
+ /** Print configuration */
58
+ printConfig?: PrintConfig;
59
+ /** Auto-reconnect on disconnect */
60
+ autoReconnect?: boolean;
61
+ /** Last connected timestamp */
62
+ lastConnected?: number;
63
+ /** Creation timestamp */
64
+ createdAt: number;
65
+ /** Update timestamp */
66
+ updatedAt: number;
67
+ }
68
+ /**
69
+ * Global configuration
70
+ */
71
+ export interface GlobalConfig {
72
+ /** Default encoding */
73
+ defaultEncoding: string;
74
+ /** Default chunk size */
75
+ defaultChunkSize: number;
76
+ /** Default chunk delay */
77
+ defaultChunkDelay: number;
78
+ /** Default retries */
79
+ defaultRetries: number;
80
+ /** Auto-reconnect by default */
81
+ defaultAutoReconnect: boolean;
82
+ /** Scan timeout in ms */
83
+ scanTimeout: number;
84
+ /** Enable logging */
85
+ enableLogging: boolean;
86
+ }
87
+ /**
88
+ * Configuration storage interface
89
+ */
90
+ export interface IConfigStorage {
91
+ get<T>(key: string, defaultValue: T): T;
92
+ set<T>(key: string, value: T): void;
93
+ remove(key: string): void;
94
+ clear(): void;
95
+ }
96
+ /**
97
+ * LocalStorage-based implementation
98
+ */
99
+ export declare class LocalStorage implements IConfigStorage {
100
+ private prefix;
101
+ constructor(prefix?: string);
102
+ get<T>(key: string, defaultValue: T): T;
103
+ set<T>(key: string, value: T): void;
104
+ remove(key: string): void;
105
+ clear(): void;
106
+ }
107
+ /**
108
+ * Printer Configuration Manager
109
+ */
110
+ export declare class PrinterConfigManager {
111
+ private readonly logger;
112
+ private readonly storage;
113
+ private printers;
114
+ private globalConfig;
115
+ private lastUsedPrinterId;
116
+ /**
117
+ * Creates a new PrinterConfigManager instance
118
+ *
119
+ * @param storage - Storage backend (defaults to LocalStorage)
120
+ */
121
+ constructor(storage?: IConfigStorage);
122
+ /**
123
+ * Load configuration from storage
124
+ */
125
+ private load;
126
+ /**
127
+ * Save configuration to storage
128
+ */
129
+ private save;
130
+ /**
131
+ * Save a printer configuration
132
+ *
133
+ * @param printer - Printer configuration to save
134
+ * @returns The saved printer ID
135
+ */
136
+ savePrinter(printer: SavedPrinter): string;
137
+ /**
138
+ * Get a saved printer by ID
139
+ */
140
+ getPrinter(id: string): SavedPrinter | undefined;
141
+ /**
142
+ * Get all saved printers
143
+ */
144
+ getSavedPrinters(): SavedPrinter[];
145
+ /**
146
+ * Get default printer
147
+ */
148
+ getDefaultPrinter(): SavedPrinter | undefined;
149
+ /**
150
+ * Remove a saved printer
151
+ */
152
+ removePrinter(id: string): boolean;
153
+ /**
154
+ * Set printer as default
155
+ */
156
+ setDefaultPrinter(id: string): void;
157
+ /**
158
+ * Update last used printer
159
+ */
160
+ setLastUsed(id: string): void;
161
+ /**
162
+ * Get last used printer ID
163
+ */
164
+ getLastUsedId(): string | null;
165
+ /**
166
+ * Get global configuration
167
+ */
168
+ getGlobalConfig(): GlobalConfig;
169
+ /**
170
+ * Update global configuration
171
+ */
172
+ updateGlobalConfig(updates: Partial<GlobalConfig>): void;
173
+ /**
174
+ * Reset global config to defaults
175
+ */
176
+ resetGlobalConfig(): void;
177
+ /**
178
+ * Load print config for a printer (with defaults applied)
179
+ */
180
+ loadPrinterConfig(printerId: string): PrintConfig;
181
+ /**
182
+ * Export all configuration as JSON
183
+ */
184
+ export(): string;
185
+ /**
186
+ * Import configuration from JSON
187
+ *
188
+ * @param json - JSON string to import
189
+ * @param merge - If true, merge with existing config; if false, replace
190
+ * @returns Number of printers imported
191
+ */
192
+ import(json: string, merge?: boolean): number;
193
+ /**
194
+ * Clear all configuration
195
+ */
196
+ clear(): void;
197
+ /**
198
+ * Get statistics
199
+ */
200
+ getStats(): {
201
+ printerCount: number;
202
+ hasDefault: boolean;
203
+ lastUsed: string | null;
204
+ };
205
+ }
206
+ export declare const printerConfigManager: PrinterConfigManager;
@@ -0,0 +1,8 @@
1
+ /**
2
+ * Config Module
3
+ * 配置模块 - 提供打印机配置管理
4
+ */
5
+ export { PrinterConfigManager, printerConfigManager } from './PrinterConfigManager';
6
+ export type { SavedPrinter, PrintConfig, GlobalConfig, IConfigStorage, } from './PrinterConfigManager';
7
+ export { DEFAULT_CONFIG, mergeConfig } from './PrinterConfig';
8
+ export type { PrinterConfig, AdapterConfig, DriverConfig, LoggingConfig } from './PrinterConfig';
@@ -0,0 +1,164 @@
1
+ import { BluetoothPrinter } from '../core/BluetoothPrinter';
2
+ /**
3
+ * Printer connection info
4
+ */
5
+ export interface PrinterConnection {
6
+ /** Custom printer ID */
7
+ printerId: string;
8
+ /** Device ID */
9
+ deviceId: string;
10
+ /** Device name */
11
+ name: string;
12
+ /** BluetoothPrinter instance */
13
+ printer: BluetoothPrinter;
14
+ /** Connection timestamp */
15
+ connectedAt: number;
16
+ /** Last activity timestamp */
17
+ lastActivity?: number;
18
+ }
19
+ /**
20
+ * Connection options
21
+ */
22
+ export interface MultiConnectOptions {
23
+ /** Custom printer ID (optional, auto-generated if not provided) */
24
+ printerId?: string;
25
+ /** Device ID to connect */
26
+ deviceId: string;
27
+ /** Connection timeout in ms */
28
+ timeout?: number;
29
+ }
30
+ /**
31
+ * Broadcast options
32
+ */
33
+ export interface BroadcastOptions {
34
+ /** Parallel or sequential broadcast */
35
+ parallel?: boolean;
36
+ /** Continue on individual failure */
37
+ continueOnError?: boolean;
38
+ }
39
+ /**
40
+ * Multi Printer Manager Events
41
+ */
42
+ export interface MultiPrinterManagerEvents {
43
+ /** Emitted when a printer connects */
44
+ 'printer-connected': (data: PrinterConnection) => void;
45
+ /** Emitted when a printer disconnects */
46
+ 'printer-disconnected': (data: {
47
+ printerId: string;
48
+ deviceId: string;
49
+ }) => void;
50
+ /** Emitted when a printer has an error */
51
+ 'printer-error': (data: {
52
+ printerId: string;
53
+ error: Error;
54
+ }) => void;
55
+ /** Emitted when broadcast completes */
56
+ 'broadcast-complete': (data: {
57
+ success: number;
58
+ failed: number;
59
+ }) => void;
60
+ }
61
+ /**
62
+ * Multi Printer Manager
63
+ *
64
+ * Manages multiple Bluetooth printer connections and supports:
65
+ * - Concurrent connections to multiple printers
66
+ * - Broadcasting print jobs to all printers
67
+ * - Individual printer control
68
+ * - Automatic reconnection
69
+ */
70
+ export declare class MultiPrinterManager {
71
+ private readonly logger;
72
+ private readonly printers;
73
+ private readonly deviceToPrinter;
74
+ private readonly listeners;
75
+ /**
76
+ * Creates a new MultiPrinterManager instance
77
+ */
78
+ constructor();
79
+ /**
80
+ * Register event listener
81
+ */
82
+ on<K extends keyof MultiPrinterManagerEvents>(event: K, callback: MultiPrinterManagerEvents[K]): void;
83
+ /**
84
+ * Remove event listener
85
+ */
86
+ off<K extends keyof MultiPrinterManagerEvents>(event: K, callback: MultiPrinterManagerEvents[K]): void;
87
+ /**
88
+ * Emit an event
89
+ */
90
+ private emit;
91
+ /**
92
+ * Connect to a printer
93
+ *
94
+ * @param printerId - Custom ID for this printer (will be auto-generated if not provided)
95
+ * @param deviceId - Bluetooth device ID
96
+ * @param deviceName - Optional device name
97
+ * @returns The printer ID used
98
+ */
99
+ connect(printerIdOrDeviceId: string, deviceId?: string, deviceName?: string): Promise<string>;
100
+ /**
101
+ * Disconnect a printer
102
+ */
103
+ disconnect(printerId: string): Promise<void>;
104
+ /**
105
+ * Disconnect all printers
106
+ */
107
+ disconnectAll(): Promise<void>;
108
+ /**
109
+ * Get a printer by ID
110
+ */
111
+ getPrinter(printerId: string): BluetoothPrinter | undefined;
112
+ /**
113
+ * Get connection info for a printer
114
+ */
115
+ getConnection(printerId: string): PrinterConnection | undefined;
116
+ /**
117
+ * Get all connected printers
118
+ */
119
+ getAllPrinters(): PrinterConnection[];
120
+ /**
121
+ * Get printer count
122
+ */
123
+ get count(): number;
124
+ /**
125
+ * Check if a printer is connected
126
+ */
127
+ isConnected(printerId: string): boolean;
128
+ /**
129
+ * Update last activity timestamp for a printer
130
+ */
131
+ touch(printerId: string): void;
132
+ /**
133
+ * Print to a specific printer
134
+ */
135
+ print(printerId: string, data: Uint8Array): void;
136
+ /**
137
+ * Broadcast data to all connected printers
138
+ */
139
+ broadcast(data: Uint8Array, options?: BroadcastOptions): Promise<{
140
+ success: number;
141
+ failed: number;
142
+ }>;
143
+ /**
144
+ * Find idle printers (for load balancing)
145
+ */
146
+ getIdlePrinters(): PrinterConnection[];
147
+ /**
148
+ * Get printer statistics
149
+ */
150
+ getStats(): {
151
+ total: number;
152
+ connected: number;
153
+ byName: Record<string, number>;
154
+ };
155
+ /**
156
+ * Clean up inactive printers (based on last activity)
157
+ */
158
+ cleanupInactive(maxIdleMs?: number): Promise<number>;
159
+ /**
160
+ * Destroy the manager and disconnect all printers
161
+ */
162
+ destroy(): Promise<void>;
163
+ }
164
+ export declare const multiPrinterManager: MultiPrinterManager;
@@ -4,3 +4,5 @@
4
4
  */
5
5
  export { DeviceManager, deviceManager } from './DeviceManager';
6
6
  export type { BluetoothDevice, ScanOptions, DeviceManagerEvents, IDeviceManager, } from './DeviceManager';
7
+ export { MultiPrinterManager, multiPrinterManager } from './MultiPrinterManager';
8
+ export type { PrinterConnection, MultiConnectOptions, BroadcastOptions, MultiPrinterManagerEvents, } from './MultiPrinterManager';
@@ -17,8 +17,10 @@ export { AdapterFactory } from './adapters/AdapterFactory';
17
17
  export { BaseAdapter } from './adapters/BaseAdapter';
18
18
  export type { WebBluetoothRequestOptions } from './adapters/WebBluetoothAdapter';
19
19
  export * from './services';
20
- export { DeviceManager } from './device/DeviceManager';
20
+ export { DeviceManager, deviceManager } from './device/DeviceManager';
21
21
  export type { BluetoothDevice, ScanOptions, DeviceManagerEvents } from './device/DeviceManager';
22
+ export { MultiPrinterManager, multiPrinterManager } from './device/MultiPrinterManager';
23
+ export type { PrinterConnection, MultiConnectOptions, BroadcastOptions, MultiPrinterManagerEvents, } from './device/MultiPrinterManager';
22
24
  export { PrintQueue } from './queue/PrintQueue';
23
25
  export type { PrintJob, PrintJobStatus, PrintJobPriority, QueueConfig, PrintQueueEvents, } from './queue/PrintQueue';
24
26
  export { OfflineCache } from './cache/OfflineCache';
@@ -40,6 +42,8 @@ export { PlatformType, detectPlatform, isPlatformSupported } from './utils/platf
40
42
  export { BluetoothPrintError, ErrorCode } from './errors/BluetoothError';
41
43
  export { DEFAULT_CONFIG, mergeConfig } from './config/PrinterConfig';
42
44
  export type { PrinterConfig, AdapterConfig, DriverConfig, LoggingConfig, } from './config/PrinterConfig';
45
+ export { PrinterConfigManager, printerConfigManager } from './config/PrinterConfigManager';
46
+ export type { SavedPrinter, GlobalConfig, IConfigStorage } from './config/PrinterConfigManager';
43
47
  export { PluginManager } from './plugins/PluginManager';
44
48
  export { createLoggingPlugin, createRetryPlugin } from './plugins';
45
49
  export type { Plugin, PluginHooks, PluginOptions, PluginFactory } from './plugins/types';
@@ -0,0 +1,205 @@
1
+ /**
2
+ * Batch Print Manager
3
+ *
4
+ * Optimizes printing multiple jobs by:
5
+ * - Merging small jobs into larger chunks
6
+ * - Reducing Bluetooth communication overhead
7
+ * - Prioritizing urgent jobs
8
+ * - Batching similar content for efficiency
9
+ *
10
+ * @example
11
+ * ```typescript
12
+ * const batchManager = new BatchPrintManager();
13
+ *
14
+ * // Add print jobs
15
+ * batchManager.addJob({ data: buffer1, priority: 1 });
16
+ * batchManager.addJob({ data: buffer2, priority: 2 });
17
+ *
18
+ * // Process batch when ready
19
+ * await batchManager.processBatch();
20
+ * ```
21
+ */
22
+ /**
23
+ * Batch job entry
24
+ */
25
+ export interface BatchJob {
26
+ /** Unique job ID */
27
+ id: string;
28
+ /** Print data */
29
+ data: Uint8Array;
30
+ /** Priority (higher = more urgent) */
31
+ priority: number;
32
+ /** Timestamp when added */
33
+ addedAt: number;
34
+ /** Metadata */
35
+ metadata?: Record<string, unknown>;
36
+ }
37
+ /**
38
+ * Batch configuration
39
+ */
40
+ export interface BatchConfig {
41
+ /** Maximum batch size in bytes */
42
+ maxBatchSize: number;
43
+ /** Maximum wait time before processing in ms */
44
+ maxWaitTime: number;
45
+ /** Minimum jobs before batching */
46
+ minBatchSize: number;
47
+ /** Merge similar content */
48
+ enableMerging: boolean;
49
+ /** Auto-process interval in ms (0 = disabled) */
50
+ autoProcessInterval: number;
51
+ }
52
+ /**
53
+ * Batch statistics
54
+ */
55
+ export interface BatchStats {
56
+ /** Total jobs added */
57
+ totalJobs: number;
58
+ /** Total bytes processed */
59
+ totalBytes: number;
60
+ /** Batches processed */
61
+ batchesProcessed: number;
62
+ /** Average batch size */
63
+ avgBatchSize: number;
64
+ /** Merged jobs count */
65
+ mergedJobs: number;
66
+ }
67
+ /**
68
+ * Batch events
69
+ */
70
+ export interface BatchEvents {
71
+ 'batch-ready': (data: BatchJob[]) => void;
72
+ 'batch-processed': (data: {
73
+ jobCount: number;
74
+ bytes: number;
75
+ }) => void;
76
+ 'job-added': (data: BatchJob) => void;
77
+ 'job-rejected': (data: {
78
+ reason: string;
79
+ }) => void;
80
+ }
81
+ /**
82
+ * Batch Print Manager
83
+ *
84
+ * Collects print jobs and processes them in optimized batches.
85
+ * Reduces Bluetooth communication overhead by combining small jobs.
86
+ */
87
+ export declare class BatchPrintManager {
88
+ private readonly logger;
89
+ private readonly jobs;
90
+ private readonly listeners;
91
+ private config;
92
+ private isProcessing;
93
+ private waitTimer;
94
+ private autoProcessTimer;
95
+ private stats;
96
+ /**
97
+ * Creates a new BatchPrintManager instance
98
+ */
99
+ constructor(config?: Partial<BatchConfig>);
100
+ /**
101
+ * Register event listener
102
+ */
103
+ on<K extends keyof BatchEvents>(event: K, callback: BatchEvents[K]): void;
104
+ /**
105
+ * Remove event listener
106
+ */
107
+ off<K extends keyof BatchEvents>(event: K, callback: BatchEvents[K]): void;
108
+ /**
109
+ * Emit an event
110
+ */
111
+ private emit;
112
+ /**
113
+ * Add a job to the batch queue
114
+ *
115
+ * @param data - Print data
116
+ * @param priority - Job priority (higher = more urgent)
117
+ * @param metadata - Optional metadata
118
+ * @returns Job ID
119
+ */
120
+ addJob(data: Uint8Array, priority?: number, metadata?: Record<string, unknown>): string;
121
+ /**
122
+ * Add multiple jobs at once
123
+ */
124
+ addJobs(jobs: Array<{
125
+ data: Uint8Array;
126
+ priority?: number;
127
+ metadata?: Record<string, unknown>;
128
+ }>): string[];
129
+ /**
130
+ * Cancel a job by ID
131
+ */
132
+ cancelJob(id: string): boolean;
133
+ /**
134
+ * Cancel all jobs
135
+ */
136
+ cancelAll(): void;
137
+ /**
138
+ * Get pending job count
139
+ */
140
+ get pendingCount(): number;
141
+ /**
142
+ * Get pending jobs
143
+ */
144
+ getPendingJobs(): BatchJob[];
145
+ /**
146
+ * Get current statistics
147
+ */
148
+ getStats(): BatchStats;
149
+ /**
150
+ * Update configuration
151
+ */
152
+ updateConfig(updates: Partial<BatchConfig>): void;
153
+ /**
154
+ * Process the current batch
155
+ *
156
+ * @param processor - Function to send batch data to printer
157
+ * @returns Number of jobs processed
158
+ */
159
+ processBatch(processor: (data: Uint8Array) => Promise<void>): Promise<number>;
160
+ /**
161
+ * Prepare batch from pending jobs
162
+ */
163
+ private prepareBatch;
164
+ /**
165
+ * Merge multiple jobs into a single buffer
166
+ */
167
+ private mergeJobs;
168
+ /**
169
+ * Check if we should process immediately
170
+ */
171
+ private shouldProcessImmediately;
172
+ /**
173
+ * Start the wait timer
174
+ */
175
+ private startWaitTimer;
176
+ /**
177
+ * Clear wait timer
178
+ */
179
+ private clearWaitTimer;
180
+ /**
181
+ * Start auto-process timer
182
+ */
183
+ private startAutoProcess;
184
+ /**
185
+ * Stop auto-process timer
186
+ */
187
+ private stopAutoProcess;
188
+ /**
189
+ * Clear all timers
190
+ */
191
+ private clearTimers;
192
+ /**
193
+ * Generate unique job ID
194
+ */
195
+ private generateId;
196
+ /**
197
+ * Reset statistics
198
+ */
199
+ resetStats(): void;
200
+ /**
201
+ * Destroy the manager
202
+ */
203
+ destroy(): void;
204
+ }
205
+ export declare const batchPrintManager: BatchPrintManager;