def main(): """ Initializes the webserver :return: """ global DEBUG, MODEL, BACKEND_CLASS, BACKEND_STRING_DESCR import argparse parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--host', default='127.0.0.1', help='The IP the webserver should bind to. Use 0.0.0.0 for all') parser.add_argument('--port', default=8013, help='The port the webserver should start on') parser.add_argument('--debug', action='store_true', default=False, help='Activate flask debugging support') parser.add_argument('--model', default='QL-500', choices=models, help='The model of your printer (default: QL-500)') parser.add_argument('printer', help='String descriptor for the printer to use (like tcp://192.168.0.23:9100 or ' 'file:///dev/usb/lp0)') args = parser.parse_args() DEBUG = args.debug MODEL = args.model try: selected_backend = guess_backend(args.printer) BACKEND_CLASS = backend_factory(selected_backend)['backend_class'] BACKEND_STRING_DESCR = args.printer except: parser.error("Couldn't guess the backend to use from the printer string descriptor") app.run(host=args.host, port=args.port, debug=DEBUG)
def print_task(printer, label): selected_backend = guess_backend(printer.connection) BACKEND_CLASS = backend_factory(selected_backend)['backend_class'] image = img_label(label) # from brother_ql qlr = BrotherQLRaster(printer.model) create_label(qlr, image, printer.width, threshold=70, cut=True, dither=False, compress=False, red=False) try: be = BACKEND_CLASS(printer.connection) be.write(qlr.data) be.dispose() del be except Exception as e: raise NameError(str(e)) return True
def print_label(text, qr=None, label="54", printer_identifier="/dev/usb/lp0", template="/home/pi/printer/templates/test.png", printer="QL-810W", cut=True, red=True, dpi_600=True, rotate="0"): # create a card from the template # card = create_card(target_file=template, text=text, qr=qr, save=False) card = generate_card(target_file=template, text=text) # convert the card to raster qlr = BrotherQLRaster(printer) qlr.exception_on_warning = True # convert takes only an array images = [card] instructions = convert(qlr=qlr, images=images, label=label, cut=cut, red=red, rotate=rotate) # get the backend identifier backend_identifier = guess_backend(printer_identifier) # send the commands to the printer print("Sending instructions to print") send(instructions=instructions, printer_identifier=printer_identifier, backend_identifier=backend_identifier)
def main(): parser = argparse.ArgumentParser() parser.add_argument('file', help='The file to analyze') parser.add_argument('dev', help='The device to use. Can be usb://0x04f9:0x2015 or /dev/usb/lp0 for example') parser.add_argument('--sleep-time', type=float, help='time in seconds to sleep between instructions') parser.add_argument('--sleep-before-read', type=float, help='time in seconds to sleep before reading response') parser.add_argument('--continue-reading-for', type=float, help='continue reading after sending the last commands (time in seconds)') parser.add_argument('--interactive', action='store_true', help='interactive mode') parser.add_argument('--split-raster', action='store_true', help='even split preamble and raster instructions into single write operations') parser.add_argument('--debug', action='store_true', help='enable debug mode') args = parser.parse_args() # SETUP loglevel = logging.DEBUG if args.debug else logging.INFO logging.basicConfig(level=loglevel, format='%(levelname)s: %(message)s') try: backend = guess_backend(args.dev) except ValueError as e: parser.error(e.msg) br = BrotherQL_USBdebug(args.dev, args.file, backend=backend) if args.interactive: br.interactive = True if args.sleep_time: br.sleep_time = args.sleep_time if args.sleep_before_read: br.sleep_before_read = args.sleep_before_read if args.split_raster: br.merge_specific_instructions = False if args.continue_reading_for: br.continue_reading_for = args.continue_reading_for # GO br.print_and_debug()
def main(): parser = argparse.ArgumentParser() parser.add_argument('file', help='The file to analyze') parser.add_argument( 'dev', help= 'The device to use. Can be usb://0x04f9:0x2015 or /dev/usb/lp0 for example' ) parser.add_argument('--sleep-time', type=float, help='time in seconds to sleep between instructions') parser.add_argument( '--sleep-before-read', type=float, help='time in seconds to sleep before reading response') parser.add_argument( '--continue-reading-for', type=float, help= 'continue reading after sending the last commands (time in seconds)') parser.add_argument('--interactive', action='store_true', help='interactive mode') parser.add_argument( '--split-raster', action='store_true', help= 'even split preamble and raster instructions into single write operations' ) parser.add_argument('--debug', action='store_true', help='enable debug mode') args = parser.parse_args() # SETUP loglevel = logging.DEBUG if args.debug else logging.INFO logging.basicConfig(level=loglevel, format='%(levelname)s: %(message)s') try: backend = guess_backend(args.dev) except ValueError as e: parser.error(e.msg) br = BrotherQL_USBdebug(args.dev, args.file, backend=backend) if args.interactive: br.interactive = True if args.sleep_time: br.sleep_time = args.sleep_time if args.sleep_before_read: br.sleep_before_read = args.sleep_before_read if args.split_raster: br.merge_specific_instructions = False if args.continue_reading_for: br.continue_reading_for = args.continue_reading_for # GO br.print_and_debug()
def main(): global DEBUG, FONTS, DEFAULT_FONT, MODEL, BACKEND_CLASS, BACKEND_STRING_DESCR, DEFAULT_ORIENTATION, DEFAULT_LABEL_SIZE import argparse parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--port', default=8013) parser.add_argument('--loglevel', type=lambda x: getattr(logging, x.upper()), default='WARNING') parser.add_argument('--font-folder', help='folder for additional .ttf/.otf fonts') parser.add_argument('--default-label-size', default="62", help='Label size inserted in your printer. Defaults to 62.') parser.add_argument('--default-orientation', default="standard", choices=('standard', 'rotated'), help='Label orientation, defaults to "standard". To turn your text by 90°, state "rotated".') parser.add_argument('--model', default='QL-500', choices=models, help='The model of your printer (default: QL-500)') parser.add_argument('printer', help='String descriptor for the printer to use (like tcp://192.168.0.23:9100 or file:///dev/usb/lp0)') args = parser.parse_args() DEBUG = args.loglevel == logging.DEBUG logging.basicConfig(level=args.loglevel) try: selected_backend = guess_backend(args.printer) except: parser.error("Couln't guess the backend to use from the printer string descriptor") BACKEND_CLASS = backend_factory(selected_backend)['backend_class'] BACKEND_STRING_DESCR = args.printer MODEL = args.model if args.default_label_size not in label_sizes: parser.error("Invalid --default-label-size. Please choose on of the following:\n:" + " ".join(label_sizes)) DEFAULT_LABEL_SIZE = args.default_label_size DEFAULT_ORIENTATION = args.default_orientation FONTS = get_fonts() if args.font_folder: FONTS.update(get_fonts(args.font_folder)) for font in DEFAULT_FONTS: try: FONTS[font['family']][font['style']] DEFAULT_FONT = font logger.debug("Selected the following default font: {}".format(font)) break except: pass if DEFAULT_FONT is None: sys.stderr.write('Could not find any of the default fonts') sys.exit() run(host='', port=args.port, debug=DEBUG)
def main(): global DEBUG, FONTS, DEFAULT_FONT, MODEL, BACKEND_CLASS, BACKEND_STRING_DESCR import argparse parser = argparse.ArgumentParser() parser.add_argument('--port', default=8013) parser.add_argument('--loglevel', type=lambda x: getattr(logging, x.upper()), default='WARNING') parser.add_argument('--font-folder', help='folder for additional .ttf/.otf fonts') parser.add_argument('--model', default='QL-500', choices=models, help='The model of your printer (default: QL-500)') parser.add_argument('printer', help='String descriptor for the printer to use (like tcp://192.168.0.23:9100 or file:///dev/usb/lp0)') args = parser.parse_args() DEBUG = args.loglevel == logging.DEBUG logging.basicConfig(level=args.loglevel) try: selected_backend = guess_backend(args.printer) except: parser.error("Couln't guess the backend to use from the printer string descriptor") BACKEND_CLASS = backend_factory(selected_backend)['backend_class'] BACKEND_STRING_DESCR = args.printer MODEL = args.model FONTS = get_fonts() if args.font_folder: FONTS.update(get_fonts(args.font_folder)) for font in DEFAULT_FONTS: try: FONTS[font['family']][font['style']] DEFAULT_FONT = font logger.debug("Selected the following default font: {}".format(font)) break except: pass if DEFAULT_FONT is None: sys.stderr.write('Could not find any of the default fonts') sys.exit() run(host='', port=args.port, debug=args.loglevel==logging.DEBUG)
def label_print(): global DEBUG, FONTS, DEFAULT_FONT, MODEL, BACKEND_CLASS, BACKEND_STRING_DESCR, DEFAULT_ORIENTATION, DEFAULT_LABEL_SIZE printer = "tcp://192.168.11.106:9100" model = "QL-720NW" # Default label size is "62x100" (DK-11202) which use "rotated" in orientation. # If label size in "62x29" (DK-11209), use "standard" in orientation. default_label_size = "62x100" default_orientation = "rotated" font_folder = "./static/fonts" selected_backend = guess_backend(printer) BACKEND_CLASS = backend_factory(selected_backend)['backend_class'] BACKEND_STRING_DESCR = printer MODEL = model #if default_label_size not in label_sizes: #parser.error("Invalid --default-label-size. Please choose on of the following:\n:" + " ".join(label_sizes)) DEFAULT_LABEL_SIZE = default_label_size DEFAULT_ORIENTATION = default_orientation FONTS = get_fonts() if font_folder: FONTS.update(get_fonts(font_folder))
def print_text(): """ API to print a label returns: JSON Ideas for additional URL parameters: - alignment """ return_dict = {'success': False} try: context = get_label_context(request) except LookupError as e: return_dict['message'] = e.msg return return_dict if not context['text'] or context['text'] is None: return_dict['message'] = 'Please provide the text for the label' return return_dict if not context['printer_name'] or context['printer_name'] is None: return_dict['message'] = 'Please select a printer' return return_dict im = create_label_im(**context) if DEBUG: im.save('sample-out.png') if context['kind'] == ENDLESS_LABEL: rotate = 0 if context['orientation'] == 'standard' else 90 elif context['kind'] in (ROUND_DIE_CUT_LABEL, DIE_CUT_LABEL): rotate = 'auto' qlr = BrotherQLRaster(PRINTERS[context['printer_name']]["MODEL"]) create_label(qlr, im, context['label_size'], threshold=context['threshold'], cut=True, rotate=rotate) try: selected_backend = guess_backend( PRINTERS[context['printer_name']]["LOCATION"]) except Exception as e: return_dict['message'] = str(e) return return_dict BACKEND_CLASS = backend_factory(selected_backend)['backend_class'] if not DEBUG: try: be = BACKEND_CLASS(PRINTERS[context['printer_name']]["LOCATION"]) be.write(qlr.data) be.dispose() del be except Exception as e: return_dict['message'] = str(e) logger.warning('Exception happened: %s', e) return return_dict return_dict['success'] = True if DEBUG: return_dict['data'] = str(qlr.data) return return_dict
def main(): global DEBUG, BACKEND_CLASS, CONFIG parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--port', default=False) parser.add_argument('--loglevel', type=lambda x: getattr(logging, x.upper()), default=False) parser.add_argument( '--font-folder', action="append", help='Specify additional folders for additional .ttf/.otf fonts.') parser.add_argument('--no-system-fonts', action="store_true", help='Do not search system folders for fonts.') parser.add_argument( '--default-label-size', default=False, help='Label size inserted in your printer. Defaults to 62.') parser.add_argument( '--default-orientation', default=False, choices=('standard', 'rotated'), help= 'Label orientation, defaults to "standard". To turn your text by 90°, state "rotated".' ) parser.add_argument('--model', default=False, choices=models, help='The model of your printer (default: QL-500)') parser.add_argument( 'printer', nargs='?', default=False, help= 'String descriptor for the printer to use (like tcp://192.168.0.23:9100 or file:///dev/usb/lp0)' ) args = parser.parse_args() if args.printer: CONFIG['PRINTER']['PRINTER'] = args.printer if args.port: PORT = args.port else: PORT = CONFIG['SERVER']['PORT'] if args.loglevel: LOGLEVEL = args.loglevel else: LOGLEVEL = CONFIG['SERVER']['LOGLEVEL'] if LOGLEVEL == 'DEBUG': DEBUG = True else: DEBUG = False if args.model: CONFIG['PRINTER']['MODEL'] = args.model if args.default_label_size: CONFIG['LABEL']['DEFAULT_SIZE'] = args.default_label_size if args.default_orientation: CONFIG['LABEL']['DEFAULT_ORIENTATION'] = args.default_orientation ADDITIONAL_FONT_FOLDERS = (args.font_folder or []) + ( CONFIG['SERVER']['ADDITIONAL_FONT_FOLDERS'] or []) NO_SYSTEM_FONTS = args.no_system_fonts or CONFIG['SERVER'][ 'NO_SYSTEM_FONTS'] logging.basicConfig(level=LOGLEVEL) try: selected_backend = guess_backend(CONFIG['PRINTER']['PRINTER']) except ValueError: parser.error( "Couln't guess the backend to use from the printer string descriptor" ) BACKEND_CLASS = backend_factory(selected_backend)['backend_class'] if CONFIG['LABEL']['DEFAULT_SIZE'] not in label_sizes: parser.error( "Invalid --default-label-size. Please choose on of the following:\n:" + " ".join(label_sizes)) if NO_SYSTEM_FONTS: fc = fontconfig.Config.create() else: fc = fontconfig.Config.get_current() if ADDITIONAL_FONT_FOLDERS: for folder in ADDITIONAL_FONT_FOLDERS: fc.app_font_add_dir(folder) props = fontconfig.PROP.FILE, fontconfig.PROP.FAMILY, fontconfig.PROP.STYLE CONFIG['FONTS'] = [] for font in fc.font_list(fontconfig.Pattern.create(), props): CONFIG['FONTS'].append(tuple(font.get(prop, 0)[0] for prop in props)) CONFIG['FONTS'].sort(key=lambda font: font[1:]) if not CONFIG['FONTS']: sys.stderr.write( "Not a single font was found on your system. Please install some or use the \"--font-folder\" argument.\n" ) sys.exit(2) for default_font in CONFIG['LABEL'].get('DEFAULT_FONTS', ()): for i, font in enumerate(CONFIG['FONTS']): if default_font['family'] == font[1] and default_font[ 'style'] == font[2]: CONFIG['LABEL']['DEFAULT_FONT'] = i logger.debug( "Selected the following default font: {}".format(font)) break if 'DEFAULT_FONT' in CONFIG['LABEL']: break else: sys.stderr.write( 'Could not find any of the default fonts. Choosing a random one.\n' ) CONFIG['LABEL']['DEFAULT_FONT'] = random.randint( 0, len(CONFIG['FONTS'])) sys.stderr.write('The default font is now set to: {1} ({2})\n'.format( *CONFIG['FONTS'][CONFIG['LABEL']['DEFAULT_FONT']])) run(host=CONFIG['SERVER']['HOST'], port=PORT, debug=DEBUG)
def print_text(**data): global DEBUG, FONTS, DEFAULT_FONT, MODEL, BACKEND_CLASS, BACKEND_STRING_DESCR, DEFAULT_ORIENTATION, DEFAULT_LABEL_SIZE BACKEND_STRING_DESCR = data["printer_uri"] # "tcp://192.168.0.10:9100" font_folder = "./static/fonts" selected_backend = guess_backend(BACKEND_STRING_DESCR) BACKEND_CLASS = backend_factory(selected_backend)["backend_class"] MODEL = data["printer_model"] # "QL-720NW" DEFAULT_LABEL_SIZE = data["label_size"] # "62x100" DEFAULT_ORIENTATION = data["orientation"] # "rotated" FONTS = get_fonts() if font_folder: FONTS.update(get_fonts(font_folder)) status = False try: context = get_label_context( data["first_name"], data["last_name"], data["company"], data["label_size"] ) except LookupError as e: return status if context["name"] is None: return status if context["company"] is None: context["company"] = "" if context["last_name"] is None: context["name"] = context["first_name"] context["event_name"] = data["event_name"] context["logo"] = data["logo"] context["label_tpl"] = data["label_tpl"] context["ticket_type"] = data["ticket_type"] im = eval("create_label_im_" + data["label_size"])(**context) if data["debug"]: data["image"] = im try: im.save( settings.MEDIA_ROOT + "/cache/label-%s_%s.png" % (data["first_name"], data["last_name"]) ) except FileNotFoundError: os.mkdir(settings.MEDIA_ROOT + "/cache") im.save( settings.MEDIA_ROOT + "/cache/label-%s_%s.png" % (data["first_name"], data["last_name"]) ) else: qlr = BrotherQLRaster(MODEL) rotate = 0 if data["orientation"] == "standard" else 90 if context["label_size"] == "62x29": rotate = 0 create_label( qlr, im, context["label_size"], threshold=context["threshold"], cut=True, rotate=rotate, ) try: be = BACKEND_CLASS(BACKEND_STRING_DESCR) be.write(qlr.data) be.dispose() del be except Exception as e: return status status = True return status
def print_text(**data): global DEBUG, FONTS, DEFAULT_FONT, MODEL, BACKEND_CLASS, BACKEND_STRING_DESCR, DEFAULT_ORIENTATION, DEFAULT_LABEL_SIZE BACKEND_STRING_DESCR = data['printer_uri'] # "tcp://192.168.0.10:9100" font_folder = "./static/fonts" selected_backend = guess_backend(BACKEND_STRING_DESCR) BACKEND_CLASS = backend_factory(selected_backend)['backend_class'] MODEL = data['printer_model'] # "QL-720NW" DEFAULT_LABEL_SIZE = data['label_size'] # "62x100" DEFAULT_ORIENTATION = data['orientation'] # "rotated" FONTS = get_fonts() if font_folder: FONTS.update(get_fonts(font_folder)) status = False try: context = get_label_context(data['first_name'], data['last_name'], data['company'], data['label_size']) except LookupError as e: return status if context['name'] is None: return status if context['company'] is None: context['company'] = '' if context['last_name'] is None: context['name'] = context['first_name'] context['event_name'] = data['event_name'] context['logo'] = data['logo'] context['label_tpl'] = data['label_tpl'] context['ticket_type'] = data['ticket_type'] im = eval('create_label_im_' + data['label_size'])(**context) if data['debug']: data['image'] = im try: im.save(settings.MEDIA_ROOT + '/cache/label-%s_%s.png' % (data['first_name'], data['last_name'])) except FileNotFoundError: os.mkdir(settings.MEDIA_ROOT + '/cache') im.save(settings.MEDIA_ROOT + '/cache/label-%s_%s.png' % (data['first_name'], data['last_name'])) else: qlr = BrotherQLRaster(MODEL) rotate = 0 if data['orientation'] == 'standard' else 90 if context['label_size'] == '62x29': rotate = 0 create_label(qlr, im, context['label_size'], threshold=context['threshold'], cut=True, rotate=rotate) try: be = BACKEND_CLASS(BACKEND_STRING_DESCR) be.write(qlr.data) be.dispose() del be except Exception as e: return status status = True return status
def send(instructions, printer_identifier=None, backend_identifier=None, blocking=True): """ Send instruction bytes to a printer. :param bytes instructions: The instructions to be sent to the printer. :param str printer_identifier: Identifier for the printer. :param str backend_identifier: Can enforce the use of a specific backend. :param bool blocking: Indicates whether the function call should block while waiting for the completion of the printing. """ selected_backend = None if backend_identifier: selected_backend = backend_identifier else: try: selected_backend = guess_backend(printer_identifier) except: logger.info("No backend stated. Selecting the default linux_kernel backend.") selected_backend = 'linux_kernel' be = backend_factory(selected_backend) list_available_devices = be['list_available_devices'] BrotherQLBackend = be['backend_class'] printer = BrotherQLBackend(printer_identifier) start = time.time() logger.info('Sending instructions to the printer. Total: %d bytes.', len(instructions)) printer.write(instructions) if not blocking: return if selected_backend == 'network': """ No need to wait for completion. The network backend doesn't support readback. """ return printing_completed = False waiting_to_receive = False while time.time() - start < 10: data = printer.read() if not data: time.sleep(0.005) continue try: result = interpret_response(data) except ValueError: logger.error("TIME %.3f - Couln't understand response: %s", time.time()-start, data) continue logger.debug('TIME %.3f - result: %s', time.time()-start, result) if result['errors']: logger.error('Errors occured: %s', result['errors']) if result['status_type'] == 'Printing completed': printing_completed = True if result['status_type'] == 'Phase change' and result['phase_type'] == 'Waiting to receive': waiting_to_receive = True if printing_completed and waiting_to_receive: break if not printing_completed: logger.warning("'printing completed' status not received.") if not waiting_to_receive: logger.warning("'waiting to receive' status not received.") if (not printing_completed) or (not waiting_to_receive): logger.warning('Printing potentially not successful?') if printing_completed and waiting_to_receive: logger.info("Printing was successful. Waiting for the next job.")
def main(): parser = argparse.ArgumentParser() parser.add_argument('--backend', choices=available_backends, help='Forces the use of a specific backend') parser.add_argument( '--list-printers', action='store_true', help='List the devices available with the selected --backend') parser.add_argument('--debug', action='store_true', help='Enable debugging output') parser.add_argument( 'instruction_file', nargs='?', help='file containing the instructions to be sent to the printer') parser.add_argument( 'device', metavar='DEVICE_STRING_DESCRIPTOR', nargs='?', help= 'String descriptor for specific device. If not specified, select first detected device' ) args = parser.parse_args() if args.list_printers and not args.backend: parser.error( 'Please specify the backend in order to list available devices.') if not args.list_printers and not args.instruction_file: parser.error("the following arguments are required: instruction_file") if args.instruction_file == '-': try: content = sys.stdin.buffer.read() except AttributeError: content = sys.stdin.read() else: with open(args.instruction_file, 'rb') as f: content = f.read() level = logging.DEBUG if args.debug else logging.WARNING logging.basicConfig(level=level) if args.backend == 'network': logger.warning( "The network backend doesn't supply any 'readback' functionality. No status reports will be received." ) selected_backend = None if args.backend: selected_backend = args.backend else: try: selected_backend = guess_backend(args.device) except: logger.info( "No backend stated. Selecting the default linux_kernel backend." ) selected_backend = 'linux_kernel' be = backend_factory(selected_backend) list_available_devices = be['list_available_devices'] BrotherQLBackend = be['backend_class'] if args.list_printers: for printer in list_available_devices(): print(printer['string_descr']) sys.exit(0) string_descr = None if not args.device: "We need to search for available devices and select the first." ad = list_available_devices() if not ad: sys.exit("No printer found") string_descr = ad[0]['string_descr'] print("Selecting first device %s" % string_descr) else: "A string descriptor for the device was given, let's use it." string_descr = args.device printer = BrotherQLBackend(string_descr) start = time.time() logger.info('Sending instructions to the printer. Total: %d bytes.', len(content)) printer.write(content) if selected_backend == 'network': """ No need to wait for completion. The network backend doesn't support readback. """ return printing_completed = False waiting_to_receive = False while time.time() - start < 10: data = printer.read() if not data: time.sleep(0.005) continue try: result = interpret_response(data) except ValueError: logger.error("TIME %.3f - Couln't understand response: %s", time.time() - start, data) continue logger.debug('TIME %.3f - result: %s', time.time() - start, result) if result['errors']: logger.error('Errors occured: %s', result['errors']) if result['status_type'] == 'Printing completed': printing_completed = True if result['status_type'] == 'Phase change' and result[ 'phase_type'] == 'Waiting to receive': waiting_to_receive = True if printing_completed and waiting_to_receive: break if not (printing_completed and waiting_to_receive): logger.warning('Printing potentially not successful?')
def main(): global DEBUG, FONTS, BACKEND_CLASS, CONFIG parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--port', default=False) parser.add_argument('--loglevel', type=str, default=False) parser.add_argument('--font-folder', default=False, help='folder for additional .ttf/.otf fonts') parser.add_argument('--system-fonts', default=False, help='Include fonts installed in OS.') parser.add_argument( '--default-label-size', default=False, help='Label size inserted in your printer. Defaults to 62.') parser.add_argument( '--default-orientation', default=False, choices=('standard', 'rotated'), help= 'Label orientation, defaults to "standard". To turn your text by 90°, state "rotated".' ) parser.add_argument( '--default-image-mode', default=False, choices=('black_and_white', 'grayscale'), help= 'Image mode, defaults to "grayscale". To print in black and white, state "black_and_white".' ) parser.add_argument('--model', default=False, choices=models, help='The model of your printer (default: QL-500)') parser.add_argument( 'printer', nargs='?', default=False, help= 'String descriptor for the printer to use (like tcp://192.168.0.23:9100 or file:///dev/usb/lp0)' ) args = parser.parse_args() if args.loglevel: LOGLEVEL_STRING = args.loglevel.upper() LOGLEVEL = getattr(logging, LOGLEVEL_STRING) else: LOGLEVEL_STRING = CONFIG['SERVER']['LOGLEVEL'].upper() LOGLEVEL = getattr(logging, LOGLEVEL_STRING) if LOGLEVEL_STRING == 'DEBUG': DEBUG = True else: DEBUG = False logging.basicConfig(level=LOGLEVEL) logger.info("Log Level set to {} ({}). DEBUG={}".format( LOGLEVEL, LOGLEVEL_STRING, DEBUG)) if args.printer: CONFIG['PRINTER']['PRINTER'] = args.printer if args.port: PORT = args.port else: PORT = CONFIG['SERVER']['PORT'] if args.model: CONFIG['PRINTER']['MODEL'] = args.model if args.default_label_size: CONFIG['LABEL']['DEFAULT_SIZE'] = args.default_label_size if args.default_orientation: CONFIG['LABEL']['DEFAULT_ORIENTATION'] = args.default_orientation if args.default_image_mode: CONFIG['LABEL']['DEFAULT_IMAGE_MODE'] = args.default_image_mode if args.font_folder: ADDITIONAL_FONT_FOLDER = args.font_folder else: ADDITIONAL_FONT_FOLDER = CONFIG['SERVER']['ADDITIONAL_FONT_FOLDER'] if args.system_fonts: SYSTEM_FONTS = True else: SYSTEM_FONTS = CONFIG['SERVER']['INCLUDE_SYSTEM_FONTS'] try: selected_backend = guess_backend(CONFIG['PRINTER']['PRINTER']) except ValueError: parser.error( "Couln't guess the backend to use from the printer string descriptor" ) BACKEND_CLASS = backend_factory(selected_backend)['backend_class'] if CONFIG['LABEL']['DEFAULT_SIZE'] not in label_sizes: parser.error( "Invalid --default-label-size. Please choose on of the following:\n:" + " ".join(label_sizes)) FONTS = fonts.Fonts() if SYSTEM_FONTS: FONTS.scan_global_fonts() else: FONTS.scan_fonts_folder('./fonts') if ADDITIONAL_FONT_FOLDER: FONTS.scan_fonts_folder(ADDITIONAL_FONT_FOLDER) if not FONTS.fonts_available(): logger.error( "Not a single font was found on your system. Please install some or use the \"--font-folder\" argument." ) sys.exit(2) DEFAULT_FONT = CONFIG['LABEL']['DEFAULT_FONT'] if not (DEFAULT_FONT['family'] in FONTS.fonts.keys() and DEFAULT_FONT['style'] in FONTS.fonts[DEFAULT_FONT['family']].keys()): family = random.choice(list(FONTS.fonts.keys())) style = random.choice(list(FONTS.fonts[family].keys())) CONFIG['LABEL']['DEFAULT_FONT'] = {'family': family, 'style': style} logger.warn( "Could not find the default font. A random font was selected: {family} ({style})" .format(**CONFIG['LABEL']['DEFAULT_FONT'])) # initialize bootstrap app.config['BOOTSTRAP_SERVE_LOCAL'] = True bootstrap = Bootstrap(app) app.run(host=CONFIG['SERVER']['HOST'], port=PORT, debug=DEBUG)
def main(): global DEBUG, BACKEND_CLASS, CONFIG, IMG_DIR, FILE_NAMES parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--port', default=False) parser.add_argument('--loglevel', type=lambda x: getattr(logging, x.upper()), default=False) parser.add_argument( '--default-label-size', default=False, help='Label size inserted in your printer. Defaults to 62.') parser.add_argument( '--default-orientation', default=False, choices=('standard', 'rotated'), help= 'Label orientation, defaults to "standard". To turn your text by 90°, state "rotated".' ) parser.add_argument('--model', default=False, choices=models, help='The model of your printer (default: QL-500)') parser.add_argument( 'printer', nargs='?', default=False, help= 'String descriptor for the printer to use (like tcp://192.168.0.23:9100 or file:///dev/usb/lp0)' ) args = parser.parse_args() IMG_DIR = "./img/" update_files() if args.printer: CONFIG['PRINTER']['PRINTER'] = args.printer if args.port: PORT = args.port else: PORT = CONFIG['SERVER']['PORT'] if args.loglevel: LOGLEVEL = args.loglevel else: LOGLEVEL = CONFIG['SERVER']['LOGLEVEL'] if LOGLEVEL == 'DEBUG': DEBUG = True else: DEBUG = False if args.model: CONFIG['PRINTER']['MODEL'] = args.model if args.default_label_size: CONFIG['LABEL']['DEFAULT_SIZE'] = args.default_label_size if args.default_orientation: CONFIG['LABEL']['DEFAULT_ORIENTATION'] = args.default_orientation logging.basicConfig(level=LOGLEVEL) try: selected_backend = guess_backend(CONFIG['PRINTER']['PRINTER']) except ValueError: parser.error( "Couln't guess the backend to use from the printer string descriptor" ) BACKEND_CLASS = backend_factory(selected_backend)['backend_class'] if CONFIG['LABEL']['DEFAULT_SIZE'] not in label_sizes: parser.error( "Invalid --default-label-size. Please choose on of the following:\n:" + " ".join(label_sizes)) run(host=CONFIG['SERVER']['HOST'], port=PORT, debug=DEBUG)
def main(): parser = argparse.ArgumentParser() parser.add_argument("--backend", choices=available_backends, help="Forces the use of a specific backend") parser.add_argument( "--list-printers", action="store_true", help="List the devices available with the selected --backend" ) parser.add_argument("--debug", action="store_true", help="Enable debugging output") parser.add_argument( "instruction_file", nargs="?", help="file containing the instructions to be sent to the printer" ) parser.add_argument( "device", metavar="DEVICE_STRING_DESCRIPTOR", nargs="?", help="String descriptor for specific device. If not specified, select first detected device", ) args = parser.parse_args() if args.list_printers and not args.backend: parser.error("Please specify the backend in order to list available devices.") if not args.list_printers and not args.instruction_file: parser.error("the following arguments are required: instruction_file") level = logging.DEBUG if args.debug else logging.WARNING logging.basicConfig(level=level) if args.backend == "network": logger.warning( "The network backend doesn't supply any 'readback' functionality. No status reports will be received." ) selected_backend = None if args.backend: selected_backend = args.backend else: try: selected_backend = guess_backend(args.device) except: logger.info("No backend stated. Selecting the default linux_kernel backend.") selected_backend = "linux_kernel" be = backend_factory(selected_backend) list_available_devices = be["list_available_devices"] BrotherQLBackend = be["backend_class"] if args.list_printers: for printer in list_available_devices(): print(printer["string_descr"]) sys.exit(0) string_descr = None if not args.device: "We need to search for available devices and select the first." ad = list_available_devices() if not ad: sys.exit("No printer found") string_descr = ad[0]["string_descr"] print("Selecting first device %s" % string_descr) else: "A string descriptor for the device was given, let's use it." string_descr = args.device printer = BrotherQLBackend(string_descr) start = time.time() with open(args.instruction_file, "rb") as f: content = f.read() logger.info("Sending instructions to the printer. Total: %d bytes.", len(content)) printer.write(content) if selected_backend == "network": """ No need to wait for completion. The network backend doesn't support readback. """ return printing_completed = False waiting_to_receive = False while time.time() - start < 10: data = printer.read() if not data: time.sleep(0.005) continue try: result = interpret_response(data) except ValueError: logger.error("TIME %.3f - Couln't understand response: %s", time.time() - start, data) continue logger.debug("TIME %.3f - result: %s", time.time() - start, result) if result["errors"]: logger.error("Errors occured: %s", result["errors"]) if result["status_type"] == "Printing completed": printing_completed = True if result["status_type"] == "Phase change" and result["phase_type"] == "Waiting to receive": waiting_to_receive = True if printing_completed and waiting_to_receive: break if not (printing_completed and waiting_to_receive): logger.warning("Printing potentially not successful?")
def main(): global DEBUG, FONTS, BACKEND_CLASS, CONFIG parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--port', default=False) parser.add_argument('--loglevel', type=lambda x: getattr(logging, x.upper()), default=False) parser.add_argument('--font-folder', default=False, help='folder for additional .ttf/.otf fonts') parser.add_argument( '--default-label-size', default=False, help='Label size inserted in your printer. Defaults to 62.') parser.add_argument( '--default-orientation', default=False, choices=('standard', 'rotated'), help= 'Label orientation, defaults to "standard". To turn your text by 90°, state "rotated".' ) parser.add_argument('--model', default=False, choices=models, help='The model of your printer (default: QL-500)') parser.add_argument( 'printer', nargs='?', default=False, help= 'String descriptor for the printer to use (like tcp://192.168.0.23:9100 or file:///dev/usb/lp0)' ) args = parser.parse_args() if args.printer: CONFIG['PRINTER']['PRINTER'] = args.printer if args.port: PORT = args.port else: PORT = CONFIG['SERVER']['PORT'] if args.loglevel: LOGLEVEL = args.loglevel else: LOGLEVEL = CONFIG['SERVER']['LOGLEVEL'] if LOGLEVEL == 'DEBUG': DEBUG = True else: DEBUG = False if args.model: CONFIG['PRINTER']['MODEL'] = args.model if args.default_label_size: CONFIG['LABEL']['DEFAULT_SIZE'] = args.default_label_size if args.default_orientation: CONFIG['LABEL']['DEFAULT_ORIENTATION'] = args.default_orientation if args.font_folder: ADDITIONAL_FONT_FOLDER = args.font_folder else: ADDITIONAL_FONT_FOLDER = CONFIG['SERVER']['ADDITIONAL_FONT_FOLDER'] logging.basicConfig(level=LOGLEVEL) try: selected_backend = guess_backend(CONFIG['PRINTER']['PRINTER']) except ValueError: parser.error( "Couln't guess the backend to use from the printer string descriptor" ) BACKEND_CLASS = backend_factory(selected_backend)['backend_class'] if CONFIG['LABEL']['DEFAULT_SIZE'] not in label_sizes: parser.error( "Invalid --default-label-size. Please choose on of the following:\n:" + " ".join(label_sizes)) FONTS = get_fonts() if ADDITIONAL_FONT_FOLDER: FONTS.update(get_fonts(ADDITIONAL_FONT_FOLDER)) if not FONTS: sys.stderr.write( "Not a single font was found on your system. Please install some or use the \"--font-folder\" argument.\n" ) sys.exit(2) for font in CONFIG['LABEL']['DEFAULT_FONTS']: try: FONTS[font['family']][font['style']] CONFIG['LABEL']['DEFAULT_FONTS'] = font logger.debug( "Selected the following default font: {}".format(font)) break except: pass if CONFIG['LABEL']['DEFAULT_FONTS'] is None: sys.stderr.write( 'Could not find any of the default fonts. Choosing a random one.\n' ) family = random.choice(list(FONTS.keys())) style = random.choice(list(FONTS[family].keys())) CONFIG['LABEL']['DEFAULT_FONTS'] = {'family': family, 'style': style} sys.stderr.write( 'The default font is now set to: {family} ({style})\n'.format( **CONFIG['LABEL']['DEFAULT_FONTS'])) run(host=CONFIG['SERVER']['HOST'], port=PORT, debug=DEBUG)
def send(instructions, printer_identifier=None, backend_identifier=None, blocking=True): """ Send instruction bytes to a printer. :param bytes instructions: The instructions to be sent to the printer. :param str printer_identifier: Identifier for the printer. :param str backend_identifier: Can enforce the use of a specific backend. :param bool blocking: Indicates whether the function call should block while waiting for the completion of the printing. """ status = { 'instructions_sent': True, # The instructions were sent to the printer. 'outcome': 'unknown', # String description of the outcome of the sending operation like: 'unknown', 'sent', 'printed', 'error' 'printer_state': None, # If the selected backend supports reading back the printer state, this key will contain it. 'did_print': False, # If True, a print was produced. It defaults to False if the outcome is uncertain (due to a backend without read-back capability). 'ready_for_next_job': False, # If True, the printer is ready to receive the next instructions. It defaults to False if the state is unknown. } selected_backend = None if backend_identifier: selected_backend = backend_identifier else: try: selected_backend = guess_backend(printer_identifier) except: logger.info( "No backend stated. Selecting the default linux_kernel backend." ) selected_backend = 'linux_kernel' be = backend_factory(selected_backend) list_available_devices = be['list_available_devices'] BrotherQLBackend = be['backend_class'] printer = BrotherQLBackend(printer_identifier) start = time.time() logger.info('Sending instructions to the printer. Total: %d bytes.', len(instructions)) printer.write(instructions) status['outcome'] = 'sent' if not blocking: return status if selected_backend == 'network': """ No need to wait for completion. The network backend doesn't support readback. """ return status while time.time() - start < 10: data = printer.read() if not data: time.sleep(0.005) continue try: result = interpret_response(data) except ValueError: logger.error("TIME %.3f - Couln't understand response: %s", time.time() - start, data) continue status['printer_state'] = result logger.debug('TIME %.3f - result: %s', time.time() - start, result) if result['errors']: logger.error('Errors occured: %s', result['errors']) status['outcome'] = 'error' break if result['status_type'] == 'Printing completed': status['did_print'] = True status['outcome'] = 'printed' if result['status_type'] == 'Phase change' and result[ 'phase_type'] == 'Waiting to receive': status['ready_for_next_job'] = True if status['did_print'] and status['ready_for_next_job']: break if not status['did_print']: logger.warning("'printing completed' status not received.") if not status['ready_for_next_job']: logger.warning("'waiting to receive' status not received.") if (not status['did_print']) or (not status['ready_for_next_job']): logger.warning('Printing potentially not successful?') if status['did_print'] and status['ready_for_next_job']: logger.info("Printing was successful. Waiting for the next job.") return status
def main(): # Command line parsing... parser = argparse.ArgumentParser() parser.add_argument('--backend', choices=available_backends, help='Forces the use of a specific backend') parser.add_argument( '--list-printers', action='store_true', help='List the devices available with the selected --backend') parser.add_argument('--debug', action='store_true', help='Enable debugging output') parser.add_argument( 'instruction_file', nargs='?', help='file containing the instructions to be sent to the printer') parser.add_argument( 'printer', metavar='PRINTER_IDENTIFIER', nargs='?', help= 'Identifier string specifying the printer. If not specified, selects the first detected device.' ) args = parser.parse_args() if args.list_printers and not args.backend: parser.error( 'Please specify the backend in order to list available devices.') if not args.list_printers and not args.instruction_file: parser.error("the following arguments are required: instruction_file") # Reading the instruction input file into content variable if args.instruction_file == '-': try: content = sys.stdin.buffer.read() except AttributeError: content = sys.stdin.read() else: with open(args.instruction_file, 'rb') as f: content = f.read() # Setting up the requested level of logging. level = logging.DEBUG if args.debug else logging.INFO logging.basicConfig(level=level) # State any shortcomings of this software early on. if args.backend == 'network': logger.warning( "The network backend doesn't supply any 'readback' functionality. No status reports will be received." ) # Select the backend based: Either explicitly stated or derived from identifier. Otherwise: Default. selected_backend = None if args.backend: selected_backend = args.backend else: try: selected_backend = guess_backend(args.printer) except: logger.info( "No backend stated. Selecting the default linux_kernel backend." ) selected_backend = 'linux_kernel' # List any printers found, if explicitly asked to do so or if no identifier has been provided. if args.list_printers or not args.printer: available_devices = discover(backend_identifier=selected_backend) log_discovered_devices(available_devices) if args.list_printers: print(textual_description_discovered_devices(available_devices)) sys.exit(0) # Determine the identifier. Either selecting the explicitly stated one or using the first found device. identifier = None if not args.printer: "We need to search for available devices and select the first." if not available_devices: sys.exit("No printer found") identifier = available_devices[0]['identifier'] print("Selecting first device %s" % identifier) else: "A string identifier for the device was given, let's use it." identifier = args.printer # Finally, do the actual printing. send(instructions=content, printer_identifier=identifier, backend_identifier=selected_backend, blocking=True)
'flask.ext.api.parsers.JSONParser', 'flask.ext.api.parsers.URLEncodedParser', 'flask.ext.api.parsers.MultiPartParser' ] app.config['WEBSITE'] = config['website'] node_path = os.path.dirname(os.path.abspath(__file__)).split(os.path.sep)[:-1] node_path.append("node_modules") app.config['node_path'] = os.path.sep.join(node_path) # initialize bootstrap bootstrap = Bootstrap(app) # get and load fonts font = fonts.Fonts() for folder in config['fonts']: font.add_fonts(folder) app.config['fonts'] = font.fontlist() logger.debug(app.config['fonts']) # setting up printer try: backend = guess_backend(config['printer']['device']) logger.info(backend) except ValueError: logger.error('Unable to select the proper backend. Check your config') sys.exit(20) from . import web