Esempio n. 1
0
    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)
Esempio n. 2
0
    def __init__(self, client, feed_key):
        self.client = client
        self.feed_key = feed_key
        self.logger = logger.Logger("logs/mood.log")

        self.values = []
        self.print_values = []

        self.color = (0, 0, 0)
        self.do_fade = False
        self.fade_started = 0
        self.fade_seconds = 8

        try:
            self.printer = Usb(0x0416, 0x5011)
        except:
            self.printer = None

        now = time.time()

        # Publish at most once every 5 seconds
        self.last_publish = now
        self.publish_interval_seconds = 5
        self.last_request = None

        # Print at most once every 15 seconds
        self.last_print = now
        self.print_interval_seconds = 10

        self.last_pulse = now
        self.pulse_interval_seconds = 30

        self.static_color = (0, 0, 0)
Esempio n. 3
0
 def __init__(self, mode, *args, **kwargs):
     Usb.__init__(self, *args, **kwargs)
     self.cutter = Cutter()
     if mode == 'rpi':
         self.cut = self._cut_rpi
     else:
         self.cut = Usb.cut
Esempio n. 4
0
class UsbPrinter(DummyPrinter):
    """
    Initialize USB printer with vendor ID and product ID
    """
    def __init__(self, config):
        super().__init__()
        vendor_id = int(
            config.config_dict['printer_config']['usb']['vendor_id'], 16)
        product_id = int(
            config.config_dict['printer_config']['usb']['product_id'], 16)
        self.p = None
        while self.p == None:
            try:
                self.p = Usb(vendor_id, product_id)

            except Exception as e:
                print(e)
                print("Trying again in 15 seconds")
                time.sleep(15)

    def print_ticket(self, order):
        super().print_ticket(order)
        y = True
        while y:
            try:
                self.p._raw(self.d.output)
                y = False
            except:
                print("might be reloading paper")
                time.sleep(10)
Esempio n. 5
0
class Photobooth:
    api = None
    printer = None
    lastMention = None

    def __init__(self, api):
        self.api = api
        self.printer = Usb(0x0416, 0x5011, 0, 0x81, 0x01)
        self.lastMention = self.api.GetMentions()[0].AsDict()

    def StartBooth(self):
        while True:
            if self.CheckForNewMention():
                print("New mention! by " + self.lastMention['user']['screen_name'])
                self.SnapAndPrint()
            time.sleep(5)

    def CheckForNewMention(self):
        recentMention = api.GetMentions()[0].AsDict()
        if self.lastMention['id'] != recentMention['id']:
            self.lastMention = recentMention
            return True
        return False

    def SnapAndPrint(self):
        subprocess.run(PIC_COMMAND.split(" ")) 
        dummy = Dummy()
        
        dummy.text("\n\n\nBravoLT - GRPS - 2019\n\n\n")
        dummy.image("out.jpg")
        dummy.text("\n\n\nBravoLT - GRPS - 2019")

        self.printer._raw(dummy.output)
Esempio n. 6
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)
Esempio n. 7
0
    def __init__(self, product_id, vendor_id, test_mode=False):
        """
        Also does error handling

        :param product_id: Printer product ID as integer
        :param vendor_id: Printer vendor ID as integer
        :param test_mode: boolean, when set to true modifies error messages and prevents modification of the global
            settings. Used for print tests (duh)

        :return: nil
        """

        self.product_id = product_id
        self.vendor_id = vendor_id

        self._printer = None

        self.test_mode = test_mode

        # changes message end if test mode is true
        message_end = "\n\nPrinting disabled"
        if self.test_mode:
            message_end = ""

        self.failed = True  # can be used to determine if a popup was shown - set false if successful in try below

        # in case printing is disabled (and test mode is disabled), just do nothing
        # if it's in test mode, you want it to actually do stuff and test...
        if not SETTINGS["printer"]["enable"] and not self.test_mode:
            return

        try:
            self._printer = Usb(self.product_id, self.vendor_id)
            self._printer.hw("INIT")
            self.failed = False
        except escpos.exceptions.USBNotFoundError:
            popup_message("Printer not found - please check the printer is plugged in and turned on and that the vendor"
                          f" and product IDs correct.{message_end}",
                          error=True)
            if not self.test_mode:
                SETTINGS["printer"]["enable"] = False
        except USBError as e:
            if "Errno 13" in str(e):
                popup_message(f"USB error 13 - it looks like something else is using the printer.\n\n{message_end}",
                              error=True)
                if not self.test_mode:
                    SETTINGS["printer"]["enable"] = False
            else:
                popup_message(f"{e}{message_end}", error=True)
                logger.exception("Unrecognised USB error")
                if not self.test_mode:
                    SETTINGS["printer"]["enable"] = False
        except NoBackendError:
            print("nobackend")
            popup_message(f"There was an issue connecting to the printer. Please refer to the documentation.{message_end}",
                          error=True)
            logger.exception("No backend was available - Possible mis-installation of libusb-1.0.dll or WinUSB driver.")
            if not self.test_mode:
                SETTINGS["printer"]["enable"] = False
Esempio n. 8
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")
Esempio n. 9
0
    def reset(self):
        """
        Closes and reopens printer connection

        :return: nil
        """

        self.close()
        try:
            self._printer = Usb(self.product_id, self.vendor_id)
        except:  # in the event of any error (eg NoBackendAvail)
            # TODO: Change to raise an exception or do something other than this
            self._printer = None
Esempio n. 10
0
 def post_add(self, item):
     stroka = str()
     len_id = len(str(item.id))
     const_len = 9
     while(len_id < const_len):
         stroka += '0'
         len_id += 1
     stroka += str(item.id)
     p = Usb(0x1d90,0x2060,0,0x81,0x02)
     p.barcode(stroka,'CODE39',250,3,'','')
     p.cut()
     p.barcode(stroka,'CODE39',250,3,'','')
     p.cut()
Esempio n. 11
0
    def __init__(self, config):
        super().__init__()
        vendor_id = int(
            config.config_dict['printer_config']['usb']['vendor_id'], 16)
        product_id = int(
            config.config_dict['printer_config']['usb']['product_id'], 16)
        self.p = None
        while self.p == None:
            try:
                self.p = Usb(vendor_id, product_id)

            except Exception as e:
                print(e)
                print("Trying again in 15 seconds")
                time.sleep(15)
Esempio n. 12
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()
    def connect_printer(self):
        try:
            self._tape.setPlainText("Printer is ready.")
            self._connect.setEnabled(False)
            self.started = True

            # Create the printer object.
            self.printer = Usb(self.vendor_id, self.prod_id, 0, self.in_ep,
                               self.out_ep)

            self.started = True

        except:
            self._tape.setPlainText(
                "Printer is not connected or cannot establish communication.")
            self._connect.setEnabled(True)
Esempio n. 14
0
def instanciarImpresora():
	try:
		Generic = Usb(0x0519, 0x0001, timeout=400)
		#Generic = Usb(0x04b8, 0x0202, timeout=400)
		return Generic
	except Exception as error:
		return "No esta conectada la impresora"
def connectToPrinter():
	try:
		p = Usb(0x0416, 0x5011, in_ep=81, out_ep=3)
	except USBNotFoundError:
		p = None
		print("Printer not connected")
	return p
Esempio n. 16
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
Esempio n. 17
0
    def __init__(self):
        diretorio = os.path.dirname(os.path.abspath(__file__))
        configFile = cfgprsr.ConfigParser()

        configFile.read(diretorio + '/config.ini')
        self.printer_type = configFile['PRINTER']['tipo']
        self.printer_device = configFile['PRINTER']['dispositivo']
        self.printer_vid = int(configFile['PRINTER']['vid'], 16)
        self.printer_pid = int(configFile['PRINTER']['pid'], 16)
        self.printer_baudrate = int(configFile['PRINTER']['baudrate'])
        self.printer_timeout = int(configFile['PRINTER']['timeout'])
        self.printer_parity = configFile['PRINTER']['parity']

        try:
            if self.printer_type.lower() == 'serial':
                self.printer = Serial(devfile=self.printer_device,
                                  baudrate=int(self.printer_baudrate),
                                  timeout=int(self.printer_timeout),
                                  parity=self.printer_parity)

                self.printer.open()
            elif self.printer_type.lower() == 'usb':
                self.printer = Usb(idVendor=self.printer_vid,
                                   idProduct=self.printer_pid)

            self.printer.codepage = 'CP860'


        except Exception as e:
            logger.logError("Erro ao comunicar com a impressora.    -    Details: {}".format(str(e)))
Esempio n. 18
0
 def _connect_usb(self, **kwargs):
     """Initializes the __printer instance with Usb printer
        @param: profile
        @retrurn: Usb()
     """
     #profile="TM-T88III"
     return Usb(0x04b8, 0x0202, 0, profile=kwargs['profile'])
Esempio n. 19
0
def printer_state():
    try:
        p = Usb(0x8866, 0x0100, timeout=0, in_ep=0x81, out_ep=0x02)
        return 0
    except escpos.exceptions.USBNotFoundError:
        print("printer not found")
        return -1
Esempio n. 20
0
def get_usb(config):
    return Usb(
        config['id_vendor'],
        config['id_product'],
        0,
        config['endpoint_in'],
        config['endpoint_out']
    )
Esempio n. 21
0
def main():
    PRINTER = None
    rate = 10
    try:
        PRINTER = Usb(0x456, 0x808, 0, 0x81, 0x03)
    except:
        PRINTER = None
    listen(PRINTER, rate)
Esempio n. 22
0
    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'
        }
Esempio n. 23
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()
Esempio n. 24
0
    def get_escpos_printer(self):

        printers = self.connected_usb_devices()
        if len(printers) > 0:
            self.set_status('connected', 'Connected to ' + printers[0]['name'])
            return Usb(printers[0]['vendor'], printers[0]['product'])
        else:
            self.set_status('disconnected', 'Printer Not Found')
            return None
Esempio n. 25
0
class ReceiptPrinter:
    def __init__(self,
                 id_vendor=0x0416,
                 id_product=0x5011,
                 in_ep=0x81,
                 out_ep=0x03):
        self._printer = Usb(id_vendor, id_product, in_ep=in_ep, out_ep=out_ep)

    def print(self, img):
        self._printer.image(img)
        self._printer.cut()

    def print_data(self, data):
        img = Receipt.from_data(data)
        self.print(img)

    def print_stream(self, stream):
        img = Receipt.from_stream(stream)
        self.print(img)
Esempio n. 26
0
def inicializarImpresora():
    try:
        global Epson
        Epson = Usb(0x04b8, 0x0e15)
        emitirSonido(1)

    except Exception as e:
        emitirSonido(3)
        logging.info('Impresora Apagada o no conectada %s' % e)
        raise ValueError('Impresora Apagada o no conectada')
Esempio n. 27
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 ''
Esempio n. 28
0
def open_printer():
    try:
        if LIB:
            p = Usb(ID_VENDOR, ID_PRODUCT, 0, IN_END, OUT_END)
        else:
            p = fakePrinter(ID_VENDOR, ID_PRODUCT, 0, IN_END, OUT_END)
    except Exception as e:
        print("[EP]", e, "using a fake printer instead")
        p = fakePrinter(ID_VENDOR, ID_PRODUCT, 0, IN_END, OUT_END)
    return p
Esempio n. 29
0
def inicializarImpresora():
	try:
		global Epson
		Epson = Usb(0x04b8,0x0e15)

	except Exception as e:
		emitirSonido('verificar_impresora.wav')
		logging.info ('Impresora Apagada o no conectada %s' % e)
		time.sleep(10)
		inicializarImpresora()
		return None
Esempio n. 30
0
    def abrir_cajon(self, *args):
        try:
            if self.tipo == "Network":
                printer = Network(self.ip_caja, timeout=1)
            if self.tipo == "Usb":
                printer = Usb(*self.usb)
            if self.tipo == "File":
                printer = File(self.url)

            printer.cashdraw(2)
        except Exception as e:
            print("[ERROR  ] %s" % e)
Esempio n. 31
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()