-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathprinter.go
88 lines (76 loc) · 1.78 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
package zplprinter
import (
"runtime"
"github.com/giddyinc/gousb/usb"
)
type UsbConfig struct {
Vendor usb.ID
Product usb.ID
Config uint8
Iface uint8
Setup uint8
Endpoint uint8
}
type UsbZplPrinter struct {
*usb.Device
Config UsbConfig
}
func (printer *UsbZplPrinter) Write(buf []byte) (int, error) {
endpoint, err := printer.OpenEndpoint(
printer.Config.Config,
printer.Config.Iface,
printer.Config.Setup,
printer.Config.Endpoint|uint8(usb.ENDPOINT_DIR_OUT),
)
if err != nil {
return 0, err
}
l, err := endpoint.Write(buf)
return l, err
}
func GetPrinters(ctx *usb.Context, config UsbConfig) ([]*UsbZplPrinter, error) {
var printers []*UsbZplPrinter
devices, err := ctx.ListDevices(func(desc *usb.Descriptor) bool {
var selected = desc.Vendor == config.Vendor
if config.Product != usb.ID(0) {
selected = selected && desc.Product == config.Product
}
return selected
})
if err != nil {
return printers, err
}
if len(devices) == 0 {
return printers, ErrorDeviceNotFound
}
getDevice:
for _, dev := range devices {
if runtime.GOOS == "linux" {
dev.DetachKernelDriver(0)
}
// get devices with IN direction on endpoint
for _, cfg := range dev.Descriptor.Configs {
for _, alt := range cfg.Interfaces {
for _, iface := range alt.Setups {
for _, end := range iface.Endpoints {
if end.Direction() == usb.ENDPOINT_DIR_OUT {
config.Config = cfg.Config
config.Iface = alt.Number
config.Setup = iface.Number
config.Endpoint = uint8(end.Number())
printer := &UsbZplPrinter{
dev,
config,
}
// don't timeout reading
printer.ReadTimeout = 0
printers = append(printers, printer)
continue getDevice
}
}
}
}
}
}
return printers, nil
}