コード例 #1
0
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']
コード例 #2
0
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']