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)
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']
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 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 {}