From 89fc9d86c727aa8dc80232b461a7903a3c16d10e Mon Sep 17 00:00:00 2001
From: Přemysl Janouch
Date: Fri, 12 Apr 2019 23:10:42 +0200
Subject: Cleanup, improve communication while printing
---
go.mod | 25 +++-
go.sum | 68 +++++++++
label-exp/main.go | 23 +--
ql/ql.go | 425 ++++--------------------------------------------------
ql/ql_linux.go | 212 +++++++++++++++++++++++++++
ql/status.go | 206 ++++++++++++++++++++++++++
6 files changed, 555 insertions(+), 404 deletions(-)
create mode 100644 ql/ql_linux.go
create mode 100644 ql/status.go
diff --git a/go.mod b/go.mod
index 21910f7..c4f03d0 100644
--- a/go.mod
+++ b/go.mod
@@ -2,4 +2,27 @@ module janouch.name/sklad
go 1.12
-require github.com/boombuler/barcode v1.0.0
+require (
+ github.com/boombuler/barcode v1.0.0
+ github.com/cosiner/argv v0.0.1 // indirect
+ github.com/cpuguy83/go-md2man v1.0.10 // indirect
+ github.com/go-delve/delve v1.2.0 // indirect
+ github.com/konsorten/go-windows-terminal-sequences v1.0.2 // indirect
+ github.com/mattn/go-colorable v0.1.1 // indirect
+ github.com/mattn/go-isatty v0.0.7 // indirect
+ github.com/mattn/go-runewidth v0.0.4 // indirect
+ github.com/peterh/liner v1.1.0 // indirect
+ github.com/pkg/profile v1.3.0 // indirect
+ github.com/russross/blackfriday v2.0.0+incompatible // indirect
+ github.com/sirupsen/logrus v1.4.1 // indirect
+ github.com/spf13/cobra v0.0.3 // indirect
+ github.com/spf13/pflag v1.0.3 // indirect
+ github.com/stretchr/objx v0.2.0 // indirect
+ golang.org/x/arch v0.0.0-20190312162104-788fe5ffcd8c // indirect
+ golang.org/x/crypto v0.0.0-20190411191339-88737f569e3a // indirect
+ golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3 // indirect
+ golang.org/x/sys v0.0.0-20190411185658-b44545bcd369 // indirect
+ golang.org/x/tools v0.0.0-20190411180116-681f9ce8ac52 // indirect
+ gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127 // indirect
+ gopkg.in/yaml.v2 v2.2.2 // indirect
+)
diff --git a/go.sum b/go.sum
index 49e97e3..53eaedf 100644
--- a/go.sum
+++ b/go.sum
@@ -1,2 +1,70 @@
github.com/boombuler/barcode v1.0.0 h1:s1TvRnXwL2xJRaccrdcBQMZxq6X7DvsMogtmJeHDdrc=
github.com/boombuler/barcode v1.0.0/go.mod h1:paBWMcWSl3LHKBqUq+rly7CNSldXjb2rDl3JlRe0mD8=
+github.com/cosiner/argv v0.0.0-20170225145430-13bacc38a0a5/go.mod h1:p/NrK5tF6ICIly4qwEDsf6VDirFiWWz0FenfYBwJaKQ=
+github.com/cosiner/argv v0.0.1 h1:2iAFN+sWPktbZ4tvxm33Ei8VY66FPCxdOxpncUGpAXE=
+github.com/cosiner/argv v0.0.1/go.mod h1:p/NrK5tF6ICIly4qwEDsf6VDirFiWWz0FenfYBwJaKQ=
+github.com/cpuguy83/go-md2man v1.0.8/go.mod h1:N6JayAiVKtlHSnuTCeuLSQVs75hb8q+dYQLjr7cDsKY=
+github.com/cpuguy83/go-md2man v1.0.10/go.mod h1:SmD6nW6nTyfqj6ABTjUi3V3JVMnlJmwcJI5acqYI6dE=
+github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
+github.com/go-delve/delve v1.2.0 h1:uwGyfYO0WsWqbnDWvxCBKOr2qFLpii3tLxwM+fTJs70=
+github.com/go-delve/delve v1.2.0/go.mod h1:yP+LD36s/ud5nm4lsQY0TwNhYu2PAwk6xItz+442j74=
+github.com/inconshreveable/mousetrap v1.0.0/go.mod h1:PxqpIevigyE2G7u3NXJIT2ANytuPF1OarO4DADm73n8=
+github.com/konsorten/go-windows-terminal-sequences v1.0.1/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
+github.com/konsorten/go-windows-terminal-sequences v1.0.2/go.mod h1:T0+1ngSBFLxvqU3pZ+m/2kptfBszLMUkC4ZK/EgS/cQ=
+github.com/mattn/go-colorable v0.0.0-20170327083344-ded68f7a9561/go.mod h1:9vuHe8Xs5qXnSaW/c/ABM9alt+Vo+STaOChaDxuIBZU=
+github.com/mattn/go-colorable v0.1.1/go.mod h1:FuOcm+DKB9mbwrcAfNl7/TZVBZ6rcnceauSikq3lYCQ=
+github.com/mattn/go-isatty v0.0.3/go.mod h1:M+lRXTBqGeGNdLjl/ufCoiOlB5xdOkqRJdNxMWT7Zi4=
+github.com/mattn/go-isatty v0.0.5/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
+github.com/mattn/go-isatty v0.0.7 h1:UvyT9uN+3r7yLEYSlJsbQGdsaB/a0DlgWP3pql6iwOc=
+github.com/mattn/go-isatty v0.0.7/go.mod h1:Iq45c/XA43vh69/j3iqttzPXn0bhXyGjM0Hdxcsrc5s=
+github.com/mattn/go-runewidth v0.0.3/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
+github.com/mattn/go-runewidth v0.0.4 h1:2BvfKmzob6Bmd4YsL0zygOqfdFnK7GR4QL06Do4/p7Y=
+github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzpuz5H//U1FU=
+github.com/peterh/liner v0.0.0-20170317030525-88609521dc4b/go.mod h1:xIteQHvHuaLYG9IFj6mSxM0fCKrs34IrEQUhOYuGPHc=
+github.com/peterh/liner v1.1.0 h1:f+aAedNJA6uk7+6rXsYBnhdo4Xux7ESLe+kcuVUF5os=
+github.com/peterh/liner v1.1.0/go.mod h1:CRroGNssyjTd/qIG2FyxByd2S8JEAZXBl4qUrZf8GS0=
+github.com/pkg/profile v0.0.0-20170413231811-06b906832ed0/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA=
+github.com/pkg/profile v1.3.0/go.mod h1:hJw3o1OdXxsrSjjVksARp5W95eeEaEfptyVZyv6JUPA=
+github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
+github.com/russross/blackfriday v0.0.0-20180428102519-11635eb403ff/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
+github.com/russross/blackfriday v1.5.2/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
+github.com/russross/blackfriday v2.0.0+incompatible/go.mod h1:JO/DiYxRf+HjHt06OyowR9PTA263kcR/rfWxYHBV53g=
+github.com/sirupsen/logrus v0.0.0-20180523074243-ea8897e79973/go.mod h1:pMByvHTf9Beacp5x1UXfOR9xyW/9antXMhjMPG0dEzc=
+github.com/sirupsen/logrus v1.4.1 h1:GL2rEmy6nsikmW0r8opw9JIRScdMF5hA8cOYLH7In1k=
+github.com/sirupsen/logrus v1.4.1/go.mod h1:ni0Sbl8bgC9z8RoU9G6nDWqqs/fq4eDPysMBDgk/93Q=
+github.com/spf13/cobra v0.0.0-20170417170307-b6cb39589372/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
+github.com/spf13/cobra v0.0.3 h1:ZlrZ4XsMRm04Fr5pSFxBgfND2EBVa1nLpiy1stUsX/8=
+github.com/spf13/cobra v0.0.3/go.mod h1:1l0Ry5zgKvJasoi3XT1TypsSe7PqH0Sj9dhYf7v3XqQ=
+github.com/spf13/pflag v0.0.0-20170417173400-9e4c21054fa1/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
+github.com/spf13/pflag v1.0.3 h1:zPAT6CGy6wXeQ7NtTnaTerfKOsV6V6F8agHXFiazDkg=
+github.com/spf13/pflag v1.0.3/go.mod h1:DYY7MBk1bdzusC3SYhjObp+wFpr4gzcvqqNjLnInEg4=
+github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/objx v0.1.1/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
+github.com/stretchr/objx v0.2.0/go.mod h1:qt09Ya8vawLte6SNmTgCsAVtYtaKzEcn8ATUoHMkEqE=
+github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
+github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
+golang.org/x/arch v0.0.0-20171004143515-077ac972c2e4/go.mod h1:cYlCBUl1MsqxdiKgmc4uh7TxZfWSFLOGSRR090WDxt8=
+golang.org/x/arch v0.0.0-20190312162104-788fe5ffcd8c h1:Rx/HTKi09myZ25t1SOlDHmHOy/mKxNAcu0hP1oPX9qM=
+golang.org/x/arch v0.0.0-20190312162104-788fe5ffcd8c/go.mod h1:flIaEI6LNU6xOCD5PaJvn9wGP0agmIOqjrtsKGRguv4=
+golang.org/x/crypto v0.0.0-20180614174826-fd5f17ee7299/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
+golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
+golang.org/x/crypto v0.0.0-20190411191339-88737f569e3a/go.mod h1:WFFai1msRO1wXaEeE5yQxYXgSfI8pQAWXbQop6sCtWE=
+golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
+golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
+golang.org/x/sys v0.0.0-20180614134839-8883426083c0/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20180905080454-ebe1bf3edb33/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20190222072716-a9d3bda3a223/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
+golang.org/x/sys v0.0.0-20190403152447-81d4e9dc473e/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/sys v0.0.0-20190411185658-b44545bcd369 h1:aBlRBZoCuZNRDClvfkDoklQqdLzBaA3uViASg2z2p24=
+golang.org/x/sys v0.0.0-20190411185658-b44545bcd369/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
+golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
+golang.org/x/tools v0.0.0-20181120060634-fc4f04983f62/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
+golang.org/x/tools v0.0.0-20190411180116-681f9ce8ac52/go.mod h1:LCzVGOaR6xXOjkQ3onu1FJEFr0SW1gC7cKk1uF8kGRs=
+gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
+gopkg.in/yaml.v2 v2.0.0-20170407172122-cd8b52f8269e/go.mod h1:JAlM8MvJe8wmxCU4Bli9HhUf9+ttbYbLASfIpnQbh74=
+gopkg.in/yaml.v2 v2.2.2 h1:ZCJp+EgiOT7lHqUV2J862kp8Qj64Jo6az82+3Td9dZw=
+gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
+rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
diff --git a/label-exp/main.go b/label-exp/main.go
index e15f71c..dd4f8c2 100644
--- a/label-exp/main.go
+++ b/label-exp/main.go
@@ -182,7 +182,6 @@ func getStatus(printer *ql.Printer) error {
if err := printer.UpdateStatus(); err != nil {
return err
}
- log.Printf("status\n%s", printer.LastStatus)
return nil
}
@@ -192,17 +191,23 @@ func handle(w http.ResponseWriter, r *http.Request) {
return
}
- var initErr error
+ var (
+ initErr error
+ mediaInfo *ql.MediaInfo
+ )
printer, printerErr := getPrinter()
if printerErr == nil {
defer printer.Close()
- initErr = getStatus(printer)
- }
+ printer.StatusNotify = func(status *ql.Status) {
+ log.Printf("\x1b[1mreceived status\x1b[m\n%s", status)
+ }
- var mediaInfo *ql.MediaInfo
- if printer.LastStatus != nil {
- mediaInfo = ql.GetMediaInfo(printer.LastStatus.MediaWidthMM(),
- printer.LastStatus.MediaLengthMM())
+ if initErr = getStatus(printer); initErr == nil {
+ mediaInfo = ql.GetMediaInfo(
+ printer.LastStatus.MediaWidthMM(),
+ printer.LastStatus.MediaLengthMM(),
+ )
+ }
}
var params = struct {
@@ -269,7 +274,7 @@ func main() {
log.Fatalln(err)
}
- log.Println("Starting server")
+ log.Println("starting server")
http.HandleFunc("/", handle)
log.Fatal(http.ListenAndServe(":8080", nil))
}
diff --git a/ql/ql.go b/ql/ql.go
index f7a23dc..ec84656 100644
--- a/ql/ql.go
+++ b/ql/ql.go
@@ -8,54 +8,11 @@ package ql
// http://www.undocprint.org/formats/communication_protocols/ieee_1284
import (
- "errors"
- "fmt"
"image"
- "io"
- "log"
- "os"
- "path/filepath"
"regexp"
"strings"
- "syscall"
- "time"
- "unsafe"
)
-// #include
-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(
@@ -96,14 +53,6 @@ func (id deviceID) FindFirst(key, abbreviation string) string {
// -----------------------------------------------------------------------------
-type Printer struct {
- File *os.File
- Manufacturer string
- Model string
- LastStatus *Status
- MediaInfo *MediaInfo
-}
-
func compatible(id deviceID) bool {
for _, commandSet := range id.Find("COMMAND SET", "CMD") {
if commandSet == "PT-CBP" {
@@ -113,118 +62,6 @@ func compatible(id deviceID) bool {
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
- }
- parsedID := parseIEEE1284DeviceID(deviceID)
- // Filter out printers that wouldn't understand the protocol.
- if !compatible(parsedID) {
- f.Close()
- continue
- }
- return &Printer{
- File: f,
- Manufacturer: parsedID.FindFirst("MANUFACTURER", "MFG"),
- Model: parsedID.FindFirst("MODEL", "MDL"),
- }, 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.
- /*
- var dummy [32]byte
- for {
- if _, err := f.Read(dummy[:]); err == io.EOF {
- break
- }
- }
- */
-
- return nil
-}
-
-var errTimeout = errors.New("timeout")
-var errInvalidRead = errors.New("invalid read")
-
-// pollStatusBytes waits for the printer to send a status packet and returns
-// it as raw data.
-func (p *Printer) pollStatusBytes(
- timeout time.Duration) (status [32]byte, err error) {
- start, n := time.Now(), 0
- for {
- if n, err = p.File.Read(status[:]); err == io.EOF {
- time.Sleep(10 * time.Millisecond)
- } else if err != nil {
- return status, err
- } else if n < 32 {
- return status, errInvalidRead
- } else {
- return status, nil
- }
- if time.Now().Sub(start) > timeout {
- return status, errTimeout
- }
- }
-}
-
-// Request new status information from the printer. The printer
-// must be in an appropriate mode, i.e. on-line and not currently printing.
-func (p *Printer) UpdateStatus() error {
- // Request status information.
- if _, err := p.File.WriteString("\x1b\x69\x53"); err != nil {
- return err
- }
-
- // Retrieve status information.
- status, err := p.pollStatusBytes(time.Second)
- if err != nil {
- p.LastStatus = nil
- return err
- }
-
- s := Status(status)
- p.LastStatus = &s
- return nil
-}
-
-// Close closes the underlying file.
-func (p *Printer) Close() error {
- return p.File.Close()
-}
-
// -----------------------------------------------------------------------------
type mediaSize struct {
@@ -278,30 +115,35 @@ func GetMediaInfo(widthMM, lengthMM int) *MediaInfo {
// -----------------------------------------------------------------------------
+const (
+ printBytes = 90
+ printPins = printBytes * 8
+)
+
// makeBitmapData converts an image to the printer's raster format.
-func makeBitmapData(src image.Image, offset, length int) (data []byte) {
+func makeBitmapData(src image.Image, margin, length int) (data []byte) {
bounds := src.Bounds()
- pixels := [720]bool{}
+ if bounds.Dy() > length {
+ bounds.Max.Y = bounds.Min.Y + length
+ }
+ if bounds.Dx() > printPins-margin {
+ bounds.Max.X = bounds.Min.X + printPins
+ }
+
+ pixels := [printPins]bool{}
for y := bounds.Min.Y; y < bounds.Max.Y; y++ {
length--
- if length <= 0 {
- break
- }
- off := offset
+ // The graphics needs to be inverted horizontally, iterating backwards.
+ offset := margin
for x := bounds.Max.X - 1; x >= bounds.Min.X; x-- {
- if off >= len(pixels) {
- break
- }
-
- // TODO: Anything to do with the ColorModel?
r, g, b, a := src.At(x, y).RGBA()
- pixels[off] = r == 0 && g == 0 && b == 0 && a != 0
- off++
+ pixels[offset] = r == 0 && g == 0 && b == 0 && a >= 0x8000
+ offset++
}
- data = append(data, 'g', 0x00, 90)
- for i := 0; i < 90; i++ {
+ data = append(data, 'g', 0x00, printBytes)
+ for i := 0; i < printBytes; i++ {
var b byte
for j := 0; j < 8; j++ {
b <<= 1
@@ -313,17 +155,20 @@ func makeBitmapData(src image.Image, offset, length int) (data []byte) {
}
}
for ; length > 0; length-- {
- data = append(data, 'g', 0x00, 90)
- data = append(data, make([]byte, 90)...)
+ data = append(data, 'g', 0x00, printBytes)
+ data = append(data, make([]byte, printBytes)...)
}
return
}
-func (p *Printer) makePrintData(image image.Image) (data []byte) {
+func makePrintData(status *Status, image image.Image) (data []byte) {
mediaInfo := GetMediaInfo(
- p.LastStatus.MediaWidthMM(),
- p.LastStatus.MediaLengthMM(),
+ status.MediaWidthMM(),
+ status.MediaLengthMM(),
)
+ if mediaInfo == nil {
+ return nil
+ }
// Raster mode.
// Should be the only supported mode for QL-800.
@@ -339,12 +184,12 @@ func (p *Printer) makePrintData(image image.Image) (data []byte) {
}
mediaType := byte(0x0a)
- if p.LastStatus.MediaLengthMM() != 0 {
+ if status.MediaLengthMM() != 0 {
mediaType = byte(0x0b)
}
data = append(data, 0x1b, 0x69, 0x7a, 0x02|0x04|0x40|0x80, mediaType,
- byte(p.LastStatus.MediaWidthMM()), byte(p.LastStatus.MediaLengthMM()),
+ byte(status.MediaWidthMM()), byte(status.MediaLengthMM()),
byte(dy), byte(dy>>8), byte(dy>>16), byte(dy>>24), 0, 0x00)
// Auto cut, each 1 label.
@@ -355,7 +200,7 @@ func (p *Printer) makePrintData(image image.Image) (data []byte) {
// Not sure what it means, doesn't seem to have any effect to turn it off.
data = append(data, 0x1b, 0x69, 0x4b, 0x08)
- if p.LastStatus.MediaLengthMM() != 0 {
+ if status.MediaLengthMM() != 0 {
// 3mm margins along the direction of feed. 0x23 = 35 dots, the minimum.
data = append(data, 0x1b, 0x69, 0x64, 0x23, 0x00)
} else {
@@ -373,211 +218,3 @@ func (p *Printer) makePrintData(image image.Image) (data []byte) {
// Print command with feeding.
return append(data, 0x1a)
}
-
-func (p *Printer) Print(image image.Image) error {
- data := p.makePrintData(image)
-
- // Print the prepared data.
- if _, err := p.File.Write(data); err != nil {
- return err
- }
-
- // TODO: We specifically need to wait for a transition to the receiving
- // state, and try to figure out something from the statuses.
- // We may also receive an error status instead of the transition to
- // the printing state. Or even after it.
- start, b := time.Now(), [32]byte{}
- for {
- if n, err := p.File.Read(b[:]); err == io.EOF {
- time.Sleep(100 * time.Millisecond)
- } else if err != nil {
- return err
- } else if n < 32 {
- return errors.New("invalid read")
- } else {
- status := Status(b)
- log.Printf("status\n%s", &status)
- }
- if time.Now().Sub(start) > 3*time.Second {
- break
- }
- }
- return nil
-}
-
-// -----------------------------------------------------------------------------
-
-// Status is a decoder for the status packed returned by the printer.
-type Status [32]byte
-
-func (s *Status) MediaWidthMM() int { return int(s[10]) }
-func (s *Status) MediaLengthMM() int { return int(s[17]) }
-
-func decodeBitfieldErrors(b byte, errors [8]string) []string {
- var result []string
- for i := uint(0); i < 8; i++ {
- if b&(1<
+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
+}
+
+// -----------------------------------------------------------------------------
+
+type Printer struct {
+ File *os.File
+ Manufacturer string
+ Model string
+
+ LastStatus *Status
+ MediaInfo *MediaInfo
+
+ // StatusNotify is called whenever we receive a status packet.
+ StatusNotify func(*Status)
+}
+
+// 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
+ }
+ parsedID := parseIEEE1284DeviceID(deviceID)
+ // Filter out printers that wouldn't understand the protocol.
+ if !compatible(parsedID) {
+ f.Close()
+ continue
+ }
+ return &Printer{
+ File: f,
+ Manufacturer: parsedID.FindFirst("MANUFACTURER", "MFG"),
+ Model: parsedID.FindFirst("MODEL", "MDL"),
+ }, 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.
+ /*
+ var dummy [32]byte
+ for {
+ if _, err := f.Read(dummy[:]); err == io.EOF {
+ break
+ }
+ }
+ */
+
+ return nil
+}
+
+var errTimeout = errors.New("timeout")
+var errInvalidRead = errors.New("invalid read")
+
+func (p *Printer) updateStatus(status Status) {
+ p.LastStatus = &status
+ if p.StatusNotify != nil {
+ p.StatusNotify(p.LastStatus)
+ }
+}
+
+// pollStatusBytes waits for the printer to send a status packet and returns
+// it as raw data.
+func (p *Printer) pollStatusBytes(
+ timeout time.Duration) (*Status, error) {
+ start, buf := time.Now(), [32]byte{}
+ for {
+ if n, err := p.File.Read(buf[:]); err == io.EOF {
+ time.Sleep(10 * time.Millisecond)
+ } else if err != nil {
+ return nil, err
+ } else if n < 32 {
+ return nil, errInvalidRead
+ } else {
+ p.updateStatus(Status(buf))
+ return p.LastStatus, nil
+ }
+ if time.Now().Sub(start) > timeout {
+ return nil, errTimeout
+ }
+ }
+}
+
+// Request new status information from the printer. The printer
+// must be in an appropriate mode, i.e. on-line and not currently printing.
+func (p *Printer) UpdateStatus() error {
+ // Request status information.
+ if _, err := p.File.WriteString("\x1b\x69\x53"); err != nil {
+ return err
+ }
+
+ // Retrieve status information.
+ if _, err := p.pollStatusBytes(time.Second); err != nil {
+ p.LastStatus = nil
+ return err
+ }
+ return nil
+}
+
+var errErrorOccurred = errors.New("error occurred")
+var errUnexpectedStatus = errors.New("unexpected status")
+var errUnknownMedia = errors.New("unknown media")
+
+func (p *Printer) Print(image image.Image) error {
+ data := makePrintData(p.LastStatus, image)
+ if data == nil {
+ return errUnknownMedia
+ }
+ if _, err := p.File.Write(data); err != nil {
+ return err
+ }
+
+ // See diagrams: we may receive an error status instead of the transition
+ // to the printing state. Or even after it.
+ //
+ // Not sure how exactly cooling behaves and I don't want to test it.
+ for {
+ status, err := p.pollStatusBytes(10 * time.Second)
+ if err != nil {
+ return err
+ }
+
+ switch status.Type() {
+ case StatusTypePhaseChange:
+ // Nothing to do.
+ case StatusTypePrintingCompleted:
+ return nil
+ case StatusTypeErrorOccurred:
+ return errErrorOccurred
+ default:
+ return errUnexpectedStatus
+ }
+ }
+}
+
+// Close closes the underlying file.
+func (p *Printer) Close() error {
+ return p.File.Close()
+}
diff --git a/ql/status.go b/ql/status.go
new file mode 100644
index 0000000..ab3e675
--- /dev/null
+++ b/ql/status.go
@@ -0,0 +1,206 @@
+package ql
+
+import (
+ "fmt"
+ "io"
+ "strings"
+)
+
+// Status is a decoder for the status packed returned by the printer.
+type Status [32]byte
+
+func (s *Status) MediaWidthMM() int { return int(s[10]) }
+func (s *Status) MediaLengthMM() int { return int(s[17]) }
+
+type StatusType byte
+
+const (
+ StatusTypeReplyToRequest StatusType = 0x00
+ StatusTypePrintingCompleted = 0x01
+ StatusTypeErrorOccurred = 0x02
+ StatusTypeTurnedOff = 0x04
+ StatusTypeNotification = 0x05
+ StatusTypePhaseChange = 0x06
+)
+
+func (s *Status) Type() StatusType { return StatusType(s[18]) }
+
+type StatusPhase byte
+
+const (
+ StatusPhaseReceiving StatusPhase = 0x00
+ StatusPhasePrinting = 0x01
+)
+
+func (s *Status) Phase() StatusPhase { return StatusPhase(s[19]) }
+
+func decodeBitfieldErrors(b byte, errors [8]string) []string {
+ var result []string
+ for i := uint(0); i < 8; i++ {
+ if b&(1<