Exemple #1
0
def printStickerLabel(orderNumber):
    stickerPrinter = Usb(0x1ba0, 0x220a, 0)
    stickerPrinter.set("center")

    mydb = mysql.connector.connect(host="62.75.152.102", user="******", passwd="GA2019!?", database="wordpress_b")
    mydb.autocommit = True
    # mycursor = mydb.cursor()
    # mycursor.execute("UPDATE orderPlaced SET collected  = IF(made = 1, 1 , 0), made  = IF(made = 0, 1 , 1) WHERE orderID = " + str(orderNumber))
    mycursor = mydb.cursor()
    mycursor.execute("SELECT IF(collected = 1, 'Collected' , 'Made') as Output, count(orderLine.extras), IF(orderPlaced.paid,'Paid On App','NEEDS TO PAY'), orderPlaced.orderID, orderPlaced.collection, orderPlaced.amount FROM orderPlaced, orderLine WHERE orderPlaced.orderID = orderLine.orderID AND orderPlaced.orderID = " + str(orderNumber))
    myresult = mycursor.fetchall()
    for x in myresult:
        for z in range(1,int(x[1]+1)):
            stickerPrinter.text(" Order Complete  \n")
            stickerPrinter.text(str(x[3]) + "\n\n")
            stickerPrinter.text(str(x[2]) + "\n\n")
            stickerPrinter.text(" Collection Time  \n")
            stickerPrinter.text(str(x[4]) + "\n\n")
            stickerPrinter.text("" + str(z) + " of " + str(int(x[1])) + "\n")
            stickerPrinter.barcode(str(x[3]), 'CODE39', 64, 2, 'OFF', 'True')
            if z != x[1]:
                stickerPrinter.text("\n\n=======================\n\n")
            else:
                stickerPrinter.cut()
    stickerPrinter.close()
Exemple #2
0
def checkout_setup(checkout_id):
    p = Usb(0x471, 0x55, 0, 0x82, 0x02)

    # p.device.read(p.in_ep, 1)

    res = requests.get('http://www.e-orders.org/api/printer/checkout-print?checkout_id={0}'.format(checkout_id))
    res_json = json.loads(res.text)
    print('response', res_json)
    items = res_json[0]
    print(items)

    p.set(align='center', text_type='B', width=3, height=3)
    p.text('CHECKOUT'+"\n")

    p.set(align='center', text_type='B', width=2, height=2)
    p.text(items['table_name']+"\n")
    p.set(align='center', text_type='normal', width=1, height=1)
    p.text(items['datetime']+"\n")

    for item in items['items']:
        p.set(align='left', text_type='B', width=2, height=1)
        p.text(str(item['quantity']) + 'x  '+ item['name']+'\n')
        p.set(align='right', text_type='B', width=1, height=1)
        p.text(str(item['quantity']) + ' x '+str(item['cost']) + '  sub total: ' + str(item['total_item_cost']) + '$' + '\n')
        # comment = item['comments']
    p.set(align='center', text_type='B', width=3, height=3)
    p.text('TOTAL: '+str(items['total'])+"\n")
    # p.text('\n\n\n\n\n\n\n\n\n\n\n\n')
    # p.text('\n\n\n\n\n\n\n\n\n\n\n\n')
    p.text('\n\n\n')
    # p.text('\n\n\n')
    p.cut()

    p.close()
Exemple #3
0
def impr(data = []):
    """
    Data = id de proyectos votados
    :param data:
    :return:
    """
    p = Usb(0x04b8, 0x0e15, 0, )
    # f = open("to_save", 'r+')
    # lines = f.readlines()[0]
    # data = ast.literal_eval(lines)
    p.image("{}functions/cabecera.jpg".format(path_proyecto))
    p.set(font='a', height=1, align='center')
    p.codepage = 'cp850'
    # p.charcode("MULTILINGUAL")
    # print(p.codepage)
    try:
        p.text('Presupuestos Participativos de Inversiones 2018\n')
        p.text('- Recibo informativo - \n')

        p.text('----------------------------------- \n')
        p.set(font='a', height=2, align='center')
        # date = datetime.now()
        date = datetime.now() + timedelta(hours=2)
        p.text('Votación realizada: \n {} \n \n'.format(date.strftime("%Y-%m-%d %H:%M:%S")))
        p.set(font='a', height=2, align='center')
        p.text('Proyectos elegidos: \n \n')
        p.set(font='a', height=1, align='center')
        #propuestas
        contMax = 0
        for i in data:
            e = propuestas.search_name_by_id(i)
            if e is None:
                print("Id de proyecto {} no valido".format(i))

            else:
                title, price = e
                contMax = contMax + int(price)
                price = format_price(price)
                p.text('{} - {} e \n\n'.format(title, price))

        p.set(font='a', height=2, align='center')
        p.text('\n Inversión total votada: ')
        p.text('{} e \n'.format(format_price(contMax)))
        p.set(font='a', height=1, align='center')
        p.text('\n \n Gracias por su participación \n')
        p.text('----------------------------------- \n')
        p.set(font='a', height=1, align='center')
        p.text(
            'Sistema presencial de votación electrónica \n')
        p.text("Evotebox \n")
        p.image("{}functions/gente.png".format(path_proyecto))
        p.cut()
        p.close()
    except:
        # print(traceback.format_exc())
        p.cut()
        p.close()
Exemple #4
0
def imprimir_ticket_final(data = {}, num_participantes=0):
    """
    Data = diccionario {id:num}
    :param data:
    :return:
    """
    p = Usb(0x04b8, 0x0e15, 0, )

    p.image("{}functions/cabecera.jpg".format(path_proyecto))
    p.set(font='a', height=1, align='center')
    p.codepage = 'cp850'
    try:
        p.text('Presupuestos Participativos de Inversiones 2018\n')
        p.text('- Acta de recuento - \n')

        p.text('----------------------------------- \n')
        p.set(font='a', height=2, align='center')
        # date = datetime.now()
        date = datetime.now() + timedelta(hours=2)
        p.text('Recuento realizado: \n {} \n \n'.format(date.strftime("%Y-%m-%d %H:%M:%S")))
        p.set(font='a', height=2, align='center')
        p.text('Participantes: {} personas\n \n'.format(num_participantes))
        p.text('Total de proyectos votados: {} proyectos \n \n'.format(len(data)))
        p.text('Proyectos votados: \n \n')
        p.set(font='a', height=1, align='center')
        if len(data) == 0:
            p.text("Lista vacia")
        #propuestas
        for i in data:
            e = propuestas.search_name_by_id(i)
            if e is None:
                print("Id de proyecto {} no valido".format(i))

            else:
                title, price = e
                votos = data[i]
                if votos == 1:
                    p.text('{} - {} voto \n\n'.format(title, votos))
                else:
                    p.text('{} - {} votos \n\n'.format(title, votos))

        p.set(font='a', height=1, align='center')
        p.text('----------------------------------- \n')
        p.set(font='a', height=1, align='center')
        p.text(
            'Sistema presencial de votación electrónica \n')
        p.text("Evotebox \n")
        p.image("{}functions/gente.png".format(path_proyecto))
        p.cut()
        p.close()
    except:
        # print(traceback.format_exc())
        p.cut()
        p.close()
Exemple #5
0
def printInitalOrderTicket(newValue):
    receiptPrinter = Usb(0x04b8, 0x0202, 0)
    receiptPrinter.set("center")

    EAN = barcode.get_barcode_class('code128')

    mydb = mysql.connector.connect(host="62.75.152.102", user="******", passwd="GA2019!?", database="wordpress_b")
    mydb.autocommit = True
    mycursor = mydb.cursor()
    mycursor.execute("SELECT lineID FROM orderLine WHERE orderID = " + str(newValue))
    myresult = mycursor.fetchall()
    orderlineIDS = []
    for x in myresult:
        orderlineIDS.append(str(x).split("(")[1].split(",")[0])

    complete = []	

    for x in orderlineIDS:
        mycursor = mydb.cursor()
        sql = "SELECT orderPlaced.orderID, DATE_FORMAT(orderPlaced.time, '%D %M %Y %T'), orderPlaced.collection, (SELECT itemDB.itemName FROM itemDB, orderLine WHERE itemDB.itemID = orderLine.foodID AND orderLine.lineID = " + str(x) + ") AS baguette, ( SELECT itemDB.itemName FROM itemDB, orderLine WHERE itemDB.itemID = orderLine.snackID AND orderLine.lineID = " + str(x) + ") AS snack, ( SELECT itemDB.itemName FROM itemDB, orderLine WHERE itemDB.itemID = orderLine.drinkID AND orderLine.lineID = " + str(x) + ") AS drink, orderLine.extras, orderLine.sauces, orderPlaced.paid, orderPlaced.amount FROM orderPlaced, orderLine WHERE orderPlaced.orderID = orderLine.orderID AND orderLine.lineID = " + str(x)
        print(sql)
        mycursor.execute(sql)
        myresult = mycursor.fetchall()
        complete.append(myresult)
        
    receiptPrinter.image("/home/pi/Documents/logo.png")
    receiptPrinter.text("\n\nNew Order Received\n")
    receiptPrinter.text("Order Number: " + str(complete[0][0][0]) + "\n\n")
    receiptPrinter.text("Date: " + str(complete[0][0][1]) + "\n\n")
    receiptPrinter.text("***************************************\n\n")
    for x in complete:
        receiptPrinter.text(str(x[0][3]).title() + " Baguette\n")
        receiptPrinter.text("(" + str(x[0][6]) + ")\n")
        receiptPrinter.text("(" + str(x[0][7]) + ")\n\n")
        if str(x[0][4]) != "None":
            receiptPrinter.text(str(x[0][4])+ "\n")
            receiptPrinter.text(str(x[0][5]) + "\n\n")  
        receiptPrinter.text("*\n\n")

    ean = EAN(str(complete[0][0][0]), writer=ImageWriter())
    fullname = ean.save('/home/pi/ean13_barcode')
    receiptPrinter.image("/home/pi/ean13_barcode.png")
    receiptPrinter.cut()
    mydb.close()
    """if str(complete[0][0][8]) == "0":
        client = Izettle(
            client_id='ccfe6b88-67e1-4f6d-94c5-34b91b11a5fa',
            client_secret='IZSEC33534207-7d83-4f70-b64d-8c54d4e21f00',
            user='******',
            password='******'
        )
        client.create_product_variant('d62f7bb0-2728-11e6-85b5-dd108c223139',{"name": "Order " + str(complete[0][0][0]) , "barcode": str(complete[0][0][0]), "price": {"amount": str(complete[0][0][9]), "currencyId": "GBP"}})
"""
    receiptPrinter.close()
Exemple #6
0
def reprintOrderTicket(orderNumber):
    receiptPrinter = Usb(0x04b8, 0x0202, 0)
    receiptPrinter.set("center")

    EAN = barcode.get_barcode_class('code128')

    mydb = mysql.connector.connect(host="62.75.152.102", user="******", passwd="GA2019!?", database="wordpress_b")
    mydb.autocommit = True
    mycursor = mydb.cursor()
    mycursor.execute("SELECT `lineID` FROM `orderLine` WHERE `orderID`= " + str(orderNumber))
    myresult = mycursor.fetchall()

    complete = []

    for x in myresult:
        x = x[0]
        mycursor = mydb.cursor()
        mycursor.execute("SELECT orderPlaced.orderID, DATE_FORMAT(orderPlaced.time, '%D %M %Y %T'), orderPlaced.collection, (SELECT itemDB.itemName FROM itemDB, orderLine WHERE itemDB.itemID = orderLine.foodID AND orderLine.lineID = " + str(x) + ") AS baguette, ( SELECT itemDB.itemName FROM itemDB, orderLine WHERE itemDB.itemID = orderLine.snackID AND orderLine.lineID = " + str(x) + ") AS snack, ( SELECT itemDB.itemName FROM itemDB, orderLine WHERE itemDB.itemID = orderLine.drinkID AND orderLine.lineID = " + str(x) + ") AS drink, orderLine.extras, orderLine.sauces, orderPlaced.paid, orderPlaced.amount FROM orderPlaced, orderLine WHERE orderPlaced.orderID = orderLine.orderID AND orderLine.lineID = " + str(x))
        myresult = mycursor.fetchall()
        complete.append(myresult)
        
    receiptPrinter.text("REPRINT ORDER TICKET\n")
    receiptPrinter.text("Order Number: " + str(complete[0][0][0]) + "\n\n")
    receiptPrinter.text("Date: " + str(complete[0][0][1]) + "\n")
    receiptPrinter.text("***************************************\n\n")
    for x in complete:
        receiptPrinter.text(str(x[0][3]).title() + " Baguette\n")
        receiptPrinter.text("(" + str(x[0][6]) + ")\n")
        receiptPrinter.text("(" + str(x[0][7]) + ")\n\n")
        if str(x[0][4]) != "None":
            receiptPrinter.text(str(x[0][4])+ "\n")
            receiptPrinter.text(str(x[0][5]) + "\n\n\n")  

    receiptPrinter.text("\n")
    ean = EAN(str(complete[0][0][0]), writer=ImageWriter())
    fullname = ean.save('/home/pi/ean13_barcode')
    receiptPrinter.image("/home/pi/ean13_barcode.png")
    receiptPrinter.cut()
    mydb.close()
    
    receiptPrinter.close()
Exemple #7
0
def main():  # Demo
    try:
        p = Usb(0x0416, 0x5011)
    except usb.core.USBError as e:
        if e.errno == 13:
            print("Printing permission is required. (are you root?)")
            subprocess.call(['sudo', '/usr/bin/env', 'python3', *sys.argv])
            quit(1)
        else:
            print(
                "Unknown Error about has catched during handling with USB Device. Program will closed.\n=========================="
            )
            raise e

    tt = softunicode(350)
    tt.changeFontTTF('neodgm.ttf', size=32)

    try:
        while True:
            p.image(tt.text(input()), impl=u'bitImageColumn')
    finally:
        p.text("\n\n\n")
        p.close()
Exemple #8
0
def do_usb_test():
    from escpos.printer import Usb
    import io
    pt = EscPosPrint(encode='gb2312', temp_path='/tmp/print', width=384)
    with io.open('test/all.xml', 'r', encoding='utf8') as f:
        pt.auto_print(f.read())
        import base64
        # print(base64.encodebytes(pt.get_data()))
        # return
        # p = Usb(0x6868, 0x0500, in_ep=0x84, out_ep=0x3)
        # p = Usb(0x154f, 0x1300, in_ep=0x82, out_ep=0x01)
        p = Usb(0x0483, 0x5720, in_ep=0x82, out_ep=0x02)
        # p._raw(bytes([0x31,0x32,0x33,0x0A,0x1D,0x4C,0x50,0x00,0x31, 0x32,0x33, 0x0A]) + pt.get_data())
        px = [
            0x1B,
            0x53,
            0x1D,
            0x57,
            0x80,
            0x01,
            0x1D,
            0x4C,
            0xF0,
            0x00,
            0x0a,
            # 0x31, 0x32, 0x33, 0x34, 0x34, 0x0A
        ]
        b = px + [
            ord(c)
            for c in '123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklnm\n'
        ]
        # b = [0x31, 0x32, 0x33, 0x0A, 0x1D, 0x4C, 0xE0, 0x00, 0x31, 0x32, 0x33, 0x0A]
        b = bytes(px) + pt.get_data()[2:]
        for i in b:
            print(hex(i))
        p._raw(bytes(b))
        p.close()
Exemple #9
0
    printer.image(image)


if __name__ == '__main__':

    # Some Text
    ptTitle = u'Test Title'
    ptText = u'Test Text'
    ptQR = u'This is my Alipay QRCode'

    # Print Something
    PrintAlign(1)
    PrintTime()
    PrintText(ptTitle, inputSize=36, inputBold=True)
    PrintSpace(20)

    PrintAlign(0)
    PrintText(ptText, inputBorder=2)
    PrintSpace(20)

    PrintAlign(1)
    PrintText(ptQR, inputSize=20)
    PrintImage("http://brainexplode.com/money.jpg")
    #printer.qr('http://brainexplode.com/me.html', ec=2, size=8)

    PrintSpace(20)
    PrintLine(1)

    printer.cut()
    printer.close()
Exemple #10
0
def orderProcess(queueType, awaitOrder, lidNoLid, tableLoc, MProc, updateCounter, updateInt, q):
    orderJob = get_current_job()
    orderJob.meta['lid'] = q["lid"]
    orderJob.meta['progress'] = 0
    try:
        if q['phone']:
           orderJob.meta['phone'] = q['phone']
    except:
        print("no phone#")
        orderJob.meta['phone'] = "0"
    orderJob.save_meta()
    print(orderJob)
    print(orderJob.meta)
    print(orderJob.kwargs)
    kukaDoneID = "ns=4;s=DI_KUKA_SIGNAL_DONE"
    kukaRunningID = "ns=4;s=DI_KUKA_SIGNAL_START"
    kukaWaitingID = "ns=4;s=DI_KUKA_SIGNAL_WAITING_ORDER"
    selectedQueueID = "ns=4;s=SELECTED_QUEUE"
    # print(q)
    # print(q["lid"])
    # print(q["dye"])
    # print(q["table"])
    isOPCAvailable = False
    try:
        # print("Order Processing")
        client = Client("opc.tcp://192.168.0.211:4870")  # Set OPC-UA Server
        # print("STOP")
        client.connect()
        awaitOrder = client.get_node(awaitOrder)
        while awaitOrder.get_value() is False:
            # print("HMI Not ready")
            sleep(1.0)
        sleep(6.0) # Need extra sleep to let all previous sequences clear out and become complete.
        # print("HMI is ready. Loading Values")
        M_Lid = client.get_node(lidNoLid)
        # print("Q" + q["lid"])
        if q["lid"] == "true":
            t = True
        else:
            t = False
        M_Lid.set_value(t)
        # print("Dye set" + str(dyeBool))
        M_Table = client.get_node(tableLoc)
        M_Table.set_value(int(q["table"]), VariantType.Int16)

        # print("table set" + q["table"])
        M_process = client.get_node(MProc)
        M_process.set_value(True)
        # print("process")
        awaitOrder.set_value(False)
        isOPCAvailable = True
    except OSError:
        print("OPC Server Unavailable")

    # Now monitor for status int changes
    # orderStatusCode = client.get_node()
    orderJob = get_current_job()
    orderJob.meta['progress'] = 0
    orderJob.save_meta()
    progressInt = 0
    if isOPCAvailable is False:
        asdf = 0
        while asdf < 10:
            orderJob.meta['progress'] = asdf
            # print(orderJob)
            # print(asdf)
            orderJob.save_meta()
            sleep(.05)
            asdf = asdf + 1
        orderJob.meta['progress'] = 10
        orderJob.save_meta()
    else:
        while orderJob.meta['progress'] != 10:
            client.disconnect()
            client.connect()
            countVal = client.get_node(updateCounter).get_value()
            intVal = client.get_node(updateInt).get_value()
            kukaQueue = client.get_node(selectedQueueID).get_value()
            kukaRun = client.get_node(kukaRunningID).get_value()
            kukaDone = client.get_node(kukaDoneID).get_value()
            estopstat = client.get_node("ns=4;s=M_E_Stop")
            print("Count" + str(countVal))
            print("INT COUNT" + str(intVal))
            print("kuka q" + str(kukaQueue))
            print("Kuka run" + str(kukaRun))
            print("kuka done" + str(kukaDone))
            print("quetype" + str(queueType))
            if(kukaQueue):
                print("kukaque is true")
            else:
                print("kukaqueue is false")
            if kukaRun:
                print("kukarun is true")
            else:
                print("kukarun is false")
            if queueType:
                print("qt is true")
            else:
                print("qt is false")

            if kukaQueue == queueType and (kukaRun or kukaDone ):  # IF The selected queue and working queue match, AND the kuka is in run sequence
                print("all true")
                orderJob.meta['progress'] = intVal
            else:
                orderJob.meta['progress'] = countVal
            if estopstat:
                orderJob.meta['progress'] = 30
                orderJob.save_meta()
                return
            orderJob.save_meta()
            sleep(1)

    try:
        client.disconnect()
    except (OSError, AttributeError) as e:
        print("OPC Unavailable")
    print("disconnect")
    #send sms
    try:
            name = ""
            if q['name']:
                name = q['name']
            n = phonenumbers.parse(orderJob.meta['phone'],"CA")
            if phonenumbers.is_possible_number(n):
                number = phonenumbers.format_number(n, phonenumbers.PhoneNumberFormat.E164)
                print(os.getenv("TSID"))
                print(os.getenv("TAUTH"))
                client = tClient(os.getenv("TSID"), os.getenv("TAUTH"))
                message = client.messages.create(body=str("Hello "+name + "\n Your order is ready at mobile pickup :)"), from_='+16042565679', to=number)
                print(message.sid)
    except:
            print("SMS Failed to send")
    try:
        printer = Usb(0x04b8, 0x0203)
        printer.set(font='a', height=2, align='CENTER', text_type="bold")
        printer.image("cup.gif")
        try:
            printer.text(q['name']+"\n")
        except:
            printer.text("No Name\n")
        printer.set(font='a', height=1, align='center', text_type='normal')
        printer.text(str("Dye: " + str(queueType) + " || Lid: " + str(q["lid"]) + "\n"))
        printer.set(font='b', height=1, align='center', text_type="bold")
        tableprint = str(int(q["table"]))
        if int(q["table"]) == 4:
            tableprint = "Mobile Pickup"
        printer.text(str("Table " + tableprint + "\n"))
        printer.cut()
        printer.close()

    except:
        print("printer error")
Exemple #11
0
#!/usr/bin/python
from escpos.printer import Usb
p = Usb(0x0416, 0x5011)
p.text("Mini Alexa Pi Printer\n")
p.close()
Exemple #12
0
def order_setup(order_id):
    myconverter = Converter(max_expansions=4)

    p = Usb(0x471, 0x55, 0, 0x82, 0x2)
    # p.codepa
    # p.device.write(p.out_ep, CHARCODE_GREEK, 5000)

    # p = Usb(0x1d6b, 0x2, 0, 0x82, 0x2)
    # p.codepage = 'cp1253'
    # p.charcode(code='AUTO')
    # p.device.read(p.in_ep, 1)

    res = requests.get('http://www.e-orders.org/api/app/order?order_id={0}'.format(order_id))
    res_json = json.loads(res.text)
    items = res_json['items']
    print(items)

    p.set(align='center', text_type='B', width=3, height=3)
    p.text('NEW ORDER'+"\n")

    p.set(align='center', text_type='B', width=2, height=2)
    p.text(items['items'][0]['table_name']+"\n")
    p.set(align='center', text_type='normal', width=1, height=1)
    p.text(items['datetime']+"\n")

    for item in items['items']:
        item_name =myconverter.convert(item['name'])[0]

        p.set(align='left', text_type='B', width=2, height=1)
        # p.text(str(item['quantity'])+'X '+item['name']+'\n')
        p.text(str(item['quantity'])+'X '+item_name+'\n')
        comment = item['comments']

        p.set(align='center', text_type='normal', width=1, height=1)
        print(comment)
        if comment =='':
            pass
        else:
            p.text('COMMENTS: '+item['comments'] + "\n")

        p.set(align='center', text_type='normal', width=2, height=1)

        for content in item['contents']:
            if content['changed'] == 1:
                if content['default'] == 0:
                    p.text('WITH   '+content['content_name']+'\n')

    p.text('\n\n\n\n\n\n\n\n\n\n\n\n')
    p.cut()
    # RT_STATUS = DLE + EOT
    # RT_STATUS_ONLINE = RT_STATUS + b'\x01'
    # RT_STATUS_PAPER = RT_STATUS + b'\x04'
    # p.barcode()
    method_list = [func for func in dir(p) if callable(getattr(p, func))]
    # print('device: ', p.query_status(PAPER_FULL_CUT))
    # print('device: ', p.query_status(PAPER_FULL_CUT))
    e = "\x10\x04\x04"
    # p.device.write(p.out_ep, RT_STATUS_PAPER)
    print('device: ', )
    print('device: ', )
    # print('device: ', p._raw(RT_STATUS_ONLINE))
    # print('device: ', p._read())
    p.close()
class Receipt:
    def __init__(self):
        from escpos.printer import Usb, Dummy

        self.eps = Usb(0x4b8, 0x0e03)
        self.dps = Dummy()

    def print_header(self, opts):
        """Responsible for printing the header part of the receipt,
           :param:opts: include all options that could go into the
           header like logo, company name and all that
        """
        if COMPANY_LOGO in opts.keys():
            self.imgesprint(opts[COMPANY_LOGO])
            self.esprint(LINE_BREAK)

        if COMPANY_NAME in opts.keys():
            self.esprint(opts[COMPANY_NAME])
            self.esprint(LINE_BREAK)

        if COMPANY_CONTACT in opts.keys():
            self.esprint(TEL)
            self.esprint(opts[COMPANY_CONTACT])
            self.esprint(LINE_BREAK)

        if COMPANY_LOCATION in opts.keys():
            self.esprint(LOC)
            self.esprint(opts[COMPANY_LOCATION])
            self.esprint(LINE_BREAK)

        self.n_char(SN_RULER, PAPER_MAX_WIDTH, w=1, h=1)
        self.esprint(LINE_BREAK)

        if RECEIPT_NAME in opts.keys():
            RNO = opts[RECEIPT_NUMBER] if RECEIPT_NUMBER in opts.keys() else ''
            RECEIPT = opts[RECEIPT_NAME] + SPACE_CHAR + HASH_NO + RNO
            self.cesprint(RECEIPT)
            char = len(RECEIPT)
            self.cesprint(self.n_char_generate(DO_RULER, char), w=1, h=2)
            self.esprint(LINE_BREAK)

        if CUSTOMER_NAME in opts.keys():
            self.lesprint(CUSTOMER, LEFT_PROPERTY_WIDTH)
            self.esprint(COLON_CHAR)
            self.n_char(SPACE_CHAR, LR_ALIGN)
            self.esprint(opts[CUSTOMER_NAME])
            self.esprint(LINE_BREAK)

        if CASHIER_NAME in opts.keys():
            self.lesprint(CASHIER, LEFT_PROPERTY_WIDTH)
            self.esprint(COLON_CHAR)
            self.n_char(SPACE_CHAR, LR_ALIGN)
            self.esprint(opts[CASHIER_NAME])
            self.esprint(LINE_BREAK)

        if RECEIPT_DATE in opts.keys():
            self.lesprint(DATE, LEFT_PROPERTY_WIDTH)
            self.esprint(COLON_CHAR)
            self.n_char(SPACE_CHAR, LR_ALIGN)
            self.esprint(opts[RECEIPT_DATE])
            self.esprint(LINE_BREAK)

        if CURRENCY_NAME in opts.keys():
            self.lesprint(CURRENCY_NAME_TITLE, LEFT_PROPERTY_WIDTH)
            self.esprint(COLON_CHAR)
            self.n_char(SPACE_CHAR, LR_ALIGN)
            self.esprint(opts[CURRENCY_NAME])
            self.esprint(LINE_BREAK)

    def print_items(self, items):
        """Responsible for printing the receipt part of
           the receipt.
        """
        self.n_char(SN_RULER, PAPER_MAX_WIDTH, w=1, h=1)
        self.esprint(LINE_BREAK)
        self.esprint(ITEM_TITLE)
        self.n_char(SPACE_CHAR, ITEM_TITLE_SPACE_AFTER)
        self.esprint(QTY_TITLE)
        self.n_char(SPACE_CHAR, QTY_TITLE_SPACE_AFTER)
        self.esprint(SP_TITLE)
        self.n_char(SPACE_CHAR, SP_TITLE_SPACE_AFTER)
        self.esprint(TOTAL_TITLE)
        self.n_char(SPACE_CHAR, TOTAL_TITLE_SPACE_AFTER)
        self.esprint(LINE_BREAK)
        self.n_char(DO_RULER, PAPER_MAX_WIDTH, w=1, h=2)
        self.esprint(LINE_BREAK)
        sum_total = 0
        for item in items:
            product = item[ITEM] if len(item[ITEM]) < ITEM_MAX_WIDTH else item[
                ITEM][:ITEM_MAX_WIDTH - ELIPSES_WIDTH] + ELIPSES
            qty = item[QTY] if isinstance(item[QTY], int) else round(
                str_2_num(item[QTY]), 2)
            price = round(str_2_num(item[SP]), 2)
            total = round(qty * price, 2)
            sum_total += total
            self.print_space(product, ITEM_MAX_WIDTH)
            self.print_space(str(qty), QTY_MAX_WIDTH)
            self.print_space(str(price), SP_MAX_WIDTH)
            self.print_space(str(total), TOTAL_MAX_WIDTH)
            self.esprint(LINE_BREAK)
        self.n_char(SN_RULER, PAPER_MAX_WIDTH, w=1, h=1)
        self.esprint(LINE_BREAK)
        self.esprint(TOTAL_TXT)
        leave = TOTAL_TXT_WIDTH
        self.n_char(SPACE_CHAR,
                    PAPER_MAX_WIDTH - TOTAL_MAX_WIDTH - leave,
                    w=1,
                    h=1)
        self.esprint(str(sum_total))
        self.esprint(LINE_BREAK)
        self.n_char(DO_RULER, PAPER_MAX_WIDTH, w=1, h=2)
        self.esprint(LINE_BREAK)

    def print_message(self, msg):
        self.cesprint(msg, char=STAR_CHAR)
        self.esprint(LINE_BREAK)

    def print_vat(self, vmsg):
        self.esprint(LINE_BREAK)
        self.cesprint(vmsg)
        self.esprint(LINE_BREAK)

    def print_me(self, me):
        self.esprint(me)

    def print_space(self, text, width, w=1, h=1):
        """Print text and then print space character
        for remaining space = width - texlen. For now texlen is not expected
        to be greater than width, if so just truncate to width.
        """
        texlen = len(text)
        if texlen > width:
            text = text[:width]
        self.lesprint(text, width)

    def imgesprint(self, path, align='center'):
        """Responsible for image printing"""
        self.dps.set(align=align)
        self.dps.image(path)

    def esprint(self, text, w=1, h=1):
        """A prudent wrapper around printing text with [self.eps.text()]"""
        self.dps.set(height=h, width=w)
        self.dps.text(text)

    def escut(self):
        self.eps.cut()

    def estop(self):
        self.eps.close()

    def cesprint(self, text, width=PAPER_MAX_WIDTH, char=SPACE_CHAR, w=1, h=1):
        """center align text and fill space left with :param:char:"""
        texlen = len(text)
        if texlen > width:
            diff = width % texlen
        else:
            diff = width - texlen
        if diff == 0:
            ldiff = rdiff = 0
        elif diff % 2 == 0:
            ldiff = rdiff = diff // 2
        else:
            ldiff = diff // 2
            rdiff = ldiff + 1
        self.n_char(char, ldiff)
        self.esprint(text, w, h)
        self.n_char(char, rdiff)

    def resprint(self, text, width=PAPER_MAX_WIDTH, char=SPACE_CHAR, w=1, h=1):
        """right align text and fill space left with :param:char:"""
        texlen = len(text)
        diff = width - texlen
        self.n_char(char, diff)
        self.esprint(text, w, h)

    def lesprint(self, text, width=PAPER_MAX_WIDTH, char=SPACE_CHAR, w=1, h=1):
        """light align text and fill space left with :param:char:"""
        texlen = len(text)
        diff = width - texlen
        self.esprint(text, w, h)
        self.n_char(char, diff, w, h)

    def n_char(self, char, n, w=1, h=1):
        """Print char n times"""
        for i in range(n):
            self.esprint(char, w, h)

    def n_char_generate(self, char, n):
        """ Return string of char n time"""
        return char * n

    def get_longest_item(self, items):
        """Return the length of the longest
           Item name in the list of items
        """
        # Assume longest is initially zero
        longest = 0
        for item in items:
            # get length of item name
            length = len(item[ITEM])
            if length > longest:
                longest = length
        return longest

    def esecute(self):
        self.eps._raw(self.dps.output)