Exemplo n.º 1
0
class Printer():

    def __init__(self, code=(0x0416, 0x5011, 0x81, 0x03)):
        self.code = code
        try:
            self.usb = Usb(*self.code)
        except Exception as e:
            print(e)

    @module_method
    def image(self, image_path):
        self.usb.image(image_path, impl='bitImageColumn')

    @module_method
    def text(self, text):
        self.usb.text(text)

    @module_method
    def html(self, html_str):
        image_file = renderer.html_to_image(html_str)
        self.image(image_file)

    @module_method
    def markdown(self, text):
        image_file = renderer.markdown_to_image(text)
        self.image(image_file)

    @module_method
    def providers(self, *providers):
        html_str = ''

        for p in providers:
            html_str += p.render()

        self.html(html_str)
Exemplo n.º 2
0
def print_thermal(header, title_first, title_seconds, date_time, qr_code,
                  gate_info, type_scan):
    result = False
    try:
        p = Usb(int(CONFIG['PRINTER']['vid'], 0),
                int(CONFIG['PRINTER']['pid'], 0),
                int(CONFIG['PRINTER']['timeout'], 0),
                int(CONFIG['PRINTER']['ep1in'], 0),
                int(CONFIG['PRINTER']['ep1out'], 0))
        p.set("CENTER", "B", "A", 2, 2)
        p.text(str(header) + "\n\n")
        p.set("CENTER", "A", "normal", 1, 1)
        p.text(str(title_first) + "\n")
        p.text(str(title_seconds) + "\n")
        p.text(str(date_time) + "\n\n")
        if (type_scan == 0):
            p.qr(str(qr_code), 0, 10)
        else:
            p.barcode(str(qr_code), "CODE128", function_type="B")
        p.text("\nPintu Masuk : " + str(gate_info) +
               "\n*** TERIMAKASIH ***\n\n\n")

        result = True
    except Exception as e:
        print(e)

    return result
Exemplo n.º 3
0
def main():
    names = [
        '神社 太郎',
        '神社 次郎',
        '神社 三郎',
    ]
    tadashi = 'xx神社祭典運営費拠出金'

    for name in names:
        create_img(name, tadashi)
        sleep(0.5)
        p = Usb(0x0416, 0x5011, out_ep=3)
        p.image('output.png')
        p.text('\n\n\n')

        print('Please hit any key')
        input()

        create_img(name, tadashi, copy=' <控>')
        sleep(0.5)
        p = Usb(0x0416, 0x5011, out_ep=3)
        p.image('output.png')
        p.text('\n\n\n')

        print('Please hit any key')
        input()
Exemplo n.º 4
0
class Peripherals:
    def __init__(self):
        self.printer = Usb(0x0416, 0x5011, profile="POS-5890")
        self.scanner = InputDevice(
            '/dev/input/event0')  # Replace with your device

        self.scancodes = {
            11: u'0',
            2: u'1',
            3: u'2',
            4: u'3',
            5: u'4',
            6: u'5',
            7: u'6',
            8: u'7',
            9: u'8',
            10: u'9'
        }

    def start_scanner(self, cbfunc):
        print("Starting scanner thread!")
        self.scanner_thr = BaseThread(name='scanner_thr',
                                      target=self.scanner_func,
                                      callback=cbfunc)
        self.scanner_thr.start()

    def scanner_func(self):
        barcode = ''
        # Make a thread
        for event in self.scanner.read_loop():
            if event.type == ecodes.EV_KEY:
                eventdata = categorize(event)
                # Keydown
                if eventdata.keystate == 1:
                    scancode = eventdata.scancode
                    # Enter
                    if scancode == 28:
                        # get the barcode (barcode)
                        return barcode
                    else:
                        key = self.scancodes.get(scancode, NOT_RECOGNIZED_KEY)
                        barcode = barcode + key
                        if key == NOT_RECOGNIZED_KEY:
                            print('unknown key, scancode=' + str(scancode))

    def start_print(self, time, order_number, barcodes):
        self.printer.set(align='left')
        self.printer.text("Time : %s \n" % time)
        self.printer.text("No Order : %s \n" % order_number)
        self.printer.text("Gate : 1")
        self.printer.text('\n')
        self.printer.soft_barcode('code128',
                                  barcodes,
                                  module_height=8,
                                  module_width=0.18)
        self.printer.text('\n')

        print("Done printing!")
Exemplo n.º 5
0
def printer_print(in_text):
    try:
        p = Usb(0x0416, 0x5011)  #, 0, profile="TM-T88III")
        p.text(in_text)
        p.text("\n")
    except:
        print("Connection to printer failed. \n")
        print(in_text)
        print("\n")
Exemplo n.º 6
0
def print_text(text):
    '''
    Prints the given text and cuts it. Returns True on success
    '''
    p = Usb(product_id, vendor_id, 2)
    curtime = time.strftime("%H:%M, %d/%m/%Y")
    to_print = curtime + "\n" + text
    p.text(to_print)
    p.text("\n")
    p.cut()
Exemplo n.º 7
0
    def __init__(self):
        load_environment()
        printer = Usb(0x0416, 0x5011)

        tweets = TweetLoader()
        user = "******"
        tweet = tweets.get(user)

        if tweet is not None:
            printer.text("@bnmcg/news: " + tweet + "\n\n")
Exemplo n.º 8
0
class ThermalPrinter():
    def __init__(self):
        self.p = Usb(0x0fe6, 0x811e, 98, 0x82, 0x02)

    def insert_imagen(self, img_surce):
        self.p.image(img_surce)

    def insert_qr(self, content, size):
        self.p.qr(content, size=size)  #size 1 - 16 default 3

    def insert_barcode(self, code, bc, height, width):
        self.p.barcode(code, bc, height=height, width=width)

    def insert_text(self, txt):
        self.p.text(txt)

    def insert_raw_txt(self, txt):
        self.p._raw(txt)

    # harware action, may be: INIT, SELECT, RESET
    def hardware_operation(self, hw):
        self.p.hw(hw)

    #string for the following control sequences:
    # LF for Line Feed
    # FF for Form Feed
    # CR for Carriage Return
    # HT for Horizontal Tab
    # VT for Vertical Tab
    #pos = horizontal tab position 1 - 16
    def feed_control(self, ctl, pos):
        self.p.control()

        self.p.charcode()


#   #def insert_textln(self, txt):
# align = CENTER LEFT RIGHT  default left
# font_type = A or B         default A
# textt_type = B(bold), U(underline), U2(underline, version2), BU(for bold and underlined, NORMAL(normal text) defaul tnormal
# width = width multiplier decimal 1 - 8 defaul 1
# heigh =  height multiplier decimal 1 - 8 defaul 1
# density = density 0 - 8
# def set_txt(self, align, font, text_type, density, height, width):

    def set_txt(self, *args, **Kwargs):
        print(Kwargs)
        self.p.set(Kwargs)

    def cut_paper(self):
        self.p.cut()
Exemplo n.º 9
0
class Print(object):
	def __init__(self):
		self.p = Usb(0x28e9, 0x0289, 0, out_ep=0x03)
	
	def __str__(self):
		return 
		
	__repr__ = __str__

	def cut(self):
		self.p.cut()
	
	def setText(self, size):
		self.p.set(align = u'center', font = u'a', smooth = True, width = size, height = size)

	def putImage(self, imagePath):
		self.p.image(str(imagePath))

	def putQr(self, qrInfo, qrSize = 10):
		self.p.qr(qrInfo, size = qrSize)

	def putBarcode(self, barcodeInfo):
		self.barcode(barcodeInfo, 'EAN13', 64, 2, '', '')

	def putText(self, text, textSize = 1):
		self.setText(textSize)
		self.p.text(text)

	def printResult(self, weight, volume, density):
		self.putText("******************************\n")
		self.putText(time.asctime())
		self.putText("\n")
		self.putText("\n")
		self.putText("Measured results are as follows:\n")
		self.putText("\n")
		self.putText("Weight: ")
		self.putText(str(weight))
		self.putText("\n")
		self.putText("Volume: ")
		self.putText(str(volume))
		self.putText("\n")
		self.putText("Density: ")
		self.putText(str(density))
		self.putText("\n")
		self.putText("\n")
		self.putText("Scan qr to check the result!\n")
		self.putQr("Weight: {weight}\nVolume: {volume}\nDensity: {density}".format(weight = weight, volume = volume, density = density))
		self.cut()
Exemplo n.º 10
0
def printer_print(code):
    from escpos.printer import Usb
    p = Usb(int(get_printer_id()[0], 16), int(get_printer_id()[1], 16), 0)
    if p.paper_status() == 2:
        text = 'Discount Code:\n\t{}\n'.format(code)
        p.text(text)
        p.barcode('1234567898765', 'EAN13', 64, 2, '', '')
        p.cut()
    elif p.paper_status() == 1:
        print('Paper running out soon!')
        # TODO: inform the manager immediately about the paper issue
        pass
    else:
        # TODO: show warning on screen that the machine is temporarily not able to print out barcode for non-app user,
        #  app users can still scan the barcode on the screen to obtain the voucher code
        pass
Exemplo n.º 11
0
def print_bar(name):
    width = 580
    height = 100

    image = Image.new('1', (width, height), 255)
    draw = ImageDraw.Draw(image)
    #font1 = ImageFont.truetype('clamp-1m-w4-regular.ttf', 50, encoding='unic')
    #draw.text((0, 0), "Barcode" + " ", font=font1, fill=0)
    font2 = ImageFont.truetype('Code39Barcode.ttf', 55)
    draw.text((0, 00), "*" + name + "*" + " ", font=font2, fill=0)

    p = Usb(0x0416, 0x5011, 0, 0x81, 0x03)
    p.text(" " + name + "\n")
    p.image(image)
    p.qr(name, size=6)
    #p.barcode("1324354", "CODE39")
    #p.barcode("{B012ABCDabcd", "CODE39", function_type="B")
    p.cut()
    return ''
Exemplo n.º 12
0
def print_trans():
  if platform.system() == 'Windows':
    process = subprocess.Popen(['php', 'printWindows.php'] + sys.argv[1:], stdout=subprocess.PIPE).communicate()[0]
    return process
  else:
    invoice = str(request.data.get('invoice', ''))
    conn = mysql.connect()
    cursor = conn.cursor()
    cursor.callproc('sp_getprint', (invoice,))
    data = cursor.fetchall()

    conn2 = mysql.connect()
    cursor2 = conn2.cursor()
    cursor2.callproc('sp_gettoko')
    toko = cursor2.fetchall()

    p = Usb(0x0416, 0x5011, 0)

    for item in toko:
      p.text(str(item[1]) + "\n")
      p.text(str(item[2]) + "\n")
      p.text("===============================\n")

    for item in data:
        p.text(str(item[0]) + " " + str(item[1]) + " " + str(item[2]) + "\n")

    p.cut()
    p.cashdraw(2)
    return "Print success"
Exemplo n.º 13
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()
Exemplo n.º 14
0
def generate_recipt(orderjson):
    p = Usb(0x0483, 0x5720, 0)

    #p.image("chainhack.png", high_density_vertical=True, high_density_horizontal=True)

    p.set(align='center',
          smooth=True,
          invert=True,
          density=8,
          width=4,
          height=4,
          font='1')
    p.text("Chainhack 4\n")
    p.set(align='center',
          smooth=True,
          invert=False,
          density=4,
          width=4,
          height=4)
    p.text("The Block\n")
    p.set(align='center',
          smooth=True,
          invert=False,
          density=4,
          width=4,
          height=4)
    p.text("Lisbon\n")
    '''
    p.set(align='left', smooth=True, invert=False, density=2, width=1, height=1)
    p.text("===========================\n")
    p.text("=============== Sales Recipt ===========\n")
    p.text("===========================\n")
    '''
    items = orderjson.get('items')

    print(items)
    '''
Exemplo n.º 15
0
from escpos.printer import Usb
from escpos import *
from time import sleep

# Adapt to your needs
p = Usb(0x0471, 0x0055, timeout=0, in_ep=0x82, out_ep=0x02)
#~ p = escpos.Escpos(0x0471, 0x0055,0)
# Print software and then hardware barcode with the same content
# p.soft_barcode('code39', '123456')

for idx in range(1):
    p.set(align='center', font='b', width=2, height=2)
    p.text('Ricevuta numero {}\n'.format(idx + 1))
    p.text('\n')
    p.set(align='left', font='c', width=3, height=3)
    p.text('Hello world\n')
    p.image('logo_bn.png')
    p.text('\n')
    p.set(align='right', font='a', width=1, height=1)
    p.text('Boxoffice LTC\n')
    p.text('\n')
    p.barcode('123456', 'CODE39')
    #~ p.print_and_feed(n=2)
    p.text('\n')
    p.qr("Prenotazione 00056", )
    p.text('\n')

    sleep(1)
    p.cut(mode=u'FULL')
Exemplo n.º 16
0
#!/usr/bin/env python3
from escpos.printer import Usb
import sys
""" TEROW 58 """
p = Usb(0x416, 0x5011)

p.text(sys.argv[1] + "\n")
Exemplo n.º 17
0
from escpos.printer import Usb

""" Set your VendorId, ProductId -> See the readme.md """
p = Usb(0x20d1, 0x7007)
p.text("Hello World\n")
p.cut()
Exemplo n.º 18
0
from escpos.printer import Usb


# Adapt to your needs
p = Usb(0x0416, 0x5011, profile="POS-5890")

# Print software and then hardware barcode with the same content
p.soft_barcode('code39', '123456')
p.text('\n')
p.text('\n')
p.barcode('123456', 'CODE39')
Exemplo n.º 19
0
#  sys.argv
# [1] Código do movimento de portaria
# [2] Nome do motorista
# [3] OC ou SCM
# [4] Código da OC ou da SCM
# [5] Nome do usuário do protheus
# [6] tipo da refeição [1]café [2]almoço [3]janta

agora = datetime.now().strftime("%d/%m/%Y  |  %H:%M")

p = Usb(0x04B8, 0x0E27, 0, 0x81,
        0x02)  # Específico para impressora Epson TM-T20X
p.set(double_width=True, double_height=True)
p.control('HT')
p.text("    TICKET REFEICAO")
p.set(double_width=True, double_height=False)
p.ln()
p.ln()
p.text('       ' + sys.argv[1])
p.ln()
p.ln()
p.text('   ' + sys.argv[2].replace('_', ' '))
p.ln()
p.ln()
p.text('     ' + sys.argv[3] + ' ' + sys.argv[4])
p.ln()
p.ln()
if sys.argv[6] == '1':
    p.text('         ' + "Cafe")
elif sys.argv[6] == '2':
Exemplo n.º 20
0
json_data = json.load(file)

printer = Usb(0x0416, 0x5011)

id_compra = json_data['id_compra']
data = json_data['data']
valor = json_data['valor']
cliente = json_data['cliente']
observacao = json_data['observacao']

cliente = unidecode(cliente)
atendente = unidecode(atendente)
observacao = unidecode(observacao)

printer.set(align='center', width=2, height=2, invert=True)
printer.text(' Paes & Cia \n\n')

printer.set(align='center', width=2, height=1)
printer.text('Recibo de\nentrega\n\n')

printer.set(align='left')
printer.text('ID: ' + id_compra + '\n')
printer.text('Data: ' + data + '\n')
printer.text('Valor: R$ ' + valor + '\n')
printer.text('Cliente: ' + cliente + '\n')
if (observacao != 'null'):
    printer.text('Observacao: ' + observacao + '\n')

printer.text('\n\n')
printer.set(align='center')
printer.text('__________________________\n')
Exemplo n.º 21
0
data = json_data['data']
valor = json_data['valor']
cliente = json_data['cliente']
atendente = json_data['atendente']
observacao = json_data['observacao']

qtd_compras = int(json_data['qtd_compras'])
compras_list = []
for i in range(qtd_compras):
	data_aux = json_data['compra_data' + str(i)]
	valor_aux = json_data['compra_valor' + str(i)]
	compras_list.append([data_aux, valor_aux])


printer.set(align='center', width=2, height=2)
printer.text('Paes & Cia\n\n')

printer.set(align='center', width=2, height=1)
printer.text('Recibo de\npagamento\n\n')

printer.set(align='left', width=1, height=1)
printer.text('ID: ' + id_pagamento + '\n')
printer.text('Data: ' + data + '\n')
printer.text('Valor total: R$ ' + valor + '\n')
printer.text('Cliente: ' + cliente + '\n')
printer.text('Atendente: ' + atendente + '\n')
if (observacao != 'null'):
	printer.text('Observacao: ' + observacao + '\n')

printer.text('\n')
for compra in compras_list:
Exemplo n.º 22
0
from escpos.printer import Usb, Dummy, Serial
import os
import hashlib
#Print System usb id information
os.system("lsusb")
print("\n\n")
#Get user usbid
'''
vid = input("\nPlease input VendorID (e.g.:0x21a1):")
vid = int(vid,16)
pid = input("\nPlease input ProductID (e.g.:0x2123):")
pid = int(pid,16)
oep = input("\nPlease input ENDPOINT:")
oep = int(oep,16)
print("\nThe USB VendorID is ["+str(vid)+"] ProductID is ["+str(pid)+"]")
'''
i = 0
p = Usb(0x0483, 0x070b, 0, out_ep=0x2)
p.text("HELLO WORLD! I'M PRINTER!\n\n")
p.image("timg.jpg")
while True:
    pstr = str(hashlib.md5(i + 123).hexdigest())
    p.text(pstr)
    i = i + 1
Exemplo n.º 23
0
def printSpanish(date, guid, city, state, receiptId, leader, cashier, subtotal, tax, total, payments, eventType, Items, Cashes, Cards):


    temp = leader.strip().split(' ')
    leader = ""
    for x in range(len(temp)):
        if (len(temp[x]) > 0):
            leader = leader + " " + temp[x].strip()

    event =   "Seminario  : " + city.strip() + ", " + state.strip()
    leader =  "Lider      : " + trimHeader( leader.strip() )
    cashier = "Cajero     : " + cashier.strip()



    #stuff
    """ Seiko Epson Corp. Receipt Printer M129 Definitions (EPSON TM-T88IV) """
    p = Usb(0x04b8,0x0202,0)
    p.set("Center")

    p.image( os.path.dirname(os.path.realpath(__file__)) + "/logo.jpg")

    p.text(date + "\n")
    p.barcode( receiptId.strip() , "EAN13")
    p.text("\n")

    p.set("left")
    p.text(event + "\n")
    p.text(leader + "\n")
    p.text(cashier + "\n")
    p.text("\n")


    p.set("left")

    #				22		       3   4   3   5
    #       1234567890123456789011   1234     12345
    p.text("Producto                 Qty     Precio\n")
    #       Items[x][0]              Items[x][1] + " " + Items[x][2] + "\n")

    for x in range(len(Items)):
        #print repr(trimPrice[x][2])
	p.text( u''.join( trimName( Items[x][0] )  + trimQty( Items[x][1] ) + trimPrice( Items[x][2] ) + "\n") )

    if len(Cards) > 0:
        p.set("center")
        p.text("\n")
        p.text("=====Pagos De Tarjeta=====")
        p.text("\n\n")
        p.set('left')

        for card in Cards:
            cardStr =           "Tipo De Tarjeta        : " + card[0] + "\n"
            cardStr = cardStr + "Numero De Cuenta       : " + card[1] + "\n"
            cardStr = cardStr + "Nombre En La Tarjeta   : " + card[2].strip() + "\n"
            cardStr = cardStr + "Codigo de Autorizacion : " + card[3] + "\n"
            cardStr = cardStr + "ID de transaccion      : " + card[4] + "\n"
            cardStr = cardStr + "Cantidad               : " + trimPrice( str(card[5]) ) + "\n"
            cardStr = cardStr + "\n"
            p.text(cardStr)


            imgData = r''.join( card[7].strip().strip("\n") )
            imgData = "%r" % imgData

            with open("curr_signature.png", "wb") as fh:
                fh.write(base64.decodestring(imgData))


            img = Image.open( os.path.dirname(os.path.realpath(__file__)) + "/curr_signature.png")
            new_width  = 100
            new_height = 50
            img = img.resize((new_width, new_height), Image.ANTIALIAS)
            img.save('curr_signature.png') # format may what u want ,*.png,*jpg,*.gif

            p.set("center")
            p.image(  os.path.dirname(os.path.realpath(__file__)) + "/curr_signature.png" )
            p.set("left")

    if len(Cashes) > 0:
        p.set('center')
        p.text("\n")
        p.text('=====Pagos En Efectivo=====')
        p.text("\n\n")
        p.set('left')
        for cash in Cashes:
            cashStr =           "Efectivo Recibido  : " +  trimPrice ( str( cash[0]) )  + "\n"
            cashStr = cashStr + "Cambio             : " +  trimPrice ( str( cash[1]) ) + "\n"
            cashStr = cashStr + "\n"
            p.text(cashStr)



    p.text("\n\n\n")
    p.set("right")
    p.text("Total parcial   : " + trimBottomRight( trimPrice( str(subtotal) ) )   + "\n")
    p.text("Impuestos       : " + trimBottomRight( trimPrice( str(tax) ) )         + "\n")
    p.text("Total           : " + trimBottomRight( trimPrice( str(total) ) )       + "\n\n")

    p.set("Center", "A","B")
    p.text("Gracias!\n")
    p.set("Center", "A", "normal")
    p.text("Customer Copy\n")
    p.cut()
Exemplo n.º 24
0
def printTicket(member_id, slot, expirationDate, username, name, email, phone, storageType, description, printTime, completion):
    """ Print a storage ticket and receipt.
    """

    p = Usb(0x04b8, 0x0e15, 0)

    p.set(align='center', text_type='B', width=4, height=4)
    p.text(expirationDate)
    p.text("\n")

    p.set(align='center', width=1, height=1)
    p.text("storage expiration date\n\n")

    p.set(align='center', width=2, height=2)
    p.text("DMS Storage Ticket\n")
    p.text(str.format("Slot:\t{}\n\n", slot))
    p.text(str.format("Name:\t{}\n\n", name))

    p.set(align='left')
    p.text("Ticket required on any items left at DMS.\n")
    p.text("Place ticket in holder or on project.\n\n")

    p.set(align='left')
    p.text(str.format("User:\t{}\n", username))
    p.text(str.format("Email:\t{}\n", email))
    p.text(str.format("Phone:\t{}\n", phone))
    p.text(str.format("Type:\t{}\n", storageType))
    p.text(str.format("Desc:\t{}\n", description))
    p.text(str.format("Start:\t{}\n", printTime))
    p.text(str.format("Compl:\t{}\n", completion))

    p.text("\n\n")
    p.text("Signature: ____________________________________\n")
    p.text("By signing you agree to follow the posted rules and remove your item before the expiration date.\n")
    p.text("Failure to remove items will result in loss of\nstorage privileges.")

    p.set(align='center')
    p.text("\n")
    qrDataString = str.format("{};{};{};{}", member_id, slot, storageType, expirationDate)
    p.qr(qrDataString, 1, 6, 2)

    p.cut()

    p.set(align='center', width=2, height=2)
    p.text("DMS Storage Receipt\n\n")

    p.set(align='left', width=1, height=1)
    p.text("Keep this receipt as a reminder that you\n")
    p.text("agreed to remove your item before:\n")
    p.set(align='center', text_type='B', width=2, height=2)
    p.text(expirationDate)
    p.text("\n\n")

    p.set(align='left')
    p.text(str.format("User:\t{}\n", username))
    p.text(str.format("Name:\t{}\n", name))
    p.text(str.format("Email:\t{}\n", email))
    p.text(str.format("Phone:\t{}\n", phone))
    p.text(str.format("Type:\t{}\n", storageType))
    p.text(str.format("Desc:\t{}\n", description))
    p.text(str.format("Start:\t{}\n", printTime))
    p.text(str.format("Compl:\t{}\n", completion))
    p.cut()
Exemplo n.º 25
0
#!/usr/bin/python
from escpos.printer import Usb
p = Usb(0x0416, 0x5011)
p.text("Mini Alexa Pi Printer\n")
p.close()
Exemplo n.º 26
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")
Exemplo n.º 27
0
cliente = json_data['cliente']
atendente = json_data['atendente']
observacao = json_data['observacao']

qtd_compras = int(json_data['qtd_compras'])
compras_list = []
for i in range(qtd_compras):
	data_aux = json_data['compra_data' + str(i)]
	valor_aux = json_data['compra_valor' + str(i)]
	compras_list.append([data_aux, valor_aux])


# recibo do cliente

printer.set(align='center', width=2, height=2, invert=True)
printer.text(' Paes & Cia \n\n')

printer.set(align='center', width=2, height=1)
printer.text('Recibo de\npagamento\n\n')

printer.set(align='left', width=1, height=1)
printer.text('ID: ' + id_pagamento + '\n')
printer.text('Data: ' + data + '\n')
printer.text('Valor total: R$ ' + valor + '\n')
printer.text('Cliente: ' + cliente + '\n')
printer.text('Atendente: ' + atendente + '\n')
if (observacao != 'null'):
	printer.text('Observacao: ' + observacao + '\n')

printer.text('\n')
for compra in compras_list:
Exemplo n.º 28
0
class Printer():
    """ Loads a printer according to the model supplied (explicit list of support)
        and provides common functions
    """
    def __init__(self, name: str = "", model: str = "", **kwargs):

        if not name:
            # Forces a unique printer name
            name = f"printer-{id(self)}"
        self.name = name

        if model:
            self.printer_spec = PRINTER_MAP.get(str(model), dict())
        else:
            self.printer_spec = PRINTER_MAP.get("default")

        self.model = self.printer_spec.get('model', 'unknown')

        valid_kwargs = getfullargspec(Usb)
        # ['self', 'idVendor', 'idProduct', 'timeout', 'in_ep', 'out_ep']

        # Look for kwargs passed that match a kwarg for Usb() and override
        for k, v in kwargs:
            if k in valid_kwargs:
                self.printer_spec["config"][k] = kwargs.pop(k, None)

        self.inputs = locals()

        config = self.printer_spec['config']
        self.printer = Usb(**config)

        # TODO: Add logic that verifies the printer is working

    def ln(self, count=1):
        """ feeds n lines to print buffer
            replicates Escpos().ln() in newer version (>=3.0)
            https://github.com/python-escpos/python-escpos/blob/f9ce77705757dcd3a3946569d02810ae7e122e88/src/escpos/escpos.py#L531
        """
        if count < 0:
            count = 0
        if count == 0:
            return False
        return self.printer.text('\n' * count)

    def text(self, text):
        """ Pass through to Escpos().text()
            https://github.com/python-escpos/python-escpos/blob/cbe38648f50dd42e25563bd8603953eaa13cb7f6/src/escpos/escpos.py#L424
        """
        self.printer.text(text)
        return True

    def cut(self, mode="PART"):
        """ Pass through to Escpos().cut()
            https://github.com/python-escpos/python-escpos/blob/cbe38648f50dd42e25563bd8603953eaa13cb7f6/src/escpos/escpos.py#L597
        """
        return self.printer.cut(mode)

    # TODO: Make this better
    def barcode(self, *args, **kwargs):
        """ Pass through to Escpos().barcode()
            https://github.com/python-escpos/python-escpos/blob/cbe38648f50dd42e25563bd8603953eaa13cb7f6/src/escpos/escpos.py#L295
        """
        return self.printer.barcode(*args, **kwargs)

    # TODO: Make this better
    def qr(self, *args, **kwargs):
        """ Pass through to Escpos().qr()
            https://github.com/python-escpos/python-escpos/blob/cbe38648f50dd42e25563bd8603953eaa13cb7f6/src/escpos/escpos.py#L134
        """
        return self.printer.qr(*args, **kwargs)
Exemplo n.º 29
0
        os.system('cls' if os.name == 'nt' else 'clear')
        if sys.stdin in select.select([sys.stdin], [], [], 0)[0]:
            line = raw_input()
            break
        if GPIO.input(SW_PIN) == GPIO.HIGH:
            print("Caught")
            os.system('fswebcam -S 10 ' + IMGFACE)
            usb = Usb(0x067b, 0x2303, 0, out_ep=0x2)
            usb.cut()
            usb.image(IMGFACE)
            with open(IMGFACE, 'rb') as source_image:
                source_bytes = source_image.read()

            time.sleep(1)
            for face in detect_faces(source_bytes):
                usb.text("Face ({0:.2f}%)\n".format(face['Confidence']))

            for emotion in face['Emotions']:
                usb.text("  {Type} : {Confidence}% \n".format(**emotion))
                emotion_type = emotion['Type']
                idx = float("{0:.2f}".format(emotion['Confidence']))

                if emotion_type == "HAPPY" and idx > 70:
                    usb.image(IMGHAPPY)
                if emotion_type == "SAD" and idx > 10:
                    usb.image(IMGSAD)
                if emotion_type == "CONFUSED" and idx > 10:
                    usb.image(IMGCONFUSED)
                if emotion_type == "ANGRY" and idx > 10:
                    usb.image(IMGSAD)
Exemplo n.º 30
0
from escpos.printer import Usb
from datetime import datetime
import csv

current_date = datetime.now()

with open('data.csv') as data:
    data_reader = csv.reader(data)  #use DictReader for list the used headers.
    for row in data_reader:
        paper_id = int(row[0])

p = Usb(0x0fe6, 0x811e, timeout=0)  #vendor id product id us lsusb to see

p.set(align="center", height=2)
p.text("AlSANCAK BELEDIYESI")
p.text("\nAKILLI COP TOPLAMA TERMINALI\n\n")

p.set(align="left", height=1, text_type='bold')
p.text("\nFIS NO:    ")
p.text(str(paper_id))
p.text("\nTARIH:     ")

p.text(str(current_date.strftime("%d-%m-%Y %H:%M")))

p.text("\n\nCOP CINSI\n\n")
p.text("METAL:       ")
p.text("2\n")
p.text("PLASTIK:     ")
p.text("3\n")
p.text("CAM:         ")
p.text("5\n")
Exemplo n.º 31
0
    image = GRAPHICS_PATH + icon + ".png"
    return image


deg = ' C'      # Degree symbol on thermal printer, need to find a better way to use a proper degree symbol

# if you want Fahrenheit change units= to 'us'
url = "https://api.darksky.net/forecast/" + API_KEY + "/" + LAT + "," + LONG + \
    "?exclude=[alerts,minutely,hourly,flags]&units=si"  # change last bit to 'us' for Fahrenheit
response = urllib.urlopen(url)
data = json.loads(response.read())

printer.print_and_feed(n=1)
printer.control("LF")
printer.set(font='a', height=2, align='center', bold=True, double_height=True)
printer.text("Weather Forecast")
printer.text("\n")
printer.set(align='center')


# Print current conditions
printer.set(font='a', height=2, align='center', bold=True, double_height=False)
printer.text('Current conditions: \n')
printer.image(icon())
printer.text("\n")

printer.set(font='a', height=2, align='left', bold=False, double_height=False)
temp = data['currently']['temperature']
cond = data['currently']['summary']
printer.text(temp)
printer.text(' ')