aboutsummaryrefslogtreecommitdiff
path: root/ql/ql.go
blob: 0d715518f424310226c7f6779a613ad99b71f2f7 (plain)
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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
// Package ql is a Linux driver for Brother QL-series printers.
package ql

// Resources:
//  http://etc.nkadesign.com/Printers/QL550LabelPrinterProtocol
//  https://github.com/torvalds/linux/blob/master/drivers/usb/class/usblp.c
//  http://www.undocprint.org/formats/page_description_languages/brother_p-touch

import (
	"errors"
	"io"
	"os"
	"path/filepath"
	"regexp"
	"strings"
	"syscall"
	"time"
	"unsafe"
)

// #include <linux/ioctl.h>
import "C"

// -----------------------------------------------------------------------------

func _IOC(dir, typ, nr, size int) uintptr {
	return (uintptr(dir) << C._IOC_DIRSHIFT) |
		(uintptr(typ) << C._IOC_TYPESHIFT) |
		(uintptr(nr) << C._IOC_NRSHIFT) |
		(uintptr(size) << C._IOC_SIZESHIFT)
}

const (
	iocnrGetDeviceID = 1
)

// lpiocGetDeviceID reads the IEEE-1284 Device ID string of a printer.
func lpiocGetDeviceID(fd uintptr) ([]byte, error) {
	var buf [1024]byte
	if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd,
		_IOC(C._IOC_READ, 'P', iocnrGetDeviceID, len(buf)),
		uintptr(unsafe.Pointer(&buf))); err != 0 {
		return nil, err
	}

	// In theory it might get trimmed along the way.
	length := int(buf[0])<<8 | int(buf[1])
	if 2+length > len(buf) {
		return buf[2:], errors.New("the device ID string got trimmed")
	}

	return buf[2 : 2+length], nil
}

// -----------------------------------------------------------------------------

var deviceIDRegexp = regexp.MustCompile(
	`(?s:\s*([^:,;]+?)\s*:\s*([^:;]*)\s*(?:;|$))`)

type deviceID map[string][]string

// parseIEEE1284DeviceID leniently parses an IEEE 1284 Device ID string
// and returns a map containing a slice of values for each key.
//
// See e.g. http://www.undocprint.org/formats/communication_protocols/ieee_1284
func parseIEEE1284DeviceID(id []byte) deviceID {
	m := make(deviceID)
	for _, kv := range deviceIDRegexp.FindAllStringSubmatch(string(id), -1) {
		var values []string
		for _, v := range strings.Split(kv[2], ",") {
			values = append(values, strings.Trim(v, "\t\n\v\f\r "))
		}
		m[kv[1]] = values
	}
	return m
}

func (id deviceID) Find(key, abbreviation string) []string {
	if values, ok := id[key]; ok {
		return values
	}
	if values, ok := id[abbreviation]; ok {
		return values
	}
	return nil
}

// -----------------------------------------------------------------------------

type Printer struct {
	File *os.File
}

func compatible(id deviceID) bool {
	for _, commandSet := range id.Find("COMMAND SET", "CMD") {
		if commandSet == "PT-CBP" {
			return true
		}
	}
	return false
}

// Open finds and initializes the first USB printer found supporting
// the appropriate protocol. Returns nil if no printer could be found.
func Open() (*Printer, error) {
	// Linux usblp module, located in /drivers/usb/class/usblp.c
	paths, err := filepath.Glob("/dev/usb/lp[0-9]*")
	if err != nil {
		return nil, err
	}
	for _, candidate := range paths {
		f, err := os.OpenFile(candidate, os.O_RDWR, 0)
		if err != nil {
			continue
		}
		// Filter out obvious non-printers.
		deviceID, err := lpiocGetDeviceID(f.Fd())
		if err != nil {
			f.Close()
			continue
		}
		// Filter out printers that wouldn't understand the protocol.
		if !compatible(parseIEEE1284DeviceID(deviceID)) {
			f.Close()
			continue
		}
		return &Printer{File: f}, nil
	}
	return nil, nil
}

// Initialize initializes the printer for further operations.
func (p *Printer) Initialize() error {
	// Clear the print buffer.
	invalidate := make([]byte, 400)
	if _, err := p.File.Write(invalidate); err != nil {
		return err
	}

	// Initialize.
	if _, err := p.File.WriteString("\x1b\x40"); err != nil {
		return err
	}

	// Flush any former responses in the printer's queue.
	//
	// I'm not sure if this is necessary, or rather whether the kernel driver
	// does any buffering that could cause data to be returned at this point.
	/*
		for {
			dummy := make([]byte, 32)
			if _, err := f.Read(dummy); err == io.EOF {
				break
			}
		}
	*/

	return nil
}

// GetStatus retrieves the printer's status as raw data. The printer must be
// in an appropriate mode, i.e. on-line and not currently printing.
func (p *Printer) GetStatus() ([]byte, error) {
	// Request status information.
	if _, err := p.File.WriteString("\x1b\x69\x53"); err != nil {
		return nil, err
	}

	// We need to poll the device a bit.
	status := make([]byte, 32)
	start := time.Now()
	for {
		if n, err := p.File.Read(status); err == io.EOF {
			time.Sleep(10 * time.Millisecond)
		} else if err != nil {
			return nil, err
		} else if n < 32 {
			return nil, errors.New("invalid read")
		} else {
			return status, nil
		}
		if time.Now().Sub(start) > time.Second {
			return nil, errors.New("timeout")
		}
	}
}

// Close closes the underlying file.
func (p *Printer) Close() error {
	return p.File.Close()
}

// -----------------------------------------------------------------------------

type mediaSize struct {
	WidthMM  int
	HeightMM int
}

type mediaInfo struct {
	// Note that these are approximates, many pins within the margins will work
	SideMarginPins int
	PrintAreaPins  int
}

var media = map[mediaSize]mediaInfo{
	// Continuous length tape
	{12, 0}: {29, 106},
	{29, 0}: {6, 306},
	{38, 0}: {12, 413},
	{50, 0}: {12, 554},
	{54, 0}: {0, 590},
	{62, 0}: {12, 696},

	// Die-cut labels
	{17, 54}:  {0, 165},
	{17, 87}:  {0, 165},
	{23, 23}:  {42, 236},
	{29, 42}:  {6, 306},
	{29, 90}:  {6, 306},
	{38, 90}:  {12, 413},
	{39, 48}:  {6, 425},
	{52, 29}:  {0, 578},
	{54, 29}:  {59, 602},
	{60, 86}:  {24, 672},
	{62, 29}:  {12, 696},
	{62, 100}: {12, 696},

	// Die-cut diameter labels
	{12, 12}: {113, 94},
	{24, 24}: {42, 236},
	{58, 58}: {51, 618},
}

type Status struct {
	MediaWidthMM  int
	MediaLengthMM int
	Errors        []string
}

// -----------------------------------------------------------------------------

func decodeBitfieldErrors(b byte, errors [8]string) []string {
	var result []string
	for i := uint(0); i < 8; i++ {
		if b&(1<<i) != 0 {
			result = append(result, errors[i])
		}
	}
	return result
}

// TODO: What exactly do we need? Probably extend as needed.
func decodeStatusInformation(d []byte) Status {
	var status Status
	status.Errors = append(status.Errors, decodeBitfieldErrors(d[8], [8]string{
		"no media", "end of media", "cutter jam", "?", "printer in use",
		"printer turned off", "high-voltage adapter", "fan motor error"})...)
	status.Errors = append(status.Errors, decodeBitfieldErrors(d[9], [8]string{
		"replace media", "expansion buffer full", "communication error",
		"communication buffer full", "cover open", "cancel key",
		"media cannot be fed", "system error"})...)
	return status
}