REFACTOR style and PEP8, fixes #66

This commit is contained in:
Patrick Kanzler 2015-11-27 21:20:12 +01:00
parent 096445631f
commit 07d8e073ae
5 changed files with 128 additions and 152 deletions

View File

@ -1 +1 @@
__all__ = ["constants","escpos","exceptions","printer"] __all__ = ["constants", "escpos", "exceptions", "printer"]

View File

@ -12,27 +12,26 @@ except ImportError:
from PIL import Image from PIL import Image
import qrcode import qrcode
import time
from constants import * from constants import *
from exceptions import * from exceptions import *
class Escpos(object): class Escpos(object):
""" ESC/POS Printer object """ """ ESC/POS Printer object """
device = None device = None
@staticmethod
def _check_image_size(self, size): def _check_image_size(size):
""" Check and fix the size of the image to 32 bits """ """ Check and fix the size of the image to 32 bits """
if size % 32 == 0: if size % 32 == 0:
return (0, 0) return 0, 0
else: else:
image_border = 32 - (size % 32) image_border = 32 - (size % 32)
if (image_border % 2) == 0: if (image_border % 2) == 0:
return (image_border / 2, image_border / 2) return image_border / 2, image_border / 2
else: else:
return (image_border / 2, (image_border / 2) + 1) return image_border / 2, (image_border / 2) + 1
def _print_image(self, line, size): def _print_image(self, line, size):
""" Print formatted image """ """ Print formatted image """
@ -41,12 +40,12 @@ class Escpos(object):
buffer = "" buffer = ""
self._raw(S_RASTER_N) self._raw(S_RASTER_N)
buffer = "%02X%02X%02X%02X" % (((size[0]/size[1])/8), 0, size[1]&0xff, size[1]>>8) buffer = "%02X%02X%02X%02X" % (((size[0]/size[1])/8), 0, size[1] & 0xff, size[1] >> 8)
self._raw(buffer.decode('hex')) self._raw(buffer.decode('hex'))
buffer = "" buffer = ""
while i < len(line): while i < len(line):
hex_string = int(line[i:i+8],2) hex_string = int(line[i:i+8], 2)
buffer += "%02X" % hex_string buffer += "%02X" % hex_string
i += 8 i += 8
cont += 1 cont += 1
@ -55,7 +54,6 @@ class Escpos(object):
buffer = "" buffer = ""
cont = 0 cont = 0
def _convert_image(self, im): def _convert_image(self, im):
""" Parse image and prepare it to a printable format """ """ Parse image and prepare it to a printable format """
pixels = [] pixels = []
@ -63,8 +61,7 @@ class Escpos(object):
im_left = "" im_left = ""
im_right = "" im_right = ""
switch = 0 switch = 0
img_size = [ 0, 0 ] img_size = [0, 0]
if im.size[0] > 512: if im.size[0] > 512:
print ("WARNING: Image is wider than 512 and could be truncated at print time ") print ("WARNING: Image is wider than 512 and could be truncated at print time ")
@ -87,7 +84,7 @@ class Escpos(object):
im_color = (RGB[0] + RGB[1] + RGB[2]) im_color = (RGB[0] + RGB[1] + RGB[2])
im_pattern = "1X0" im_pattern = "1X0"
pattern_len = len(im_pattern) pattern_len = len(im_pattern)
switch = (switch - 1 ) * (-1) switch = (switch - 1) * (-1)
for x in range(pattern_len): for x in range(pattern_len):
if im_color <= (255 * 3 / pattern_len * (x+1)): if im_color <= (255 * 3 / pattern_len * (x+1)):
if im_pattern[x] == "X": if im_pattern[x] == "X":
@ -103,8 +100,7 @@ class Escpos(object):
self._print_image(pix_line, img_size) self._print_image(pix_line, img_size)
def image(self, path_img):
def image(self,path_img):
""" Open image file """ """ Open image file """
im_open = Image.open(path_img) im_open = Image.open(path_img)
@ -119,8 +115,7 @@ class Escpos(object):
# Convert the RGB image in printable image # Convert the RGB image in printable image
self._convert_image(im) self._convert_image(im)
def qr(self, text):
def qr(self,text):
""" Print QR Code for the provided string """ """ Print QR Code for the provided string """
qr_code = qrcode.QRCode(version=4, box_size=4, border=1) qr_code = qrcode.QRCode(version=4, box_size=4, border=1)
qr_code.add_data(text) qr_code.add_data(text)
@ -131,8 +126,7 @@ class Escpos(object):
# Convert the RGB image in printable image # Convert the RGB image in printable image
self._convert_image(im) self._convert_image(im)
def charcode(self, code):
def charcode(self,code):
""" Set Character Code Table """ """ Set Character Code Table """
if code.upper() == "USA": if code.upper() == "USA":
self._raw(CHARCODE_PC437) self._raw(CHARCODE_PC437)
@ -184,12 +178,12 @@ class Escpos(object):
# Align Bar Code() # Align Bar Code()
self._raw(TXT_ALIGN_CT) self._raw(TXT_ALIGN_CT)
# Height # Height
if height >=2 or height <=6: if height >= 2 or height <= 6:
self._raw(BARCODE_HEIGHT) self._raw(BARCODE_HEIGHT)
else: else:
raise BarcodeSizeError() raise BarcodeSizeError()
# Width # Width
if width >= 1 or width <=255: if width >= 1 or width <= 255:
self._raw(BARCODE_WIDTH) self._raw(BARCODE_WIDTH)
else: else:
raise BarcodeSizeError() raise BarcodeSizeError()
@ -228,8 +222,7 @@ class Escpos(object):
if code: if code:
self._raw(code) self._raw(code)
else: else:
raise exception.BarcodeCodeError() raise BarcodeCodeError()
def text(self, txt): def text(self, txt):
""" Print alpha-numeric text """ """ Print alpha-numeric text """
@ -238,7 +231,6 @@ class Escpos(object):
else: else:
raise TextError() raise TextError()
def set(self, align='left', font='a', type='normal', width=1, height=1, density=9): def set(self, align='left', font='a', type='normal', width=1, height=1, density=9):
""" Set text properties """ """ Set text properties """
# Width # Width
@ -303,10 +295,9 @@ class Escpos(object):
self._raw(PD_P37) self._raw(PD_P37)
elif density == 8: elif density == 8:
self._raw(PD_P50) self._raw(PD_P50)
else:# DEFAULT: DOES NOTHING else: # DEFAULT: DOES NOTHING
pass pass
def cut(self, mode=''): def cut(self, mode=''):
""" Cut paper """ """ Cut paper """
# Fix the size between last line and cut # Fix the size between last line and cut
@ -317,7 +308,6 @@ class Escpos(object):
else: # DEFAULT MODE: FULL CUT else: # DEFAULT MODE: FULL CUT
self._raw(PAPER_FULL_CUT) self._raw(PAPER_FULL_CUT)
def cashdraw(self, pin): def cashdraw(self, pin):
""" Send pulse to kick the cash drawer """ """ Send pulse to kick the cash drawer """
if pin == 2: if pin == 2:
@ -327,7 +317,6 @@ class Escpos(object):
else: else:
raise CashDrawerError() raise CashDrawerError()
def hw(self, hw): def hw(self, hw):
""" Hardware operations """ """ Hardware operations """
if hw.upper() == "INIT": if hw.upper() == "INIT":
@ -339,14 +328,13 @@ class Escpos(object):
else: # DEFAULT: DOES NOTHING else: # DEFAULT: DOES NOTHING
pass pass
def control(self, ctl, pos=4): def control(self, ctl, pos=4):
""" Feed control sequences """ """ Feed control sequences """
# Set tab positions # Set tab positions
if pos < 1 or pos > 16: if pos < 1 or pos > 16:
raise TabError() raise TabError()
else: else:
self._raw("".join([CTL_SET_HT,hex(pos)])) self._raw("".join([CTL_SET_HT, hex(pos)]))
# Set position # Set position
if ctl.upper() == "LF": if ctl.upper() == "LF":
self._raw(CTL_LF) self._raw(CTL_LF)

View File

@ -1,6 +1,5 @@
""" ESC/POS Exceptions classes """ """ ESC/POS Exceptions classes """
import os
class Error(Exception): class Error(Exception):
""" Base class for ESC/POS errors """ """ Base class for ESC/POS errors """
@ -35,6 +34,7 @@ class BarcodeTypeError(Error):
def __str__(self): def __str__(self):
return "No Barcode type is defined" return "No Barcode type is defined"
class BarcodeSizeError(Error): class BarcodeSizeError(Error):
def __init__(self, msg=""): def __init__(self, msg=""):
Error.__init__(self, msg) Error.__init__(self, msg)
@ -44,6 +44,7 @@ class BarcodeSizeError(Error):
def __str__(self): def __str__(self):
return "Barcode size is out of range" return "Barcode size is out of range"
class BarcodeCodeError(Error): class BarcodeCodeError(Error):
def __init__(self, msg=""): def __init__(self, msg=""):
Error.__init__(self, msg) Error.__init__(self, msg)
@ -53,6 +54,7 @@ class BarcodeCodeError(Error):
def __str__(self): def __str__(self):
return "Code was not supplied" return "Code was not supplied"
class ImageSizeError(Error): class ImageSizeError(Error):
def __init__(self, msg=""): def __init__(self, msg=""):
Error.__init__(self, msg) Error.__init__(self, msg)
@ -62,6 +64,7 @@ class ImageSizeError(Error):
def __str__(self): def __str__(self):
return "Image height is longer than 255px and can't be printed" return "Image height is longer than 255px and can't be printed"
class TextError(Error): class TextError(Error):
def __init__(self, msg=""): def __init__(self, msg=""):
Error.__init__(self, msg) Error.__init__(self, msg)

View File

@ -12,9 +12,9 @@ import serial
import socket import socket
from escpos import * from escpos import *
from constants import *
from exceptions import * from exceptions import *
class Usb(Escpos): class Usb(Escpos):
""" Define USB printer """ """ Define USB printer """
@ -33,7 +33,6 @@ class Usb(Escpos):
self.out_ep = out_ep self.out_ep = out_ep
self.open() self.open()
def open(self): def open(self):
""" Search device on USB tree and set is as escpos device """ """ Search device on USB tree and set is as escpos device """
self.device = usb.core.find(idVendor=self.idVendor, idProduct=self.idProduct) self.device = usb.core.find(idVendor=self.idVendor, idProduct=self.idProduct)
@ -52,7 +51,7 @@ class Usb(Escpos):
self.device.detach_kernel_driver(0) self.device.detach_kernel_driver(0)
except usb.core.USBError as e: except usb.core.USBError as e:
if check_driver is not None: if check_driver is not None:
print "Could not detatch kernel driver: %s" % str(e) print "Could not detach kernel driver: %s" % str(e)
try: try:
self.device.set_configuration() self.device.set_configuration()
@ -60,12 +59,10 @@ class Usb(Escpos):
except usb.core.USBError as e: except usb.core.USBError as e:
print "Could not set configuration: %s" % str(e) print "Could not set configuration: %s" % str(e)
def _raw(self, msg): def _raw(self, msg):
""" Print any command sent in raw format """ """ Print any command sent in raw format """
self.device.write(self.out_ep, msg, self.interface) self.device.write(self.out_ep, msg, self.interface)
def __del__(self): def __del__(self):
""" Release USB interface """ """ Release USB interface """
if self.device: if self.device:
@ -73,13 +70,12 @@ class Usb(Escpos):
self.device = None self.device = None
class Serial(Escpos): class Serial(Escpos):
""" Define Serial printer """ """ Define Serial printer """
def __init__(self, devfile="/dev/ttyS0", baudrate=9600, bytesize=8, timeout=1, def __init__(self, devfile="/dev/ttyS0", baudrate=9600, bytesize=8, timeout=1,
parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE, parity=serial.PARITY_NONE, stopbits=serial.STOPBITS_ONE,
xonxoff=False , dsrdtr=True): xonxoff=False, dsrdtr=True):
""" """
@param devfile : Device file under dev filesystem @param devfile : Device file under dev filesystem
@param baudrate : Baud rate for serial transmission @param baudrate : Baud rate for serial transmission
@ -103,7 +99,6 @@ class Serial(Escpos):
self.open() self.open()
def open(self): def open(self):
""" Setup serial port and set is as escpos device """ """ Setup serial port and set is as escpos device """
self.device = serial.Serial(port=self.devfile, baudrate=self.baudrate, self.device = serial.Serial(port=self.devfile, baudrate=self.baudrate,
@ -116,23 +111,20 @@ class Serial(Escpos):
else: else:
print "Unable to open serial printer on: %s" % self.devfile print "Unable to open serial printer on: %s" % self.devfile
def _raw(self, msg): def _raw(self, msg):
""" Print any command sent in raw format """ """ Print any command sent in raw format """
self.device.write(msg) self.device.write(msg)
def __del__(self): def __del__(self):
""" Close Serial interface """ """ Close Serial interface """
if self.device is not None: if self.device is not None:
self.device.close() self.device.close()
class Network(Escpos): class Network(Escpos):
""" Define Network printer """ """ Define Network printer """
def __init__(self,host,port=9100): def __init__(self, host, port=9100):
""" """
@param host : Printer's hostname or IP address @param host : Printer's hostname or IP address
@param port : Port to write to @param port : Port to write to
@ -141,7 +133,6 @@ class Network(Escpos):
self.port = port self.port = port
self.open() self.open()
def open(self): def open(self):
""" Open TCP socket and set it as escpos device """ """ Open TCP socket and set it as escpos device """
self.device = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self.device = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
@ -150,18 +141,15 @@ class Network(Escpos):
if self.device is None: if self.device is None:
print "Could not open socket for %s" % self.host print "Could not open socket for %s" % self.host
def _raw(self, msg): def _raw(self, msg):
""" Print any command sent in raw format """ """ Print any command sent in raw format """
self.device.send(msg) self.device.send(msg)
def __del__(self): def __del__(self):
""" Close TCP connection """ """ Close TCP connection """
self.device.close() self.device.close()
class File(Escpos): class File(Escpos):
""" Define Generic file printer """ """ Define Generic file printer """
@ -172,7 +160,6 @@ class File(Escpos):
self.devfile = devfile self.devfile = devfile
self.open() self.open()
def open(self): def open(self):
""" Open system file """ """ Open system file """
self.device = open(self.devfile, "wb") self.device = open(self.devfile, "wb")
@ -180,11 +167,9 @@ class File(Escpos):
if self.device is None: if self.device is None:
print "Could not open the specified file %s" % self.devfile print "Could not open the specified file %s" % self.devfile
def _raw(self, msg): def _raw(self, msg):
""" Print any command sent in raw format """ """ Print any command sent in raw format """
self.device.write(msg); self.device.write(msg)
def __del__(self): def __del__(self):
""" Close system file """ """ Close system file """