73 lines
2.3 KiB
Python
73 lines
2.3 KiB
Python
import wmill
|
|
import requests
|
|
import datetime
|
|
|
|
LATITUDE = 33.213
|
|
LONGITUDE = 133.133
|
|
TIMEZONE = "Asia/Tokyo"
|
|
|
|
OPEN_METEO_URL = "https://archive-api.open-meteo.com/v1/archive"
|
|
DAILY_VARS = [
|
|
"temperature_2m_mean",
|
|
"temperature_2m_max",
|
|
"temperature_2m_min",
|
|
"sunshine_duration",
|
|
"precipitation_sum",
|
|
"wind_speed_10m_max",
|
|
"surface_pressure_min",
|
|
]
|
|
|
|
|
|
def main():
|
|
api_key = wmill.get_variable("u/admin/KEINASYSTEM_API_KEY")
|
|
base_url = wmill.get_variable("u/admin/KEINASYSTEM_API_URL").rstrip("/")
|
|
sync_url = f"{base_url}/api/weather/sync/"
|
|
|
|
yesterday = (datetime.date.today() - datetime.timedelta(days=1)).isoformat()
|
|
print(f"Fetching weather data for {yesterday} ...")
|
|
|
|
params = {
|
|
"latitude": LATITUDE,
|
|
"longitude": LONGITUDE,
|
|
"start_date": yesterday,
|
|
"end_date": yesterday,
|
|
"daily": DAILY_VARS,
|
|
"timezone": TIMEZONE,
|
|
}
|
|
resp = requests.get(OPEN_METEO_URL, params=params, timeout=30)
|
|
if resp.status_code != 200:
|
|
raise Exception(f"Open-Meteo API error: {resp.status_code} {resp.text[:300]}")
|
|
|
|
daily = resp.json().get("daily", {})
|
|
dates = daily.get("time", [])
|
|
if not dates:
|
|
print("No data returned from Open-Meteo.")
|
|
return {"status": "no_data"}
|
|
|
|
sunshine_raw = daily.get("sunshine_duration", [])
|
|
records = []
|
|
for i, d in enumerate(dates):
|
|
sun_sec = sunshine_raw[i]
|
|
records.append({
|
|
"date": d,
|
|
"temp_mean": daily["temperature_2m_mean"][i],
|
|
"temp_max": daily["temperature_2m_max"][i],
|
|
"temp_min": daily["temperature_2m_min"][i],
|
|
"sunshine_h": round(sun_sec / 3600, 2) if sun_sec is not None else None,
|
|
"precip_mm": daily["precipitation_sum"][i],
|
|
"wind_max": daily["wind_speed_10m_max"][i],
|
|
"pressure_min": daily["surface_pressure_min"][i],
|
|
})
|
|
|
|
headers = {
|
|
"X-API-Key": api_key,
|
|
"Content-Type": "application/json",
|
|
}
|
|
post_resp = requests.post(sync_url, json=records, headers=headers, timeout=30)
|
|
if post_resp.status_code not in (200, 201):
|
|
raise Exception(f"Keinasystem sync error: {post_resp.status_code} {post_resp.text[:300]}")
|
|
|
|
result = post_resp.json()
|
|
print(f"Sync complete: {result}")
|
|
return result
|