Add files via upload
This commit is contained in:
parent
415705d555
commit
52b300bda2
@ -1,508 +1,537 @@
|
|||||||
#!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
|
||||||
parses weather details from openweathermap
|
parses weather details from openweathermap
|
||||||
"""
|
"""
|
||||||
name = "Weather (openweathermap) - Get weather forecasts from openweathermap"
|
name = "Weather (openweathermap) - Get weather forecasts from openweathermap"
|
||||||
|
|
||||||
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"
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
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"],
|
||||||
},
|
},
|
||||||
|
|
||||||
"units": {
|
"units": {
|
||||||
"label": "Which units should be used?",
|
"label": "Which units should be used?",
|
||||||
"options": ["metric", "imperial"],
|
"options": ["metric", "imperial"],
|
||||||
},
|
},
|
||||||
|
|
||||||
"hour_format": {
|
"hour_format": {
|
||||||
"label": "Which hour format do you prefer?",
|
"label": "Which hour format do you prefer?",
|
||||||
"options": [24, 12],
|
"options": [24, 12],
|
||||||
},
|
},
|
||||||
|
|
||||||
"use_beaufort": {
|
"use_beaufort": {
|
||||||
"label": "Use beaufort scale for windspeed?",
|
"label": "Use beaufort scale for windspeed?",
|
||||||
"options": [True, False],
|
"options": [True, False],
|
||||||
},
|
},
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
def __init__(self, config):
|
def __init__(self, config):
|
||||||
"""Initialize inkycal_weather module"""
|
"""Initialize inkycal_weather module"""
|
||||||
|
|
||||||
super().__init__(config)
|
super().__init__(config)
|
||||||
|
|
||||||
config = config['config']
|
config = config['config']
|
||||||
|
|
||||||
# Check if all required parameters are present
|
# Check if all required parameters are present
|
||||||
for param in self.requires:
|
for param in self.requires:
|
||||||
if not param in config:
|
if not param in config:
|
||||||
raise Exception(f'config is missing {param}')
|
raise Exception(f'config is missing {param}')
|
||||||
|
|
||||||
# required parameters
|
# required parameters
|
||||||
self.api_key = config['api_key']
|
self.api_key = config['api_key']
|
||||||
self.location = config['location']
|
self.location = config['location']
|
||||||
|
|
||||||
# optional parameters
|
# optional parameters
|
||||||
self.round_temperature = config['round_temperature']
|
self.round_temperature = config['round_temperature']
|
||||||
self.round_windspeed = config['round_windspeed']
|
self.round_windspeed = config['round_windspeed']
|
||||||
self.forecast_interval = config['forecast_interval']
|
self.forecast_interval = config['forecast_interval']
|
||||||
self.units = config['units']
|
self.units = config['units']
|
||||||
self.hour_format = int(config['hour_format'])
|
self.hour_format = int(config['hour_format'])
|
||||||
self.use_beaufort = config['use_beaufort']
|
self.use_beaufort = config['use_beaufort']
|
||||||
|
|
||||||
# additional configuration
|
# additional configuration
|
||||||
self.owm = OWM(self.api_key).weather_manager()
|
self.owm = OWM(self.api_key).weather_manager()
|
||||||
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):
|
|
||||||
"""Generate image for this module"""
|
|
||||||
|
|
||||||
# Define new image size with respect to padding
|
def generate_image(self):
|
||||||
im_width = int(self.width - (2 * self.padding_left))
|
"""Generate image for this module"""
|
||||||
im_height = int(self.height - (2 * self.padding_top))
|
|
||||||
im_size = im_width, im_height
|
|
||||||
logger.info(f'Image size: {im_size}')
|
|
||||||
|
|
||||||
# Create an image for black pixels and one for coloured pixels
|
# Define new image size with respect to padding
|
||||||
im_black = Image.new('RGB', size=im_size, color='white')
|
im_width = int(self.width - (2 * self.padding_left))
|
||||||
im_colour = Image.new('RGB', size=im_size, color='white')
|
im_height = int(self.height - (2 * self.padding_top))
|
||||||
|
im_size = im_width, im_height
|
||||||
|
logger.info(f'Image size: {im_size}')
|
||||||
|
|
||||||
# Check if internet is available
|
# Create an image for black pixels and one for coloured pixels
|
||||||
if internet_available():
|
im_black = Image.new('RGB', size = im_size, color = 'white')
|
||||||
logger.info('Connection test passed')
|
im_colour = Image.new('RGB', size = im_size, color = 'white')
|
||||||
else:
|
|
||||||
raise NetworkNotReachableError
|
|
||||||
|
|
||||||
def get_moon_phase():
|
# Check if internet is available
|
||||||
"""Calculate the current (approximate) moon phase"""
|
if internet_available() == True:
|
||||||
|
logger.info('Connection test passed')
|
||||||
|
else:
|
||||||
|
logger.exception('Network could not be reached :(')
|
||||||
|
raise
|
||||||
|
|
||||||
dec = decimal.Decimal
|
def get_moon_phase():
|
||||||
diff = now - arrow.get(2001, 1, 1)
|
"""Calculate the current (approximate) moon phase"""
|
||||||
days = dec(diff.days) + (dec(diff.seconds) / dec(86400))
|
|
||||||
lunations = dec("0.20439731") + (days * dec("0.03386319269"))
|
|
||||||
position = lunations % dec(1)
|
|
||||||
index = math.floor((position * dec(8)) + dec("0.5"))
|
|
||||||
return {0: '\uf095', 1: '\uf099', 2: '\uf09c', 3: '\uf0a0',
|
|
||||||
4: '\uf0a3', 5: '\uf0a7', 6: '\uf0aa', 7: '\uf0ae'}[int(index) & 7]
|
|
||||||
|
|
||||||
def is_negative(temp):
|
dec = decimal.Decimal
|
||||||
"""Check if temp is below freezing point of water (0°C/30°F)
|
diff = now - arrow.get(2001, 1, 1)
|
||||||
returns True if temp below freezing point, else False"""
|
days = dec(diff.days) + (dec(diff.seconds) / dec(86400))
|
||||||
answer = False
|
lunations = dec("0.20439731") + (days * dec("0.03386319269"))
|
||||||
|
position = lunations % dec(1)
|
||||||
|
index = math.floor((position * dec(8)) + dec("0.5"))
|
||||||
|
return {0: '\uf095',1: '\uf099',2: '\uf09c',3: '\uf0a0',
|
||||||
|
4: '\uf0a3',5: '\uf0a7',6: '\uf0aa',7: '\uf0ae' }[int(index) & 7]
|
||||||
|
|
||||||
if temp_unit == 'celsius' and round(float(temp.split('°')[0])) <= 0:
|
|
||||||
answer = True
|
|
||||||
elif temp_unit == 'fahrenheit' and round(float(temp.split('°')[0])) <= 0:
|
|
||||||
answer = True
|
|
||||||
return answer
|
|
||||||
|
|
||||||
# Lookup-table for weather icons and weather codes
|
def is_negative(temp):
|
||||||
weathericons = {
|
"""Check if temp is below freezing point of water (0°C/30°F)
|
||||||
'01d': '\uf00d', '02d': '\uf002', '03d': '\uf013',
|
returns True if temp below freezing point, else False"""
|
||||||
'04d': '\uf012', '09d': '\uf01a ', '10d': '\uf019',
|
answer = False
|
||||||
'11d': '\uf01e', '13d': '\uf01b', '50d': '\uf014',
|
|
||||||
'01n': '\uf02e', '02n': '\uf013', '03n': '\uf013',
|
if temp_unit == 'celsius' and round(float(temp.split('°')[0])) <= 0:
|
||||||
'04n': '\uf013', '09n': '\uf037', '10n': '\uf036',
|
answer = True
|
||||||
'11n': '\uf03b', '13n': '\uf038', '50n': '\uf023'
|
elif temp_unit == 'fahrenheit' and round(float(temp.split('°')[0])) <= 0:
|
||||||
|
answer = True
|
||||||
|
return answer
|
||||||
|
|
||||||
|
# Lookup-table for weather icons and weather codes
|
||||||
|
weathericons = {
|
||||||
|
'01d': '\uf00d', '02d': '\uf002', '03d': '\uf013',
|
||||||
|
'04d': '\uf012', '09d': '\uf01a', '10d': '\uf019',
|
||||||
|
'11d': '\uf01e', '13d': '\uf01b', '50d': '\uf014',
|
||||||
|
'01n': '\uf02e', '02n': '\uf013', '03n': '\uf013',
|
||||||
|
'04n': '\uf013', '09n': '\uf037', '10n': '\uf036',
|
||||||
|
'11n': '\uf03b', '13n': '\uf038', '50n': '\uf023'
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def draw_icon(image, xy, box_size, icon, rotation = None):
|
||||||
|
"""Custom function to add icons of weather font on image
|
||||||
|
image = on which image should the text be added?
|
||||||
|
xy = xy-coordinates as tuple -> (x,y)
|
||||||
|
box_size = size of text-box -> (width,height)
|
||||||
|
icon = icon-unicode, looks this up in weathericons dictionary
|
||||||
|
"""
|
||||||
|
|
||||||
|
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
|
||||||
}
|
}
|
||||||
|
|
||||||
def draw_icon(image, xy, box_size, icon, rotation=None):
|
x,y = xy
|
||||||
"""Custom function to add icons of weather font on image
|
box_width, box_height = box_size
|
||||||
image = on which image should the text be added?
|
text = icon
|
||||||
xy = xy-coordinates as tuple -> (x,y)
|
font = self.weatherfont
|
||||||
box_size = size of text-box -> (width,height)
|
|
||||||
icon = icon-unicode, looks this up in weathericons dictionary
|
# Increase fontsize to fit specified height and width of text box
|
||||||
"""
|
size = 8
|
||||||
x, y = xy
|
font = ImageFont.truetype(font.path, size)
|
||||||
box_width, box_height = box_size
|
text_width, text_height = font.getsize(text)
|
||||||
text = icon
|
|
||||||
font = self.weatherfont
|
while (text_width < int(box_width * 0.9) and
|
||||||
|
text_height < int(box_height * 0.9)):
|
||||||
# Increase fontsize to fit specified height and width of text box
|
size += 1
|
||||||
size = 8
|
font = ImageFont.truetype(font.path, size)
|
||||||
font = ImageFont.truetype(font.path, size)
|
text_width, text_height = font.getsize(text)
|
||||||
text_width, text_height = font.getsize(text)
|
|
||||||
|
text_width, text_height = font.getsize(text)
|
||||||
while (text_width < int(box_width * 0.9) and
|
|
||||||
text_height < int(box_height * 0.9)):
|
# Align text to desired position
|
||||||
size += 1
|
x = int((box_width / 2) - (text_width / 2))
|
||||||
font = ImageFont.truetype(font.path, size)
|
y = int((box_height / 2) - (text_height / 2) - (icon_size_correction[icon]*size)/2)
|
||||||
text_width, text_height = font.getsize(text)
|
|
||||||
|
# Draw the text in the text-box
|
||||||
text_width, text_height = font.getsize(text)
|
draw = ImageDraw.Draw(image)
|
||||||
|
space = Image.new('RGBA', (box_width, box_height))
|
||||||
# Align text to desired position
|
ImageDraw.Draw(space).text((x, y), text, fill='black', font=font)
|
||||||
x = int((box_width / 2) - (text_width / 2))
|
|
||||||
y = int((box_height / 2) - (text_height / 2))
|
if rotation != None:
|
||||||
|
space.rotate(rotation, expand = True)
|
||||||
# Draw the text in the text-box
|
|
||||||
draw = ImageDraw.Draw(image)
|
# Update only region with text (add text with transparent background)
|
||||||
space = Image.new('RGBA', (box_width, box_height))
|
image.paste(space, xy, space)
|
||||||
ImageDraw.Draw(space).text((x, y), text, fill='black', font=font)
|
|
||||||
|
|
||||||
if rotation != None:
|
|
||||||
space.rotate(rotation, expand=True)
|
# column1 column2 column3 column4 column5 column6 column7
|
||||||
|
# |----------|----------|----------|----------|----------|----------|----------|
|
||||||
# Update only region with text (add text with transparent background)
|
# | time | temperat.| moonphase| forecast1| forecast2| forecast3| forecast4|
|
||||||
image.paste(space, xy, space)
|
# | current |----------|----------|----------|----------|----------|----------|
|
||||||
|
# | weather | humidity | sunrise | icon1 | icon2 | icon3 | icon4 |
|
||||||
# column1 column2 column3 column4 column5 column6 column7
|
# | icon |----------|----------|----------|----------|----------|----------|
|
||||||
# |----------|----------|----------|----------|----------|----------|----------|
|
# | | windspeed| sunset | temperat.| temperat.| temperat.| temperat.|
|
||||||
# | time | temperat.| moonphase| forecast1| forecast2| forecast3| forecast4|
|
# |----------|----------|----------|----------|----------|----------|----------|
|
||||||
# | current |----------|----------|----------|----------|----------|----------|
|
|
||||||
# | weather | humidity | sunrise | icon1 | icon2 | icon3 | icon4 |
|
|
||||||
# | icon |----------|----------|----------|----------|----------|----------|
|
# Calculate size rows and columns
|
||||||
# | | windspeed| sunset | temperat.| temperat.| temperat.| temperat.|
|
col_width = im_width // 7
|
||||||
# |----------|----------|----------|----------|----------|----------|----------|
|
|
||||||
|
# Ratio width height
|
||||||
# Calculate size rows and columns
|
image_ratio = im_width / im_height
|
||||||
col_width = im_width // 7
|
|
||||||
|
if image_ratio >= 4:
|
||||||
# Ratio width height
|
row_height = im_height // 3
|
||||||
image_ratio = im_width / im_height
|
else:
|
||||||
|
logger.info('Please consider decreasing the height.')
|
||||||
if image_ratio >= 4:
|
row_height = int( (im_height* (1-im_height/im_width)) / 3 )
|
||||||
row_height = im_height // 3
|
|
||||||
else:
|
logger.debug(f"row_height: {row_height} | col_width: {col_width}")
|
||||||
logger.info('Please consider decreasing the height.')
|
|
||||||
row_height = int((im_height * (1 - im_height / im_width)) / 3)
|
# Calculate spacings for better centering
|
||||||
|
spacing_top = int( (im_width % col_width) / 2 )
|
||||||
logger.debug(f"row_height: {row_height} | col_width: {col_width}")
|
spacing_left = int( (im_height % row_height) / 2 )
|
||||||
|
|
||||||
# Calculate spacings for better centering
|
# Define sizes for weather icons
|
||||||
spacing_top = int((im_width % col_width) / 2)
|
icon_small = int(col_width / 3)
|
||||||
spacing_left = int((im_height % row_height) / 2)
|
icon_medium = icon_small * 2
|
||||||
|
icon_large = icon_small * 3
|
||||||
# Define sizes for weather icons
|
|
||||||
icon_small = int(col_width / 3)
|
# Calculate the x-axis position of each col
|
||||||
icon_medium = icon_small * 2
|
col1 = spacing_top
|
||||||
icon_large = icon_small * 3
|
col2 = col1 + col_width
|
||||||
|
col3 = col2 + col_width
|
||||||
# Calculate the x-axis position of each col
|
col4 = col3 + col_width
|
||||||
col1 = spacing_top
|
col5 = col4 + col_width
|
||||||
col2 = col1 + col_width
|
col6 = col5 + col_width
|
||||||
col3 = col2 + col_width
|
col7 = col6 + col_width
|
||||||
col4 = col3 + col_width
|
|
||||||
col5 = col4 + col_width
|
# Calculate the y-axis position of each row
|
||||||
col6 = col5 + col_width
|
line_gap = int((im_height - spacing_top - 3*row_height) // 4)
|
||||||
col7 = col6 + col_width
|
|
||||||
|
row1 = line_gap
|
||||||
# Calculate the y-axis position of each row
|
row2 = row1 + line_gap + row_height
|
||||||
line_gap = int((im_height - spacing_top - 3 * row_height) // 4)
|
row3 = row2+ line_gap + row_height
|
||||||
|
|
||||||
row1 = line_gap
|
# Draw lines on each row and border
|
||||||
row2 = row1 + line_gap + row_height
|
############################################################################
|
||||||
row3 = row2 + line_gap + row_height
|
## draw = ImageDraw.Draw(im_black)
|
||||||
|
## draw.line((0, 0, im_width, 0), fill='red')
|
||||||
# Draw lines on each row and border
|
## draw.line((0, im_height-1, im_width, im_height-1), fill='red')
|
||||||
############################################################################
|
## draw.line((0, row1, im_width, row1), fill='black')
|
||||||
## draw = ImageDraw.Draw(im_black)
|
## draw.line((0, row1+row_height, im_width, row1+row_height), fill='black')
|
||||||
## draw.line((0, 0, im_width, 0), fill='red')
|
## draw.line((0, row2, im_width, row2), fill='black')
|
||||||
## draw.line((0, im_height-1, im_width, im_height-1), fill='red')
|
## draw.line((0, row2+row_height, im_width, row2+row_height), fill='black')
|
||||||
## draw.line((0, row1, im_width, row1), fill='black')
|
## draw.line((0, row3, im_width, row3), fill='black')
|
||||||
## draw.line((0, row1+row_height, im_width, row1+row_height), fill='black')
|
## draw.line((0, row3+row_height, im_width, row3+row_height), 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, row3, im_width, row3), fill='black')
|
|
||||||
## draw.line((0, row3+row_height, im_width, row3+row_height), fill='black')
|
# Positions for current weather details
|
||||||
############################################################################
|
weather_icon_pos = (col1, 0)
|
||||||
|
temperature_icon_pos = (col2, row1)
|
||||||
# Positions for current weather details
|
temperature_pos = (col2+icon_small, row1)
|
||||||
weather_icon_pos = (col1, 0)
|
humidity_icon_pos = (col2, row2)
|
||||||
temperature_icon_pos = (col2, row1)
|
humidity_pos = (col2+icon_small, row2)
|
||||||
temperature_pos = (col2 + icon_small, row1)
|
windspeed_icon_pos = (col2, row3)
|
||||||
humidity_icon_pos = (col2, row2)
|
windspeed_pos = (col2+icon_small, row3)
|
||||||
humidity_pos = (col2 + icon_small, row2)
|
|
||||||
windspeed_icon_pos = (col2, row3)
|
# Positions for sunrise, sunset, moonphase
|
||||||
windspeed_pos = (col2 + icon_small, row3)
|
moonphase_pos = (col3, row1)
|
||||||
|
sunrise_icon_pos = (col3, row2)
|
||||||
# Positions for sunrise, sunset, moonphase
|
sunrise_time_pos = (col3+icon_small, row2)
|
||||||
moonphase_pos = (col3, row1)
|
sunset_icon_pos = (col3, row3)
|
||||||
sunrise_icon_pos = (col3, row2)
|
sunset_time_pos = (col3+ icon_small, row3)
|
||||||
sunrise_time_pos = (col3 + icon_small, row2)
|
|
||||||
sunset_icon_pos = (col3, row3)
|
# Positions for forecast 1
|
||||||
sunset_time_pos = (col3 + icon_small, row3)
|
stamp_fc1 = (col4, row1)
|
||||||
|
icon_fc1 = (col4, row1+row_height)
|
||||||
# Positions for forecast 1
|
temp_fc1 = (col4, row3)
|
||||||
stamp_fc1 = (col4, row1)
|
|
||||||
icon_fc1 = (col4, row1 + row_height)
|
# Positions for forecast 2
|
||||||
temp_fc1 = (col4, row3)
|
stamp_fc2 = (col5, row1)
|
||||||
|
icon_fc2 = (col5, row1+row_height)
|
||||||
# Positions for forecast 2
|
temp_fc2 = (col5, row3)
|
||||||
stamp_fc2 = (col5, row1)
|
|
||||||
icon_fc2 = (col5, row1 + row_height)
|
# Positions for forecast 3
|
||||||
temp_fc2 = (col5, row3)
|
stamp_fc3 = (col6, row1)
|
||||||
|
icon_fc3 = (col6, row1+row_height)
|
||||||
# Positions for forecast 3
|
temp_fc3 = (col6, row3)
|
||||||
stamp_fc3 = (col6, row1)
|
|
||||||
icon_fc3 = (col6, row1 + row_height)
|
# Positions for forecast 4
|
||||||
temp_fc3 = (col6, row3)
|
stamp_fc4 = (col7, row1)
|
||||||
|
icon_fc4 = (col7, row1+row_height)
|
||||||
# Positions for forecast 4
|
temp_fc4 = (col7, row3)
|
||||||
stamp_fc4 = (col7, row1)
|
|
||||||
icon_fc4 = (col7, row1 + row_height)
|
# Create current-weather and weather-forecast objects
|
||||||
temp_fc4 = (col7, row3)
|
if self.location.isdigit():
|
||||||
|
logging.debug('looking up location by ID')
|
||||||
# Create current-weather and weather-forecast objects
|
weather = self.owm.weather_at_id(int(self.location)).weather
|
||||||
if self.location.isdigit():
|
forecast = self.owm.forecast_at_id(int(self.location), '3h')
|
||||||
logging.debug('looking up location by ID')
|
else:
|
||||||
weather = self.owm.weather_at_id(int(self.location)).weather
|
logging.debug('looking up location by string')
|
||||||
forecast = self.owm.forecast_at_id(int(self.location), '3h')
|
weather = self.owm.weather_at_place(self.location).weather
|
||||||
else:
|
forecast = self.owm.forecast_at_place(self.location, '3h')
|
||||||
logging.debug('looking up location by string')
|
|
||||||
weather = self.owm.weather_at_place(self.location).weather
|
# Set decimals
|
||||||
forecast = self.owm.forecast_at_place(self.location, '3h')
|
dec_temp = None if self.round_temperature == True else 1
|
||||||
|
dec_wind = None if self.round_windspeed == True else 1
|
||||||
# Set decimals
|
|
||||||
dec_temp = None if self.round_temperature == True else 1
|
# Set correct temperature units
|
||||||
dec_wind = None if self.round_windspeed == True else 1
|
if self.units == 'metric':
|
||||||
|
temp_unit = 'celsius'
|
||||||
# Set correct temperature units
|
elif self.units == 'imperial':
|
||||||
if self.units == 'metric':
|
temp_unit = 'fahrenheit'
|
||||||
temp_unit = 'celsius'
|
|
||||||
elif self.units == 'imperial':
|
logging.debug(f'temperature unit: {temp_unit}')
|
||||||
temp_unit = 'fahrenheit'
|
logging.debug(f'decimals temperature: {dec_temp} | decimals wind: {dec_wind}')
|
||||||
|
|
||||||
logging.debug(f'temperature unit: {temp_unit}')
|
# Get current time
|
||||||
logging.debug(f'decimals temperature: {dec_temp} | decimals wind: {dec_wind}')
|
now = arrow.utcnow()
|
||||||
|
|
||||||
# Get current time
|
if self.forecast_interval == 'hourly':
|
||||||
now = arrow.utcnow()
|
|
||||||
|
logger.debug("getting hourly forecasts")
|
||||||
if self.forecast_interval == 'hourly':
|
|
||||||
|
# Forecasts are provided for every 3rd full hour
|
||||||
logger.debug("getting hourly forecasts")
|
# find out how many hours there are until the next 3rd full hour
|
||||||
|
if (now.hour % 3) != 0:
|
||||||
# Forecasts are provided for every 3rd full hour
|
hour_gap = 3 - (now.hour % 3)
|
||||||
# find out how many hours there are until the next 3rd full hour
|
else:
|
||||||
if (now.hour % 3) != 0:
|
hour_gap = 3
|
||||||
hour_gap = 3 - (now.hour % 3)
|
|
||||||
else:
|
# Create timings for hourly forcasts
|
||||||
hour_gap = 3
|
forecast_timings = [now.shift(hours = + hour_gap + _).floor('hour')
|
||||||
|
for _ in range(0,12,3)]
|
||||||
# Create timings for hourly forcasts
|
|
||||||
forecast_timings = [now.shift(hours=+ hour_gap + _).floor('hour')
|
# Create forecast objects for given timings
|
||||||
for _ in range(0, 12, 3)]
|
forecasts = [forecast.get_weather_at(forecast_time.datetime) for
|
||||||
|
forecast_time in forecast_timings]
|
||||||
# Create forecast objects for given timings
|
|
||||||
forecasts = [forecast.get_weather_at(forecast_time.datetime) for
|
# Add forecast-data to fc_data dictionary
|
||||||
forecast_time in forecast_timings]
|
fc_data = {}
|
||||||
|
for forecast in forecasts:
|
||||||
# Add forecast-data to fc_data dictionary
|
temp = '{}°'.format(round(
|
||||||
fc_data = {}
|
forecast.temperature(unit=temp_unit)['temp'], ndigits=dec_temp))
|
||||||
for forecast in forecasts:
|
|
||||||
temp = '{}°'.format(round(
|
icon = forecast.weather_icon_name
|
||||||
forecast.temperature(unit=temp_unit)['temp'], ndigits=dec_temp))
|
fc_data['fc'+str(forecasts.index(forecast)+1)] = {
|
||||||
|
'temp':temp,
|
||||||
icon = forecast.weather_icon_name
|
'icon':icon,
|
||||||
fc_data['fc' + str(forecasts.index(forecast) + 1)] = {
|
'stamp': forecast_timings[forecasts.index(forecast)].to(
|
||||||
'temp': temp,
|
get_system_tz()).format('H.00' if self.hour_format == 24 else 'h a')
|
||||||
'icon': icon,
|
}
|
||||||
'stamp': forecast_timings[forecasts.index(forecast)].to(
|
|
||||||
get_system_tz()).format('H.00' if self.hour_format == 24 else 'h a')
|
elif self.forecast_interval == 'daily':
|
||||||
}
|
|
||||||
|
logger.debug("getting daily forecasts")
|
||||||
elif self.forecast_interval == 'daily':
|
|
||||||
|
|
||||||
logger.debug("getting daily forecasts")
|
def calculate_forecast(days_from_today):
|
||||||
|
"""Get temperature range and most frequent icon code for forecast
|
||||||
def calculate_forecast(days_from_today):
|
days_from_today should be int from 1-4: e.g. 2 -> 2 days from today
|
||||||
"""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
|
|
||||||
"""
|
# Create a list containing time-objects for every 3rd hour of the day
|
||||||
|
time_range = list(arrow.Arrow.range('hour',
|
||||||
# Create a list containing time-objects for every 3rd hour of the day
|
now.shift(days=days_from_today).floor('day'),
|
||||||
time_range = list(arrow.Arrow.range('hour',
|
now.shift(days=days_from_today).ceil('day')
|
||||||
now.shift(days=days_from_today).floor('day'),
|
))[::3]
|
||||||
now.shift(days=days_from_today).ceil('day')
|
|
||||||
))[::3]
|
# Get forecasts for each time-object
|
||||||
|
forecasts = [forecast.get_weather_at(_.datetime) for _ in time_range]
|
||||||
# Get forecasts for each time-object
|
|
||||||
forecasts = [forecast.get_weather_at(_.datetime) for _ in time_range]
|
# Get all temperatures for this day
|
||||||
|
daily_temp = [round(_.temperature(unit=temp_unit)['temp'],
|
||||||
# Get all temperatures for this day
|
ndigits=dec_temp) for _ in forecasts]
|
||||||
daily_temp = [round(_.temperature(unit=temp_unit)['temp'],
|
# Calculate min. and max. temp for this day
|
||||||
ndigits=dec_temp) for _ in forecasts]
|
temp_range = f'{max(daily_temp)}°/{min(daily_temp)}°'
|
||||||
# Calculate min. and max. temp for this day
|
|
||||||
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
|
status = max(set(daily_icons), key=daily_icons.count)
|
||||||
status = max(set(daily_icons), key=daily_icons.count)
|
|
||||||
|
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():
|
|
||||||
logger.debug((key, val))
|
|
||||||
|
|
||||||
# Get some current weather details
|
|
||||||
temperature = '{}°'.format(round(
|
|
||||||
weather.temperature(unit=temp_unit)['temp'], ndigits=dec_temp))
|
|
||||||
|
|
||||||
weather_icon = weather.weather_icon_name
|
|
||||||
humidity = str(weather.humidity)
|
|
||||||
sunrise_raw = arrow.get(weather.sunrise_time()).to(self.timezone)
|
|
||||||
sunset_raw = arrow.get(weather.sunset_time()).to(self.timezone)
|
|
||||||
|
|
||||||
logger.debug(f'weather_icon: {weather_icon}')
|
for key,val in fc_data.items():
|
||||||
|
logger.debug((key,val))
|
||||||
|
|
||||||
if self.hour_format == 12:
|
# Get some current weather details
|
||||||
logger.debug('using 12 hour format for sunrise/sunset')
|
temperature = '{}°'.format(round(
|
||||||
sunrise = sunrise_raw.format('h:mm a')
|
weather.temperature(unit=temp_unit)['temp'], ndigits=dec_temp))
|
||||||
sunset = sunset_raw.format('h:mm a')
|
|
||||||
|
|
||||||
elif self.hour_format == 24:
|
weather_icon = weather.weather_icon_name
|
||||||
logger.debug('using 24 hour format for sunrise/sunset')
|
humidity = str(weather.humidity)
|
||||||
sunrise = sunrise_raw.format('H:mm')
|
sunrise_raw = arrow.get(weather.sunrise_time()).to(self.timezone)
|
||||||
sunset = sunset_raw.format('H:mm')
|
sunset_raw = arrow.get(weather.sunset_time()).to(self.timezone)
|
||||||
|
|
||||||
# Format the windspeed to user preference
|
logger.debug(f'weather_icon: {weather_icon}')
|
||||||
if self.use_beaufort:
|
|
||||||
logger.debug("using beaufort for wind")
|
|
||||||
wind = str(weather.wind(unit='beaufort')['speed'])
|
|
||||||
|
|
||||||
else:
|
|
||||||
|
|
||||||
if self.units == 'metric':
|
|
||||||
logging.debug('getting windspeed in metric unit')
|
|
||||||
wind = str(weather.wind(unit='meters_sec')['speed']) + 'm/s'
|
|
||||||
|
|
||||||
elif self.units == 'imperial':
|
if self.hour_format == 12:
|
||||||
logging.debug('getting windspeed in imperial unit')
|
logger.debug('using 12 hour format for sunrise/sunset')
|
||||||
wind = str(weather.wind(unit='miles_hour')['speed']) + 'miles/h'
|
sunrise = sunrise_raw.format('h:mm a')
|
||||||
|
sunset = sunset_raw.format('h:mm a')
|
||||||
|
|
||||||
dec = decimal.Decimal
|
elif self.hour_format == 24:
|
||||||
moonphase = get_moon_phase()
|
logger.debug('using 24 hour format for sunrise/sunset')
|
||||||
|
sunrise = sunrise_raw.format('H:mm')
|
||||||
|
sunset = sunset_raw.format('H:mm')
|
||||||
|
|
||||||
# Fill weather details in col 1 (current weather icon)
|
# Format the windspeed to user preference
|
||||||
draw_icon(im_colour, weather_icon_pos, (col_width, im_height),
|
if self.use_beaufort == True:
|
||||||
weathericons[weather_icon])
|
logger.debug("using beaufort for wind")
|
||||||
|
wind = str(weather.wind(unit='beaufort')['speed'])
|
||||||
|
|
||||||
# Fill weather details in col 2 (temp, humidity, wind)
|
elif self.use_beaufort == False:
|
||||||
draw_icon(im_colour, temperature_icon_pos, (icon_small, row_height),
|
|
||||||
'\uf053')
|
|
||||||
|
|
||||||
if is_negative(temperature):
|
if self.units == 'metric':
|
||||||
write(im_black, temperature_pos, (col_width - icon_small, row_height),
|
logging.debug('getting windspeed in metric unit')
|
||||||
temperature, font=self.font)
|
wind = str(weather.wind(unit='meters_sec')['speed']) + 'm/s'
|
||||||
else:
|
|
||||||
write(im_black, temperature_pos, (col_width - icon_small, row_height),
|
|
||||||
temperature, font=self.font)
|
|
||||||
|
|
||||||
draw_icon(im_colour, humidity_icon_pos, (icon_small, row_height),
|
elif self.units == 'imperial':
|
||||||
'\uf07a')
|
logging.debug('getting windspeed in imperial unit')
|
||||||
|
wind = str(weather.wind(unit='miles_hour')['speed']) + 'miles/h'
|
||||||
|
|
||||||
write(im_black, humidity_pos, (col_width - icon_small, row_height),
|
dec = decimal.Decimal
|
||||||
humidity + '%', font=self.font)
|
moonphase = get_moon_phase()
|
||||||
|
|
||||||
draw_icon(im_colour, windspeed_icon_pos, (icon_small, icon_small),
|
# Fill weather details in col 1 (current weather icon)
|
||||||
'\uf050')
|
draw_icon(im_colour, weather_icon_pos, (col_width, im_height),
|
||||||
|
weathericons[weather_icon])
|
||||||
|
|
||||||
write(im_black, windspeed_pos, (col_width - icon_small, row_height),
|
# Fill weather details in col 2 (temp, humidity, wind)
|
||||||
wind, font=self.font)
|
draw_icon(im_colour, temperature_icon_pos, (icon_small, row_height),
|
||||||
|
'\uf053')
|
||||||
|
|
||||||
# Fill weather details in col 3 (moonphase, sunrise, sunset)
|
if is_negative(temperature):
|
||||||
draw_icon(im_colour, moonphase_pos, (col_width, row_height), moonphase)
|
write(im_black, temperature_pos, (col_width-icon_small, row_height),
|
||||||
|
temperature, font = self.font)
|
||||||
|
else:
|
||||||
|
write(im_black, temperature_pos, (col_width-icon_small, row_height),
|
||||||
|
temperature, font = self.font)
|
||||||
|
|
||||||
draw_icon(im_colour, sunrise_icon_pos, (icon_small, icon_small), '\uf051')
|
draw_icon(im_colour, humidity_icon_pos, (icon_small, row_height),
|
||||||
write(im_black, sunrise_time_pos, (col_width - icon_small, row_height),
|
'\uf07a')
|
||||||
sunrise, font=self.font)
|
|
||||||
|
|
||||||
draw_icon(im_colour, sunset_icon_pos, (icon_small, icon_small), '\uf052')
|
write(im_black, humidity_pos, (col_width-icon_small, row_height),
|
||||||
write(im_black, sunset_time_pos, (col_width - icon_small, row_height), sunset,
|
humidity+'%', font = self.font)
|
||||||
font=self.font)
|
|
||||||
|
|
||||||
# Add the forecast data to the correct places
|
draw_icon(im_colour, windspeed_icon_pos, (icon_small, icon_small),
|
||||||
for pos in range(1, len(fc_data) + 1):
|
'\uf050')
|
||||||
stamp = fc_data[f'fc{pos}']['stamp']
|
|
||||||
|
|
||||||
icon = weathericons[fc_data[f'fc{pos}']['icon']]
|
write(im_black, windspeed_pos, (col_width-icon_small, row_height),
|
||||||
temp = fc_data[f'fc{pos}']['temp']
|
wind, font=self.font)
|
||||||
|
|
||||||
write(im_black, eval(f'stamp_fc{pos}'), (col_width, row_height),
|
# Fill weather details in col 3 (moonphase, sunrise, sunset)
|
||||||
stamp, font=self.font)
|
draw_icon(im_colour, moonphase_pos, (col_width, row_height), moonphase)
|
||||||
draw_icon(im_colour, eval(f'icon_fc{pos}'), (col_width, row_height + line_gap * 2),
|
|
||||||
icon)
|
|
||||||
write(im_black, eval(f'temp_fc{pos}'), (col_width, row_height),
|
|
||||||
temp, font=self.font)
|
|
||||||
|
|
||||||
border_h = row3 + row_height
|
draw_icon(im_colour, sunrise_icon_pos, (icon_small, icon_small), '\uf051')
|
||||||
border_w = col_width - 3 # leave 3 pixels gap
|
write(im_black, sunrise_time_pos, (col_width-icon_small, row_height),
|
||||||
|
sunrise, font = self.font)
|
||||||
|
|
||||||
# Add borders around each sub-section
|
draw_icon(im_colour, sunset_icon_pos, (icon_small, icon_small), '\uf052')
|
||||||
draw_border(im_black, (col1, row1), (col_width * 3 - 3, border_h),
|
write(im_black, sunset_time_pos, (col_width-icon_small, row_height), sunset,
|
||||||
shrinkage=(0, 0))
|
font = self.font)
|
||||||
|
|
||||||
for _ in range(4, 8):
|
# Add the forecast data to the correct places
|
||||||
draw_border(im_black, (eval(f'col{_}'), row1), (border_w, border_h),
|
for pos in range(1, len(fc_data)+1):
|
||||||
shrinkage=(0, 0))
|
stamp = fc_data[f'fc{pos}']['stamp']
|
||||||
|
|
||||||
# return the images ready for the display
|
icon = weathericons[fc_data[f'fc{pos}']['icon']]
|
||||||
return im_black, im_colour
|
temp = fc_data[f'fc{pos}']['temp']
|
||||||
|
|
||||||
|
write(im_black, eval(f'stamp_fc{pos}'), (col_width, row_height),
|
||||||
|
stamp, font = self.font)
|
||||||
|
draw_icon(im_colour, eval(f'icon_fc{pos}'), (col_width, row_height+line_gap*2),
|
||||||
|
icon)
|
||||||
|
write(im_black, eval(f'temp_fc{pos}'), (col_width, row_height),
|
||||||
|
temp, font = self.font)
|
||||||
|
|
||||||
|
|
||||||
|
border_h = row3 + row_height
|
||||||
|
border_w = col_width - 3 #leave 3 pixels gap
|
||||||
|
|
||||||
|
# Add borders around each sub-section
|
||||||
|
draw_border(im_black, (col1, row1), (col_width*3 - 3, border_h),
|
||||||
|
shrinkage=(0,0))
|
||||||
|
|
||||||
|
for _ in range(4,8):
|
||||||
|
draw_border(im_black, (eval(f'col{_}'), row1), (border_w, border_h),
|
||||||
|
shrinkage=(0,0))
|
||||||
|
|
||||||
|
# return the images ready for the display
|
||||||
|
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')
|
||||||
|
Loading…
Reference in New Issue
Block a user