Implementation of interface (template) for all modules
- Correct setup of logging - all inkycal-modules inherit from the given template - Added basic, optional validation - more code cleanups - fixed a few minor bugs
This commit is contained in:
@@ -0,0 +1,4 @@
|
||||
##from .inkycal_agenda import agenda
|
||||
##from .inkycal_calendar import calendar
|
||||
##from .inkycal_weather import weather
|
||||
##from .inkycal_rss import rss
|
||||
|
@@ -5,7 +5,7 @@ iCalendar (parsing) module for Inky-Calendar Project
|
||||
Copyright by aceisace
|
||||
"""
|
||||
|
||||
""" ---info about iCalendars---
|
||||
""" ---info about iCalendars---
|
||||
• all day events start at midnight, ending at midnight of the next day
|
||||
• iCalendar saves all event timings in UTC -> need to be converted into local
|
||||
time
|
||||
@@ -17,6 +17,7 @@ import arrow
|
||||
from urllib.request import urlopen
|
||||
import logging
|
||||
import time # timezone, timing speed of execution
|
||||
import os
|
||||
|
||||
try:
|
||||
import recurring_ical_events
|
||||
@@ -30,20 +31,15 @@ except ModuleNotFoundError:
|
||||
print('icalendar library could not be found. Please install this with:')
|
||||
print('pip3 install icalendar')
|
||||
|
||||
urls = [
|
||||
# Default calendar
|
||||
'https://calendar.google.com/calendar/ical/en.usa%23holiday%40group.v.calendar.google.com/public/basic.ics',
|
||||
# inkycal debug calendar
|
||||
'https://calendar.google.com/calendar/ical/6nqv871neid5l0t7hgk6jgr24c%40group.calendar.google.com/private-c9ab692c99fb55360cbbc28bf8dedb3a/basic.ics'
|
||||
]
|
||||
|
||||
filename = os.path.basename(__file__).split('.py')[0]
|
||||
logger = logging.getLogger(filename)
|
||||
logger.setLevel(level=logging.INFO)
|
||||
|
||||
class icalendar:
|
||||
"""iCalendar parsing moudule for inkycal.
|
||||
Parses events from given iCalendar URLs / paths"""
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
|
||||
def __init__(self):
|
||||
self.icalendars = []
|
||||
self.parsed_events = []
|
||||
@@ -82,7 +78,7 @@ class icalendar:
|
||||
|
||||
# Add the parsed icalendar/s to the self.icalendars list
|
||||
if ical: self.icalendars += ical
|
||||
logging.info('loaded iCalendars from URLs')
|
||||
logger.info('loaded iCalendars from URLs')
|
||||
|
||||
def load_from_file(self, filepath):
|
||||
"""Input a string or list of strings containing valid iCalendar filepaths
|
||||
@@ -97,7 +93,7 @@ class icalendar:
|
||||
raise Exception ("Input: '{}' is not a string or list!".format(url))
|
||||
|
||||
self.icalendars += icals
|
||||
logging.info('loaded iCalendars from filepaths')
|
||||
logger.info('loaded iCalendars from filepaths')
|
||||
|
||||
def get_events(self, timeline_start, timeline_end, timezone=None):
|
||||
"""Input an arrow (time) object for:
|
||||
@@ -148,8 +144,6 @@ class icalendar:
|
||||
if arrow.get(events.get('dtstart').dt).format('HH:mm') != '00:00' else 'UTC')
|
||||
} for ical in recurring_events for events in ical]
|
||||
|
||||
|
||||
|
||||
# if any recurring events were found, add them to parsed_events
|
||||
if re_events: self.parsed_events += re_events
|
||||
|
||||
@@ -159,9 +153,9 @@ class icalendar:
|
||||
return self.parsed_events
|
||||
|
||||
def sort(self):
|
||||
"""Sort all parsed events"""
|
||||
"""Sort all parsed events in order of beginning time"""
|
||||
if not self.parsed_events:
|
||||
logging.debug('no events found to be sorted')
|
||||
logger.debug('no events found to be sorted')
|
||||
else:
|
||||
by_date = lambda event: event['begin']
|
||||
self.parsed_events.sort(key=by_date)
|
||||
@@ -208,7 +202,7 @@ class icalendar:
|
||||
"""
|
||||
|
||||
if not self.parsed_events:
|
||||
logging.debug('no events found to be shown')
|
||||
logger.debug('no events found to be shown')
|
||||
else:
|
||||
line_width = max(len(_['title']) for _ in self.parsed_events)
|
||||
for events in self.parsed_events:
|
||||
@@ -217,6 +211,18 @@ class icalendar:
|
||||
print('{0} {1} | {2} | {3}'.format(
|
||||
title, ' ' * (line_width - len(title)), begin, end))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print('running {0} in standalone mode'.format(filename))
|
||||
|
||||
|
||||
urls = [
|
||||
# Default calendar
|
||||
'https://calendar.google.com/calendar/ical/en.usa%23holiday%40group.v.calendar.google.com/public/basic.ics',
|
||||
# inkycal debug calendar
|
||||
'https://calendar.google.com/calendar/ical/6nqv871neid5l0t7hgk6jgr24c%40group.calendar.google.com/private-c9ab692c99fb55360cbbc28bf8dedb3a/basic.ics'
|
||||
]
|
||||
|
||||
##a = icalendar()
|
||||
##a.load_url(urls)
|
||||
##a.get_events(arrow.now(), arrow.now().shift(weeks=4), timezone = a.get_system_tz())
|
||||
|
@@ -5,85 +5,74 @@ Agenda module for Inky-Calendar Project
|
||||
Copyright by aceisace
|
||||
"""
|
||||
|
||||
from inkycal.modules.template import inkycal_module
|
||||
from inkycal.custom import *
|
||||
import calendar as cal
|
||||
import arrow
|
||||
from inkycal.modules.ical_parser import icalendar
|
||||
|
||||
size = (400, 520)
|
||||
config = {'week_starts_on': 'Monday', 'ical_urls': ['https://calendar.google.com/calendar/ical/en.usa%23holiday%40group.v.calendar.google.com/public/basic.ics']}
|
||||
import calendar as cal
|
||||
import arrow
|
||||
|
||||
filename = os.path.basename(__file__).split('.py')[0]
|
||||
logger = logging.getLogger(filename)
|
||||
logger.setLevel(level=logging.INFO)
|
||||
|
||||
|
||||
class agenda:
|
||||
class agenda(inkycal_module):
|
||||
"""Agenda class
|
||||
Create agenda and show events from given icalendars
|
||||
"""
|
||||
logger = logging.getLogger(__name__)
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
|
||||
def __init__(self, section_size, section_config):
|
||||
"""Initialize inkycal_agenda module"""
|
||||
self.name = os.path.basename(__file__).split('.py')[0]
|
||||
self.config = section_config
|
||||
self.width, self.height = section_size
|
||||
self.background_colour = 'white'
|
||||
self.font_colour = 'black'
|
||||
self.fontsize = 12
|
||||
self.font = ImageFont.truetype(
|
||||
fonts['NotoSans-SemiCondensed'], size = self.fontsize)
|
||||
self.padding_x = 0.02 #rename to margin?
|
||||
self.padding_y = 0.05
|
||||
|
||||
# Section specific config
|
||||
# Format for formatting dates
|
||||
super().__init__(section_size, section_config)
|
||||
# Module specific parameters
|
||||
required = ['week_starts_on', 'ical_urls']
|
||||
for param in required:
|
||||
if not param in section_config:
|
||||
raise Exception('config is missing {}'.format(param))
|
||||
|
||||
# module name
|
||||
self.name = filename
|
||||
|
||||
# module specific parameters
|
||||
self.date_format = 'ddd D MMM'
|
||||
# Fromat for formatting event timings
|
||||
self.time_format = "HH:mm" #use auto for 24/12 hour format?
|
||||
self.language = 'en' # Grab from settings file?
|
||||
self.time_format = "HH:mm"
|
||||
self.language = 'en'
|
||||
self.timezone = get_system_tz()
|
||||
# urls of icalendars
|
||||
self.ical_urls = config['ical_urls']
|
||||
# filepaths of icalendar files
|
||||
self.ical_files = []
|
||||
|
||||
# give an OK message
|
||||
print('{0} loaded'.format(self.name))
|
||||
|
||||
def set(self, **kwargs):
|
||||
"""Manually set some parameters of this module"""
|
||||
|
||||
for key, value in kwargs.items():
|
||||
if key in self.__dict__:
|
||||
setattr(self, key, value)
|
||||
else:
|
||||
print('{0} does not exist'.format(key))
|
||||
pass
|
||||
|
||||
def get(self, **kwargs):
|
||||
"""Manually get some parameters of this module"""
|
||||
|
||||
for key, value in kwargs.items():
|
||||
if key in self.__dict__:
|
||||
getattr(self, key, value)
|
||||
else:
|
||||
print('{0} does not exist'.format(key))
|
||||
pass
|
||||
|
||||
def get_options(self):
|
||||
"""Get all options which can be changed"""
|
||||
|
||||
return self.__dict__
|
||||
def _validate(self):
|
||||
"""Validate module-specific parameters"""
|
||||
if not isinstance(self.date_format, str):
|
||||
print('date_format has to be an arrow-compatible token')
|
||||
if not isinstance(self.time_format, str):
|
||||
print('time_format has to be an arrow-compatible token')
|
||||
if not isinstance(self.language, str):
|
||||
print('language has to be a string: "en" ')
|
||||
if not isinstance(self.timezone, str):
|
||||
print('The timezone has bo be a string.')
|
||||
if not isinstance(self.ical_urls, list):
|
||||
print('ical_urls has to be a list ["url1", "url2"] ')
|
||||
if not isinstance(self.ical_files, list):
|
||||
print('ical_files has to be a list ["path1", "path2"] ')
|
||||
|
||||
def generate_image(self):
|
||||
"""Generate image for this module"""
|
||||
|
||||
# Define new image size with respect to padding
|
||||
im_width = int(self.width - (self.width * 2 * self.padding_x))
|
||||
im_height = int(self.height - (self.height * 2 * self.padding_y))
|
||||
im_width = int(self.width - (self.width * 2 * self.margin_x))
|
||||
im_height = int(self.height - (self.height * 2 * self.margin_y))
|
||||
im_size = im_width, im_height
|
||||
|
||||
logging.info('Image size: {0}'.format(im_size))
|
||||
logger.info('Image size: {0}'.format(im_size))
|
||||
|
||||
# Create an image for black pixels and one for coloured pixels
|
||||
im_black = Image.new('RGB', size = im_size, color = self.background_colour)
|
||||
im_black = Image.new('RGB', size = im_size, color = 'white')
|
||||
im_colour = Image.new('RGB', size = im_size, color = 'white')
|
||||
|
||||
# Calculate the max number of lines that can fit on the image
|
||||
@@ -91,7 +80,7 @@ class agenda:
|
||||
line_height = int(self.font.getsize('hg')[1]) + line_spacing
|
||||
line_width = im_width
|
||||
max_lines = im_height // line_height
|
||||
logging.debug(('max lines:',max_lines))
|
||||
logger.debug(('max lines:',max_lines))
|
||||
|
||||
# Create timeline for agenda
|
||||
now = arrow.now()
|
||||
@@ -117,37 +106,37 @@ class agenda:
|
||||
# Sort events by beginning time
|
||||
parser.sort()
|
||||
# parser.show_events()
|
||||
|
||||
|
||||
# Set the width for date, time and event titles
|
||||
date_width = int(max([self.font.getsize(
|
||||
dates['begin'].format(self.date_format, locale=self.language))[0]
|
||||
for dates in agenda_events]) * 1.2)
|
||||
logging.debug(('date_width:', date_width))
|
||||
logger.debug(('date_width:', date_width))
|
||||
|
||||
# Check if any events were filtered
|
||||
if upcoming_events:
|
||||
|
||||
|
||||
# Find out how much space the event times take
|
||||
time_width = int(max([self.font.getsize(
|
||||
events['begin'].format(self.time_format, locale=self.language))[0]
|
||||
for events in upcoming_events]) * 1.2)
|
||||
logging.debug(('time_width:', time_width))
|
||||
logger.debug(('time_width:', time_width))
|
||||
|
||||
# Calculate x-pos for time
|
||||
x_time = date_width
|
||||
logging.debug(('x-time:', x_time))
|
||||
logger.debug(('x-time:', x_time))
|
||||
|
||||
# Find out how much space is left for event titles
|
||||
event_width = im_width - time_width - date_width
|
||||
logging.debug(('width for events:', event_width))
|
||||
logger.debug(('width for events:', event_width))
|
||||
|
||||
# Calculate x-pos for event titles
|
||||
x_event = date_width + time_width
|
||||
logging.debug(('x-event:', x_event))
|
||||
logger.debug(('x-event:', x_event))
|
||||
|
||||
# Calculate positions for each line
|
||||
line_pos = [(0, int(line * line_height)) for line in range(max_lines)]
|
||||
logging.debug(('line_pos:', line_pos))
|
||||
logger.debug(('line_pos:', line_pos))
|
||||
|
||||
# Merge list of dates and list of events
|
||||
agenda_events += upcoming_events
|
||||
@@ -159,7 +148,7 @@ class agenda:
|
||||
# Delete more entries than can be displayed (max lines)
|
||||
del agenda_events[max_lines:]
|
||||
|
||||
#print(agenda_events)
|
||||
self._agenda_events = agenda_events
|
||||
|
||||
cursor = 0
|
||||
for _ in agenda_events:
|
||||
@@ -170,7 +159,7 @@ class agenda:
|
||||
ImageDraw.Draw(im_colour).line(
|
||||
(0, line_pos[cursor][1], im_width, line_pos[cursor][1]),
|
||||
fill = 'black')
|
||||
|
||||
|
||||
write(im_black, line_pos[cursor], (date_width, line_height),
|
||||
title, font = self.font, alignment='left')
|
||||
|
||||
@@ -185,12 +174,12 @@ class agenda:
|
||||
write(im_black, (x_time, line_pos[cursor][1]),
|
||||
(time_width, line_height), time,
|
||||
font = self.font, alignment='left')
|
||||
|
||||
|
||||
write(im_black, (x_event, line_pos[cursor][1]),
|
||||
(event_width, line_height),
|
||||
'• '+title, font = self.font, alignment='left')
|
||||
cursor += 1
|
||||
|
||||
|
||||
# If no events were found, write only dates and lines
|
||||
else:
|
||||
cursor = 0
|
||||
@@ -199,25 +188,21 @@ class agenda:
|
||||
ImageDraw.Draw(im_colour).line(
|
||||
(0, line_pos[cursor][1], im_width, line_pos[cursor][1]),
|
||||
fill = 'black')
|
||||
|
||||
|
||||
write(im_black, line_pos[cursor], (date_width, line_height),
|
||||
title, font = self.font, alignment='left')
|
||||
|
||||
cursor += 1
|
||||
|
||||
logging.info('no events found')
|
||||
|
||||
############################################################################
|
||||
# Exception handling
|
||||
############################################################################
|
||||
logger.info('no events found')
|
||||
|
||||
# Save image of black and colour channel in image-folder
|
||||
im_black.save(images+self.name+'.png')
|
||||
im_colour.save(images+self.name+'_colour.png')
|
||||
|
||||
if __name__ == '__main__':
|
||||
print('running {0} in standalone mode'.format(
|
||||
os.path.basename(__file__).split('.py')[0]))
|
||||
print('running {0} in standalone mode'.format(filename))
|
||||
|
||||
# remove below line later!
|
||||
a = agenda(size, config).generate_image()
|
||||
##size = (400, 520)
|
||||
##config = {'week_starts_on': 'Monday', 'ical_urls': ['https://calendar.google.com/calendar/ical/en.usa%23holiday%40group.v.calendar.google.com/public/basic.ics']}
|
||||
##a = agenda(size, config).generate_image()
|
||||
|
@@ -4,81 +4,62 @@
|
||||
Calendar module for Inky-Calendar Project
|
||||
Copyright by aceisace
|
||||
"""
|
||||
|
||||
from inkycal.modules.template import inkycal_module
|
||||
from inkycal.custom import *
|
||||
|
||||
import calendar as cal
|
||||
import arrow
|
||||
|
||||
size = (400, 520)
|
||||
config = {'week_starts_on': 'Monday', 'ical_urls': ['https://calendar.google.com/calendar/ical/en.usa%23holiday%40group.v.calendar.google.com/public/basic.ics']}
|
||||
filename = os.path.basename(__file__).split('.py')[0]
|
||||
logger = logging.getLogger(filename)
|
||||
logger.setLevel(level=logging.INFO)
|
||||
|
||||
|
||||
class calendar:
|
||||
class calendar(inkycal_module):
|
||||
"""Calendar class
|
||||
Create monthly calendar and show events from given icalendars
|
||||
"""
|
||||
logger = logging.getLogger(__name__)
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
|
||||
def __init__(self, section_size, section_config):
|
||||
"""Initialize inkycal_calendar module"""
|
||||
|
||||
self.name = os.path.basename(__file__).split('.py')[0]
|
||||
self.config = section_config
|
||||
self.width, self.height = section_size
|
||||
self.fontsize = 12
|
||||
self.font = ImageFont.truetype(
|
||||
fonts['NotoSans-SemiCondensed'], size = self.fontsize)
|
||||
self.padding_x = 0.02
|
||||
self.padding_y = 0.05
|
||||
super().__init__(section_size, section_config)
|
||||
|
||||
# Module specific parameters
|
||||
required = ['week_starts_on']
|
||||
for param in required:
|
||||
if not param in section_config:
|
||||
raise Exception('config is missing {}'.format(param))
|
||||
|
||||
# module name
|
||||
self.name = filename
|
||||
|
||||
# module specific parameters
|
||||
self.shuffle_feeds = True
|
||||
|
||||
self.num_font = ImageFont.truetype(
|
||||
fonts['NotoSans-SemiCondensed'], size = self.fontsize)
|
||||
self.weekstart = 'Monday'
|
||||
self.weekstart = self.config['week_starts_on']
|
||||
self.show_events = True
|
||||
self.date_format = 'D MMM' # used for dates
|
||||
self.time_format = "HH:mm" # used for timings
|
||||
self.language = 'en' # Grab from settings file?
|
||||
|
||||
self.timezone = get_system_tz()
|
||||
self.ical_urls = config['ical_urls']
|
||||
self.ical_urls = self.config['ical_urls']
|
||||
self.ical_files = []
|
||||
|
||||
# give an OK message
|
||||
print('{0} loaded'.format(self.name))
|
||||
|
||||
def set(self, **kwargs):
|
||||
"""Manually set some parameters of this module"""
|
||||
|
||||
for key, value in kwargs.items():
|
||||
if key in self.__dict__:
|
||||
setattr(self, key, value)
|
||||
else:
|
||||
print('{0} does not exist'.format(key))
|
||||
pass
|
||||
|
||||
def get(self, **kwargs):
|
||||
"""Manually get some parameters of this module"""
|
||||
|
||||
for key, value in kwargs.items():
|
||||
if key in self.__dict__:
|
||||
getattr(self, key, value)
|
||||
else:
|
||||
print('{0} does not exist'.format(key))
|
||||
pass
|
||||
|
||||
def get_options(self):
|
||||
"""Get all options which can be changed"""
|
||||
|
||||
return self.__dict__
|
||||
|
||||
def generate_image(self):
|
||||
"""Generate image for this module"""
|
||||
|
||||
# Define new image size with respect to padding
|
||||
im_width = int(self.width - (self.width * 2 * self.padding_x))
|
||||
im_height = int(self.height - (self.height * 2 * self.padding_y))
|
||||
im_width = int(self.width - (self.width * 2 * self.margin_x))
|
||||
im_height = int(self.height - (self.height * 2 * self.margin_y))
|
||||
im_size = im_width, im_height
|
||||
|
||||
logging.info('Image size: {0}'.format(im_size))
|
||||
logger.info('Image size: {0}'.format(im_size))
|
||||
|
||||
# Create an image for black pixels and one for coloured pixels
|
||||
im_black = Image.new('RGB', size = im_size, color = 'white')
|
||||
@@ -91,13 +72,13 @@ class calendar:
|
||||
if self.show_events == True:
|
||||
calendar_height = int(self.height*0.6)
|
||||
events_height = int(self.height*0.25)
|
||||
logging.debug('calendar-section size: {0} x {1} px'.format(
|
||||
logger.debug('calendar-section size: {0} x {1} px'.format(
|
||||
im_width, calendar_height))
|
||||
logging.debug('events-section size: {0} x {1} px'.format(
|
||||
logger.debug('events-section size: {0} x {1} px'.format(
|
||||
im_width, events_height))
|
||||
else:
|
||||
calendar_height = self.height - month_name_height - weekday_height
|
||||
logging.debug('calendar-section size: {0} x {1} px'.format(
|
||||
logger.debug('calendar-section size: {0} x {1} px'.format(
|
||||
im_width, calendar_height))
|
||||
|
||||
# Create grid and calculate icon sizes
|
||||
@@ -141,7 +122,7 @@ class calendar:
|
||||
# Set up weeknames in local language and add to main section
|
||||
weekday_names = [weekstart.shift(days=+_).format('ddd',locale=self.language)
|
||||
for _ in range(7)]
|
||||
logging.debug('weekday names: {}'.format(weekday_names))
|
||||
logger.debug('weekday names: {}'.format(weekday_names))
|
||||
|
||||
for _ in range(len(weekday_pos)):
|
||||
write(
|
||||
@@ -300,8 +281,10 @@ class calendar:
|
||||
im_colour.save(images+self.name+'_colour.png')
|
||||
|
||||
if __name__ == '__main__':
|
||||
print('running {0} in standalone mode'.format(
|
||||
os.path.basename(__file__).split('.py')[0]))
|
||||
print('running {0} in standalone mode'.format(filename))
|
||||
|
||||
|
||||
##size = (400, 520)
|
||||
##config = {'week_starts_on': 'Monday', 'ical_urls': ['https://calendar.google.com/calendar/ical/en.usa%23holiday%40group.v.calendar.google.com/public/basic.ics']}
|
||||
##a = calendar(size, config)
|
||||
##a.generate_image()
|
||||
|
@@ -1,81 +1,64 @@
|
||||
#!/usr/bin/python3
|
||||
# -*- coding: utf-8 -*-
|
||||
|
||||
"""
|
||||
RSS module for Inky-Calendar Project
|
||||
Copyright by aceisace
|
||||
"""
|
||||
|
||||
from inkycal.modules.template import inkycal_module
|
||||
from inkycal.custom import *
|
||||
from random import shuffle
|
||||
|
||||
from random import shuffle
|
||||
try:
|
||||
import feedparser
|
||||
except ImportError:
|
||||
print('feedparser is not installed! Please install with:')
|
||||
print('pip3 install feedparser')
|
||||
|
||||
filename = os.path.basename(__file__).split('.py')[0]
|
||||
logger = logging.getLogger(filename)
|
||||
logger.setLevel(level=logging.INFO)
|
||||
|
||||
# Debug Data (not for production use!)
|
||||
size = (384, 160)
|
||||
config = {'rss_urls': ['http://feeds.bbci.co.uk/news/world/rss.xml#']}
|
||||
#config = {'rss_urls': ['http://www.tagesschau.de/xml/atom/']}
|
||||
#https://www.tagesschau.de/xml/rss2
|
||||
|
||||
class rss:
|
||||
class rss(inkycal_module):
|
||||
"""RSS class
|
||||
parses rss feeds from given urls
|
||||
"""
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logging.basicConfig(level=logging.DEBUG)
|
||||
|
||||
def __init__(self, section_size, section_config):
|
||||
"""Initialize inkycal_rss module"""
|
||||
|
||||
super().__init__(section_size, section_config)
|
||||
|
||||
self.name = os.path.basename(__file__).split('.py')[0]
|
||||
self.config = section_config
|
||||
self.width, self.height = section_size
|
||||
self.fontsize = 12
|
||||
self.padding_x = 0.02
|
||||
self.padding_y = 0.05
|
||||
self.font = ImageFont.truetype(fonts['NotoSans-SemiCondensed'],
|
||||
size = self.fontsize)
|
||||
# Module specific parameters
|
||||
required = ['rss_urls']
|
||||
for param in required:
|
||||
if not param in section_config:
|
||||
raise Exception('config is missing {}'.format(param))
|
||||
|
||||
# module specifc config
|
||||
# module name
|
||||
self.name = filename
|
||||
|
||||
# module specific parameters
|
||||
self.shuffle_feeds = True
|
||||
|
||||
# give an OK message
|
||||
print('{0} loaded'.format(self.name))
|
||||
|
||||
def set(self, **kwargs):
|
||||
"""Manually set some parameters of this module"""
|
||||
for key, value in kwargs.items():
|
||||
if key in self.__dict__:
|
||||
setattr(self, key, value)
|
||||
else:
|
||||
print('{0} does not exist'.format(key))
|
||||
pass
|
||||
def _validate(self):
|
||||
"""Validate module-specific parameters"""
|
||||
if not isinstance(self.shuffle_feeds, bool):
|
||||
print('shuffle_feeds has to be a boolean: True/False')
|
||||
|
||||
def get(self, **kwargs):
|
||||
"""Manually get some parameters of this module"""
|
||||
for key, value in kwargs.items():
|
||||
if key in self.__dict__:
|
||||
getattr(self, key, value)
|
||||
else:
|
||||
print('{0} does not exist'.format(key))
|
||||
pass
|
||||
|
||||
def get_options(self):
|
||||
"""Get all options which can be changed"""
|
||||
return self.__dict__
|
||||
|
||||
def generate_image(self):
|
||||
"""Generate image for this module"""
|
||||
|
||||
# Define new image size with respect to padding
|
||||
im_width = int(self.width - (self.width * 2 * self.padding_x))
|
||||
im_height = int(self.height - (self.height * 2 * self.padding_y))
|
||||
im_width = int(self.width - (self.width * 2 * self.margin_x))
|
||||
im_height = int(self.height - (self.height * 2 * self.margin_y))
|
||||
im_size = im_width, im_height
|
||||
logging.info('image size: {} x {} px'.format(im_width, im_height))
|
||||
logger.info('image size: {} x {} px'.format(im_width, im_height))
|
||||
|
||||
# Create an image for black pixels and one for coloured pixels
|
||||
im_black = Image.new('RGB', size = im_size, color = 'white')
|
||||
@@ -83,7 +66,7 @@ class rss:
|
||||
|
||||
# Check if internet is available
|
||||
if internet_available() == True:
|
||||
logging.info('Connection test passed')
|
||||
logger.info('Connection test passed')
|
||||
else:
|
||||
raise Exception('Network could not be reached :/')
|
||||
|
||||
@@ -101,8 +84,6 @@ class rss:
|
||||
line_positions = [
|
||||
(0, spacing_top + _ * line_height ) for _ in range(max_lines)]
|
||||
|
||||
|
||||
|
||||
# Create list containing all rss-feeds from all rss-feed urls
|
||||
parsed_feeds = []
|
||||
for feeds in self.config['rss_urls']:
|
||||
@@ -149,9 +130,20 @@ class rss:
|
||||
im_black.save(images+self.name+'.png', 'PNG')
|
||||
im_colour.save(images+self.name+'_colour.png', 'PNG')
|
||||
|
||||
if __name__ == '__main__':
|
||||
print('running {0} in standalone mode'.format(
|
||||
os.path.basename(__file__).split('.py')[0]))
|
||||
|
||||
##def main():
|
||||
## print('Main got executed just now~~~~')
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print('running {0} in standalone/debug mode'.format(filename))
|
||||
##else:
|
||||
## print(filename, 'imported')
|
||||
## main()
|
||||
|
||||
##a = rss(size, config)
|
||||
##a.generate_image()
|
||||
##size = (384, 160)
|
||||
##config = {'rss_urls': ['http://feeds.bbci.co.uk/news/world/rss.xml#']}
|
||||
#config = {'rss_urls': ['http://www.tagesschau.de/xml/atom/']}
|
||||
#https://www.tagesschau.de/xml/rss2 -> problematic feed
|
||||
|
@@ -4,46 +4,43 @@
|
||||
Weather module for Inky-Calendar software.
|
||||
Copyright by aceisace
|
||||
"""
|
||||
|
||||
from inkycal.modules.template import inkycal_module
|
||||
from inkycal.custom import *
|
||||
|
||||
import math, decimal
|
||||
import arrow
|
||||
from locale import getdefaultlocale as sys_locale
|
||||
|
||||
try:
|
||||
import pyowm
|
||||
except ImportError:
|
||||
print('pyowm is not installed! Please install with:')
|
||||
print('pip3 install pyowm')
|
||||
|
||||
filename = os.path.basename(__file__).split('.py')[0]
|
||||
logger = logging.getLogger(filename)
|
||||
logger.setLevel(level=logging.INFO)
|
||||
|
||||
# Debug Data (not for production use!)
|
||||
config = {'api_key': 'secret', 'location': 'Stuttgart, DE'}
|
||||
size = (384,80)
|
||||
|
||||
class weather:
|
||||
class weather(inkycal_module):
|
||||
"""weather class
|
||||
parses weather details from openweathermap
|
||||
"""
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
logging.basicConfig(level=logging.INFO)
|
||||
|
||||
def __init__(self, section_size, section_config):
|
||||
"""Initialize inkycal_weather module"""
|
||||
self.name = os.path.basename(__file__).split('.py')[0]
|
||||
self.config = section_config
|
||||
self.width, self.height = section_size
|
||||
self.background_colour = 'white'
|
||||
self.font_colour = 'black'
|
||||
self.fontsize = 12
|
||||
self.font = ImageFont.truetype(fonts['NotoSans-SemiCondensed'],
|
||||
size = self.fontsize)
|
||||
self.padding_x = 0.02
|
||||
self.padding_y = 0.05
|
||||
|
||||
super().__init__(section_size, section_config)
|
||||
|
||||
# Weather-specfic options
|
||||
self.owm = pyowm.OWM(config['api_key'])
|
||||
# Module specific parameters
|
||||
required = ['api_key','location']
|
||||
for param in required:
|
||||
if not param in section_config:
|
||||
raise Exception('config is missing {}'.format(param))
|
||||
|
||||
# module name
|
||||
self.name = filename
|
||||
|
||||
# module specific parameters
|
||||
self.owm = pyowm.OWM(self.config['api_key'])
|
||||
self.units = 'metric' # metric # imperial
|
||||
self.hour_format = '24' # 12 #24
|
||||
self.timezone = get_system_tz()
|
||||
@@ -54,52 +51,25 @@ class weather:
|
||||
self.locale = sys_locale()[0]
|
||||
self.weatherfont = ImageFont.truetype(fonts['weathericons-regular-webfont'],
|
||||
size = self.fontsize)
|
||||
|
||||
# give an OK message
|
||||
print('{0} loaded'.format(self.name))
|
||||
|
||||
def set(self, **kwargs):
|
||||
"""Manually set some parameters of this module"""
|
||||
|
||||
for key, value in kwargs.items():
|
||||
if key in self.__dict__:
|
||||
setattr(self, key, value)
|
||||
else:
|
||||
print('{0} does not exist'.format(key))
|
||||
pass
|
||||
|
||||
def get(self, **kwargs):
|
||||
"""Manually get some parameters of this module"""
|
||||
|
||||
for key, value in kwargs.items():
|
||||
if key in self.__dict__:
|
||||
getattr(self, key, value)
|
||||
else:
|
||||
print('{0} does not exist'.format(key))
|
||||
pass
|
||||
|
||||
|
||||
def get_options(self):
|
||||
"""Get all options which can be changed"""
|
||||
|
||||
return self.__dict__
|
||||
|
||||
|
||||
def generate_image(self):
|
||||
"""Generate image for this module"""
|
||||
|
||||
# Define new image size with respect to padding
|
||||
im_width = int(self.width - (self.width * 2 * self.padding_x))
|
||||
im_height = int(self.height - (self.height * 2 * self.padding_y))
|
||||
im_width = int(self.width - (self.width * 2 * self.margin_x))
|
||||
im_height = int(self.height - (self.height * 2 * self.margin_y))
|
||||
im_size = im_width, im_height
|
||||
logging.info('image size: {} x {} px'.format(im_width, im_height))
|
||||
logger.info('image size: {} x {} px'.format(im_width, im_height))
|
||||
|
||||
# Create an image for black pixels and one for coloured pixels
|
||||
im_black = Image.new('RGB', size = im_size, color = self.background_colour)
|
||||
im_black = Image.new('RGB', size = im_size, color = 'white')
|
||||
im_colour = Image.new('RGB', size = im_size, color = 'white')
|
||||
|
||||
# Check if internet is available
|
||||
if internet_available() == True:
|
||||
logging.info('Connection test passed')
|
||||
logger.info('Connection test passed')
|
||||
else:
|
||||
raise Exception('Network could not be reached :(')
|
||||
|
||||
@@ -353,7 +323,7 @@ class weather:
|
||||
}
|
||||
|
||||
for key,val in fc_data.items():
|
||||
logging.info((key,val))
|
||||
logger.info((key,val))
|
||||
|
||||
# Get some current weather details
|
||||
temperature = '{}°'.format(weather.get_temperature(unit=temp_unit)['temp'])
|
||||
@@ -450,16 +420,16 @@ class weather:
|
||||
draw_border(im_black, (col6, row1), (col_width, im_height))
|
||||
draw_border(im_black, (col7, row1), (col_width, im_height))
|
||||
|
||||
##############################################################################
|
||||
# Error Handling
|
||||
##############################################################################
|
||||
|
||||
# Save image of black and colour channel in image-folder
|
||||
# Save image of black and colour channel in image-folder
|
||||
im_black.save(images+self.name+'.png', "PNG")
|
||||
im_colour.save(images+self.name+'_colour.png', "PNG")
|
||||
|
||||
if __name__ == '__main__':
|
||||
print('running {0} in standalone mode'.format(
|
||||
os.path.basename(__file__).split('.py')[0]))
|
||||
a = weather(size, config)
|
||||
a.generate_image()
|
||||
print('running {0} in standalone mode'.format(filename))
|
||||
|
||||
|
||||
##config = {'api_key': 'secret', 'location': 'Stuttgart, DE'}
|
||||
##size = (384,80)
|
||||
##a = weather(size, config)
|
||||
##a.generate_image()
|
||||
# Debug Data (not for production use!)
|
||||
|
54
inkycal/modules/template.py
Normal file
54
inkycal/modules/template.py
Normal file
@@ -0,0 +1,54 @@
|
||||
import abc
|
||||
from inkycal.custom import *
|
||||
|
||||
class inkycal_module(metaclass=abc.ABCMeta):
|
||||
"""Generic base class for inykcal modules"""
|
||||
|
||||
@classmethod
|
||||
def __subclasshook__(cls, subclass):
|
||||
return (hasattr(subclass, 'generate_image') and
|
||||
callable(subclass.generate_image) or
|
||||
NotImplemented)
|
||||
|
||||
def __init__(self, section_size, section_config):
|
||||
# Initializes base module
|
||||
# sets properties shared amongst all sections
|
||||
self.config = section_config
|
||||
self.width, self.height = section_size
|
||||
self.fontsize = 12
|
||||
self.margin_x = 0.02
|
||||
self.margin_y = 0.05
|
||||
self.font = ImageFont.truetype(
|
||||
fonts['NotoSans-SemiCondensed'], size = self.fontsize)
|
||||
|
||||
def set(self, help=False, **kwargs):
|
||||
"""Set attributes of class, e.g. class.set(key=value)
|
||||
see that can be changed by setting help to True
|
||||
"""
|
||||
lst = dir(self).copy()
|
||||
options = [_ for _ in lst if not _.startswith('_')]
|
||||
if 'logger' in options: options.remove('logger')
|
||||
|
||||
if help == True:
|
||||
print('The following can be configured:')
|
||||
print(options)
|
||||
|
||||
for key, value in kwargs.items():
|
||||
if key in options:
|
||||
setattr(self, key, value)
|
||||
print("set '{}' to '{}'".format(key,value))
|
||||
else:
|
||||
print('{0} does not exist'.format(key))
|
||||
pass
|
||||
|
||||
# Check if validation has been implemented
|
||||
try:
|
||||
self._validate()
|
||||
except AttributeError:
|
||||
print('no validation implemented')
|
||||
|
||||
@abc.abstractmethod
|
||||
def generate_image(self):
|
||||
# Generate image for this module with specified parameters
|
||||
raise NotImplementedError(
|
||||
'The developers were too lazy to implement this function')
|
137
inkycal/modules/test.py
Normal file
137
inkycal/modules/test.py
Normal file
@@ -0,0 +1,137 @@
|
||||
#!/usr/bin/python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
Module template for Inky-Calendar Project
|
||||
|
||||
Create your own module with this template
|
||||
|
||||
Copyright by aceisace
|
||||
"""
|
||||
|
||||
#############################################################################
|
||||
# Required imports (do not remove)
|
||||
#############################################################################
|
||||
# Required for setting up this module
|
||||
from inkycal.modules.template import inkycal_module
|
||||
from inkycal.custom import *
|
||||
|
||||
|
||||
#############################################################################
|
||||
# Built-in library imports
|
||||
#############################################################################
|
||||
|
||||
# Built-in libraries go here
|
||||
from random import shuffle
|
||||
|
||||
|
||||
#############################################################################
|
||||
# External library imports
|
||||
#############################################################################
|
||||
|
||||
# For external libraries, which require installing,
|
||||
# use try...except ImportError to check if it has been installed
|
||||
# If it is not found, print a short message on how to install this dependency
|
||||
try:
|
||||
import feedparser
|
||||
except ImportError:
|
||||
print('feedparser is not installed! Please install with:')
|
||||
print('pip3 install feedparser')
|
||||
|
||||
|
||||
#############################################################################
|
||||
# Filename + logging (do not remove)
|
||||
#############################################################################
|
||||
|
||||
# Get the name of this file, set up logging for this filename
|
||||
filename = os.path.basename(__file__).split('.py')[0]
|
||||
logger = logging.getLogger(filename)
|
||||
logger.setLevel(level=logging.INFO)
|
||||
|
||||
#############################################################################
|
||||
# Class setup
|
||||
#############################################################################
|
||||
|
||||
class simple(inkycal_module):
|
||||
""" Simple Class
|
||||
Explain what this module does...
|
||||
"""
|
||||
|
||||
# Initialise the class (do not remove)
|
||||
def __init__(self, section_size, section_config):
|
||||
"""Initialize inkycal_rss module"""
|
||||
|
||||
# Initialise this module via the inkycal_module template (required)
|
||||
super().__init__(section_size, section_config)
|
||||
|
||||
# module name (required)
|
||||
self.name = filename
|
||||
|
||||
# module specific parameters (optional)
|
||||
self.do_something = True
|
||||
|
||||
# give an OK message (optional)
|
||||
print('{0} loaded'.format(self.name))
|
||||
|
||||
#############################################################################
|
||||
# Validation of module specific parameters #
|
||||
#############################################################################
|
||||
|
||||
def _validate(self):
|
||||
"""Validate module-specific parameters"""
|
||||
# Check the type of module-specific parameters
|
||||
# This function is optional, but very useful for debugging.
|
||||
|
||||
# Here, we are checking if do_something (from init) is True/False
|
||||
if not isinstance(self.do_something, bool):
|
||||
print('do_something has to be a boolean: True/False')
|
||||
|
||||
|
||||
#############################################################################
|
||||
# Generating the image #
|
||||
#############################################################################
|
||||
|
||||
def generate_image(self):
|
||||
"""Generate image for this module"""
|
||||
|
||||
# Define new image size with respect to padding (required)
|
||||
im_width = int(self.width - (self.width * 2 * self.margin_x))
|
||||
im_height = int(self.height - (self.height * 2 * self.margin_y))
|
||||
im_size = im_width, im_height
|
||||
|
||||
# Use logger.info(), logger.debug(), logger.warning() to display
|
||||
# useful information for the developer
|
||||
logger.info('image size: {} x {} px'.format(im_width, im_height))
|
||||
|
||||
# Create an image for black pixels and one for coloured pixels (required)
|
||||
im_black = Image.new('RGB', size = im_size, color = 'white')
|
||||
im_colour = Image.new('RGB', size = im_size, color = 'white')
|
||||
|
||||
#################################################################
|
||||
|
||||
# Your code goes here #
|
||||
|
||||
# Write/Draw something on the image
|
||||
|
||||
# You can use these custom functions to help you create the image:
|
||||
# - write() -> write text on the image
|
||||
# - get_fonts() -> see which fonts are available
|
||||
# - get_system_tz() -> Get the system's current timezone
|
||||
# - auto_fontsize() -> Scale the fontsize to the provided height
|
||||
# - textwrap() -> Split a paragraph into smaller lines
|
||||
# - internet_available() -> Check if internet is available
|
||||
# - draw_border() -> Draw a border around the specified area
|
||||
|
||||
# If these aren't enough, take a look at python Pillow (imaging library)'s
|
||||
# documentation.
|
||||
|
||||
|
||||
#################################################################
|
||||
|
||||
# Save image of black and colour channel in image-folder
|
||||
im_black.save(images+self.name+'.png', 'PNG')
|
||||
im_colour.save(images+self.name+'_colour.png', 'PNG')
|
||||
|
||||
|
||||
# Check if the module is being run by itself
|
||||
if __name__ == '__main__':
|
||||
print('running {0} in standalone mode'.format(filename))
|
Reference in New Issue
Block a user