88 lines
2.9 KiB
Python
88 lines
2.9 KiB
Python
from datetime import datetime, timedelta, timezone
|
|
import json
|
|
import os
|
|
import urllib.parse
|
|
import urllib.request
|
|
|
|
from PIL import Image, ImageDraw, ImageFont
|
|
|
|
class RATPAPI:
|
|
|
|
fnt_R_path = "./fonts/Parisine-Regular.ttf"
|
|
fnt_RB_path = "./fonts/Parisine-Bold.ttf"
|
|
|
|
def __init__(self):
|
|
self.baseurl = "https://ratp.p0m.fr/api"
|
|
|
|
self._cached_file = ".ratp-%s.cache"
|
|
|
|
def get_weather(self):
|
|
# Read the mod time
|
|
statinfo = None
|
|
try:
|
|
statinfo = os.stat(self._cached_file % "traffic")
|
|
except:
|
|
pass
|
|
|
|
if statinfo is None or datetime.fromtimestamp(statinfo.st_mtime, tz=timezone.utc) + timedelta(minutes=5) < datetime.now(tz=timezone.utc):
|
|
# Do the request and save it
|
|
with urllib.request.urlopen(self.baseurl + "/traffic") as f:
|
|
with open(self._cached_file % "traffic", 'wb') as fd:
|
|
fd.write(f.read())
|
|
|
|
# Retrieve cached data
|
|
res = {}
|
|
with open(self._cached_file % "traffic") as f:
|
|
res = json.load(f)
|
|
|
|
return res["result"]
|
|
|
|
|
|
class RATPWeatherModule:
|
|
|
|
def draw_module(self, config, width, height, line_height=19):
|
|
image = Image.new('RGB', (width, height), '#fff')
|
|
draw = ImageDraw.Draw(image)
|
|
|
|
fnt_icon = ImageFont.truetype(RATPAPI.fnt_RB_path, line_height-1)
|
|
|
|
weather = RATPAPI().get_weather()
|
|
|
|
align_x = 0
|
|
align_y = 0
|
|
for mode in weather:
|
|
if mode != "rers":
|
|
align_x = 0
|
|
|
|
|
|
# display mode icon
|
|
icon = Image.open("icons/" + mode + ".png").resize((line_height, line_height))
|
|
image.paste(icon, (align_x,align_y), icon)
|
|
|
|
align_x += line_height + 10
|
|
|
|
for line in weather[mode]:
|
|
if align_x + line_height >= width:
|
|
align_x = line_height + 10
|
|
align_y += line_height + 6
|
|
|
|
fill = "gray" if line["slug"] == "normal" else "black"
|
|
|
|
if mode == "metros":
|
|
draw.ellipse((align_x - 1, align_y - 1, align_x + line_height + 1, align_y + line_height + 1), fill=fill)
|
|
elif mode == "tramways":
|
|
draw.rectangle((align_x - 2, align_y - 2, align_x + line_height, align_y), fill=fill)
|
|
draw.rectangle((align_x - 1, align_y + line_height - 1, align_x + line_height + 1, align_y + line_height + 1), fill=fill)
|
|
else:
|
|
draw.rectangle((align_x - 1, align_y - 1, align_x + line_height + 1, align_y + line_height + 1), fill=fill)
|
|
draw.text((align_x + 1 + line_height / 2, align_y + line_height / 2), line["line"], fill="white" if mode != "tramways" else "black", anchor="mm", font=fnt_icon)
|
|
|
|
align_x += line_height + 5
|
|
|
|
if mode != "metros":
|
|
align_y += line_height + 10
|
|
else:
|
|
align_y += 10
|
|
|
|
return image
|