Add files via upload

This commit is contained in:
ch3lmi 2023-02-10 14:50:16 +01:00 committed by GitHub
parent 415705d555
commit 52b300bda2
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -1,21 +1,25 @@
#!python3 #!/usr/bin/python3
# -*- coding: utf-8 -*-
""" """
Inkycal weather module Weather module for Inky-Calendar software.
Copyright by aceisace Copyright by aceisace
""" """
from inkycal.modules.template import inkycal_module from inkycal.modules.template import inkycal_module
from inkycal.custom import * from inkycal.custom import *
import math import math, decimal
import decimal
import arrow import arrow
from locale import getdefaultlocale as sys_locale
from pyowm.owm import OWM try:
from pyowm.owm import OWM
logger = logging.getLogger(__name__) 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)
class Weather(inkycal_module): class Weather(inkycal_module):
"""Weather class """Weather class
@ -25,13 +29,13 @@ class Weather(inkycal_module):
requires = { requires = {
"api_key": { "api_key" : {
"label": "Please enter openweathermap api-key. You can create one for free on openweathermap", "label":"Please enter openweathermap api-key. You can create one for free on openweathermap",
}, },
"location": { "location": {
"label": "Please enter your location in the following format: City, Country-Code. " + "label":"Please enter your location in the following format: City, Country-Code. "+
"You can also enter the location ID found in the url " + "You can also enter the location ID found in the url "+
"e.g. https://openweathermap.org/city/4893171 -> ID is 4893171" "e.g. https://openweathermap.org/city/4893171 -> ID is 4893171"
} }
} }
@ -39,17 +43,17 @@ class Weather(inkycal_module):
optional = { optional = {
"round_temperature": { "round_temperature": {
"label": "Round temperature to the nearest degree?", "label":"Round temperature to the nearest degree?",
"options": [True, False], "options": [True, False],
}, },
"round_windspeed": { "round_windspeed": {
"label": "Round windspeed?", "label":"Round windspeed?",
"options": [True, False], "options": [True, False],
}, },
"forecast_interval": { "forecast_interval": {
"label": "Please select the forecast interval", "label":"Please select the forecast interval",
"options": ["daily", "hourly"], "options": ["daily", "hourly"],
}, },
@ -99,10 +103,11 @@ class Weather(inkycal_module):
self.timezone = get_system_tz() self.timezone = get_system_tz()
self.locale = config['language'] self.locale = config['language']
self.weatherfont = ImageFont.truetype( self.weatherfont = ImageFont.truetype(
fonts['weathericons-regular-webfont'], size=self.fontsize) fonts['weathericons-regular-webfont'], size = self.fontsize)
# give an OK message # give an OK message
print(f"{__name__} loaded") print(f"{filename} loaded")
def generate_image(self): def generate_image(self):
"""Generate image for this module""" """Generate image for this module"""
@ -114,14 +119,15 @@ class Weather(inkycal_module):
logger.info(f'Image size: {im_size}') logger.info(f'Image size: {im_size}')
# Create an image for black pixels and one for coloured pixels # Create an image for black pixels and one for coloured pixels
im_black = Image.new('RGB', size=im_size, color='white') im_black = Image.new('RGB', size = im_size, color = 'white')
im_colour = Image.new('RGB', size=im_size, color='white') im_colour = Image.new('RGB', size = im_size, color = 'white')
# Check if internet is available # Check if internet is available
if internet_available(): if internet_available() == True:
logger.info('Connection test passed') logger.info('Connection test passed')
else: else:
raise NetworkNotReachableError logger.exception('Network could not be reached :(')
raise
def get_moon_phase(): def get_moon_phase():
"""Calculate the current (approximate) moon phase""" """Calculate the current (approximate) moon phase"""
@ -132,8 +138,9 @@ class Weather(inkycal_module):
lunations = dec("0.20439731") + (days * dec("0.03386319269")) lunations = dec("0.20439731") + (days * dec("0.03386319269"))
position = lunations % dec(1) position = lunations % dec(1)
index = math.floor((position * dec(8)) + dec("0.5")) index = math.floor((position * dec(8)) + dec("0.5"))
return {0: '\uf095', 1: '\uf099', 2: '\uf09c', 3: '\uf0a0', return {0: '\uf095',1: '\uf099',2: '\uf09c',3: '\uf0a0',
4: '\uf0a3', 5: '\uf0a7', 6: '\uf0aa', 7: '\uf0ae'}[int(index) & 7] 4: '\uf0a3',5: '\uf0a7',6: '\uf0aa',7: '\uf0ae' }[int(index) & 7]
def is_negative(temp): def is_negative(temp):
"""Check if temp is below freezing point of water (0°C/30°F) """Check if temp is below freezing point of water (0°C/30°F)
@ -149,21 +156,37 @@ class Weather(inkycal_module):
# Lookup-table for weather icons and weather codes # Lookup-table for weather icons and weather codes
weathericons = { weathericons = {
'01d': '\uf00d', '02d': '\uf002', '03d': '\uf013', '01d': '\uf00d', '02d': '\uf002', '03d': '\uf013',
'04d': '\uf012', '09d': '\uf01a ', '10d': '\uf019', '04d': '\uf012', '09d': '\uf01a', '10d': '\uf019',
'11d': '\uf01e', '13d': '\uf01b', '50d': '\uf014', '11d': '\uf01e', '13d': '\uf01b', '50d': '\uf014',
'01n': '\uf02e', '02n': '\uf013', '03n': '\uf013', '01n': '\uf02e', '02n': '\uf013', '03n': '\uf013',
'04n': '\uf013', '09n': '\uf037', '10n': '\uf036', '04n': '\uf013', '09n': '\uf037', '10n': '\uf036',
'11n': '\uf03b', '13n': '\uf038', '50n': '\uf023' '11n': '\uf03b', '13n': '\uf038', '50n': '\uf023'
} }
def draw_icon(image, xy, box_size, icon, rotation=None):
def draw_icon(image, xy, box_size, icon, rotation = None):
"""Custom function to add icons of weather font on image """Custom function to add icons of weather font on image
image = on which image should the text be added? image = on which image should the text be added?
xy = xy-coordinates as tuple -> (x,y) xy = xy-coordinates as tuple -> (x,y)
box_size = size of text-box -> (width,height) box_size = size of text-box -> (width,height)
icon = icon-unicode, looks this up in weathericons dictionary icon = icon-unicode, looks this up in weathericons dictionary
""" """
x, y = xy
icon_size_correction = {
'\uf00d': 10/60, '\uf02e': 51/150, '\uf019': 21/60,
'\uf01b': 21/60, '\uf0b5': 51/150, '\uf050': 25/60,
'\uf013': 51/150, '\uf002': 0, '\uf031': 29/100,
'\uf015': 21/60, '\uf01e': 52/150, '\uf056': 51/150,
'\uf053': 14/150, '\uf012': 51/150, '\uf01a': 51/150,
'\uf014': 51/150, '\uf037': 42/150, '\uf036': 42/150,
'\uf03b': 42/150, '\uf038': 42/150, '\uf023': 35/150,
'\uf07a': 35/150, '\uf051': 18/150, '\uf052': 18/150,
'\uf0aa': 0, '\uf095': 0, '\uf099': 0, '\uf09c': 0,
'\uf0a0': 0, '\uf0a3': 0, '\uf0a7': 0, '\uf0aa': 0,
'\uf0ae': 0
}
x,y = xy
box_width, box_height = box_size box_width, box_height = box_size
text = icon text = icon
font = self.weatherfont font = self.weatherfont
@ -183,7 +206,7 @@ class Weather(inkycal_module):
# Align text to desired position # Align text to desired position
x = int((box_width / 2) - (text_width / 2)) x = int((box_width / 2) - (text_width / 2))
y = int((box_height / 2) - (text_height / 2)) y = int((box_height / 2) - (text_height / 2) - (icon_size_correction[icon]*size)/2)
# Draw the text in the text-box # Draw the text in the text-box
draw = ImageDraw.Draw(image) draw = ImageDraw.Draw(image)
@ -191,19 +214,22 @@ class Weather(inkycal_module):
ImageDraw.Draw(space).text((x, y), text, fill='black', font=font) ImageDraw.Draw(space).text((x, y), text, fill='black', font=font)
if rotation != None: if rotation != None:
space.rotate(rotation, expand=True) space.rotate(rotation, expand = True)
# Update only region with text (add text with transparent background) # Update only region with text (add text with transparent background)
image.paste(space, xy, space) image.paste(space, xy, space)
# column1 column2 column3 column4 column5 column6 column7
# |----------|----------|----------|----------|----------|----------|----------|
# | time | temperat.| moonphase| forecast1| forecast2| forecast3| forecast4| # column1 column2 column3 column4 column5 column6 column7
# | current |----------|----------|----------|----------|----------|----------| # |----------|----------|----------|----------|----------|----------|----------|
# | weather | humidity | sunrise | icon1 | icon2 | icon3 | icon4 | # | time | temperat.| moonphase| forecast1| forecast2| forecast3| forecast4|
# | icon |----------|----------|----------|----------|----------|----------| # | current |----------|----------|----------|----------|----------|----------|
# | | windspeed| sunset | temperat.| temperat.| temperat.| temperat.| # | weather | humidity | sunrise | icon1 | icon2 | icon3 | icon4 |
# |----------|----------|----------|----------|----------|----------|----------| # | icon |----------|----------|----------|----------|----------|----------|
# | | windspeed| sunset | temperat.| temperat.| temperat.| temperat.|
# |----------|----------|----------|----------|----------|----------|----------|
# Calculate size rows and columns # Calculate size rows and columns
col_width = im_width // 7 col_width = im_width // 7
@ -215,13 +241,13 @@ class Weather(inkycal_module):
row_height = im_height // 3 row_height = im_height // 3
else: else:
logger.info('Please consider decreasing the height.') logger.info('Please consider decreasing the height.')
row_height = int((im_height * (1 - im_height / im_width)) / 3) row_height = int( (im_height* (1-im_height/im_width)) / 3 )
logger.debug(f"row_height: {row_height} | col_width: {col_width}") logger.debug(f"row_height: {row_height} | col_width: {col_width}")
# Calculate spacings for better centering # Calculate spacings for better centering
spacing_top = int((im_width % col_width) / 2) spacing_top = int( (im_width % col_width) / 2 )
spacing_left = int((im_height % row_height) / 2) spacing_left = int( (im_height % row_height) / 2 )
# Define sizes for weather icons # Define sizes for weather icons
icon_small = int(col_width / 3) icon_small = int(col_width / 3)
@ -238,59 +264,60 @@ class Weather(inkycal_module):
col7 = col6 + col_width col7 = col6 + col_width
# Calculate the y-axis position of each row # Calculate the y-axis position of each row
line_gap = int((im_height - spacing_top - 3 * row_height) // 4) line_gap = int((im_height - spacing_top - 3*row_height) // 4)
row1 = line_gap row1 = line_gap
row2 = row1 + line_gap + row_height row2 = row1 + line_gap + row_height
row3 = row2 + line_gap + row_height row3 = row2+ line_gap + row_height
# Draw lines on each row and border # Draw lines on each row and border
############################################################################ ############################################################################
## draw = ImageDraw.Draw(im_black) ## draw = ImageDraw.Draw(im_black)
## draw.line((0, 0, im_width, 0), fill='red') ## draw.line((0, 0, im_width, 0), fill='red')
## draw.line((0, im_height-1, im_width, im_height-1), fill='red') ## draw.line((0, im_height-1, im_width, im_height-1), fill='red')
## draw.line((0, row1, im_width, row1), fill='black') ## draw.line((0, row1, im_width, row1), fill='black')
## draw.line((0, row1+row_height, im_width, row1+row_height), fill='black') ## draw.line((0, row1+row_height, im_width, row1+row_height), fill='black')
## draw.line((0, row2, im_width, row2), fill='black') ## draw.line((0, row2, im_width, row2), fill='black')
## draw.line((0, row2+row_height, im_width, row2+row_height), fill='black') ## draw.line((0, row2+row_height, im_width, row2+row_height), fill='black')
## draw.line((0, row3, im_width, row3), fill='black') ## draw.line((0, row3, im_width, row3), fill='black')
## draw.line((0, row3+row_height, im_width, row3+row_height), fill='black') ## draw.line((0, row3+row_height, im_width, row3+row_height), fill='black')
############################################################################ ############################################################################
# Positions for current weather details # Positions for current weather details
weather_icon_pos = (col1, 0) weather_icon_pos = (col1, 0)
temperature_icon_pos = (col2, row1) temperature_icon_pos = (col2, row1)
temperature_pos = (col2 + icon_small, row1) temperature_pos = (col2+icon_small, row1)
humidity_icon_pos = (col2, row2) humidity_icon_pos = (col2, row2)
humidity_pos = (col2 + icon_small, row2) humidity_pos = (col2+icon_small, row2)
windspeed_icon_pos = (col2, row3) windspeed_icon_pos = (col2, row3)
windspeed_pos = (col2 + icon_small, row3) windspeed_pos = (col2+icon_small, row3)
# Positions for sunrise, sunset, moonphase # Positions for sunrise, sunset, moonphase
moonphase_pos = (col3, row1) moonphase_pos = (col3, row1)
sunrise_icon_pos = (col3, row2) sunrise_icon_pos = (col3, row2)
sunrise_time_pos = (col3 + icon_small, row2) sunrise_time_pos = (col3+icon_small, row2)
sunset_icon_pos = (col3, row3) sunset_icon_pos = (col3, row3)
sunset_time_pos = (col3 + icon_small, row3) sunset_time_pos = (col3+ icon_small, row3)
# Positions for forecast 1 # Positions for forecast 1
stamp_fc1 = (col4, row1) stamp_fc1 = (col4, row1)
icon_fc1 = (col4, row1 + row_height) icon_fc1 = (col4, row1+row_height)
temp_fc1 = (col4, row3) temp_fc1 = (col4, row3)
# Positions for forecast 2 # Positions for forecast 2
stamp_fc2 = (col5, row1) stamp_fc2 = (col5, row1)
icon_fc2 = (col5, row1 + row_height) icon_fc2 = (col5, row1+row_height)
temp_fc2 = (col5, row3) temp_fc2 = (col5, row3)
# Positions for forecast 3 # Positions for forecast 3
stamp_fc3 = (col6, row1) stamp_fc3 = (col6, row1)
icon_fc3 = (col6, row1 + row_height) icon_fc3 = (col6, row1+row_height)
temp_fc3 = (col6, row3) temp_fc3 = (col6, row3)
# Positions for forecast 4 # Positions for forecast 4
stamp_fc4 = (col7, row1) stamp_fc4 = (col7, row1)
icon_fc4 = (col7, row1 + row_height) icon_fc4 = (col7, row1+row_height)
temp_fc4 = (col7, row3) temp_fc4 = (col7, row3)
# Create current-weather and weather-forecast objects # Create current-weather and weather-forecast objects
@ -331,8 +358,8 @@ class Weather(inkycal_module):
hour_gap = 3 hour_gap = 3
# Create timings for hourly forcasts # Create timings for hourly forcasts
forecast_timings = [now.shift(hours=+ hour_gap + _).floor('hour') forecast_timings = [now.shift(hours = + hour_gap + _).floor('hour')
for _ in range(0, 12, 3)] for _ in range(0,12,3)]
# Create forecast objects for given timings # Create forecast objects for given timings
forecasts = [forecast.get_weather_at(forecast_time.datetime) for forecasts = [forecast.get_weather_at(forecast_time.datetime) for
@ -345,9 +372,9 @@ class Weather(inkycal_module):
forecast.temperature(unit=temp_unit)['temp'], ndigits=dec_temp)) forecast.temperature(unit=temp_unit)['temp'], ndigits=dec_temp))
icon = forecast.weather_icon_name icon = forecast.weather_icon_name
fc_data['fc' + str(forecasts.index(forecast) + 1)] = { fc_data['fc'+str(forecasts.index(forecast)+1)] = {
'temp': temp, 'temp':temp,
'icon': icon, 'icon':icon,
'stamp': forecast_timings[forecasts.index(forecast)].to( 'stamp': forecast_timings[forecasts.index(forecast)].to(
get_system_tz()).format('H.00' if self.hour_format == 24 else 'h a') get_system_tz()).format('H.00' if self.hour_format == 24 else 'h a')
} }
@ -356,6 +383,7 @@ class Weather(inkycal_module):
logger.debug("getting daily forecasts") logger.debug("getting daily forecasts")
def calculate_forecast(days_from_today): def calculate_forecast(days_from_today):
"""Get temperature range and most frequent icon code for forecast """Get temperature range and most frequent icon code for forecast
days_from_today should be int from 1-4: e.g. 2 -> 2 days from today days_from_today should be int from 1-4: e.g. 2 -> 2 days from today
@ -376,6 +404,7 @@ class Weather(inkycal_module):
# Calculate min. and max. temp for this day # Calculate min. and max. temp for this day
temp_range = f'{max(daily_temp)}°/{min(daily_temp)}°' temp_range = f'{max(daily_temp)}°/{min(daily_temp)}°'
# Get all weather icon codes for this day # Get all weather icon codes for this day
daily_icons = [_.weather_icon_name for _ in forecasts] daily_icons = [_.weather_icon_name for _ in forecasts]
# Find most common element from all weather icon codes # Find most common element from all weather icon codes
@ -383,20 +412,20 @@ class Weather(inkycal_module):
weekday = now.shift(days=days_from_today).format('ddd', locale= weekday = now.shift(days=days_from_today).format('ddd', locale=
self.locale) self.locale)
return {'temp': temp_range, 'icon': status, 'stamp': weekday} return {'temp':temp_range, 'icon':status, 'stamp': weekday}
forecasts = [calculate_forecast(days) for days in range(1, 5)] forecasts = [calculate_forecast(days) for days in range (1,5)]
fc_data = {} fc_data = {}
for forecast in forecasts: for forecast in forecasts:
fc_data['fc' + str(forecasts.index(forecast) + 1)] = { fc_data['fc'+str(forecasts.index(forecast)+1)] = {
'temp': forecast['temp'], 'temp':forecast['temp'],
'icon': forecast['icon'], 'icon':forecast['icon'],
'stamp': forecast['stamp'] 'stamp': forecast['stamp']
} }
for key, val in fc_data.items(): for key,val in fc_data.items():
logger.debug((key, val)) logger.debug((key,val))
# Get some current weather details # Get some current weather details
temperature = '{}°'.format(round( temperature = '{}°'.format(round(
@ -420,11 +449,11 @@ class Weather(inkycal_module):
sunset = sunset_raw.format('H:mm') sunset = sunset_raw.format('H:mm')
# Format the windspeed to user preference # Format the windspeed to user preference
if self.use_beaufort: if self.use_beaufort == True:
logger.debug("using beaufort for wind") logger.debug("using beaufort for wind")
wind = str(weather.wind(unit='beaufort')['speed']) wind = str(weather.wind(unit='beaufort')['speed'])
else: elif self.use_beaufort == False:
if self.units == 'metric': if self.units == 'metric':
logging.debug('getting windspeed in metric unit') logging.debug('getting windspeed in metric unit')
@ -446,63 +475,63 @@ class Weather(inkycal_module):
'\uf053') '\uf053')
if is_negative(temperature): if is_negative(temperature):
write(im_black, temperature_pos, (col_width - icon_small, row_height), write(im_black, temperature_pos, (col_width-icon_small, row_height),
temperature, font=self.font) temperature, font = self.font)
else: else:
write(im_black, temperature_pos, (col_width - icon_small, row_height), write(im_black, temperature_pos, (col_width-icon_small, row_height),
temperature, font=self.font) temperature, font = self.font)
draw_icon(im_colour, humidity_icon_pos, (icon_small, row_height), draw_icon(im_colour, humidity_icon_pos, (icon_small, row_height),
'\uf07a') '\uf07a')
write(im_black, humidity_pos, (col_width - icon_small, row_height), write(im_black, humidity_pos, (col_width-icon_small, row_height),
humidity + '%', font=self.font) humidity+'%', font = self.font)
draw_icon(im_colour, windspeed_icon_pos, (icon_small, icon_small), draw_icon(im_colour, windspeed_icon_pos, (icon_small, icon_small),
'\uf050') '\uf050')
write(im_black, windspeed_pos, (col_width - icon_small, row_height), write(im_black, windspeed_pos, (col_width-icon_small, row_height),
wind, font=self.font) wind, font=self.font)
# Fill weather details in col 3 (moonphase, sunrise, sunset) # Fill weather details in col 3 (moonphase, sunrise, sunset)
draw_icon(im_colour, moonphase_pos, (col_width, row_height), moonphase) draw_icon(im_colour, moonphase_pos, (col_width, row_height), moonphase)
draw_icon(im_colour, sunrise_icon_pos, (icon_small, icon_small), '\uf051') draw_icon(im_colour, sunrise_icon_pos, (icon_small, icon_small), '\uf051')
write(im_black, sunrise_time_pos, (col_width - icon_small, row_height), write(im_black, sunrise_time_pos, (col_width-icon_small, row_height),
sunrise, font=self.font) sunrise, font = self.font)
draw_icon(im_colour, sunset_icon_pos, (icon_small, icon_small), '\uf052') draw_icon(im_colour, sunset_icon_pos, (icon_small, icon_small), '\uf052')
write(im_black, sunset_time_pos, (col_width - icon_small, row_height), sunset, write(im_black, sunset_time_pos, (col_width-icon_small, row_height), sunset,
font=self.font) font = self.font)
# Add the forecast data to the correct places # Add the forecast data to the correct places
for pos in range(1, len(fc_data) + 1): for pos in range(1, len(fc_data)+1):
stamp = fc_data[f'fc{pos}']['stamp'] stamp = fc_data[f'fc{pos}']['stamp']
icon = weathericons[fc_data[f'fc{pos}']['icon']] icon = weathericons[fc_data[f'fc{pos}']['icon']]
temp = fc_data[f'fc{pos}']['temp'] temp = fc_data[f'fc{pos}']['temp']
write(im_black, eval(f'stamp_fc{pos}'), (col_width, row_height), write(im_black, eval(f'stamp_fc{pos}'), (col_width, row_height),
stamp, font=self.font) stamp, font = self.font)
draw_icon(im_colour, eval(f'icon_fc{pos}'), (col_width, row_height + line_gap * 2), draw_icon(im_colour, eval(f'icon_fc{pos}'), (col_width, row_height+line_gap*2),
icon) icon)
write(im_black, eval(f'temp_fc{pos}'), (col_width, row_height), write(im_black, eval(f'temp_fc{pos}'), (col_width, row_height),
temp, font=self.font) temp, font = self.font)
border_h = row3 + row_height border_h = row3 + row_height
border_w = col_width - 3 # leave 3 pixels gap border_w = col_width - 3 #leave 3 pixels gap
# Add borders around each sub-section # Add borders around each sub-section
draw_border(im_black, (col1, row1), (col_width * 3 - 3, border_h), draw_border(im_black, (col1, row1), (col_width*3 - 3, border_h),
shrinkage=(0, 0)) shrinkage=(0,0))
for _ in range(4, 8): for _ in range(4,8):
draw_border(im_black, (eval(f'col{_}'), row1), (border_w, border_h), draw_border(im_black, (eval(f'col{_}'), row1), (border_w, border_h),
shrinkage=(0, 0)) shrinkage=(0,0))
# return the images ready for the display # return the images ready for the display
return im_black, im_colour return im_black, im_colour
if __name__ == '__main__': if __name__ == '__main__':
print(f'running {__name__} in standalone mode') print(f'running {filename} in standalone mode')