diff --git a/cmd/poster/main.go b/cmd/poster/main.go index bf1e850..c663c1b 100644 --- a/cmd/poster/main.go +++ b/cmd/poster/main.go @@ -9,6 +9,7 @@ import ( "log" "os" "runtime" + "strings" "github.com/adcondev/poster/pkg/composer" "github.com/adcondev/poster/pkg/connection" @@ -107,7 +108,8 @@ func parseArgs() *Config { flag.StringVar(&config.NetworkAddr, "network", "", "Network address (e.g., 192.168.1.100:9100)") flag.StringVar(&config.SerialPort, "serial", "", "Serial port (e.g., COM1, /dev/ttyUSB0)") flag.IntVar(&config.BaudRate, "baud", 9600, "Serial baud rate") - flag.StringVar(&config.OutputFile, "output", "output.prn", "Output file for file type") + flag.StringVar(&config.OutputFile, "output", "", "Output file path for file connection mode (-t file)") + flag.StringVar(&config.OutputFile, "o", "", "Output file path (shorthand)") flag.StringVar(&config.PreviewPath, "preview", "", "Render visual PNG receipt preview to file (no hardware printer required)") flag.BoolVar(&config.DryRun, "dry-run", false, "Validate without printing") @@ -130,7 +132,7 @@ func parseArgs() *Config { config.PrinterName = args[1] } - if !config.DryRun && config.PreviewPath == "" && config.PrinterName == "" && config.ConnectionType == win { + if !config.DryRun && config.PreviewPath == "" && config.PrinterName == "" && strings.ToLower(config.ConnectionType) == win { config.PrinterName = detectPrinter() } @@ -287,11 +289,14 @@ func executePrint(config *Config) error { return emuPrinter.SavePNG(config.PreviewPath) } - printerName, err := getPrinterNameFromDocument(config, jsonData) - if err != nil && config.ConnectionType == win { - return err + connType := strings.ToLower(config.ConnectionType) + if connType == win && config.PrinterName == "" { + printerName, err := getPrinterNameFromDocument(config, jsonData) + if err != nil { + return err + } + config.PrinterName = printerName } - config.PrinterName = printerName conn, err := createConnection(config) if err != nil { diff --git a/cmd/poster/parsing.go b/cmd/poster/parsing.go index 30e011b..9dacd53 100644 --- a/cmd/poster/parsing.go +++ b/cmd/poster/parsing.go @@ -7,10 +7,12 @@ import ( "log" "os" "path/filepath" + "strings" "github.com/adcondev/poster/internal/load" "github.com/adcondev/poster/pkg/constants" "github.com/adcondev/poster/pkg/document/schema" + "github.com/adcondev/poster/pkg/profile" ) func loadJSON(filePath string) ([]byte, error) { @@ -147,5 +149,46 @@ func getPrinterNameFromDocument(config *Config, jsonData []byte) (string, error) return detected, nil } - return "", fmt.Errorf("no printer specified and none found in JSON profile. model") + return "", fmt.Errorf("no printer specified and none found in JSON profile.model") } + +func createProfile(doc *schema.Document) *profile.Escpos { + var prof *profile.Escpos + + // Select profile based on paper width or model + if doc.Profile.Model != "" { + switch strings.ToLower(doc.Profile.Model) { + case "80mm ec-pm-80250", "ec-pm-80250": + prof = profile.CreateECPM80250() + case "58mm pt-210", "pt-210": + prof = profile.CreatePt210() + case "58mm gp-58n", "gp-58n": + prof = profile.CreateGP58N() + default: + if doc.Profile.PaperWidth >= 80 { + prof = profile.CreateProfile80mm() + } else { + prof = profile.CreateProfile58mm() + } + } + } else { + // Default based on paper width + if doc.Profile.PaperWidth >= 80 { + prof = profile.CreateProfile80mm() + } else { + prof = profile.CreateProfile58mm() + } + } + + // Apply JSON overrides + if doc.Profile.Model != "" { + prof.Model = doc.Profile.Model + } + if doc.Profile.DPI > 0 { + prof.DPI = doc.Profile.DPI + } + prof.HasQR = doc.Profile.HasQR + + return prof +} + diff --git a/cmd/poster/parsing_test.go b/cmd/poster/parsing_test.go index d702216..7cbbae0 100644 --- a/cmd/poster/parsing_test.go +++ b/cmd/poster/parsing_test.go @@ -1,11 +1,15 @@ package main import ( + "bytes" + "context" "encoding/json" + "net" "os" "path/filepath" "strings" "testing" + "time" "github.com/adcondev/poster/pkg/constants" "github.com/adcondev/poster/pkg/document/schema" @@ -190,3 +194,168 @@ func TestValidateJSON(t *testing.T) { } }) } + +const validTicketJSON = `{ + "version": "1.0", + "profile": { + "model": "POS-80", + "paper_width": 80, + "dpi": 203 + }, + "commands": [ + { + "type": "text", + "data": { + "content": {"text": "Receipt Header"} + } + }, + { + "type": "cut", + "data": { + "mode": "partial", + "feed": 0 + } + } + ] +}` + +func TestExecutePrint_Preview(t *testing.T) { + tempDir := t.TempDir() + jsonPath := filepath.Join(tempDir, "ticket.json") + if err := os.WriteFile(jsonPath, []byte(validTicketJSON), 0600); err != nil { + t.Fatalf("Failed to write ticket json: %v", err) + } + + previewPath := filepath.Join(tempDir, "preview.png") + cfg := &Config{ + JSONFile: jsonPath, + PreviewPath: previewPath, + } + + if err := executePrint(cfg); err != nil { + t.Fatalf("executePrint preview failed: %v", err) + } + + fi, err := os.Stat(previewPath) + if err != nil { + t.Fatalf("failed to stat preview png: %v", err) + } + if fi.Size() == 0 { + t.Errorf("expected non-empty preview file, got 0 bytes") + } + + data, err := os.ReadFile(filepath.Clean(previewPath)) + if err != nil { + t.Fatalf("failed to read preview png: %v", err) + } + if len(data) < 8 || string(data[:8]) != "\x89PNG\r\n\x1a\n" { + t.Errorf("preview file does not have valid PNG header") + } +} + +func TestExecutePrint_FileOutput(t *testing.T) { + tempDir := t.TempDir() + jsonPath := filepath.Join(tempDir, "ticket.json") + if err := os.WriteFile(jsonPath, []byte(validTicketJSON), 0600); err != nil { + t.Fatalf("Failed to write ticket json: %v", err) + } + + binPath := filepath.Join(tempDir, "receipt.bin") + cfg := &Config{ + JSONFile: jsonPath, + ConnectionType: "file", + OutputFile: binPath, + } + + if err := executePrint(cfg); err != nil { + t.Fatalf("executePrint file output failed: %v", err) + } + + fi, err := os.Stat(binPath) + if err != nil { + t.Fatalf("failed to stat output bin file: %v", err) + } + if fi.Size() == 0 { + t.Errorf("expected non-empty bin output file, got 0 bytes") + } + + data, err := os.ReadFile(filepath.Clean(binPath)) + if err != nil { + t.Fatalf("failed to read bin output: %v", err) + } + if !strings.Contains(string(data), "Receipt Header") { + t.Errorf("expected bin output to contain 'Receipt Header', got %q", string(data)) + } +} + +func TestExecutePrint_TCP(t *testing.T) { + tempDir := t.TempDir() + jsonPath := filepath.Join(tempDir, "ticket.json") + if err := os.WriteFile(jsonPath, []byte(validTicketJSON), 0600); err != nil { + t.Fatalf("Failed to write ticket json: %v", err) + } + + var lc net.ListenConfig + ln, err := lc.Listen(context.Background(), "tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("failed to listen on local tcp: %v", err) + } + defer func() { + _ = ln.Close() + }() + + addr := ln.Addr().String() + + receivedCh := make(chan []byte, 1) + errCh := make(chan error, 1) + + go func() { + conn, err := ln.Accept() + if err != nil { + errCh <- err + return + } + defer func() { + _ = conn.Close() + }() + + var buf bytes.Buffer + tmp := make([]byte, 1024) + for { + _ = conn.SetReadDeadline(time.Now().Add(2 * time.Second)) + n, err := conn.Read(tmp) + if n > 0 { + buf.Write(tmp[:n]) + } + if err != nil { + break + } + } + receivedCh <- buf.Bytes() + }() + + cfg := &Config{ + JSONFile: jsonPath, + ConnectionType: "tcp", + PrinterName: addr, + } + + if err := executePrint(cfg); err != nil { + t.Fatalf("executePrint tcp failed: %v", err) + } + + select { + case err := <-errCh: + t.Fatalf("tcp server error: %v", err) + case received := <-receivedCh: + if len(received) == 0 { + t.Errorf("expected non-empty bytes over tcp") + } + if !strings.Contains(string(received), "Receipt Header") { + t.Errorf("expected tcp data to contain 'Receipt Header', got %q", string(received)) + } + case <-time.After(5 * time.Second): + t.Fatal("timed out waiting for tcp transmission") + } +} + diff --git a/cmd/poster/printing.go b/cmd/poster/printing.go index 2de7e53..3dca4f4 100644 --- a/cmd/poster/printing.go +++ b/cmd/poster/printing.go @@ -10,8 +10,6 @@ import ( "strings" "github.com/adcondev/poster/pkg/connection" - "github.com/adcondev/poster/pkg/document/schema" - "github.com/adcondev/poster/pkg/profile" ) func detectPrinter() string { @@ -76,17 +74,24 @@ func createConnection(config *Config) (connection.Connector, error) { if runtime.GOOS != win { return nil, errors.New("windows connection type requires Windows OS") } - if config.PrinterName == "" { + printerName := config.PrinterName + if printerName == "" { + printerName = detectPrinter() + } + if printerName == "" { return nil, fmt.Errorf("printer name required for Windows connection") } - return connection.NewWindowsPrintConnector(config.PrinterName) + return connection.NewWindowsPrintConnector(printerName) - case "network": - if config.NetworkAddr == "" { - return nil, fmt.Errorf("network address required") + case "network", "tcp": + target := config.PrinterName + if target == "" { + target = config.NetworkAddr } - // TODO: Implement when available in library - return nil, fmt.Errorf("network connection not yet implemented") + if target == "" { + return nil, fmt.Errorf("printer name or address required for network/tcp connection") + } + return connection.NewTCPConnector(target) case "serial": if config.SerialPort == "" { @@ -96,50 +101,16 @@ func createConnection(config *Config) (connection.Connector, error) { return nil, fmt.Errorf("serial connection not yet implemented") case "file": - // TODO: Implement file output connector - return nil, fmt.Errorf("file output not yet implemented") - - default: - return nil, fmt.Errorf("unknown connection type: %s", config.ConnectionType) - } -} - -func createProfile(doc *schema.Document) *profile.Escpos { - var prof *profile.Escpos - - // Select profile based on paper width or model - if doc.Profile.Model != "" { - switch strings.ToLower(doc.Profile.Model) { - case "80mm ec-pm-80250", "ec-pm-80250": - prof = profile.CreateECPM80250() - case "58mm pt-210", "pt-210": - prof = profile.CreatePt210() - case "58mm gp-58n", "gp-58n": - prof = profile.CreateGP58N() - default: - if doc.Profile.PaperWidth >= 80 { - prof = profile.CreateProfile80mm() - } else { - prof = profile.CreateProfile58mm() - } + targetPath := config.OutputFile + if targetPath == "" { + targetPath = config.PrinterName } - } else { - // Default based on paper width - if doc.Profile.PaperWidth >= 80 { - prof = profile.CreateProfile80mm() - } else { - prof = profile.CreateProfile58mm() + if targetPath == "" { + return nil, fmt.Errorf("output file path required for file connection (use -output or -p)") } - } + return connection.NewFileConnector(targetPath) - // Apply JSON overrides - if doc.Profile.Model != "" { - prof.Model = doc.Profile.Model - } - if doc.Profile.DPI > 0 { - prof.DPI = doc.Profile.DPI + default: + return nil, fmt.Errorf("unknown connection type: %s", config.ConnectionType) } - prof.HasQR = doc.Profile.HasQR - - return prof } diff --git a/cmd/poster/printing_stub.go b/cmd/poster/printing_stub.go index bc201b1..212f0b2 100644 --- a/cmd/poster/printing_stub.go +++ b/cmd/poster/printing_stub.go @@ -4,21 +4,48 @@ package main import ( "fmt" + "strings" "github.com/adcondev/poster/pkg/connection" - "github.com/adcondev/poster/pkg/document/schema" - "github.com/adcondev/poster/pkg/profile" ) func detectPrinter() string { return "" } -func createConnection(_ *Config) (connection.Connector, error) { - return nil, fmt.Errorf("printing is only supported on Windows") -} +func createConnection(config *Config) (connection.Connector, error) { + switch strings.ToLower(config.ConnectionType) { + case win: + return nil, fmt.Errorf("windows spooler connection is only supported on Windows (use -t tcp, -t file, --preview, or --dry-run on this OS)") + + case "network", "tcp": + target := config.PrinterName + if target == "" { + target = config.NetworkAddr + } + if target == "" { + return nil, fmt.Errorf("printer name or address required for network/tcp connection") + } + return connection.NewTCPConnector(target) + + case "serial": + if config.SerialPort == "" { + return nil, fmt.Errorf("serial port required") + } + return nil, fmt.Errorf("serial connection not yet implemented") -func createProfile(_ *schema.Document) *profile.Escpos { - // Retornar un perfil dummy o nil para que compile - return &profile.Escpos{} + case "file": + targetPath := config.OutputFile + if targetPath == "" { + targetPath = config.PrinterName + } + if targetPath == "" { + return nil, fmt.Errorf("output file path required for file connection (use -output or -p)") + } + return connection.NewFileConnector(targetPath) + + default: + return nil, fmt.Errorf("unknown connection type: %s", config.ConnectionType) + } } + diff --git a/pkg/connection/buffer_connector.go b/pkg/connection/buffer_connector.go new file mode 100644 index 0000000..a020d00 --- /dev/null +++ b/pkg/connection/buffer_connector.go @@ -0,0 +1,94 @@ +package connection + +import ( + "bytes" + "errors" + "sync" +) + +// BufferConnector is a thread-safe in-memory Connector for testing and previewing. +type BufferConnector struct { + buf bytes.Buffer + mu sync.RWMutex + closed bool +} + +// NewBufferConnector creates a new in-memory buffer connector. +func NewBufferConnector() *BufferConnector { + return &BufferConnector{} +} + +// Write appends data to the internal buffer. Returns an error if the connector is closed. +func (b *BufferConnector) Write(data []byte) (int, error) { + b.mu.Lock() + defer b.mu.Unlock() + + if b.closed { + return 0, errors.New("buffer connector is closed") + } + + if len(data) == 0 { + return 0, nil + } + + return b.buf.Write(data) +} + +// Close marks the buffer connector as closed. It is idempotent. +func (b *BufferConnector) Close() error { + b.mu.Lock() + defer b.mu.Unlock() + + b.closed = true + return nil +} + +// Bytes returns a safe copy of the buffered bytes. +func (b *BufferConnector) Bytes() []byte { + b.mu.RLock() + defer b.mu.RUnlock() + + raw := b.buf.Bytes() + if len(raw) == 0 { + return nil + } + cp := make([]byte, len(raw)) + copy(cp, raw) + return cp +} + +// String returns the contents of the buffer as a string. +func (b *BufferConnector) String() string { + b.mu.RLock() + defer b.mu.RUnlock() + + return b.buf.String() +} + +// Len returns the number of bytes written to the buffer. +func (b *BufferConnector) Len() int { + b.mu.RLock() + defer b.mu.RUnlock() + + return b.buf.Len() +} + +// Reset clears the buffer and re-opens the connector if it was closed. +func (b *BufferConnector) Reset() { + b.mu.Lock() + defer b.mu.Unlock() + + b.buf.Reset() + b.closed = false +} + +// Closed returns true if the buffer connector has been closed. +func (b *BufferConnector) Closed() bool { + b.mu.RLock() + defer b.mu.RUnlock() + + return b.closed +} + +// Ensure BufferConnector implements Connector. +var _ Connector = (*BufferConnector)(nil) diff --git a/pkg/connection/buffer_connector_test.go b/pkg/connection/buffer_connector_test.go new file mode 100644 index 0000000..cc0c8b4 --- /dev/null +++ b/pkg/connection/buffer_connector_test.go @@ -0,0 +1,122 @@ +package connection + +import ( + "bytes" + "fmt" + "sync" + "testing" +) + +func TestBufferConnector_Basic(t *testing.T) { + b := NewBufferConnector() + if b.Closed() { + t.Error("expected new buffer connector to be open") + } + if b.Len() != 0 { + t.Errorf("expected len 0, got %d", b.Len()) + } + if b.Bytes() != nil { + t.Errorf("expected nil bytes for empty buffer, got %v", b.Bytes()) + } + if b.String() != "" { + t.Errorf("expected empty string, got %q", b.String()) + } + + // Write empty slice + n, err := b.Write([]byte{}) + if err != nil || n != 0 { + t.Errorf("empty Write() = (%d, %v), want (0, nil)", n, err) + } + + // Write data + msg := []byte("hello thermal buffer") + n, err = b.Write(msg) + if err != nil || n != len(msg) { + t.Fatalf("Write() = (%d, %v), want (%d, nil)", n, err, len(msg)) + } + + if b.Len() != len(msg) { + t.Errorf("expected len %d, got %d", len(msg), b.Len()) + } + if !bytes.Equal(b.Bytes(), msg) { + t.Errorf("Bytes() = %v, want %v", b.Bytes(), msg) + } + if b.String() != string(msg) { + t.Errorf("String() = %q, want %q", b.String(), string(msg)) + } + + // Verify Bytes() returns an independent copy + cp := b.Bytes() + cp[0] = 'X' + if b.Bytes()[0] == 'X' { + t.Error("Bytes() did not return an independent copy") + } + + // Close + if err := b.Close(); err != nil { + t.Errorf("Close() error = %v", err) + } + if !b.Closed() { + t.Error("expected Closed() to be true") + } + + // Idempotent second Close + if err := b.Close(); err != nil { + t.Errorf("second Close() error = %v", err) + } + + // Write after close + _, err = b.Write([]byte("more data")) + if err == nil { + t.Error("expected error writing to closed buffer connector, got nil") + } + + // Reset re-opens the connector and clears buffer + b.Reset() + if b.Closed() { + t.Error("expected connector to be open after Reset()") + } + if b.Len() != 0 { + t.Errorf("expected len 0 after Reset(), got %d", b.Len()) + } + + // Can write again after Reset + _, err = b.Write([]byte("reopened")) + if err != nil { + t.Fatalf("Write after Reset failed: %v", err) + } + if b.String() != "reopened" { + t.Errorf("String() = %q, want 'reopened'", b.String()) + } +} + +func TestBufferConnector_ConcurrentWrites(t *testing.T) { + b := NewBufferConnector() + const numGoroutines = 20 + const writesPerGoroutine = 50 + + var wg sync.WaitGroup + wg.Add(numGoroutines) + + for i := 0; i < numGoroutines; i++ { + go func(id int) { + defer wg.Done() + for j := 0; j < writesPerGoroutine; j++ { + data := []byte(fmt.Sprintf("[%d:%d]", id, j)) + _, err := b.Write(data) + if err != nil { + t.Errorf("concurrent write error: %v", err) + } + _ = b.Len() + _ = b.Bytes() + _ = b.String() + } + }(i) + } + + wg.Wait() + + if b.Len() == 0 { + t.Error("expected non-zero length after concurrent writes") + } +} diff --git a/pkg/connection/file_connector.go b/pkg/connection/file_connector.go new file mode 100644 index 0000000..71cca38 --- /dev/null +++ b/pkg/connection/file_connector.go @@ -0,0 +1,88 @@ +package connection + +import ( + "errors" + "fmt" + "os" + "path/filepath" + "strings" + "sync" +) + +var ( + // ErrClosedConnector is returned when attempting an operation on a closed connector. + ErrClosedConnector = errors.New("connector is closed") + + // ErrEmptyPath is returned when the provided file path is empty. + ErrEmptyPath = errors.New("file path cannot be empty") +) + +var _ Connector = (*FileConnector)(nil) + +// FileConnector writes raw ESC/POS output to a file or device node. +type FileConnector struct { + file *os.File + path string + closed bool + mu sync.Mutex +} + +// NewFileConnector creates a new FileConnector at the specified path. +func NewFileConnector(path string) (*FileConnector, error) { + if strings.TrimSpace(path) == "" { + return nil, ErrEmptyPath + } + + cleanPath := filepath.Clean(path) + file, err := os.OpenFile(cleanPath, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) + if err != nil { + return nil, fmt.Errorf("failed to open file %s: %w", cleanPath, err) + } + + return &FileConnector{ + file: file, + path: cleanPath, + }, nil +} + +// Write writes data bytes to the file connector. +func (c *FileConnector) Write(data []byte) (int, error) { + c.mu.Lock() + defer c.mu.Unlock() + + if c.closed { + return 0, ErrClosedConnector + } + if len(data) == 0 { + return 0, nil + } + + n, err := c.file.Write(data) + if err != nil { + return n, fmt.Errorf("failed to write to file: %w", err) + } + return n, nil +} + +// Close closes the file connector idempotently. +func (c *FileConnector) Close() error { + c.mu.Lock() + defer c.mu.Unlock() + + if c.closed { + return nil + } + c.closed = true + + if err := c.file.Close(); err != nil { + return fmt.Errorf("failed to close file: %w", err) + } + return nil +} + +// Path returns the cleaned file path of the connector. +func (c *FileConnector) Path() string { + c.mu.Lock() + defer c.mu.Unlock() + return c.path +} diff --git a/pkg/connection/file_connector_test.go b/pkg/connection/file_connector_test.go new file mode 100644 index 0000000..83cd2a3 --- /dev/null +++ b/pkg/connection/file_connector_test.go @@ -0,0 +1,112 @@ +package connection_test + +import ( + "errors" + "os" + "path/filepath" + "testing" + + "github.com/adcondev/poster/pkg/connection" +) + +func TestFileConnector_WriteAndVerify(t *testing.T) { + tempDir := t.TempDir() + filePath := filepath.Join(tempDir, "test_output.bin") + + conn, err := connection.NewFileConnector(filePath) + if err != nil { + t.Fatalf("NewFileConnector failed: %v", err) + } + + if conn.Path() != filePath { + t.Errorf("Path() = %q, want %q", conn.Path(), filePath) + } + + testData := []byte{0x1B, 0x40, 0x48, 0x65, 0x6C, 0x6C, 0x6F, 0x0A} // ESC @ + "Hello\n" + + // Write empty slice + n, err := conn.Write([]byte{}) + if err != nil { + t.Errorf("Write([]byte{}) error: %v", err) + } + if n != 0 { + t.Errorf("Write([]byte{}) = %d, want 0", n) + } + + // Write test data + n, err = conn.Write(testData) + if err != nil { + t.Fatalf("Write failed: %v", err) + } + if n != len(testData) { + t.Fatalf("Write returned %d, want %d", n, len(testData)) + } + + if err := conn.Close(); err != nil { + t.Fatalf("Close failed: %v", err) + } + + // Verify file content on disk + content, err := os.ReadFile(filepath.Clean(filePath)) + if err != nil { + t.Fatalf("ReadFile failed: %v", err) + } + if string(content) != string(testData) { + t.Errorf("file content = %v, want %v", content, testData) + } +} + +func TestFileConnector_EmptyPath(t *testing.T) { + testCases := []string{ + "", + " ", + "\t\n", + } + + for _, tc := range testCases { + conn, err := connection.NewFileConnector(tc) + if err == nil { + if conn != nil { + _ = conn.Close() + } + t.Errorf("NewFileConnector(%q) expected error, got nil", tc) + } + if !errors.Is(err, connection.ErrEmptyPath) { + t.Errorf("NewFileConnector(%q) error = %v, want %v", tc, err, connection.ErrEmptyPath) + } + } +} + +func TestFileConnector_IdempotentCloseAndWriteAfterClose(t *testing.T) { + tempDir := t.TempDir() + filePath := filepath.Join(tempDir, "idempotent.bin") + + conn, err := connection.NewFileConnector(filePath) + if err != nil { + t.Fatalf("NewFileConnector failed: %v", err) + } + + // First close + if err := conn.Close(); err != nil { + t.Fatalf("First Close failed: %v", err) + } + + // Second close should be idempotent + if err := conn.Close(); err != nil { + t.Errorf("Second Close should be idempotent, got: %v", err) + } + + // Third close + if err := conn.Close(); err != nil { + t.Errorf("Third Close should be idempotent, got: %v", err) + } + + // Write after close should fail + _, err = conn.Write([]byte{0x01, 0x02}) + if err == nil { + t.Fatal("Write after Close expected error, got nil") + } + if !errors.Is(err, connection.ErrClosedConnector) { + t.Errorf("Write after Close error = %v, want %v", err, connection.ErrClosedConnector) + } +} diff --git a/pkg/connection/printer_filter.go b/pkg/connection/printer_filter.go new file mode 100644 index 0000000..572016f --- /dev/null +++ b/pkg/connection/printer_filter.go @@ -0,0 +1,346 @@ +package connection + +import ( + "fmt" + "strings" +) + +// Printer type string constants. +const ( + // PrinterTypeThermal indicates a thermal ESC/POS or receipt printer. + PrinterTypeThermal = "thermal" + // PrinterTypeVirtual indicates a virtual or software printer (PDF, XPS, etc.). + PrinterTypeVirtual = "virtual" + // PrinterTypeNetwork indicates a network-connected printer. + PrinterTypeNetwork = "network" + // PrinterTypeUSB indicates a USB-connected printer. + PrinterTypeUSB = "usb" + // PrinterTypeSerial indicates a serial/parallel connected printer. + PrinterTypeSerial = "serial" + // PrinterTypeUnknown indicates an unknown printer type. + PrinterTypeUnknown = "unknown" +) + +// Printer status flags (from winspool.h) +const ( + // PrinterStatusPaused indicates the printer is paused. + PrinterStatusPaused uint32 = 0x00000001 + // PrinterStatusError indicates the printer is in an error state. + PrinterStatusError uint32 = 0x00000002 + // PrinterStatusPendingDeletion indicates the printer is pending deletion. + PrinterStatusPendingDeletion uint32 = 0x00000004 + // PrinterStatusPaperJam indicates paper is jammed in the printer. + PrinterStatusPaperJam uint32 = 0x00000008 + // PrinterStatusPaperOut indicates the printer is out of paper. + PrinterStatusPaperOut uint32 = 0x00000010 + // PrinterStatusManualFeed indicates the printer is in manual feed mode. + PrinterStatusManualFeed uint32 = 0x00000020 + // PrinterStatusPaperProblem indicates a paper problem in the printer. + PrinterStatusPaperProblem uint32 = 0x00000040 + // PrinterStatusOffline indicates the printer is offline. + PrinterStatusOffline uint32 = 0x00000080 + // PrinterStatusIOActive indicates the printer I/O is active. + PrinterStatusIOActive uint32 = 0x00000100 + // PrinterStatusBusy indicates the printer is busy. + PrinterStatusBusy uint32 = 0x00000200 + // PrinterStatusPrinting indicates the printer is currently printing. + PrinterStatusPrinting uint32 = 0x00000400 + // PrinterStatusOutputBinFull indicates the output bin is full. + PrinterStatusOutputBinFull uint32 = 0x00000800 + // PrinterStatusNotAvailable indicates the printer is not available. + PrinterStatusNotAvailable uint32 = 0x00001000 + // PrinterStatusWaiting indicates the printer is waiting. + PrinterStatusWaiting uint32 = 0x00002000 + // PrinterStatusProcessing indicates the printer is processing a job. + PrinterStatusProcessing uint32 = 0x00004000 + // PrinterStatusInitializing indicates the printer is initializing. + PrinterStatusInitializing uint32 = 0x00008000 + // PrinterStatusWarmingUp indicates the printer is warming up. + PrinterStatusWarmingUp uint32 = 0x00010000 + // PrinterStatusTonerLow indicates the toner is low. + PrinterStatusTonerLow uint32 = 0x00020000 + // PrinterStatusNoToner indicates the printer has no toner. + PrinterStatusNoToner uint32 = 0x00040000 + // PrinterStatusPagePunt indicates the printer cannot print the current page. + PrinterStatusPagePunt uint32 = 0x00080000 + // PrinterStatusUserIntervention indicates user intervention is required. + PrinterStatusUserIntervention uint32 = 0x00100000 + // PrinterStatusOutOfMemory indicates the printer is out of memory. + PrinterStatusOutOfMemory uint32 = 0x00200000 + // PrinterStatusDoorOpen indicates the printer door is open. + PrinterStatusDoorOpen uint32 = 0x00400000 + // PrinterStatusServerUnknown indicates the printer server is unknown. + PrinterStatusServerUnknown uint32 = 0x00800000 + // PrinterStatusPowerSave indicates the printer is in power save mode. + PrinterStatusPowerSave uint32 = 0x01000000 +) + +// Windows winspool.h PRINTER_STATUS_* aliases +// +//nolint:revive // Windows winspool.h API compatibility constants +const ( + // PRINTER_STATUS_PAUSED indicates the printer is paused. + PRINTER_STATUS_PAUSED = PrinterStatusPaused + // PRINTER_STATUS_ERROR indicates the printer is in an error state. + PRINTER_STATUS_ERROR = PrinterStatusError + // PRINTER_STATUS_PENDING_DELETION indicates the printer is pending deletion. + PRINTER_STATUS_PENDING_DELETION = PrinterStatusPendingDeletion + // PRINTER_STATUS_PAPER_JAM indicates paper is jammed in the printer. + PRINTER_STATUS_PAPER_JAM = PrinterStatusPaperJam + // PRINTER_STATUS_PAPER_OUT indicates the printer is out of paper. + PRINTER_STATUS_PAPER_OUT = PrinterStatusPaperOut + // PRINTER_STATUS_MANUAL_FEED indicates the printer is in manual feed mode. + PRINTER_STATUS_MANUAL_FEED = PrinterStatusManualFeed + // PRINTER_STATUS_PAPER_PROBLEM indicates a paper problem in the printer. + PRINTER_STATUS_PAPER_PROBLEM = PrinterStatusPaperProblem + // PRINTER_STATUS_OFFLINE indicates the printer is offline. + PRINTER_STATUS_OFFLINE = PrinterStatusOffline + // PRINTER_STATUS_IO_ACTIVE indicates the printer I/O is active. + PRINTER_STATUS_IO_ACTIVE = PrinterStatusIOActive + // PRINTER_STATUS_BUSY indicates the printer is busy. + PRINTER_STATUS_BUSY = PrinterStatusBusy + // PRINTER_STATUS_PRINTING indicates the printer is currently printing. + PRINTER_STATUS_PRINTING = PrinterStatusPrinting + // PRINTER_STATUS_OUTPUT_BIN_FULL indicates the output bin is full. + PRINTER_STATUS_OUTPUT_BIN_FULL = PrinterStatusOutputBinFull + // PRINTER_STATUS_NOT_AVAILABLE indicates the printer is not available. + PRINTER_STATUS_NOT_AVAILABLE = PrinterStatusNotAvailable + // PRINTER_STATUS_WAITING indicates the printer is waiting. + PRINTER_STATUS_WAITING = PrinterStatusWaiting + // PRINTER_STATUS_PROCESSING indicates the printer is processing a job. + PRINTER_STATUS_PROCESSING = PrinterStatusProcessing + // PRINTER_STATUS_INITIALIZING indicates the printer is initializing. + PRINTER_STATUS_INITIALIZING = PrinterStatusInitializing + // PRINTER_STATUS_WARMING_UP indicates the printer is warming up. + PRINTER_STATUS_WARMING_UP = PrinterStatusWarmingUp + // PRINTER_STATUS_TONER_LOW indicates the toner is low. + PRINTER_STATUS_TONER_LOW = PrinterStatusTonerLow + // PRINTER_STATUS_NO_TONER indicates the printer has no toner. + PRINTER_STATUS_NO_TONER = PrinterStatusNoToner + // PRINTER_STATUS_PAGE_PUNT indicates the printer cannot print the current page. + PRINTER_STATUS_PAGE_PUNT = PrinterStatusPagePunt + // PRINTER_STATUS_USER_INTERVENTION indicates user intervention is required. + PRINTER_STATUS_USER_INTERVENTION = PrinterStatusUserIntervention + // PRINTER_STATUS_OUT_OF_MEMORY indicates the printer is out of memory. + PRINTER_STATUS_OUT_OF_MEMORY = PrinterStatusOutOfMemory + // PRINTER_STATUS_DOOR_OPEN indicates the printer door is open. + PRINTER_STATUS_DOOR_OPEN = PrinterStatusDoorOpen + // PRINTER_STATUS_SERVER_UNKNOWN indicates the printer server is unknown. + PRINTER_STATUS_SERVER_UNKNOWN = PrinterStatusServerUnknown + // PRINTER_STATUS_POWER_SAVE indicates the printer is in power save mode. + PRINTER_STATUS_POWER_SAVE = PrinterStatusPowerSave +) + +// Printer attribute flags (from winspool.h) +const ( + // PrinterAttributeQueued indicates print jobs are queued. + PrinterAttributeQueued uint32 = 0x00000001 + // PrinterAttributeDirect indicates jobs are sent directly to the printer. + PrinterAttributeDirect uint32 = 0x00000002 + // PrinterAttributeDefault indicates this is the default printer. + PrinterAttributeDefault uint32 = 0x00000004 + // PrinterAttributeShared indicates the printer is shared. + PrinterAttributeShared uint32 = 0x00000008 + // PrinterAttributeNetwork indicates the printer is a network printer. + PrinterAttributeNetwork uint32 = 0x00000010 + // PrinterAttributeHidden indicates the printer is hidden. + PrinterAttributeHidden uint32 = 0x00000020 + // PrinterAttributeLocal indicates the printer is directly connected. + PrinterAttributeLocal uint32 = 0x00000040 + // PrinterAttributeEnableDevq indicates devquery is enabled. + PrinterAttributeEnableDevq uint32 = 0x00000080 + // PrinterAttributeKeepprintedjobs indicates printed jobs should be kept. + PrinterAttributeKeepprintedjobs uint32 = 0x00000100 + // PrinterAttributeDoCompleteFirst indicates jobs should be completed before others. + PrinterAttributeDoCompleteFirst uint32 = 0x00000200 + // PrinterAttributeWorkOffline indicates the printer is configured to work offline. + PrinterAttributeWorkOffline uint32 = 0x00000400 + // PrinterAttributeEnableBidi indicates bidirectional communication is enabled. + PrinterAttributeEnableBidi uint32 = 0x00000800 + // PrinterAttributeRawOnly indicates only raw data type is accepted. + PrinterAttributeRawOnly uint32 = 0x00001000 + // PrinterAttributePublished indicates the printer is published in directory service. + PrinterAttributePublished uint32 = 0x00002000 +) + +// Windows winspool.h PRINTER_ATTRIBUTE_* aliases +// +//nolint:revive // Windows winspool.h API compatibility constants +const ( + // PRINTER_ATTRIBUTE_QUEUED indicates print jobs are queued. + PRINTER_ATTRIBUTE_QUEUED = PrinterAttributeQueued + // PRINTER_ATTRIBUTE_DIRECT indicates jobs are sent directly to the printer. + PRINTER_ATTRIBUTE_DIRECT = PrinterAttributeDirect + // PRINTER_ATTRIBUTE_DEFAULT indicates this is the default printer. + PRINTER_ATTRIBUTE_DEFAULT = PrinterAttributeDefault + // PRINTER_ATTRIBUTE_SHARED indicates the printer is shared. + PRINTER_ATTRIBUTE_SHARED = PrinterAttributeShared + // PRINTER_ATTRIBUTE_NETWORK indicates the printer is a network printer. + PRINTER_ATTRIBUTE_NETWORK = PrinterAttributeNetwork + // PRINTER_ATTRIBUTE_HIDDEN indicates the printer is hidden. + PRINTER_ATTRIBUTE_HIDDEN = PrinterAttributeHidden + // PRINTER_ATTRIBUTE_LOCAL indicates the printer is directly connected. + PRINTER_ATTRIBUTE_LOCAL = PrinterAttributeLocal + // PRINTER_ATTRIBUTE_ENABLE_DEVQ indicates devquery is enabled. + PRINTER_ATTRIBUTE_ENABLE_DEVQ = PrinterAttributeEnableDevq + // PRINTER_ATTRIBUTE_KEEPPRINTEDJOBS indicates printed jobs should be kept. + PRINTER_ATTRIBUTE_KEEPPRINTEDJOBS = PrinterAttributeKeepprintedjobs + // PRINTER_ATTRIBUTE_DO_COMPLETE_FIRST indicates jobs should be completed before others. + PRINTER_ATTRIBUTE_DO_COMPLETE_FIRST = PrinterAttributeDoCompleteFirst + // PRINTER_ATTRIBUTE_WORK_OFFLINE indicates the printer is configured to work offline. + PRINTER_ATTRIBUTE_WORK_OFFLINE = PrinterAttributeWorkOffline + // PRINTER_ATTRIBUTE_ENABLE_BIDI indicates bidirectional communication is enabled. + PRINTER_ATTRIBUTE_ENABLE_BIDI = PrinterAttributeEnableBidi + // PRINTER_ATTRIBUTE_RAW_ONLY indicates only raw data type is accepted. + PRINTER_ATTRIBUTE_RAW_ONLY = PrinterAttributeRawOnly + // PRINTER_ATTRIBUTE_PUBLISHED indicates the printer is published in directory service. + PRINTER_ATTRIBUTE_PUBLISHED = PrinterAttributePublished +) + +// virtualPrinterPatternsList contains substrings indicating virtual/software printers. +var virtualPrinterPatternsList = []string{ + "microsoft print to pdf", + "microsoft xps document writer", + "onenote", + "fax", + "send to onenote", + "adobe pdf", + "cutepdf", + "pdfcreator", + "foxit", + "dopdf", + "bullzip", + "primopdf", + "nitro", +} + +// thermalDriverPatternsList contains patterns suggesting ESC/POS or receipt thermal printers. +var thermalDriverPatternsList = []string{ + "epson", + "star", + "citizen", + "bixolon", + "sewoo", + "pos-", + "pos ", + PrinterTypeThermal, + "receipt", + "esc/pos", + "zj-", + "xp-", + "pt-", + "ec-pm", + "gp-", + "tsc", + "zebra", + "honeywell", + "datamax", + "58mm", + "80mm", +} + +// isVirtualPrinter checks whether the printer name, driver, or port corresponds to a virtual printer. +func isVirtualPrinter(name, driver, port string) bool { + combined := strings.ToLower(name + " " + driver) + for _, pattern := range virtualPrinterPatternsList { + if strings.Contains(combined, pattern) { + return true + } + } + + portLower := strings.ToLower(port) + virtualPorts := []string{"file:", "portprompt:", "nul:", "xpsport:"} + for _, vp := range virtualPorts { + if strings.HasPrefix(portLower, vp) { + return true + } + } + return false +} + +// detectPrinterType categorizes a printer as "virtual", "thermal", "network", "usb", "serial", or "unknown". +func detectPrinterType(portName, driverName, printerName string) string { + if isVirtualPrinter(printerName, driverName, portName) { + return PrinterTypeVirtual + } + + combined := strings.ToLower(printerName + " " + driverName) + for _, pattern := range thermalDriverPatternsList { + if strings.Contains(combined, pattern) { + return PrinterTypeThermal + } + } + + portLower := strings.ToLower(portName) + if strings.HasPrefix(portLower, `\\`) || strings.Contains(portLower, "wsd") || + strings.HasPrefix(portLower, "ip_") || strings.HasPrefix(portLower, "tcp") { + return PrinterTypeNetwork + } + + if strings.HasPrefix(portLower, "usb") { + return PrinterTypeUSB + } + + if strings.HasPrefix(portLower, "com") || strings.HasPrefix(portLower, "lpt") || + strings.Contains(portLower, "serial") { + return PrinterTypeSerial + } + + return PrinterTypeUnknown +} + +// interpretStatus converts Windows printer status and attribute bitmasks into a PrinterState. +func interpretStatus(status, attributes uint32) PrinterState { + switch { + case status&PrinterStatusOffline != 0 || attributes&PrinterAttributeWorkOffline != 0: + return StateOffline + case status&PrinterStatusPaused != 0: + return StatePaused + case status&(PrinterStatusError|PrinterStatusPaperJam|PrinterStatusPaperOut|PrinterStatusDoorOpen| + PrinterStatusPaperProblem|PrinterStatusNoToner|PrinterStatusOutOfMemory|PrinterStatusUserIntervention) != 0: + return StateError + case status&(PrinterStatusPrinting|PrinterStatusProcessing|PrinterStatusBusy) != 0: + return StateReady + case status == 0: + return StateReady + default: + return StateUnknown + } +} + +// FilterPhysicalPrinters returns non-virtual printers. +func FilterPhysicalPrinters(printers []PrinterDetail) []PrinterDetail { + if len(printers) == 0 { + return []PrinterDetail{} + } + result := make([]PrinterDetail, 0, len(printers)) + for _, p := range printers { + if !p.IsVirtual { + result = append(result, p) + } + } + return result +} + +// FilterThermalPrinters returns only thermal/POS printers. +func FilterThermalPrinters(printers []PrinterDetail) []PrinterDetail { + if len(printers) == 0 { + return []PrinterDetail{} + } + result := make([]PrinterDetail, 0, len(printers)) + for _, p := range printers { + if p.PrinterType == PrinterTypeThermal { + result = append(result, p) + } + } + return result +} + +// FindThermalPrinters enumerates system printers and returns only thermal/POS printers. +func FindThermalPrinters() ([]PrinterDetail, error) { + printers, err := ListAvailablePrinters() + if err != nil { + return nil, fmt.Errorf("list available printers: %w", err) + } + return FilterThermalPrinters(printers), nil +} diff --git a/pkg/connection/printer_filter_test.go b/pkg/connection/printer_filter_test.go new file mode 100644 index 0000000..a81c5eb --- /dev/null +++ b/pkg/connection/printer_filter_test.go @@ -0,0 +1,496 @@ +package connection + +import ( + "runtime" + "testing" +) + +func TestInterpretStatus(t *testing.T) { + tests := []struct { + name string + status uint32 + attributes uint32 + want PrinterState + }{ + { + name: "zero status and attributes is ready", + status: 0, + attributes: 0, + want: StateReady, + }, + { + name: "status offline", + status: PrinterStatusOffline, + attributes: 0, + want: StateOffline, + }, + { + name: "status PRINTER_STATUS_OFFLINE alias", + status: PRINTER_STATUS_OFFLINE, + attributes: 0, + want: StateOffline, + }, + { + name: "attribute work offline with zero status", + status: 0, + attributes: PrinterAttributeWorkOffline, + want: StateOffline, + }, + { + name: "attribute PRINTER_ATTRIBUTE_WORK_OFFLINE alias", + status: 0, + attributes: PRINTER_ATTRIBUTE_WORK_OFFLINE, + want: StateOffline, + }, + { + name: "status paused", + status: PrinterStatusPaused, + attributes: 0, + want: StatePaused, + }, + { + name: "status PRINTER_STATUS_PAUSED alias", + status: PRINTER_STATUS_PAUSED, + attributes: 0, + want: StatePaused, + }, + { + name: "status error", + status: PrinterStatusError, + attributes: 0, + want: StateError, + }, + { + name: "status paper jam", + status: PrinterStatusPaperJam, + attributes: 0, + want: StateError, + }, + { + name: "status paper out", + status: PrinterStatusPaperOut, + attributes: 0, + want: StateError, + }, + { + name: "status door open", + status: PrinterStatusDoorOpen, + attributes: 0, + want: StateError, + }, + { + name: "status paper problem", + status: PrinterStatusPaperProblem, + attributes: 0, + want: StateError, + }, + { + name: "status no toner", + status: PrinterStatusNoToner, + attributes: 0, + want: StateError, + }, + { + name: "status out of memory", + status: PrinterStatusOutOfMemory, + attributes: 0, + want: StateError, + }, + { + name: "status user intervention", + status: PrinterStatusUserIntervention, + attributes: 0, + want: StateError, + }, + { + name: "status printing is ready", + status: PrinterStatusPrinting, + attributes: 0, + want: StateReady, + }, + { + name: "status processing is ready", + status: PrinterStatusProcessing, + attributes: 0, + want: StateReady, + }, + { + name: "status busy is ready", + status: PrinterStatusBusy, + attributes: 0, + want: StateReady, + }, + { + name: "offline precedence over paused", + status: PrinterStatusOffline | PrinterStatusPaused, + attributes: 0, + want: StateOffline, + }, + { + name: "offline attribute precedence over error", + status: PrinterStatusError, + attributes: PrinterAttributeWorkOffline, + want: StateOffline, + }, + { + name: "unknown status flags", + status: PrinterStatusPowerSave, + attributes: 0, + want: StateUnknown, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := interpretStatus(tt.status, tt.attributes) + if got != tt.want { + t.Errorf("interpretStatus(%#x, %#x) = %v, want %v", tt.status, tt.attributes, got, tt.want) + } + }) + } +} + +func TestIsVirtualPrinter(t *testing.T) { + tests := []struct { + name string + pName string + driver string + port string + want bool + }{ + { + name: "Microsoft Print to PDF", + pName: "Microsoft Print to PDF", + driver: "Microsoft Print To PDF", + port: "PORTPROMPT:", + want: true, + }, + { + name: "Microsoft XPS Document Writer", + pName: "Microsoft XPS Document Writer", + driver: "Microsoft XPS Document Writer v4", + port: "XPSPort:", + want: true, + }, + { + name: "OneNote", + pName: "Send to OneNote 2016", + driver: "Send to Microsoft OneNote 16 Driver", + port: "nul:", + want: true, + }, + { + name: "Adobe PDF", + pName: "Adobe PDF", + driver: "Adobe PDF Converter", + port: "Documents\\*.pdf", + want: true, + }, + { + name: "CutePDF", + pName: "CutePDF Writer", + driver: "CutePDF Writer Driver", + port: "CPW2:", + want: true, + }, + { + name: "Fax", + pName: "Fax", + driver: "Microsoft Shared Fax Driver", + port: "SHRFAX:", + want: true, + }, + { + name: "File port virtual prefix", + pName: "Custom Exporter", + driver: "Generic Driver", + port: "FILE:", + want: true, + }, + { + name: "Nul port virtual prefix", + pName: "Null Sink", + driver: "Raw Driver", + port: "NUL:", + want: true, + }, + { + name: "Physical EPSON thermal printer", + pName: "EPSON TM-T88V", + driver: "EPSON TM-T88V Receipt", + port: "USB001", + want: false, + }, + { + name: "Physical HP LaserJet", + pName: "HP LaserJet Pro MFP M428fdw", + driver: "HP LaserJet Pro PCL 6", + port: "WSD-9876", + want: false, + }, + { + name: "Physical Star printer", + pName: "Star TSP100", + driver: "Star TSP100 Cutter", + port: "TCP_192.168.1.100", + want: false, + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := isVirtualPrinter(tt.pName, tt.driver, tt.port) + if got != tt.want { + t.Errorf("isVirtualPrinter(%q, %q, %q) = %v, want %v", tt.pName, tt.driver, tt.port, got, tt.want) + } + }) + } +} + +func TestDetectPrinterType(t *testing.T) { + tests := []struct { + name string + port string + driver string + printer string + wantType string + }{ + { + name: "virtual PDF printer", + port: "PORTPROMPT:", + driver: "Microsoft Print To PDF", + printer: "Microsoft Print to PDF", + wantType: "virtual", + }, + { + name: "virtual XPS printer", + port: "XPSPort:", + driver: "Microsoft XPS Document Writer v4", + printer: "Microsoft XPS Document Writer", + wantType: "virtual", + }, + { + name: "virtual OneNote printer", + port: "nul:", + driver: "Send to Microsoft OneNote 16 Driver", + printer: "OneNote", + wantType: "virtual", + }, + { + name: "thermal EPSON USB", + port: "USB001", + driver: "EPSON TM-T88V Receipt", + printer: "Receipt Printer", + wantType: "thermal", + }, + { + name: "thermal Star Network", + port: "TCP_192.168.1.200", + driver: "Star TSP143IIIL", + printer: "Kitchen Star", + wantType: "thermal", + }, + { + name: "thermal POS-80 Serial", + port: "COM1", + driver: "POS-80 Series Driver", + printer: "POS-80", + wantType: "thermal", + }, + { + name: "thermal 58mm", + port: "USB002", + driver: "58mm Series Printer", + printer: "Mini Receipt", + wantType: "thermal", + }, + { + name: "thermal Citizen", + port: "USB003", + driver: "Citizen CT-S310II", + printer: "Front Desk", + wantType: "thermal", + }, + { + name: "thermal Bixolon", + port: "USB004", + driver: "Bixolon SRP-350plusIII", + printer: "Bar Ticket", + wantType: "thermal", + }, + { + name: "thermal ESC/POS pattern", + port: "USB005", + driver: "Generic ESC/POS Driver", + printer: "POS Terminal", + wantType: "thermal", + }, + { + name: "network UNC path non-thermal", + port: `\\PRINTSERVER\OfficeLaser`, + driver: "HP LaserJet 4000", + printer: "Office LaserJet", + wantType: "network", + }, + { + name: "network WSD non-thermal", + port: "WSD-12345", + driver: "Canon iR-ADV C5535", + printer: "Canon Copier", + wantType: "network", + }, + { + name: "network IP_ prefix non-thermal", + port: "IP_192.168.1.150", + driver: "Brother HL-L2350DW", + printer: "Office Brother", + wantType: "network", + }, + { + name: "network TCP prefix non-thermal", + port: "tcp_10.0.0.88", + driver: "Lexmark MS810", + printer: "Floor Lexmark", + wantType: "network", + }, + { + name: "usb non-thermal", + port: "USB001", + driver: "HP DeskJet 2700 series", + printer: "Color DeskJet", + wantType: "usb", + }, + { + name: "serial COM non-thermal", + port: "COM3", + driver: "Generic Text", + printer: "Line Matrix", + wantType: "serial", + }, + { + name: "serial LPT non-thermal", + port: "LPT1", + driver: "Generic Text", + printer: "Dot Matrix", + wantType: "serial", + }, + { + name: "serial word in port non-thermal", + port: "SerialPort0", + driver: "Industrial Scale", + printer: "Scale Indicator", + wantType: "serial", + }, + { + name: "unknown printer port and driver", + port: "BLUETOOTH_DEV1", + driver: "Custom Device Driver", + printer: "Unknown Peripheral", + wantType: "unknown", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got := detectPrinterType(tt.port, tt.driver, tt.printer) + if got != tt.wantType { + t.Errorf("detectPrinterType(%q, %q, %q) = %q, want %q", tt.port, tt.driver, tt.printer, got, tt.wantType) + } + }) + } +} + +func TestFilterPhysicalPrinters(t *testing.T) { + t.Run("filters out virtual printers", func(t *testing.T) { + input := []PrinterDetail{ + {Name: "Microsoft Print to PDF", IsVirtual: true, PrinterType: "virtual"}, + {Name: "Microsoft XPS Document Writer", IsVirtual: true, PrinterType: "virtual"}, + {Name: "OneNote", IsVirtual: true, PrinterType: "virtual"}, + {Name: "EPSON TM-T88V", IsVirtual: false, PrinterType: "thermal"}, + {Name: "HP LaserJet Pro", IsVirtual: false, PrinterType: "network"}, + {Name: "Canon TS3300", IsVirtual: false, PrinterType: "usb"}, + } + + got := FilterPhysicalPrinters(input) + if len(got) != 3 { + t.Fatalf("FilterPhysicalPrinters returned %d printers, want 3", len(got)) + } + + expectedNames := []string{"EPSON TM-T88V", "HP LaserJet Pro", "Canon TS3300"} + for i, name := range expectedNames { + if got[i].Name != name { + t.Errorf("got[%d].Name = %q, want %q", i, got[i].Name, name) + } + } + }) + + t.Run("empty input returns empty slice", func(t *testing.T) { + got := FilterPhysicalPrinters(nil) + if len(got) != 0 { + t.Errorf("FilterPhysicalPrinters(nil) returned %d items, want 0", len(got)) + } + + got = FilterPhysicalPrinters([]PrinterDetail{}) + if len(got) != 0 { + t.Errorf("FilterPhysicalPrinters([]) returned %d items, want 0", len(got)) + } + }) +} + +func TestFilterThermalPrinters(t *testing.T) { + t.Run("filters only thermal printers", func(t *testing.T) { + input := []PrinterDetail{ + {Name: "EPSON TM-T88V", PrinterType: "thermal"}, + {Name: "Star TSP100", PrinterType: "thermal"}, + {Name: "POS-80 Printer", PrinterType: "thermal"}, + {Name: "58mm Mini Receipt", PrinterType: "thermal"}, + {Name: "Microsoft Print to PDF", PrinterType: "virtual"}, + {Name: "HP LaserJet Pro", PrinterType: "network"}, + {Name: "Canon TS3300", PrinterType: "usb"}, + {Name: "Generic Serial", PrinterType: "serial"}, + } + + got := FilterThermalPrinters(input) + if len(got) != 4 { + t.Fatalf("FilterThermalPrinters returned %d printers, want 4", len(got)) + } + + expectedNames := []string{"EPSON TM-T88V", "Star TSP100", "POS-80 Printer", "58mm Mini Receipt"} + for i, name := range expectedNames { + if got[i].Name != name { + t.Errorf("got[%d].Name = %q, want %q", i, got[i].Name, name) + } + } + }) + + t.Run("empty input returns empty slice", func(t *testing.T) { + got := FilterThermalPrinters(nil) + if len(got) != 0 { + t.Errorf("FilterThermalPrinters(nil) returned %d items, want 0", len(got)) + } + + got = FilterThermalPrinters([]PrinterDetail{}) + if len(got) != 0 { + t.Errorf("FilterThermalPrinters([]) returned %d items, want 0", len(got)) + } + }) +} + +func TestFindThermalPrinters(t *testing.T) { + printers, err := FindThermalPrinters() + if runtime.GOOS != "windows" { + if err == nil { + t.Errorf("FindThermalPrinters() on %s expected error, got nil (printers: %v)", runtime.GOOS, printers) + } + } else { + if err != nil { + t.Logf("FindThermalPrinters() on Windows returned error: %v", err) + } else { + for _, p := range printers { + if p.PrinterType != "thermal" { + t.Errorf("FindThermalPrinters() returned non-thermal printer: %+v", p) + } + } + } + } +} diff --git a/pkg/connection/tcp_connector.go b/pkg/connection/tcp_connector.go new file mode 100644 index 0000000..8d626e6 --- /dev/null +++ b/pkg/connection/tcp_connector.go @@ -0,0 +1,139 @@ +package connection + +import ( + "context" + "errors" + "fmt" + "net" + "strings" + "sync" + "time" +) + +const ( + // DefaultTCPPort is the standard port for network thermal printers (RAW 9100). + DefaultTCPPort = "9100" + + // DefaultDialTimeout is the default connection timeout. + DefaultDialTimeout = 5 * time.Second + + // DefaultWriteTimeout is the default timeout for write operations. + DefaultWriteTimeout = 10 * time.Second +) + +// TCPOption configures a TCPConnector. +type TCPOption func(*TCPConnector) + +// WithDialTimeout sets the network dial timeout. +func WithDialTimeout(d time.Duration) TCPOption { + return func(c *TCPConnector) { + c.dialTimeout = d + } +} + +// WithWriteTimeout sets the network write deadline timeout. +func WithWriteTimeout(d time.Duration) TCPOption { + return func(c *TCPConnector) { + c.writeTimeout = d + } +} + +// TCPConnector implements Connector over a raw TCP socket connection. +type TCPConnector struct { + conn net.Conn + address string + dialTimeout time.Duration + writeTimeout time.Duration + mu sync.Mutex + closed bool +} + +// NewTCPConnector connects to a network thermal printer at the given address. +// If address does not include a port, DefaultTCPPort (9100) is appended. +func NewTCPConnector(address string, opts ...TCPOption) (*TCPConnector, error) { + trimmed := strings.TrimSpace(address) + if trimmed == "" { + return nil, errors.New("tcp address cannot be empty") + } + + if !strings.Contains(trimmed, ":") { + trimmed = trimmed + ":" + DefaultTCPPort + } + + c := &TCPConnector{ + address: trimmed, + dialTimeout: DefaultDialTimeout, + writeTimeout: DefaultWriteTimeout, + } + + for _, opt := range opts { + if opt != nil { + opt(c) + } + } + + dialer := &net.Dialer{ + Timeout: c.dialTimeout, + } + conn, err := dialer.DialContext(context.Background(), "tcp", c.address) + if err != nil { + return nil, fmt.Errorf("dialing tcp %s: %w", c.address, err) + } + + if tcpConn, ok := conn.(*net.TCPConn); ok { + _ = tcpConn.SetKeepAlive(true) + } + + c.conn = conn + return c, nil +} + +// Write sends raw ESC/POS bytes over the TCP connection. +func (c *TCPConnector) Write(data []byte) (int, error) { + c.mu.Lock() + defer c.mu.Unlock() + + if c.closed { + return 0, errors.New("tcp connector is closed") + } + + if len(data) == 0 { + return 0, nil + } + + if c.writeTimeout > 0 { + _ = c.conn.SetWriteDeadline(time.Now().Add(c.writeTimeout)) + } + + n, err := c.conn.Write(data) + if err != nil { + return n, fmt.Errorf("tcp write to %s: %w", c.address, err) + } + return n, nil +} + +// Close terminates the TCP connection. It is idempotent. +func (c *TCPConnector) Close() error { + c.mu.Lock() + defer c.mu.Unlock() + + if c.closed { + return nil + } + c.closed = true + + if c.conn != nil { + if err := c.conn.Close(); err != nil { + return fmt.Errorf("closing tcp connection to %s: %w", c.address, err) + } + } + return nil +} + +// Address returns the normalized TCP target address. +func (c *TCPConnector) Address() string { + return c.address +} + +// Ensure TCPConnector implements Connector. +var _ Connector = (*TCPConnector)(nil) diff --git a/pkg/connection/tcp_connector_test.go b/pkg/connection/tcp_connector_test.go new file mode 100644 index 0000000..5db87b8 --- /dev/null +++ b/pkg/connection/tcp_connector_test.go @@ -0,0 +1,104 @@ +package connection + +import ( + "context" + "io" + "net" + "strings" + "testing" + "time" +) + +func TestNewTCPConnector_Success(t *testing.T) { + var lc net.ListenConfig + ln, err := lc.Listen(context.Background(), "tcp", "127.0.0.1:0") + if err != nil { + t.Fatalf("net.Listen failed: %v", err) + } + defer func() { _ = ln.Close() }() + + serverReceived := make(chan []byte, 1) + go func() { + conn, err := ln.Accept() + if err != nil { + return + } + defer func() { _ = conn.Close() }() + data, _ := io.ReadAll(conn) + serverReceived <- data + }() + + addr := ln.Addr().String() + connector, err := NewTCPConnector(addr, + WithDialTimeout(2*time.Second), + WithWriteTimeout(2*time.Second), + ) + if err != nil { + t.Fatalf("NewTCPConnector failed: %v", err) + } + if connector.Address() != addr { + t.Errorf("expected address %s, got %s", addr, connector.Address()) + } + + // Empty write + n, err := connector.Write([]byte{}) + if err != nil || n != 0 { + t.Errorf("empty Write() = (%d, %v), want (0, nil)", n, err) + } + + // Data write + msg := []byte("Hello Thermal Printer\n") + n, err = connector.Write(msg) + if err != nil || n != len(msg) { + t.Errorf("Write() = (%d, %v), want (%d, nil)", n, err, len(msg)) + } + + // Close + if err := connector.Close(); err != nil { + t.Errorf("Close() failed: %v", err) + } + + // Idempotent second Close + if err := connector.Close(); err != nil { + t.Errorf("second Close() failed: %v", err) + } + + // Write after close + _, err = connector.Write([]byte("after close")) + if err == nil { + t.Error("expected error writing after close, got nil") + } + + select { + case received := <-serverReceived: + if string(received) != string(msg) { + t.Errorf("server received %q, want %q", string(received), string(msg)) + } + case <-time.After(2 * time.Second): + t.Fatal("timed out waiting for server to receive data") + } +} + +func TestNewTCPConnector_DefaultPortNormalization(t *testing.T) { + _, err := NewTCPConnector("192.0.2.1", WithDialTimeout(20*time.Millisecond)) + if err == nil { + t.Fatal("expected dial error to test address, got nil") + } + if !strings.Contains(err.Error(), ":9100") { + t.Errorf("expected error message to contain ':9100', got %v", err) + } +} + +func TestNewTCPConnector_EmptyAddress(t *testing.T) { + _, err := NewTCPConnector(" ") + if err == nil { + t.Fatal("expected error for empty address, got nil") + } +} + +func TestNewTCPConnector_DialFailure(t *testing.T) { + _, err := NewTCPConnector("127.0.0.1:1", WithDialTimeout(50*time.Millisecond)) + if err == nil { + t.Fatal("expected dial error for unreachable port, got nil") + } +} diff --git a/pkg/connection/windows_enum.go b/pkg/connection/windows_enum.go index be6453e..4ffa771 100644 --- a/pkg/connection/windows_enum.go +++ b/pkg/connection/windows_enum.go @@ -3,7 +3,6 @@ package connection import ( - "strings" "syscall" "unsafe" ) @@ -14,18 +13,6 @@ const ( PrinterEnumConnections = 0x00000004 ) -// Printer status flags (from winspool.h) -const ( - PrinterStatusPaused = 0x00000001 - PrinterStatusError = 0x00000002 - PrinterStatusPaperJam = 0x00000008 - PrinterStatusPaperOut = 0x00000010 - PrinterStatusOffline = 0x00000080 - PrinterStatusBusy = 0x00000200 - PrinterStatusPrinting = 0x00000400 - PrinterStatusProcessing = 0x00004000 - PrinterStatusDoorOpen = 0x00400000 -) // PRINTER_INFO_2 structure (matches Windows API layout) type printerInfo2 struct { @@ -112,11 +99,11 @@ func ListAvailablePrinters() ([]PrinterDetail, error) { Name: name, Port: port, Driver: driver, - Status: interpretStatus(info.Status), + Status: interpretStatus(info.Status, info.Attributes), StatusRaw: info.Status, IsDefault: name == defaultPrinter, - IsVirtual: isVirtualPrinter(name, port), - PrinterType: detectPrinterType(name, port, driver), + IsVirtual: isVirtualPrinter(name, driver, port), + PrinterType: detectPrinterType(port, driver, name), }) } @@ -166,79 +153,12 @@ func utf16PtrToString(p *uint16) string { return syscall.UTF16ToString(s) } -func interpretStatus(status uint32) PrinterState { - switch { - case status == 0: - return StateReady - case status&PrinterStatusOffline != 0: - return StateOffline - case status&PrinterStatusPaused != 0: - return StatePaused - case status&(PrinterStatusError|PrinterStatusPaperJam|PrinterStatusPaperOut|PrinterStatusDoorOpen) != 0: - return StateError - case status&(PrinterStatusPrinting|PrinterStatusProcessing|PrinterStatusBusy) != 0: - return StateReady - default: - return StateUnknown - } -} - -func isVirtualPrinter(name, port string) bool { - nameLower := strings.ToLower(name) - portLower := strings.ToLower(port) - - for _, pattern := range virtualPrinterPatterns { - if strings.Contains(nameLower, pattern) { - return true - } +func init() { + if len(virtualPrinterPatterns) > 0 { + virtualPrinterPatternsList = virtualPrinterPatterns } - - virtualPorts := []string{"file:", "portprompt:", "nul:", "xpsport:"} - for _, vp := range virtualPorts { - if strings.HasPrefix(portLower, vp) { - return true - } + if len(thermalDriverPatterns) > 0 { + thermalDriverPatternsList = thermalDriverPatterns } - return false } -func detectPrinterType(name, port, driver string) string { - if isVirtualPrinter(name, port) { - return "virtual" - } - - portLower := strings.ToLower(port) - if strings.HasPrefix(portLower, "\\\\") || strings.Contains(portLower, "wsd") { - return "network" - } - - combined := strings.ToLower(name + " " + driver) - for _, pattern := range thermalDriverPatterns { - if strings.Contains(combined, pattern) { - return "thermal" - } - } - return "unknown" -} - -// FilterThermalPrinters returns only thermal/POS printers -func FilterThermalPrinters(printers []PrinterDetail) []PrinterDetail { - result := make([]PrinterDetail, 0, len(printers)/2) - for _, p := range printers { - if p.PrinterType == "thermal" { - result = append(result, p) - } - } - return result -} - -// FilterPhysicalPrinters returns non-virtual printers -func FilterPhysicalPrinters(printers []PrinterDetail) []PrinterDetail { - result := make([]PrinterDetail, 0, len(printers)/2) - for _, p := range printers { - if !p.IsVirtual { - result = append(result, p) - } - } - return result -} diff --git a/pkg/connection/windows_enum_stub.go b/pkg/connection/windows_enum_stub.go index 29c7886..58fcf84 100644 --- a/pkg/connection/windows_enum_stub.go +++ b/pkg/connection/windows_enum_stub.go @@ -9,12 +9,3 @@ func ListAvailablePrinters() ([]PrinterDetail, error) { return nil, errors.New("printer enumeration is only available on Windows") } -// FilterThermalPrinters stub -func FilterThermalPrinters(_ []PrinterDetail) []PrinterDetail { - return nil -} - -// FilterPhysicalPrinters stub -func FilterPhysicalPrinters(_ []PrinterDetail) []PrinterDetail { - return nil -}