-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprinter.go
144 lines (123 loc) · 2.44 KB
/
printer.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
package gongoff
import (
"bufio"
"errors"
"fmt"
"go.bug.st/serial"
"net"
)
type Printer interface {
Open() error
IsOpen() bool
PrintDocument(Document) error
PrintCommands([]Command) error
Close() error
flush() error
}
type GenericPrinter struct {
dst *bufio.Writer
}
func (p *GenericPrinter) IsOpen() bool {
return p.dst != nil
}
func (p *GenericPrinter) flush() error {
return p.dst.Flush()
}
func (p *GenericPrinter) PrintDocument(doc Document) error {
return p.PrintCommands(doc.get())
}
// PrintCommands prints the given commands to the printer.
// It allows for more flexibility than PrintDocument
func (p *GenericPrinter) PrintCommands(commands []Command) error {
for _, command := range commands {
commandString, err := command.get()
if err != nil {
return err
}
_, err = p.dst.Write([]byte(commandString))
if err != nil {
return err
}
}
err := p.flush()
if err != nil {
return err
}
return nil
}
type NetworkPrinter struct {
GenericPrinter
socket *net.Conn
ip string
port int
}
func NewNetworkPrinter(ip string, port int) *NetworkPrinter {
return &NetworkPrinter{ip: ip, port: port}
}
func (p *NetworkPrinter) Open() error {
socket, err := net.Dial("tcp", fmt.Sprintf("%s:%d", p.ip, p.port))
if err != nil {
return err
}
p.socket = &socket
p.dst = bufio.NewWriter(socket)
return nil
}
func (p *NetworkPrinter) Close() error {
if p.socket != nil {
sP := *p.socket
err := sP.Close()
if err != nil {
return err
}
p.dst = nil
p.socket = nil
return nil
} else {
return nil
}
}
type SerialPrinter struct {
GenericPrinter
serialPort *serial.Port
port string
baudRate int
}
func NewSerialPrinter(port string) *SerialPrinter {
return &SerialPrinter{port: port, baudRate: 9600}
}
func (p *SerialPrinter) Open() error {
ports, err := serial.GetPortsList()
if err != nil {
return err
}
if len(ports) == 0 {
return errors.New("no serial ports found")
}
for _, port := range ports {
if port == p.port {
serialPort, err := serial.Open(port, &serial.Mode{BaudRate: p.baudRate})
if err != nil {
return err
}
p.serialPort = &serialPort
p.dst = bufio.NewWriter(serialPort)
return nil
}
}
return errors.New("chosen serial port not found")
}
func (p *SerialPrinter) Close() error {
if p.serialPort != nil {
sP := *p.serialPort
err := sP.Close()
if err != nil {
return err
}
p.dst = nil
p.serialPort = nil
return nil
} else {
return nil
}
}