def __init__(self, print_welcome=True): self.printer = ThermalPrinter("/dev/serial0", 9600, heat_time=60, heat_interval=15) if check_printer_status(self.printer): if print_welcome: self.print_boot_image() self.printer.sleep()
def Lista(self, Fecha, tabla): with ThermalPrinter(port='/dev/serial0', baudrate=9600) as printer: printer.out('--------------------------------', bold=True) printer.out('Blanco Joyeros', justify='C', double_height=True) printer.out('--------------------------------', bold=True) printer.out('Resumen del Día: ' + str(Fecha), justify='L') printer.out('════════════════════════════════', bold=True) printer.out('Num-Descripción Importe|FP', bold=True) printer.out('════════════════════════════════', bold=True) Total = 0 for a in tabla: if a[4] != 0.0: iva = "+ " + str(a[4]) else: iva = "" if a[3] == "Al contado": forma = "C" elif a[3] == "Tarjeta de crédito/Débito": forma = "T" else: forma = "V" Total = round(Total + a[2] + a[4], 2) printer.out(str(a[0]) + ' - ' + str(a[1]), justify='L') printer.out(str(a[2]) + str(iva) + ' - ' + str(forma), justify='R') printer.out('════════════════════════════════', bold=True) printer.out('Total: ' + str(Total), justify='R', bold=True) printer.feed(3)
def test_changing_good_values(port): opt = {'heat_time': 120, 'heat_interval': 8, 'most_heated_point': 5} printer = ThermalPrinter(port=port, baudrate=9600, **opt) assert printer._baudrate == 9600 assert printer.heat_time == 120 assert printer.heat_interval == 8 assert printer.most_heated_point == 5
def test_default_values(port): printer = ThermalPrinter(port=port) assert repr(printer) assert printer._baudrate == 19200 assert printer.heat_time == 80 assert printer.heat_interval == 12 assert printer.most_heated_point == 3
def test_changing_bad_values(port): opt = { 'heat_time': 512, 'heat_interval': -42, 'most_heated_point': -42, } with pytest.raises(ThermalPrinterValueError): printer = ThermalPrinter(port=port, baudrate=9600, **opt) del printer
def Ticket(self): #printer = ThermalPrinter(baudrate=9600,port='/dev/serial0') #printer.out("xxxx", justify = 'C' ) with ThermalPrinter(port='/dev/serial0', baudrate=9600) as printer: printer.out('--------------------------------', bold=True) #printer.out('Blanco Joyeros', justify='C', double_height=True) printer.out('Blanco Joyeros', justify='C', double_width=True) printer.out('Paseo Gral. Dávila 264 Nº 2', justify='C') printer.out('Santander - Cantabria', justify='C') printer.out('--------------------------------', bold=True) printer.out('Número Ticket: ' + str(self.ticket[0]), justify='L') printer.out('Fecha: ' + str(self.ticket[1]), justify='L') printer.out('Hora: ' + str(self.ticket[2]), justify='L') printer.out('Forma de pago: ', justify='L') printer.out(str(self.ticket[3]), justify='R') printer.out('───────────────────────┬────────') printer.out('Artículo │ Importe') printer.out('───────────────────────┴────────') for lista in self.detalleTicket: printer.out(str(lista[1]), justify='L') printer.out(str(lista[2]), justify='R') printer.out('════════════════════════════════', bold=True) if str(self.ticket[5] ) != "0.0": #No Imprimir el IVA si este vale CERO printer.out('Suma Importes: ' + str(self.ticket[4]), justify='R') printer.out('IVA 21%:' + str(self.ticket[5]), justify='R') printer.out('TOTAL TICKET: ' + str(self.ticket[6]), justify='R') printer.out('════════════════════════════════', bold=True) printer.out('Para devolución conserve ticket', bold=True) printer.out('Plazo de Devolución: 15 días', bold=True) printer.out('Teléfono Atención: 942 34 34 24') printer.out('════════════════════════════════', bold=True) printer.out('MUCHAS GRACIAS POR SU COMPRA', bold=True, justify='C') printer.out('════════════════════════════════', bold=True) # Line feeds printer.feed(3)
def receipt(): global printer my_date = datetime.datetime.now() my_date_string = my_date.strftime('%x') my_time_string = my_date.strftime('%X') printer = ThermalPrinter(port='/dev/serial0') printer.out('MORALITY', double_width=True) printer.out('') printer.out('TIME: ' + my_time_string) printer.out('DATE: ' + my_date_string) printer.out('NAME: Spartan John') printer.out('VIOLATION: Sotto voce verbal') printer.out('PUNISHMENT: Warning & fine') printer.out('FINE: 1.5 Credits') printer.out('') printer.out('VIOLATION', double_width=True) printer.feed(3)
# Buttons BLACK_BUTTON_GPIO = 17 RED_BUTTON_GPIO = 27 mode = 0 recording = False # Audio recording parameters RATE = 44100 CHUNK = int(RATE / 10) # 100ms DEVICE = 1 print('Demolition Man Morality Violation Ticketing Machine') os.system('espeak starting\ up') # Printer printer = ThermalPrinter(port='/dev/serial0') receipt = Image.open(os.path.join(os.path.dirname(__file__), 'dm.jpg')) def shutdown(): os.system('espeak shutting\ down') os.system('sudo shutdown -h now') def black_button_pressed(): global mode, recording print('Black button pressed') recording = False if mode == 0: print('Switching to stenographer mode') os.system('espeak stenographer\ mode')
def set_printer(self): """ Connection to the printer. """ self.printer = ThermalPrinter() return self.printer.status()['paper']
class Calendar: printer = None url = 'GOOGLE_CALENDAR_URL' def __enter__(self): return self def __exit__(self, *_): pass def start(self): """ La méthode qui s'occupe de tout gérer. """ events = self.get_events() if events: if not self.set_printer(): return 1 self.print_data(events) return 0 def set_printer(self): """ Connection to the printer. """ self.printer = ThermalPrinter() return self.printer.status()['paper'] def get_events(self): """ Retrieve events of the day. """ now = utc.localize(datetime.utcnow()) events = icalevents.events(url=self.url, end=now + timedelta(days=1)) data = [] for event in events: data.append((event.start.strftime('%H:%M'), event.end.strftime('%H:%M'), event.summary)) return sorted(set(data), key=lambda x: x[0]) def print_data(self, events): """ Just print. """ def header(): """ Print the header. """ self.printer.codepage(CodePage.ISO_8859_1) self.printer.feed() self.printer.image(Image.open('agenda.png')) self.printer.feed() def line(evt, first_line=False, last_line=False): """ Impression d'un événement. """ start, end, sumary = evt hour = '{} - {}'.format(start, end) if start == end: hour = 'Whole day' if first_line: self.printer.out(b'\xd5', line_feed=False, codepage=CodePage.CP437) self.printer.out(b'\xcd' * (self.printer.max_column - 2), line_feed=False, codepage=CodePage.CP437) self.printer.out(b'\xb8', codepage=CodePage.CP437) self.printer.out(b'\xb3', line_feed=False, codepage=CodePage.CP437) self.printer.out(' {0: <{1}} '.format(hour, self.printer.max_column - 4), line_feed=False, codepage=CodePage.ISO_8859_1) self.printer.out(b'\xb3', codepage=CodePage.CP437) for line_ in wrap(sumary, self.printer.max_column - 4): self.printer.out(b'\xb3', line_feed=False, codepage=CodePage.CP437) self.printer.out(' {0: <{1}} '.format( line_, self.printer.max_column - 4), line_feed=False, codepage=CodePage.ISO_8859_1) self.printer.out(b'\xb3', codepage=CodePage.CP437) if not last_line: self.printer.out(b'\xc3', line_feed=False, codepage=CodePage.CP437) self.printer.out(b'\xc4' * (self.printer.max_column - 2), line_feed=False, codepage=CodePage.CP437) self.printer.out(b'\xb4', codepage=CodePage.CP437) else: self.printer.out(b'\xd4', line_feed=False, codepage=CodePage.CP437) self.printer.out(b'\xcd' * (self.printer.max_column - 2), line_feed=False, codepage=CodePage.CP437) self.printer.out(b'\xbe', codepage=CodePage.CP437) def footer(): """ Printed the footer. """ self.printer.feed() self.printer.out('Have a nice day :)', justify='C', codepage=CodePage.ISO_8859_1) self.printer.feed(4) header() if events: first, last = events[0], events[-1] for event in events: line(event, first_line=event is first, last_line=event is last) footer() return self.printer.status()['paper']
class Weather: data = {} printer = None fi_params = 'parameters.ini' fi_models = 'models.ini' url = 'https://api.forecast.io/forecast/{key}/{lat},{lon}?units=ca&lang=fr' def __init__(self): url = self.url.format(**self.get_params()) self.forecast = manual(url) def __enter__(self): return self def __exit__(self, *_): pass def start(self): """ La méthode qui s'occupe de tout gérer. """ daily = self.forecast.daily() today = daily.data[3] self.data['icon'] = daily.data[0].icon self.data['temp_min'] = int(today.temperatureMin) self.data['temp_max'] = int(today.temperatureMax) self.data['wind'] = int(today.windSpeed) self.data['wind_dir'] = today.windBearing if self.data['wind'] else -1 self.data['humidity'] = int(today.humidity * 100) self.data['precipitations'] = int(today.precipIntensityMax * 100) model = self.get_model() if not self.set_printer(): return 1 self.print_data(model) return 0 def set_printer(self): """ Connection to the printer. """ self.printer = ThermalPrinter() return self.printer.status()['paper'] def get_params(self): """ Retrieve parameters. """ if not self.fi_params: return ini = ConfigParser() ini.read(self.fi_params) return ini['general'] def get_model(self): """ Retrieve all ASCII art models. Inspiration: https://github.com/schachmat/wego """ if not self.fi_models: return ini = ConfigParser() ini.read(self.fi_models) model = '{}-{}'.format(self.data['icon'], precipitations(self.data['precipitations'])) # Model name try: # Example: snow-heavy summary = ini['summary'][model] except KeyError: try: # Example: snow model = self.data['icon'] summary = ini['summary'][model] except KeyError: print('Missing model: {}'.format(model)) model = 'unknown' summary = ini['summary'][model] if summary.startswith('::'): summary = ini['summary'][summary[2:]] self.data['summary'] = summary # ASCII art ^^ try: # Example: rain-heavy ascii_art = ini['models'][model] except KeyError: try: # Example: rain model = self.data['icon'] ascii_art = ini['models'][model] except KeyError: print('ASCII art manquant : {}'.format(model)) model = 'unknown' ascii_art = ini['models'][model] if ascii_art.startswith('::'): ascii_art = ini['models'][ascii_art[2:]] return ascii_art.replace('a', '') def print_data(self, model): """ Just print. """ self.printer.codepage(CodePage.ISO_8859_1) self.printer.feed() self.printer.out('Weather', bold=True, size='L') self.printer.out(datetime.now().strftime('%Y-%m-%d')) self.printer.feed() lines = model.splitlines()[1:] self.printer.out(lines[0]) # State self.printer.out(lines[1].format(self.data['summary'])) # Temperature self.printer.out(lines[2].format(self.data['temp_min'], self.data['temp_max'])) # Wind part1, part2 = lines[3].split('&') self.printer.out(part1, line_feed=False) if self.data['wind_dir'] == -1: self.printer.out(b'\af', line_feed=False, codepage=CodePage.CP865) else: char = wind_dir(self.data['wind_dir']) if not isinstance(char, bytes): self.printer.out(char, line_feed=False) else: self.printer.out(char, line_feed=False, codepage=CodePage.THAI2) self.printer.out(part2.format(self.data['wind'])) # Precipitations self.printer.out(lines[4].format(self.data['precipitations'], self.data['humidity'])) self.printer.feed(3) return self.printer.status()['paper']
def test_initialiation_with_context_manager(port): with ThermalPrinter(port=port) as printer: repr(printer)
def test_initialiation_without_context_manager(port): printer = ThermalPrinter(port=port) printer.close()
class PrinterWrapper: def __init__(self, print_welcome=True): self.printer = ThermalPrinter("/dev/serial0", 9600, heat_time=60, heat_interval=15) if check_printer_status(self.printer): if print_welcome: self.print_boot_image() self.printer.sleep() def print_boot_image(self): self.printer.image(Image.open(image_path), True) self.printer.feed(3) # function also wraps by words # look at string, count characters def print_line(self, text, formatting=None): if formatting is None: formatting = { 'justify': 'C', 'size': 'L', 'bold': False, 'upside_down': False, 'underline': 0 } if check_printer_status(self.printer): max_col = (self.printer.max_column / (2 if formatting['size'] == 'L' else 1)) - 1 print("Max col", self.printer.max_column) text = textwrap.fill(text, max_col) self.printer.wake() self.printer.out(text, justify=formatting['justify'], size=formatting['size'], bold=formatting['bold'], upside_down=formatting['upside_down'], underline=formatting['underline']) self.printer.feed(1) self.printer.sleep() else: self.printer.sleep() raise RuntimeError("Printer is out of paper") def print_image(self, image_data, is_data_uri=True): if is_data_uri: image = get_image_from_data_uri(data_uri=image_data) else: image = image_data self.printer.wake() self.printer.image(image) self.printer.sleep() def print_signature(self, sig): self.printer.wake() date_string = get_date_string() # padding to right-justify the timestamp (date_sting) space_padding = ' ' * (self.printer.max_column - 1 - (len(date_string) + len(sig))) self.printer.out('', line_feed=True) self.printer.out(f'{sig}{space_padding}{date_string}'.strip(), justify='L', size='S', underline=False) self.printer.feed(3) self.printer.sleep() def get_status(self): try: return self.printer.status() except: return {}
fh = logging.FileHandler('../thermal_printer.log') fh.setLevel(logging.DEBUG) formatter = logging.Formatter('%(asctime)s, %(message)s') fh.setFormatter(formatter) logger.addHandler(fh) # params printer_port = '/dev/tty.usbserial-A601E88T' baudrate = 9600 flask_host = '0.0.0.0' flask_port = 5000 doLogging = True # start printer #TODO error if cannot connect to the printer printer = ThermalPrinter(port=printer_port, baudrate=baudrate) app = Flask(__name__) CORS(app) @app.route('/') def index(): return '' #TODO 400 BAD REQUEST if print parameter error @app.route('/thermal-printer/v1/print', methods=['POST']) def thermal_print(): content = request.json lines = content.get('lines', [])
from thermalprinter import ThermalPrinter with ThermalPrinter(port='/dev/serial0') as printer: printer.out("Hello, world!") printer.feed(2)