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
39 changes: 37 additions & 2 deletions cmd/poster/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@ import (

"github.com/adcondev/poster/pkg/composer"
"github.com/adcondev/poster/pkg/connection"
"github.com/adcondev/poster/pkg/constants"
"github.com/adcondev/poster/pkg/document/executor"
"github.com/adcondev/poster/pkg/document/schema"
"github.com/adcondev/poster/pkg/emulator"
"github.com/adcondev/poster/pkg/service"
)

Expand Down Expand Up @@ -42,6 +44,7 @@ type Config struct {
SerialPort string
BaudRate int
OutputFile string
PreviewPath string
}

func main() {
Expand Down Expand Up @@ -105,6 +108,7 @@ func parseArgs() *Config {
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.PreviewPath, "preview", "", "Render visual PNG receipt preview to file (no hardware printer required)")

flag.BoolVar(&config.DryRun, "dry-run", false, "Validate without printing")
flag.BoolVar(&config.Debug, "debug", false, "Enable debug logging")
Expand All @@ -126,7 +130,7 @@ func parseArgs() *Config {
config.PrinterName = args[1]
}

if !config.DryRun && config.PrinterName == "" && config.ConnectionType == win {
if !config.DryRun && config.PreviewPath == "" && config.PrinterName == "" && config.ConnectionType == win {
config.PrinterName = detectPrinter()
}

Expand All @@ -149,14 +153,15 @@ USAGE:
EXAMPLES:
%s ticket.json
%s ticket.json "POS-80"
%s --preview receipt.png ticket.json
%s -t file -output receipt.prn ticket.json
%s --dry-run ticket.json
%s --list
%s --list-thermal
%s --list-physical

OPTIONS:
`, AppName, AppVersion, AppName, AppName, AppName, AppName, AppName, AppName, AppName, AppName)
`, AppName, AppVersion, AppName, AppName, AppName, AppName, AppName, AppName, AppName, AppName, AppName)

flag.PrintDefaults()

Expand Down Expand Up @@ -252,6 +257,36 @@ func executePrint(config *Config) error {
return validateDocument(&doc)
}

if config.PreviewPath != "" {
prof := createProfile(&doc)
if prof.PaperWidth == 0 && doc.Profile.PaperWidth > 0 {
prof.PaperWidth = float64(doc.Profile.PaperWidth)
}
if prof.DotsPerLine == 0 {
if doc.Profile.PaperWidth == 58 {
prof.DotsPerLine = constants.PaperPxWidth58mm
} else {
prof.DotsPerLine = constants.PaperPxWidth80mm
}
}
if prof.DPI == 0 {
if doc.Profile.DPI > 0 {
prof.DPI = doc.Profile.DPI
} else {
prof.DPI = constants.DefaultDPI
}
}
emuPrinter, err := emulator.NewPrinter(prof)
if err != nil {
return fmt.Errorf("failed to create emulator printer: %w", err)
}
exec := executor.NewExecutor(emuPrinter)
if err := exec.Execute(&doc); err != nil {
return fmt.Errorf("failed to execute document in preview: %w", err)
}
return emuPrinter.SavePNG(config.PreviewPath)
}

printerName, err := getPrinterNameFromDocument(config, jsonData)
if err != nil && config.ConnectionType == win {
return err
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import (
"os"
"path/filepath"

"github.com/adcondev/poster/internal/load"
"github.com/adcondev/poster/pkg/composer"
"github.com/adcondev/poster/pkg/connection"
"github.com/adcondev/poster/pkg/constants"
Expand Down Expand Up @@ -247,7 +246,7 @@ func printReceipt(baseDir, fileName, printerName string) error {
// ============================================================================
// Load and Process Image
// ============================================================================
img, err := load.ImgFromFile(baseDir, fileName)
img, _, err := graphics.LoadImageFromFile(baseDir, fileName)
if err != nil {
return fmt.Errorf("load image: %w", err)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ import (
"fmt"
"log"

"github.com/adcondev/poster/internal/load"
"github.com/adcondev/poster/pkg/composer"
"github.com/adcondev/poster/pkg/connection"
"github.com/adcondev/poster/pkg/graphics"
Expand Down Expand Up @@ -50,7 +49,7 @@ func main() {

// Load the image
log.Print("Loading image from Base64")
img, _, err := load.ImgFromBase64(Data)
img, _, err := graphics.LoadImageFromBase64(Data)
if err != nil {
log.Panicf("Failed to load image: %v", err)
}
Expand Down
18 changes: 18 additions & 0 deletions pkg/commands/bitimage/bitimage.go
Original file line number Diff line number Diff line change
Expand Up @@ -141,6 +141,9 @@ type Capability interface {
PrintDownloadedBitImage(mode PrintMode) ([]byte, error)
PrintVariableVerticalSizeBitImage(mode PrintMode, width, height uint16, data []byte) ([]byte, error) // Variable size bit image commands (deprecated)
PrintRasterBitImage(mode PrintMode, width, height uint16, data []byte) ([]byte, error)
GraphicsCmds() GraphicsCapability
NVGraphicsCmds() NVGraphicsCapability
DownloadGraphicsCmds() DownloadGraphicsCapability
}

// ============================================================================
Expand All @@ -163,6 +166,21 @@ func NewCommands() *Commands {
}
}

// GraphicsCmds returns the graphics capability.
func (c *Commands) GraphicsCmds() GraphicsCapability {
return c.Graphics
}

// NVGraphicsCmds returns the NV graphics capability.
func (c *Commands) NVGraphicsCmds() NVGraphicsCapability {
return c.NvGraphics
}

// DownloadGraphicsCmds returns the download graphics capability.
func (c *Commands) DownloadGraphicsCmds() DownloadGraphicsCapability {
return c.DownloadGraphics
}

// ============================================================================
// Helper Functions
// ============================================================================
Expand Down
18 changes: 18 additions & 0 deletions pkg/commands/character/character.go
Original file line number Diff line number Diff line change
Expand Up @@ -444,6 +444,9 @@ type Capability interface {
SelectCharacterSize(sizeConfig Size) []byte
SetWhiteBlackReverseMode(mode ReverseMode) []byte
SetSmoothingMode(mode SmoothingMode) []byte
EffectsCmds() EffectsCapability
CodeConversionCmds() CodeConversionCapability
UserDefinedCmds() UserDefinedCapability
}

// ============================================================================
Expand All @@ -468,6 +471,21 @@ func NewCommands() *Commands {
}
}

// EffectsCmds returns the effects capability.
func (c *Commands) EffectsCmds() EffectsCapability {
return c.Effects
}

// CodeConversionCmds returns the code conversion capability.
func (c *Commands) CodeConversionCmds() CodeConversionCapability {
return c.CodeConversion
}

// UserDefinedCmds returns the user-defined character capability.
func (c *Commands) UserDefinedCmds() UserDefinedCapability {
return c.UserDefined
}

// ============================================================================
// Helper Functions
// ============================================================================
Expand Down
6 changes: 6 additions & 0 deletions pkg/commands/mechanismcontrol/mechanism_control.go
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,10 @@ var (
ErrPositionCutMode = errors.New("invalid position cut mode (try 97 or 98)")
// ErrFeedCutReturnMode indicates an invalid feed, cut and return mode
ErrFeedCutReturnMode = errors.New("invalid feed, cut and return mode (try 103 or 104)")
// ErrInvalidDrawerPin indicates an invalid drawer pin
ErrInvalidDrawerPin = errors.New("invalid drawer pin (must be 0 or 1)")
// ErrInvalidBeepParams indicates invalid beep parameters
ErrInvalidBeepParams = errors.New("invalid beep parameters (times and lapse must be >= 1)")
)

// ============================================================================
Expand All @@ -124,6 +128,8 @@ type Capability interface {
FeedAndCutPaper(mode FeedCut, feedAmount byte) ([]byte, error)
SetCutPosition(mode PositionCut, position byte) ([]byte, error)
FeedCutAndReturnPaper(mode FeedCutReturn, feedAmount byte) ([]byte, error)
Pulse(pin byte, onTime byte, offTime byte) ([]byte, error)
Beep(times byte, lapse byte) ([]byte, error)
}

// ============================================================================
Expand Down
47 changes: 47 additions & 0 deletions pkg/commands/mechanismcontrol/mechanism_control_commands.go
Original file line number Diff line number Diff line change
Expand Up @@ -432,3 +432,50 @@ func (c *Commands) FeedCutAndReturnPaper(m FeedCutReturn, n byte) ([]byte, error
}
return []byte{shared.GS, 'V', byte(m), n}, nil
}

// Pulse generates the ESC p command to open a cash drawer connected to pin 2 or pin 5.
//
// Format:
//
// ASCII: ESC p m t1 t2
// Hex: 0x1B 0x70 m t1 t2
// Decimal: 27 112 m t1 t2
//
// Range:
//
// m = 0, 1
// t1 = 0–255 (on-time = t1 * 2ms)
// t2 = 0–255 (off-time = t2 * 2ms)
//
// Errors:
//
// Returns ErrInvalidDrawerPin if pin > 1.
func (c *Commands) Pulse(pin byte, onTime byte, offTime byte) ([]byte, error) {
if pin > 1 {
return nil, ErrInvalidDrawerPin
}
return []byte{shared.ESC, 0x70, pin, onTime, offTime}, nil
}

// Beep generates the ESC B command to emit a buzzer sound.
//
// Format:
//
// ASCII: ESC B n t
// Hex: 0x1B 0x42 n t
// Decimal: 27 66 n t
//
// Range:
//
// n >= 1 (number of times)
// t >= 1 (time lapse)
//
// Errors:
//
// Returns ErrInvalidBeepParams if times == 0 or lapse == 0.
func (c *Commands) Beep(times byte, lapse byte) ([]byte, error) {
if times == 0 || lapse == 0 {
return nil, ErrInvalidBeepParams
}
return []byte{shared.ESC, 0x42, times, lapse}, nil
}
121 changes: 121 additions & 0 deletions pkg/commands/mechanismcontrol/mechanism_control_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,121 @@
package mechanismcontrol_test

import (
"errors"
"testing"

"github.com/adcondev/poster/internal/testutils"
"github.com/adcondev/poster/pkg/commands/mechanismcontrol"
"github.com/adcondev/poster/pkg/commands/shared"
)

func TestCommands_Pulse(t *testing.T) {
cmd := mechanismcontrol.NewCommands()

tests := []struct {
name string
pin byte
onTime byte
offTime byte
want []byte
expectedErr error
}{
{
name: "valid pin 0",
pin: 0,
onTime: 50,
offTime: 50,
want: []byte{shared.ESC, 0x70, 0, 50, 50},
expectedErr: nil,
},
{
name: "valid pin 1",
pin: 1,
onTime: 100,
offTime: 200,
want: []byte{shared.ESC, 0x70, 1, 100, 200},
expectedErr: nil,
},
{
name: "invalid pin 2",
pin: 2,
onTime: 50,
offTime: 50,
want: nil,
expectedErr: mechanismcontrol.ErrInvalidDrawerPin,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := cmd.Pulse(tt.pin, tt.onTime, tt.offTime)
if tt.expectedErr != nil {
if !errors.Is(err, tt.expectedErr) {
t.Fatalf("Pulse() error = %v, want %v", err, tt.expectedErr)
}
return
}
if err != nil {
t.Fatalf("Pulse() unexpected error: %v", err)
}
testutils.AssertBytes(t, got, tt.want, "Pulse()")
})
}
}

func TestCommands_Beep(t *testing.T) {
cmd := mechanismcontrol.NewCommands()

tests := []struct {
name string
times byte
lapse byte
want []byte
expectedErr error
}{
{
name: "valid beep",
times: 2,
lapse: 3,
want: []byte{shared.ESC, 0x42, 2, 3},
expectedErr: nil,
},
{
name: "invalid times zero",
times: 0,
lapse: 3,
want: nil,
expectedErr: mechanismcontrol.ErrInvalidBeepParams,
},
{
name: "invalid lapse zero",
times: 2,
lapse: 0,
want: nil,
expectedErr: mechanismcontrol.ErrInvalidBeepParams,
},
{
name: "invalid times and lapse zero",
times: 0,
lapse: 0,
want: nil,
expectedErr: mechanismcontrol.ErrInvalidBeepParams,
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
got, err := cmd.Beep(tt.times, tt.lapse)
if tt.expectedErr != nil {
if !errors.Is(err, tt.expectedErr) {
t.Fatalf("Beep() error = %v, want %v", err, tt.expectedErr)
}
return
}
if err != nil {
t.Fatalf("Beep() unexpected error: %v", err)
}
testutils.AssertBytes(t, got, tt.want, "Beep()")
})
}
}
Loading
Loading