import { EventEmitter } from '../core/EventEmitter'; /** * Batch job entry */ export interface BatchJob { /** Unique job ID */ id: string; /** Print data */ data: Uint8Array; /** Priority (higher = more urgent) */ priority: number; /** Timestamp when added */ addedAt: number; /** Metadata */ metadata?: Record; } /** * Batch configuration */ export interface BatchConfig { /** Maximum batch size in bytes */ maxBatchSize: number; /** Maximum wait time before processing in ms */ maxWaitTime: number; /** Minimum jobs before batching */ minBatchSize: number; /** Merge similar content */ enableMerging: boolean; /** Auto-process interval in ms (0 = disabled) */ autoProcessInterval: number; /** Small job size threshold for merging (bytes, default: 50) */ smallJobThreshold: number; /** Interval timeout for auto-flush in ms (0 = disabled) */ flushIntervalTimeout: number; /** Unified cut command appended after batch merge (default: ESC d 4) */ unifiedCutCommand?: Uint8Array; } /** * Batch statistics */ export interface BatchStats { /** Total jobs added */ totalJobs: number; /** Total bytes processed */ totalBytes: number; /** Batches processed */ batchesProcessed: number; /** Average batch size */ avgBatchSize: number; /** Merged jobs count (small jobs combined) */ mergedJobs: number; /** Auto-flush triggered count */ autoFlushCount: number; /** Unified cuts applied */ unifiedCutsApplied: number; } /** * Batch events */ export interface BatchEvents { 'batch-ready': BatchJob[]; 'batch-processed': { jobCount: number; bytes: number; }; 'job-added': BatchJob; 'job-rejected': { reason: string; }; 'auto-flush': { jobCount: number; bytes: number; }; 'jobs-merged': { fromCount: number; toCount: number; savedBytes: number; }; } /** * Batch Print Manager * * Collects print jobs and processes them in optimized batches. * Features: * - Small job merging: consecutive jobs < smallJobThreshold bytes are combined * - Interval timeout auto-flush: flushes pending jobs if no new jobs arrive within timeout * - Unified cut: optionally appends a single cut command after batch merge * - Priority sorting: higher priority jobs are processed first */ export declare class BatchPrintManager extends EventEmitter { protected readonly logger: { debug: (message: string, ...args: unknown[]) => void; info: (message: string, ...args: unknown[]) => void; warn: (message: string, ...args: unknown[]) => void; error: (message: string, ...args: unknown[]) => void; }; private readonly jobs; private config; private isProcessing; private watchTimer; private waitFired; private flushFired; private pendingBytes; private stats; /** * Last job timestamp for interval timeout tracking */ private lastJobAt; /** * Creates a new BatchPrintManager instance * * @param config - Optional configuration overrides */ constructor(config?: Partial); /** * Add a job to the batch queue * * @param data - Print data * @param priority - Job priority (higher = more urgent) * @param metadata - Optional metadata * @returns Job ID */ addJob(data: Uint8Array, priority?: number, metadata?: Record): string; /** * Add multiple jobs at once * * @param jobs - Array of job data with optional priority and metadata * @returns Array of job IDs */ addJobs(jobs: Array<{ data: Uint8Array; priority?: number; metadata?: Record; }>): string[]; /** * Cancel a job by ID * * @param id - Job ID to cancel * @returns true if cancelled, false if not found */ cancelJob(id: string): boolean; /** * Cancel all jobs */ cancelAll(): void; /** * Get pending job count */ get pendingCount(): number; /** * Get pending jobs * * @returns Copy of pending jobs array */ getPendingJobs(): BatchJob[]; /** * Get current statistics * * @returns Copy of current stats */ getStats(): BatchStats; /** * Update configuration * * @param updates - Configuration fields to update */ updateConfig(updates: Partial): void; /** * Process the current batch * * @param processor - Function to send batch data to printer * @returns Number of jobs processed */ processBatch(processor: (data: Uint8Array) => Promise): Promise; /** * Prepare batch from pending jobs */ private prepareBatch; /** * Merge multiple jobs into a single buffer. * * Features: * - Consecutive small jobs (< smallJobThreshold bytes) are combined into a single job * - Applies unified cut command after all jobs if configured * * @param jobs - Jobs to merge * @returns Merged data with metadata about the merge operation */ private mergeJobs; /** * Merge consecutive small jobs (< smallJobThreshold bytes) into combined buffers * * Small jobs that arrive consecutively are combined to reduce Bluetooth overhead. * The merge preserves job boundaries conceptually but sends as a single chunk. * * @param jobs - Input jobs * @returns Jobs after merging consecutive small ones */ private mergeConsecutiveSmallJobs; /** * Create a merged job from multiple small buffers * * @param buffers - Array of small buffers to combine * @param priority - Priority of the merged job * @param addedAt - Timestamp of the first job in the merge * @returns Merged BatchJob */ private createMergedJob; /** * Concatenate multiple Uint8Array buffers into one * * @param buffers - Array of buffers to concatenate * @returns Combined buffer */ private concatBuffers; /** * Check if we should process immediately * Uses cached pendingBytes instead of reduce() */ private shouldProcessImmediately; /** * Restart the unified watch timer after a job is added. * Combines the behavior of waitTimer, flushTimer, and autoProcessTimer * into a single timer with dynamic interval recalculation. */ private restartWatchTimer; /** * Recalculate and schedule the next watch timer fire. * Selects the minimum delay among all configured timer sources. * One-shot timers (wait, flush) are skipped once they have fired. */ private updateWatchTimer; /** * Clear the unified watch timer */ private clearWatchTimer; /** * Binary search to find the insertion index for a new job. * Maintains descending priority order (highest priority first). * * @param priority - Priority of the job to insert * @returns Index where the new job should be inserted */ private findInsertIndex; /** * Generate unique job ID */ private generateId; /** * Reset statistics */ resetStats(): void; /** * Destroy the manager */ destroy(): void; } export declare const batchPrintManager: BatchPrintManager;