Files

581 lines
14 KiB
Go

package main
// Weather data for the flyout. The location comes from the ZIP code typed in
// the settings window: Open-Meteo's geocoder turns it into a place (with
// api.zippopotam.us as a backup), then Open-Meteo's forecast service gives the
// current conditions and the next days, in Fahrenheit and miles per hour. The
// moon phase needs no service at all; it is worked out from the date.
//
// Everything that touches the network runs on its own goroutine. The result is
// kept under a lock and the bar is told with a posted message (wmWxDone), so
// the bar itself never waits on the internet.
import (
"encoding/json"
"fmt"
"io"
"math"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"sync"
"time"
)
const wmWxDone = wmUser + 2
const (
wxFresh = 10 * time.Minute // how long a forecast counts as current
)
// Icon kinds, chosen from the WMO weather code Open-Meteo reports.
const (
wxSun = iota
wxPartly
wxCloudy
wxFog
wxRain
wxSnow
wxStorm
)
type wxNow struct {
temp, feels float64
humidity int
wind float64
code int
day bool
}
type wxDay struct {
date time.Time
code int
hi, lo float64
rain int
uv float64
sunrise string
sunset string
}
type wxState struct {
zip string
place string
lat float64
lon float64
now wxNow
days []wxDay // today first
ok bool // now and days hold a good forecast for zip
loading bool
err string
fetched time.Time
}
var (
wxMu sync.Mutex
wx wxState
wxGen int // bumped whenever the ZIP changes, so an old answer can be thrown away
wxZip string // the saved ZIP code; used on the bar's own thread only
wxClient = &http.Client{Timeout: 12 * time.Second}
)
// ---------- the saved ZIP code ----------
func zipFile() string { return filepath.Join(dataDir(), "zip.txt") }
func locCacheFile() string { return filepath.Join(dataDir(), "weatherloc.txt") }
func loadZip() {
b, err := os.ReadFile(zipFile())
if err != nil {
return
}
if z := onlyDigits(string(b)); len(z) == 5 {
wxZip = z
}
}
func saveZip() {
_ = os.MkdirAll(dataDir(), 0o755)
_ = os.WriteFile(zipFile(), []byte(wxZip), 0o644)
}
func onlyDigits(s string) string {
var sb strings.Builder
for _, r := range s {
if r >= '0' && r <= '9' {
sb.WriteRune(r)
}
}
return sb.String()
}
// weatherSetZip is called by the settings window when the ZIP code changes.
// An empty string clears it.
func weatherSetZip(z string) {
if z == wxZip {
return
}
wxZip = z
saveZip()
if z == "" {
_ = os.Remove(locCacheFile())
}
weatherRefresh(true)
newsRefresh(true) // the local news follows the same ZIP code
}
// weatherRefresh starts a fetch if the forecast is missing or old (or force is
// set). Safe to call as often as you like.
func weatherRefresh(force bool) {
if !showWeather {
return
}
zip := wxZip
wxMu.Lock()
if len(zip) != 5 {
wx = wxState{}
wxGen++
wxMu.Unlock()
weatherNotify()
return
}
same := wx.zip == zip
if same && wx.loading && !force {
wxMu.Unlock()
return
}
if same && wx.ok && time.Since(wx.fetched) < wxFresh && !force {
wxMu.Unlock()
return
}
if !same {
wx = wxState{zip: zip}
}
wx.loading = true
wx.err = ""
wxGen++
gen := wxGen
wxMu.Unlock()
weatherNotify()
go wxFetch(zip, gen)
}
func weatherNotify() {
if hwndMain != 0 {
pPostMessage.Call(hwndMain, wmWxDone, 0, 0)
}
}
func wxSnapshot() wxState {
wxMu.Lock()
defer wxMu.Unlock()
s := wx
s.days = append([]wxDay(nil), wx.days...)
return s
}
// ---------- fetching ----------
func wxFetch(zip string, gen int) {
defer func() {
if r := recover(); r != nil {
wxFinish(gen, nil, "The weather lookup failed.")
}
}()
lat, lon, place, err := wxLocate(zip)
if err != nil {
wxFinish(gen, nil, err.Error())
return
}
st := wxState{zip: zip, place: place, lat: lat, lon: lon}
if err := wxForecast(&st); err != nil {
wxFinish(gen, nil, err.Error())
return
}
st.ok = true
st.fetched = time.Now()
wxFinish(gen, &st, "")
}
// wxFinish stores a result, unless the ZIP changed while it was being fetched.
func wxFinish(gen int, st *wxState, errText string) {
wxMu.Lock()
if gen != wxGen {
wxMu.Unlock()
return
}
if st != nil {
wx = *st
} else {
wx.loading = false
wx.err = errText
}
wxMu.Unlock()
weatherNotify()
}
func wxGetJSON(u string, v any) (status int, err error) {
req, err := http.NewRequest("GET", u, nil)
if err != nil {
return 0, err
}
req.Header.Set("User-Agent", "MirrorBar weather flyout")
resp, err := wxClient.Do(req)
if err != nil {
return 0, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return resp.StatusCode, fmt.Errorf("HTTP %d", resp.StatusCode)
}
return resp.StatusCode, json.NewDecoder(io.LimitReader(resp.Body, 2<<20)).Decode(v)
}
// wxGetBytes downloads one file (a picture tile), up to 4 MB.
func wxGetBytes(u string) ([]byte, error) {
req, err := http.NewRequest("GET", u, nil)
if err != nil {
return nil, err
}
req.Header.Set("User-Agent", "MirrorBar weather flyout")
resp, err := wxClient.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
return nil, fmt.Errorf("HTTP %d", resp.StatusCode)
}
return io.ReadAll(io.LimitReader(resp.Body, 4<<20))
}
// wxLocate turns a ZIP code into a place. The answer is kept in a small file so
// the lookup happens once per ZIP code, not every time the bar starts.
func wxLocate(zip string) (lat, lon float64, place string, err error) {
if b, e := os.ReadFile(locCacheFile()); e == nil {
p := strings.Split(strings.TrimSpace(string(b)), "\t")
if len(p) == 4 && p[0] == zip {
la, e1 := strconv.ParseFloat(p[1], 64)
lo, e2 := strconv.ParseFloat(p[2], 64)
if e1 == nil && e2 == nil {
return la, lo, p[3], nil
}
}
}
reached := false
// Open-Meteo's own geocoder lists postal codes with each place. Other countries
// can share a number (46750 is also a town in Spain), so only a US match counts.
var gr struct {
Results []struct {
Name string `json:"name"`
Latitude float64 `json:"latitude"`
Longitude float64 `json:"longitude"`
CountryCode string `json:"country_code"`
Admin1 string `json:"admin1"`
Postcodes []string `json:"postcodes"`
} `json:"results"`
}
if st, e := wxGetJSON("https://geocoding-api.open-meteo.com/v1/search?name="+zip+"&count=10&language=en&format=json", &gr); e == nil || st != 0 {
reached = true
}
for _, r := range gr.Results {
if r.CountryCode != "US" {
continue
}
for _, pc := range r.Postcodes {
if pc == zip {
place = r.Name
if r.Admin1 != "" {
place += ", " + r.Admin1
}
wxSaveLoc(zip, r.Latitude, r.Longitude, place)
return r.Latitude, r.Longitude, place, nil
}
}
}
// Backup: a ZIP code service, for codes the geocoder doesn't list.
var zr struct {
Places []struct {
Name string `json:"place name"`
Latitude string `json:"latitude"`
Longitude string `json:"longitude"`
State string `json:"state"`
} `json:"places"`
}
st, e := wxGetJSON("https://api.zippopotam.us/us/"+zip, &zr)
if e == nil || st != 0 {
reached = true
}
if e == nil && len(zr.Places) > 0 {
p := zr.Places[0]
la, e1 := strconv.ParseFloat(p.Latitude, 64)
lo, e2 := strconv.ParseFloat(p.Longitude, 64)
if e1 == nil && e2 == nil {
place = p.Name
if p.State != "" {
place += ", " + p.State
}
wxSaveLoc(zip, la, lo, place)
return la, lo, place, nil
}
}
if !reached {
return 0, 0, "", fmt.Errorf("Can't reach the weather service. Check your internet connection.")
}
return 0, 0, "", fmt.Errorf("ZIP code %s was not found.", zip)
}
func wxSaveLoc(zip string, lat, lon float64, place string) {
_ = os.MkdirAll(dataDir(), 0o755)
s := zip + "\t" + strconv.FormatFloat(lat, 'f', 5, 64) + "\t" + strconv.FormatFloat(lon, 'f', 5, 64) + "\t" + place
_ = os.WriteFile(locCacheFile(), []byte(s), 0o644)
}
func wxForecast(st *wxState) error {
u := fmt.Sprintf("https://api.open-meteo.com/v1/forecast?latitude=%.4f&longitude=%.4f"+
"&current=temperature_2m,apparent_temperature,relative_humidity_2m,weather_code,wind_speed_10m,is_day"+
"&daily=weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max,uv_index_max,sunrise,sunset"+
"&temperature_unit=fahrenheit&wind_speed_unit=mph&timezone=auto&forecast_days=6", st.lat, st.lon)
var fr struct {
Current struct {
Temp float64 `json:"temperature_2m"`
Feels float64 `json:"apparent_temperature"`
Humidity float64 `json:"relative_humidity_2m"`
Code int `json:"weather_code"`
Wind float64 `json:"wind_speed_10m"`
IsDay int `json:"is_day"`
} `json:"current"`
Daily struct {
Time []string `json:"time"`
Code []int `json:"weather_code"`
Max []float64 `json:"temperature_2m_max"`
Min []float64 `json:"temperature_2m_min"`
Rain []float64 `json:"precipitation_probability_max"`
UV []float64 `json:"uv_index_max"`
Sunrise []string `json:"sunrise"`
Sunset []string `json:"sunset"`
} `json:"daily"`
}
status, err := wxGetJSON(u, &fr)
if err != nil {
if status == 0 {
return fmt.Errorf("Can't reach the weather service. Check your internet connection.")
}
return fmt.Errorf("The weather service returned an error (%v).", err)
}
d := fr.Daily
n := len(d.Time)
if n < 2 || len(d.Code) < n || len(d.Max) < n || len(d.Min) < n {
return fmt.Errorf("The weather service sent a forecast MirrorBar couldn't read.")
}
st.now = wxNow{
temp: fr.Current.Temp,
feels: fr.Current.Feels,
humidity: int(math.Round(fr.Current.Humidity)),
wind: fr.Current.Wind,
code: fr.Current.Code,
day: fr.Current.IsDay != 0,
}
st.days = st.days[:0]
for i := 0; i < n; i++ {
dt, err := time.Parse("2006-01-02", d.Time[i])
if err != nil {
return fmt.Errorf("The weather service sent a forecast MirrorBar couldn't read.")
}
day := wxDay{date: dt, code: d.Code[i], hi: d.Max[i], lo: d.Min[i]}
if i < len(d.Rain) {
day.rain = int(math.Round(d.Rain[i]))
}
if i < len(d.UV) {
day.uv = d.UV[i]
}
if i < len(d.Sunrise) {
day.sunrise = wxClockText(d.Sunrise[i])
}
if i < len(d.Sunset) {
day.sunset = wxClockText(d.Sunset[i])
}
st.days = append(st.days, day)
}
return nil
}
// wxClockText turns "2026-11-07T07:19" into "7:19 AM".
func wxClockText(s string) string {
t, err := time.Parse("2006-01-02T15:04", s)
if err != nil {
return ""
}
return t.Format("3:04 PM")
}
// ---------- what the codes mean ----------
// wxKind picks the picture for a WMO weather code.
func wxKind(code int) int {
switch {
case code == 0, code == 1:
return wxSun
case code == 2:
return wxPartly
case code == 3:
return wxCloudy
case code == 45, code == 48:
return wxFog
case code >= 51 && code <= 67, code >= 80 && code <= 82:
return wxRain
case code >= 71 && code <= 77, code == 85, code == 86:
return wxSnow
case code >= 95:
return wxStorm
}
return wxCloudy
}
func wxDesc(code int) string {
switch code {
case 0:
return "Clear sky"
case 1:
return "Mostly clear"
case 2:
return "Partly cloudy"
case 3:
return "Overcast"
case 45, 48:
return "Fog"
case 51, 53, 55:
return "Drizzle"
case 56, 57:
return "Freezing drizzle"
case 61:
return "Light rain"
case 63:
return "Rain"
case 65:
return "Heavy rain"
case 66, 67:
return "Freezing rain"
case 71:
return "Light snow"
case 73:
return "Snow"
case 75:
return "Heavy snow"
case 77:
return "Snow grains"
case 80:
return "Light showers"
case 81:
return "Showers"
case 82:
return "Heavy showers"
case 85, 86:
return "Snow showers"
case 95:
return "Thunderstorm"
case 96, 99:
return "Thunderstorm with hail"
}
return "Cloudy"
}
func wxDeg(v float64) string { return strconv.Itoa(int(math.Round(v))) + "°" }
func wxF(v float64) string { return strconv.Itoa(int(math.Round(v))) + "°F" }
// ---------- the moon ----------
const synodicMonth = 29.530588853 // days from one new moon to the next
type moonInfo struct {
frac float64 // 0 is new, 0.5 is full, back to 1 at the next new moon
illum float64 // 0 to 1, how much of the face is lit
name string
fullIn int // whole days until the next full moon
tonight bool // it is full right now (within about half a day)
}
// moonElongation is how far the moon is ahead of the sun in the sky, in degrees
// (0 at new moon, 180 at full). It is the moon's mean position plus the main
// corrections for its uneven orbit (Meeus, Astronomical Algorithms, chapter 48),
// which keeps the phase within a fraction of a percent. Counting the average
// month from a known new moon would be up to 15 hours off.
func moonElongation(t time.Time) float64 {
jd := float64(t.Unix())/86400 + 2440587.5
T := (jd - 2451545.0) / 36525
T2, T3, T4 := T*T, T*T*T, T*T*T*T
D := 297.8501921 + 445267.1114034*T - 0.0018819*T2 + T3/545868 - T4/113065000
M := 357.5291092 + 35999.0502909*T - 0.0001536*T2 + T3/24490000
Mp := 134.9633964 + 477198.8675055*T + 0.0087414*T2 + T3/69699 - T4/14712000
r := math.Pi / 180
e := D + 6.289*math.Sin(Mp*r) - 2.100*math.Sin(M*r) + 1.274*math.Sin((2*D-Mp)*r) +
0.658*math.Sin(2*D*r) + 0.214*math.Sin(2*Mp*r) + 0.110*math.Sin(D*r)
e = math.Mod(e, 360)
if e < 0 {
e += 360
}
return e
}
func moonAt(t time.Time) moonInfo {
e := moonElongation(t)
m := moonInfo{frac: e / 360}
m.illum = (1 - math.Cos(e*math.Pi/180)) / 2
// Eight named phases, each an eighth of the cycle centered on its moment.
switch f := m.frac * 16; {
case f < 1:
m.name = "New Moon"
case f < 3:
m.name = "Waxing Crescent"
case f < 5:
m.name = "First Quarter"
case f < 7:
m.name = "Waxing Gibbous"
case f < 9:
m.name = "Full Moon"
case f < 11:
m.name = "Waning Gibbous"
case f < 13:
m.name = "Last Quarter"
case f < 15:
m.name = "Waning Crescent"
default:
m.name = "New Moon"
}
// Hours from now to the nearest full moon (negative just after one).
m.tonight = math.Abs(e-180)/360*synodicMonth*24 < 14
// Walk forward an hour at a time to the moment the moon next passes 180 degrees.
prev := e
for h := 1; h <= 31*24; h++ {
cur := moonElongation(t.Add(time.Duration(h) * time.Hour))
if prev < 180 && cur >= 180 {
m.fullIn = int(math.Round(float64(h) / 24))
break
}
prev = cur
}
return m
}
func (m moonInfo) fullText() string {
switch {
case m.tonight:
return "Full moon tonight"
case m.fullIn <= 1:
return "Full moon in 1 day"
}
return "Full moon in " + strconv.Itoa(m.fullIn) + " days"
}