Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 11 additions & 6 deletions cmd/poster/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import (
"log"
"os"
"runtime"
"strings"

"github.com/adcondev/poster/pkg/composer"
"github.com/adcondev/poster/pkg/connection"
Expand Down Expand Up @@ -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")
Expand All @@ -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()
}

Expand Down Expand Up @@ -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 {
Expand Down
45 changes: 44 additions & 1 deletion cmd/poster/parsing.go
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down Expand Up @@ -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
}

169 changes: 169 additions & 0 deletions cmd/poster/parsing_test.go
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -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")
}
}

73 changes: 22 additions & 51 deletions cmd/poster/printing.go
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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 == "" {
Expand All @@ -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
}
Loading
Loading