omnipython-applibs 0.1.2__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- appkit/__init__.py +52 -0
- appkit/__init__.pyi +17 -0
- appkit/data.py +149 -0
- appkit/data.pyi +25 -0
- appkit/foreground.py +357 -0
- appkit/foreground.pyi +45 -0
- appkit/home.py +19 -0
- appkit/home.pyi +8 -0
- appkit/hover.py +59 -0
- appkit/hover.pyi +13 -0
- appkit/index.py +199 -0
- appkit/index.pyi +30 -0
- appkit/launcher.py +1075 -0
- appkit/launcher.pyi +96 -0
- appkit/manifest.py +75 -0
- appkit/manifest.pyi +8 -0
- appkit/net.py +167 -0
- appkit/net.pyi +34 -0
- appkit/places.py +202 -0
- appkit/places.pyi +39 -0
- appkit/py.typed +0 -0
- appkit/scope.py +636 -0
- appkit/scope.pyi +110 -0
- appkit/shell.py +121 -0
- appkit/shell.pyi +32 -0
- appkit/worker.py +409 -0
- appkit/worker.pyi +83 -0
- controlkit/__init__.py +19 -0
- controlkit/__init__.pyi +10 -0
- controlkit/_draw.py +88 -0
- controlkit/_safe.py +29 -0
- controlkit/dotmatrix.py +101 -0
- controlkit/dotmatrix.pyi +23 -0
- controlkit/encoder.py +297 -0
- controlkit/encoder.pyi +55 -0
- controlkit/font5x7.py +22 -0
- controlkit/font5x7.pyi +11 -0
- controlkit/lamp_button.py +92 -0
- controlkit/lamp_button.pyi +40 -0
- controlkit/meter.py +86 -0
- controlkit/meter.pyi +30 -0
- controlkit/mock.py +116 -0
- controlkit/mock.pyi +35 -0
- controlkit/pad_grid.py +113 -0
- controlkit/pad_grid.pyi +41 -0
- controlkit/py.typed +0 -0
- controlkit/slider.py +185 -0
- controlkit/slider.pyi +49 -0
- controlkit/sprites.py +279 -0
- controlkit/sprites.pyi +22 -0
- controlkit/theme.py +120 -0
- controlkit/theme.pyi +15 -0
- deskkit/__init__.py +74 -0
- deskkit/__init__.pyi +18 -0
- deskkit/forecast.py +261 -0
- deskkit/forecast.pyi +40 -0
- deskkit/localtime.py +215 -0
- deskkit/localtime.pyi +33 -0
- deskkit/py.typed +0 -0
- deskkit/shell.py +113 -0
- deskkit/shell.pyi +33 -0
- omnipython_applibs-0.1.2.dist-info/METADATA +90 -0
- omnipython_applibs-0.1.2.dist-info/RECORD +143 -0
- omnipython_applibs-0.1.2.dist-info/WHEEL +5 -0
- omnipython_applibs-0.1.2.dist-info/licenses/LICENSE +21 -0
- omnipython_applibs-0.1.2.dist-info/top_level.txt +9 -0
- programkit/__init__.py +27 -0
- programkit/__init__.pyi +8 -0
- programkit/board.py +56 -0
- programkit/board.pyi +20 -0
- programkit/press.py +63 -0
- programkit/press.pyi +17 -0
- programkit/py.typed +0 -0
- programkit/rows.py +149 -0
- programkit/rows.pyi +34 -0
- sayso/__init__.py +109 -0
- sayso/__init__.pyi +124 -0
- sayso/auth.py +811 -0
- sayso/auth.pyi +102 -0
- sayso/client.py +1286 -0
- sayso/client.pyi +138 -0
- sayso/keepalive.py +371 -0
- sayso/keepalive.pyi +53 -0
- sayso/local.py +85 -0
- sayso/local.pyi +28 -0
- sayso/object_specs.py +706 -0
- sayso/object_specs.pyi +8 -0
- sayso/objects.py +411 -0
- sayso/objects.pyi +854 -0
- sayso/py.typed +0 -0
- sayso/schema_coverage.py +210 -0
- sayso/schema_coverage.pyi +13 -0
- sayso/transport.py +426 -0
- sayso/transport.pyi +47 -0
- songmodel/__init__.py +30 -0
- songmodel/__init__.pyi +9 -0
- songmodel/link.py +189 -0
- songmodel/link.pyi +53 -0
- songmodel/model.py +238 -0
- songmodel/model.pyi +40 -0
- songmodel/page.html +225 -0
- songmodel/page_data.py +236 -0
- songmodel/page_data.pyi +6 -0
- songmodel/py.typed +0 -0
- soundmodule/__init__.py +7 -0
- soundmodule/__init__.pyi +6 -0
- soundmodule/engine.py +1001 -0
- soundmodule/engine.pyi +196 -0
- soundmodule/names.py +298 -0
- soundmodule/names.pyi +30 -0
- soundmodule/pipes.py +105 -0
- soundmodule/pipes.pyi +31 -0
- soundmodule/py.typed +0 -0
- soundmodule/run.py +249 -0
- soundmodule/run.pyi +49 -0
- spectrum/__init__.py +72 -0
- spectrum/__init__.pyi +30 -0
- spectrum/analyzer.py +231 -0
- spectrum/analyzer.pyi +67 -0
- spectrum/fake_music.py +201 -0
- spectrum/fake_music.pyi +36 -0
- spectrum/pump_levels.py +126 -0
- spectrum/pump_levels.pyi +46 -0
- spectrum/py.typed +0 -0
- spectrum/spectrum_view.py +403 -0
- spectrum/spectrum_view.pyi +80 -0
- touchkit/__init__.py +4 -0
- touchkit/__init__.pyi +4 -0
- touchkit/cam.py +146 -0
- touchkit/cam.pyi +35 -0
- touchkit/clock.py +18 -0
- touchkit/clock.pyi +6 -0
- touchkit/ecp.py +134 -0
- touchkit/ecp.pyi +28 -0
- touchkit/net.py +347 -0
- touchkit/net.pyi +27 -0
- touchkit/py.typed +0 -0
- touchkit/settings.py +85 -0
- touchkit/settings.pyi +17 -0
- touchkit/shell.py +268 -0
- touchkit/shell.pyi +42 -0
- touchkit/ui.py +167 -0
- touchkit/ui.pyi +53 -0
deskkit/__init__.py
ADDED
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Brad Barnett
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
"""deskkit: put a clock and the weather on a screen that sits on a desk.
|
|
5
|
+
|
|
6
|
+
``main.py`` is two lines::
|
|
7
|
+
|
|
8
|
+
import deskkit
|
|
9
|
+
deskkit.run()
|
|
10
|
+
|
|
11
|
+
It joins Wi-Fi with `wifi_manager`, sets the clock and starts the first app.
|
|
12
|
+
A swipe left or right moves between the apps, and anything but the first goes
|
|
13
|
+
back to it after a minute without a touch. The screen goes dark outside the
|
|
14
|
+
hours you pass.
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
APPS = ("clock", "weather")
|
|
18
|
+
|
|
19
|
+
launcher = None # the running one, to reach from the REPL
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _say(lv, text):
|
|
23
|
+
# Joining can take a minute on a weak link, and a dark screen looks broken.
|
|
24
|
+
scr = lv.screen_active()
|
|
25
|
+
scr.set_style_bg_color(lv.color_hex(0), 0)
|
|
26
|
+
label = lv.label(scr)
|
|
27
|
+
label.set_style_text_color(lv.color_hex(0xFFFFFF), 0)
|
|
28
|
+
label.set_style_text_font(lv.font_montserrat_24, 0)
|
|
29
|
+
label.set_text(text)
|
|
30
|
+
label.center()
|
|
31
|
+
lv.refr_now(None)
|
|
32
|
+
return label
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
def run(*, hostname=None, apps=APPS, awake=(7, 18), weekends=False, idle_ms=60_000):
|
|
36
|
+
"""Join Wi-Fi, set the clock and run *apps* until the program ends.
|
|
37
|
+
|
|
38
|
+
Args:
|
|
39
|
+
hostname (str): The name the board answers to on the network, for
|
|
40
|
+
this run. None is the board's name, ``boarddev.name()``.
|
|
41
|
+
apps (tuple): The apps to swipe between, first one the home screen.
|
|
42
|
+
Each is a folder under ``apps/``.
|
|
43
|
+
awake (tuple): The hours the screen stays lit, as ``(from, until)``,
|
|
44
|
+
or None to leave it on.
|
|
45
|
+
weekends (bool): True to keep those hours on Saturday and Sunday too.
|
|
46
|
+
idle_ms (int): How long without a touch before going back to the first
|
|
47
|
+
app, and before a screen woken at night goes dark again.
|
|
48
|
+
"""
|
|
49
|
+
# Here rather than at the top, so an app can import deskkit.forecast without
|
|
50
|
+
# opening the display.
|
|
51
|
+
import lvgl as lv
|
|
52
|
+
import wifi_manager
|
|
53
|
+
from appkit import Launcher, serve
|
|
54
|
+
from display_driver import app
|
|
55
|
+
|
|
56
|
+
from . import forecast, localtime
|
|
57
|
+
from .shell import DeskShell
|
|
58
|
+
|
|
59
|
+
global launcher
|
|
60
|
+
label = _say(lv, "Joining Wi-Fi")
|
|
61
|
+
wifi_manager.connect(hostname=hostname)
|
|
62
|
+
label.set_text("Setting the time")
|
|
63
|
+
lv.refr_now(None)
|
|
64
|
+
localtime.resync_if_due()
|
|
65
|
+
label.delete()
|
|
66
|
+
|
|
67
|
+
launcher = Launcher(app)
|
|
68
|
+
for name in apps:
|
|
69
|
+
launcher.add(name, "apps." + name)
|
|
70
|
+
launcher.shell = DeskShell(launcher, apps, awake=awake, weekends=weekends, idle_ms=idle_ms)
|
|
71
|
+
# With no place, chosen or found from the IP address, there's no weather,
|
|
72
|
+
# so the place comes first.
|
|
73
|
+
launcher.boot(apps[0] if forecast.current() else "weather")
|
|
74
|
+
serve(app)
|
deskkit/__init__.pyi
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Brad Barnett
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
"""deskkit: put a clock and the weather on a screen that sits on a desk."""
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
APPS: tuple[str, ...]
|
|
8
|
+
launcher: Any
|
|
9
|
+
|
|
10
|
+
def run(
|
|
11
|
+
*,
|
|
12
|
+
hostname: str | None = None,
|
|
13
|
+
apps: tuple[str, ...] = ...,
|
|
14
|
+
awake: tuple[int, int] | None = (7, 18),
|
|
15
|
+
weekends: bool = False,
|
|
16
|
+
idle_ms: int = 60000,
|
|
17
|
+
) -> None:
|
|
18
|
+
"""Join Wi-Fi, set the clock and run `apps` until the program ends."""
|
deskkit/forecast.py
ADDED
|
@@ -0,0 +1,261 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Brad Barnett
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
"""deskkit.forecast: the place you've chosen and its weather, from Open-Meteo.
|
|
5
|
+
|
|
6
|
+
Open-Meteo needs no account or key, and is free for non-commercial use. Its
|
|
7
|
+
reply also carries the place's UTC offset, which is how the clock follows the
|
|
8
|
+
place's timezone and daylight saving.
|
|
9
|
+
|
|
10
|
+
Until you choose a place, the forecast is for the city the board's public IP
|
|
11
|
+
address is in, which ``deskkit.localtime`` looks up when the board joins a
|
|
12
|
+
network. That default is never saved: a place you choose wins, and is what's
|
|
13
|
+
kept.
|
|
14
|
+
|
|
15
|
+
The forecast lives here rather than in an app, so it stays while apps open and
|
|
16
|
+
close. It's kept in RAM: writing flash every half hour would wear it for
|
|
17
|
+
something a boot gets back in seconds. Only the place is saved.
|
|
18
|
+
"""
|
|
19
|
+
|
|
20
|
+
import json
|
|
21
|
+
import time
|
|
22
|
+
|
|
23
|
+
import wifi_manager
|
|
24
|
+
from appkit import data, net
|
|
25
|
+
|
|
26
|
+
from . import localtime
|
|
27
|
+
|
|
28
|
+
try:
|
|
29
|
+
import network
|
|
30
|
+
except ImportError: # a desktop
|
|
31
|
+
network = None
|
|
32
|
+
|
|
33
|
+
MAX_AGE_S = 30 * 60
|
|
34
|
+
RETRY_S = 5 * 60
|
|
35
|
+
|
|
36
|
+
_GEO_URL = (
|
|
37
|
+
"https://geocoding-api.open-meteo.com/v1/search"
|
|
38
|
+
"?name=%s&count=1&language=en&format=json&countryCode=US"
|
|
39
|
+
)
|
|
40
|
+
_URL = (
|
|
41
|
+
"https://api.open-meteo.com/v1/forecast?latitude=%s&longitude=%s"
|
|
42
|
+
"¤t=temperature_2m,apparent_temperature,weather_code,is_day"
|
|
43
|
+
"&daily=weather_code,temperature_2m_max,temperature_2m_min,precipitation_probability_max"
|
|
44
|
+
"&temperature_unit=fahrenheit&timezone=auto&forecast_days=5"
|
|
45
|
+
)
|
|
46
|
+
_DAYS = ("Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun")
|
|
47
|
+
|
|
48
|
+
latest = None # what parse() made from the last good reply
|
|
49
|
+
last_error = None
|
|
50
|
+
_tried_at = None
|
|
51
|
+
_got_at = None
|
|
52
|
+
_place = None
|
|
53
|
+
ip_place = None # where the board's IP address is, until a place is chosen
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _place_file():
|
|
57
|
+
return data.join(data.app_dir("deskkit"), "place.json")
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def place():
|
|
61
|
+
"""Return the saved place as a dict, or None before one is chosen."""
|
|
62
|
+
global _place
|
|
63
|
+
if _place is None:
|
|
64
|
+
try:
|
|
65
|
+
with open(_place_file()) as f:
|
|
66
|
+
_place = json.load(f)
|
|
67
|
+
except (OSError, ValueError):
|
|
68
|
+
return None
|
|
69
|
+
localtime.offset_s = _place.get("utc_offset")
|
|
70
|
+
localtime.zone = None
|
|
71
|
+
return _place
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def current():
|
|
75
|
+
"""Return the place the forecast is for: the chosen one, else the one
|
|
76
|
+
from the board's IP address (``from_ip`` is True), else None."""
|
|
77
|
+
return place() or ip_place
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _save():
|
|
81
|
+
with open(_place_file(), "w") as f:
|
|
82
|
+
json.dump(_place, f)
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
def choose(zip_code):
|
|
86
|
+
"""Look up *zip_code* and make it the place. It blocks: call it from a worker.
|
|
87
|
+
|
|
88
|
+
Args:
|
|
89
|
+
zip_code (str): A US ZIP code.
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
dict: The place.
|
|
93
|
+
|
|
94
|
+
Raises:
|
|
95
|
+
ValueError: Open-Meteo knows no place with that code.
|
|
96
|
+
"""
|
|
97
|
+
global _place, latest, _got_at
|
|
98
|
+
resp = net.requests().get(_GEO_URL % zip_code, timeout=15)
|
|
99
|
+
try:
|
|
100
|
+
results = resp.json().get("results")
|
|
101
|
+
finally:
|
|
102
|
+
resp.close()
|
|
103
|
+
if not results:
|
|
104
|
+
raise ValueError("no place for " + zip_code)
|
|
105
|
+
found = results[0]
|
|
106
|
+
here = current()
|
|
107
|
+
units = here.get("units", "F") if here else "F"
|
|
108
|
+
_place = {
|
|
109
|
+
"zip": zip_code,
|
|
110
|
+
"name": found["name"],
|
|
111
|
+
"lat": found["latitude"],
|
|
112
|
+
"lon": found["longitude"],
|
|
113
|
+
"units": units,
|
|
114
|
+
}
|
|
115
|
+
_save()
|
|
116
|
+
latest = None
|
|
117
|
+
_got_at = None
|
|
118
|
+
fetch()
|
|
119
|
+
return _place
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def set_units(units):
|
|
123
|
+
"""Show temperatures in *units*, ``"F"`` or ``"C"``, from now on.
|
|
124
|
+
|
|
125
|
+
It's saved with a chosen place. The place from the IP keeps it until the
|
|
126
|
+
board restarts."""
|
|
127
|
+
here = current()
|
|
128
|
+
if here is not None:
|
|
129
|
+
here["units"] = units
|
|
130
|
+
if here is _place:
|
|
131
|
+
_save()
|
|
132
|
+
|
|
133
|
+
|
|
134
|
+
def degrees(fahrenheit):
|
|
135
|
+
"""Return a Fahrenheit reading as whole degrees in the chosen units."""
|
|
136
|
+
here = current()
|
|
137
|
+
if here is not None and here.get("units") == "C":
|
|
138
|
+
return round((fahrenheit - 32) * 5 / 9)
|
|
139
|
+
return round(fahrenheit)
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
def _weekday(date):
|
|
143
|
+
y, m, d = date.split("-")
|
|
144
|
+
return _DAYS[localtime.gmtime(time.mktime((int(y), int(m), int(d), 12, 0, 0, 0, 0, 0)))[6]]
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def parse(reply):
|
|
148
|
+
"""Turn an Open-Meteo reply into the plain dict the apps show.
|
|
149
|
+
|
|
150
|
+
Args:
|
|
151
|
+
reply (dict): The decoded JSON.
|
|
152
|
+
|
|
153
|
+
Returns:
|
|
154
|
+
dict: ``temp``, ``feels``, ``code``, ``is_day``, ``hi``, ``lo``, ``as_of``
|
|
155
|
+
(``"HH:MM"`` at the place), ``utc_offset`` and ``days``, a list of
|
|
156
|
+
``(weekday, code, hi, lo, chance_of_rain)``.
|
|
157
|
+
"""
|
|
158
|
+
now = reply["current"]
|
|
159
|
+
daily = reply["daily"]
|
|
160
|
+
days = []
|
|
161
|
+
for i, date in enumerate(daily["time"]):
|
|
162
|
+
days.append(
|
|
163
|
+
(
|
|
164
|
+
_weekday(date),
|
|
165
|
+
daily["weather_code"][i],
|
|
166
|
+
daily["temperature_2m_max"][i],
|
|
167
|
+
daily["temperature_2m_min"][i],
|
|
168
|
+
daily["precipitation_probability_max"][i],
|
|
169
|
+
)
|
|
170
|
+
)
|
|
171
|
+
return {
|
|
172
|
+
"temp": now["temperature_2m"],
|
|
173
|
+
"feels": now["apparent_temperature"],
|
|
174
|
+
"code": now["weather_code"],
|
|
175
|
+
"is_day": bool(now["is_day"]),
|
|
176
|
+
"hi": daily["temperature_2m_max"][0],
|
|
177
|
+
"lo": daily["temperature_2m_min"][0],
|
|
178
|
+
"as_of": now["time"].split("T")[1],
|
|
179
|
+
"utc_offset": reply["utc_offset_seconds"],
|
|
180
|
+
"days": days,
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _rejoin():
|
|
185
|
+
if network is not None and not network.WLAN(network.STA_IF).isconnected():
|
|
186
|
+
wifi_manager.connect(setup=False)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
def fetch():
|
|
190
|
+
"""Get the forecast now, and keep the clock right. It blocks: call it from a worker.
|
|
191
|
+
|
|
192
|
+
A failure keeps the last forecast, so the app can say how old it is.
|
|
193
|
+
|
|
194
|
+
Returns:
|
|
195
|
+
bool: True when the forecast is new.
|
|
196
|
+
"""
|
|
197
|
+
global latest, last_error, _tried_at, _got_at
|
|
198
|
+
_tried_at = time.time()
|
|
199
|
+
try:
|
|
200
|
+
_rejoin()
|
|
201
|
+
localtime.resync_if_due()
|
|
202
|
+
here = current()
|
|
203
|
+
if here is None:
|
|
204
|
+
raise ValueError("no place")
|
|
205
|
+
resp = net.requests().get(_URL % (here["lat"], here["lon"]), timeout=15)
|
|
206
|
+
try:
|
|
207
|
+
latest = parse(resp.json())
|
|
208
|
+
finally:
|
|
209
|
+
resp.close()
|
|
210
|
+
except Exception as exc:
|
|
211
|
+
last_error = exc
|
|
212
|
+
print("deskkit: no forecast: %r" % (exc,))
|
|
213
|
+
return False
|
|
214
|
+
last_error = None
|
|
215
|
+
_got_at = time.time()
|
|
216
|
+
localtime.offset_s = latest["utc_offset"]
|
|
217
|
+
if here is not _place:
|
|
218
|
+
return True # the place from the IP isn't saved
|
|
219
|
+
localtime.zone = None
|
|
220
|
+
if _place.get("utc_offset") != latest["utc_offset"]:
|
|
221
|
+
_place["utc_offset"] = latest["utc_offset"]
|
|
222
|
+
_save() # rare: the first time, and at each daylight saving change
|
|
223
|
+
return True
|
|
224
|
+
|
|
225
|
+
|
|
226
|
+
def is_stale():
|
|
227
|
+
"""Return True when a fetch is due: the data is old and no try was recent."""
|
|
228
|
+
if _got_at is not None and time.time() - _got_at < MAX_AGE_S:
|
|
229
|
+
return False
|
|
230
|
+
return _tried_at is None or time.time() - _tried_at >= RETRY_S
|
|
231
|
+
|
|
232
|
+
|
|
233
|
+
def keep_fresh(scope, on_update=None):
|
|
234
|
+
"""Fetch whenever the forecast goes stale, for as long as *scope* is open.
|
|
235
|
+
|
|
236
|
+
Args:
|
|
237
|
+
scope (AppScope): The app that wants it.
|
|
238
|
+
on_update (callable): Called with no arguments on the main thread after
|
|
239
|
+
each fetch, good or bad, while the app is open.
|
|
240
|
+
|
|
241
|
+
Before a place is chosen, it first lets the board find where it is from
|
|
242
|
+
its IP address, if it hasn't tried yet.
|
|
243
|
+
"""
|
|
244
|
+
|
|
245
|
+
def done(_value, _error):
|
|
246
|
+
if on_update is not None:
|
|
247
|
+
on_update()
|
|
248
|
+
|
|
249
|
+
def found(_value, _error):
|
|
250
|
+
done(_value, _error)
|
|
251
|
+
check()
|
|
252
|
+
|
|
253
|
+
def check(_timer=None):
|
|
254
|
+
if current() is None:
|
|
255
|
+
if localtime.finding():
|
|
256
|
+
scope.worker.submit(localtime.resync_if_due, found, key="forecast")
|
|
257
|
+
elif is_stale():
|
|
258
|
+
scope.worker.submit(fetch, done, key="forecast")
|
|
259
|
+
|
|
260
|
+
scope.every(60_000, check)
|
|
261
|
+
check()
|
deskkit/forecast.pyi
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Brad Barnett
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
"""deskkit.forecast: the place you've chosen and its weather, from Open-Meteo."""
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from typing import Any, Protocol
|
|
7
|
+
|
|
8
|
+
from . import localtime as localtime
|
|
9
|
+
|
|
10
|
+
class _Worker(Protocol):
|
|
11
|
+
def submit(self, work: Callable[[], Any], done: Callable[[Any, Any], None] | None = None, *, key: str | None = None) -> Any: ...
|
|
12
|
+
|
|
13
|
+
class _AppScope(Protocol):
|
|
14
|
+
worker: _Worker
|
|
15
|
+
def every(self, ms: int, callback: Callable[..., None]) -> Any: ...
|
|
16
|
+
|
|
17
|
+
MAX_AGE_S: int
|
|
18
|
+
RETRY_S: int
|
|
19
|
+
latest: dict[str, Any] | None
|
|
20
|
+
last_error: BaseException | None
|
|
21
|
+
ip_place: dict[str, Any] | None
|
|
22
|
+
|
|
23
|
+
def place() -> dict[str, Any] | None:
|
|
24
|
+
"""Return the saved place as a dict, or None before one is chosen."""
|
|
25
|
+
def current() -> dict[str, Any] | None:
|
|
26
|
+
"""Return the place the forecast is for: the chosen one, else the one from the board's IP address, else None."""
|
|
27
|
+
def choose(zip_code: str) -> dict[str, Any]:
|
|
28
|
+
"""Look up `zip_code` and make it the place. It blocks: call it from a worker."""
|
|
29
|
+
def set_units(units: str) -> None:
|
|
30
|
+
"""Show temperatures in `units`, `"F"` or `"C"`, from now on."""
|
|
31
|
+
def degrees(fahrenheit: float) -> int:
|
|
32
|
+
"""Return a Fahrenheit reading as whole degrees in the chosen units."""
|
|
33
|
+
def parse(reply: dict[str, Any]) -> dict[str, Any]:
|
|
34
|
+
"""Turn an Open-Meteo reply into the plain dict the apps show."""
|
|
35
|
+
def fetch() -> bool:
|
|
36
|
+
"""Get the forecast now, and keep the clock right. It blocks: call it from a worker."""
|
|
37
|
+
def is_stale() -> bool:
|
|
38
|
+
"""Return True when a fetch is due: the data is old and no try was recent."""
|
|
39
|
+
def keep_fresh(scope: _AppScope, on_update: Callable[[], None] | None = None) -> None:
|
|
40
|
+
"""Fetch whenever the forecast goes stale, for as long as `scope` is open."""
|
deskkit/localtime.py
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Brad Barnett
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
"""deskkit.localtime: keep the board's clock right, and read it in local time.
|
|
5
|
+
|
|
6
|
+
A board with no battery-backed clock forgets the time when it loses power, so
|
|
7
|
+
it asks the network. It tries NTP first. Guest and office networks often block
|
|
8
|
+
NTP, so a web server's ``Date`` header is the fallback.
|
|
9
|
+
|
|
10
|
+
The clock reads in the chosen place's time once Weather has a place
|
|
11
|
+
(``deskkit.forecast``). Until then the board asks ipwho.is where its public IP
|
|
12
|
+
address is: the city, its coordinates, an IANA zone such as
|
|
13
|
+
``America/Chicago`` and that zone's offset from UTC right now. The zone sets
|
|
14
|
+
the clock, and the city becomes Weather's place until you choose one, so the
|
|
15
|
+
weather shows at once. ipwho.is is free and needs no key, and like any web
|
|
16
|
+
service it sees the board's public IP address. The answer is asked for again
|
|
17
|
+
with each daily resync, so a daylight saving change lands within a day. When
|
|
18
|
+
the lookup fails, the clock keeps what it had (UTC at first), Weather asks for
|
|
19
|
+
a ZIP code, and the board asks again at the next resync.
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
import time
|
|
23
|
+
|
|
24
|
+
from appkit import net
|
|
25
|
+
|
|
26
|
+
# CircuitPython has no time.gmtime. It keeps no timezone, so its localtime()
|
|
27
|
+
# is UTC and does the same job.
|
|
28
|
+
gmtime = getattr(time, "gmtime", time.localtime)
|
|
29
|
+
|
|
30
|
+
_FIRST_VALID_YEAR = 2025
|
|
31
|
+
_MONTHS = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec")
|
|
32
|
+
_DATE_URL = "https://api.open-meteo.com/"
|
|
33
|
+
_IP_URL = (
|
|
34
|
+
"https://ipwho.is/?fields=success,message,city,country_code,latitude,longitude,"
|
|
35
|
+
"timezone.id,timezone.offset"
|
|
36
|
+
)
|
|
37
|
+
# Where the IP is in one of these, temperatures start in Fahrenheit.
|
|
38
|
+
_FAHRENHEIT = ("US", "PR", "GU", "VI", "AS", "MP", "LR", "KY", "BS", "BZ", "PW", "FM", "MH")
|
|
39
|
+
_RESYNC_S = 24 * 3600
|
|
40
|
+
|
|
41
|
+
offset_s = None # seconds east of UTC: the chosen place's (forecast sets it), or the IP's
|
|
42
|
+
zone = None # the IANA zone the IP lookup found, while no place is chosen
|
|
43
|
+
_synced_at = None
|
|
44
|
+
_looked = False # a resync has run since boot, so the IP lookup is done or failed
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def is_set():
|
|
48
|
+
"""Return True once the clock holds a real date."""
|
|
49
|
+
return gmtime()[0] >= _FIRST_VALID_YEAR
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def parse_http_date(text):
|
|
53
|
+
"""Return ``(year, month, day, hour, minute, second)`` from a ``Date`` header.
|
|
54
|
+
|
|
55
|
+
Args:
|
|
56
|
+
text (str): A date such as ``Wed, 04 Nov 2026 02:36:50 GMT``.
|
|
57
|
+
|
|
58
|
+
Raises:
|
|
59
|
+
ValueError: The text isn't in that format.
|
|
60
|
+
"""
|
|
61
|
+
parts = text.split()
|
|
62
|
+
if len(parts) != 6 or parts[2] not in _MONTHS:
|
|
63
|
+
raise ValueError("bad date: %s" % text)
|
|
64
|
+
hour, minute, second = parts[4].split(":")
|
|
65
|
+
return (
|
|
66
|
+
int(parts[3]),
|
|
67
|
+
_MONTHS.index(parts[2]) + 1,
|
|
68
|
+
int(parts[1]),
|
|
69
|
+
int(hour),
|
|
70
|
+
int(minute),
|
|
71
|
+
int(second),
|
|
72
|
+
)
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _set_from_web():
|
|
76
|
+
resp = net.requests().get(_DATE_URL, timeout=10)
|
|
77
|
+
try:
|
|
78
|
+
for name, value in resp.headers.items():
|
|
79
|
+
if name.lower() == "date":
|
|
80
|
+
break
|
|
81
|
+
else:
|
|
82
|
+
raise ValueError("no Date header")
|
|
83
|
+
finally:
|
|
84
|
+
resp.close()
|
|
85
|
+
net.set_clock(*parse_http_date(value))
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def sync():
|
|
89
|
+
"""Set the clock from the network. It blocks: call it from a worker.
|
|
90
|
+
|
|
91
|
+
Returns:
|
|
92
|
+
bool: True when the clock was set, or the host keeps its own time.
|
|
93
|
+
"""
|
|
94
|
+
global _synced_at
|
|
95
|
+
if not net.sets_clock():
|
|
96
|
+
return True
|
|
97
|
+
try:
|
|
98
|
+
net.ntp(3)
|
|
99
|
+
except Exception as exc:
|
|
100
|
+
print("deskkit: NTP failed (%r), asking a web server" % (exc,))
|
|
101
|
+
try:
|
|
102
|
+
_set_from_web()
|
|
103
|
+
except Exception as exc2:
|
|
104
|
+
print("deskkit: could not set the clock: %r" % (exc2,))
|
|
105
|
+
return False
|
|
106
|
+
_synced_at = time.time()
|
|
107
|
+
return True
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def due():
|
|
111
|
+
"""Return True when the clock is unset, or this program hasn't set it in a day."""
|
|
112
|
+
return not is_set() or _synced_at is None or time.time() - _synced_at >= _RESYNC_S
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def parse_ip_zone(reply):
|
|
116
|
+
"""Return ``(zone, offset_s)`` from an ipwho.is reply.
|
|
117
|
+
|
|
118
|
+
Args:
|
|
119
|
+
reply (dict): The decoded JSON.
|
|
120
|
+
|
|
121
|
+
Raises:
|
|
122
|
+
ValueError: The reply says the lookup failed.
|
|
123
|
+
"""
|
|
124
|
+
if not reply.get("success"):
|
|
125
|
+
raise ValueError(reply.get("message") or "no timezone in the reply")
|
|
126
|
+
tz = reply["timezone"]
|
|
127
|
+
return tz["id"], int(tz["offset"])
|
|
128
|
+
|
|
129
|
+
|
|
130
|
+
def parse_ip_place(reply):
|
|
131
|
+
"""Return the place an ipwho.is reply points at, for Weather to start on.
|
|
132
|
+
|
|
133
|
+
Args:
|
|
134
|
+
reply (dict): The decoded JSON.
|
|
135
|
+
|
|
136
|
+
Returns:
|
|
137
|
+
dict: ``name``, ``lat``, ``lon``, ``units`` and ``from_ip`` (True), or
|
|
138
|
+
None when the reply has no coordinates.
|
|
139
|
+
"""
|
|
140
|
+
lat = reply.get("latitude")
|
|
141
|
+
lon = reply.get("longitude")
|
|
142
|
+
if lat is None or lon is None:
|
|
143
|
+
return None
|
|
144
|
+
return {
|
|
145
|
+
"name": reply.get("city") or "Near you",
|
|
146
|
+
"lat": lat,
|
|
147
|
+
"lon": lon,
|
|
148
|
+
"units": "F" if reply.get("country_code") in _FAHRENHEIT else "C",
|
|
149
|
+
"from_ip": True,
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
|
|
153
|
+
def follow_ip_zone():
|
|
154
|
+
"""Take the timezone, and Weather's place until one is chosen, from the
|
|
155
|
+
board's public IP address. Nothing changes once a place is chosen. It
|
|
156
|
+
blocks: call it from a worker. A desktop keeps its own timezone.
|
|
157
|
+
|
|
158
|
+
Returns:
|
|
159
|
+
bool: True when the offset now comes from the IP.
|
|
160
|
+
"""
|
|
161
|
+
global offset_s, zone
|
|
162
|
+
if not net.sets_clock():
|
|
163
|
+
return False
|
|
164
|
+
from . import forecast # here: forecast imports this module
|
|
165
|
+
|
|
166
|
+
if forecast.place() is not None:
|
|
167
|
+
zone = None
|
|
168
|
+
return False # a chosen place wins
|
|
169
|
+
try:
|
|
170
|
+
resp = net.requests().get(_IP_URL, timeout=10)
|
|
171
|
+
try:
|
|
172
|
+
reply = resp.json()
|
|
173
|
+
finally:
|
|
174
|
+
resp.close()
|
|
175
|
+
found, offset = parse_ip_zone(reply)
|
|
176
|
+
except Exception as exc:
|
|
177
|
+
print("deskkit: no place from the IP address, keeping %s: %r" % (zone or "UTC", exc))
|
|
178
|
+
return False
|
|
179
|
+
if forecast.place() is not None:
|
|
180
|
+
return False # chosen while the lookup ran
|
|
181
|
+
zone = found
|
|
182
|
+
offset_s = offset
|
|
183
|
+
here = parse_ip_place(reply)
|
|
184
|
+
if here is not None:
|
|
185
|
+
if forecast.ip_place is not None:
|
|
186
|
+
here["units"] = forecast.ip_place["units"] # keep a switch made since
|
|
187
|
+
forecast.ip_place = here
|
|
188
|
+
return True
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def resync_if_due():
|
|
192
|
+
"""Set the clock, the timezone and the place from the IP when the clock
|
|
193
|
+
is unset or a day has passed. Call it from a worker."""
|
|
194
|
+
global _looked
|
|
195
|
+
if due() and sync():
|
|
196
|
+
follow_ip_zone()
|
|
197
|
+
_looked = True
|
|
198
|
+
|
|
199
|
+
|
|
200
|
+
def finding():
|
|
201
|
+
"""Return True while a board hasn't yet tried to find where it is."""
|
|
202
|
+
return net.sets_clock() and not _looked
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def now():
|
|
206
|
+
"""Return the local time as a ``time.gmtime``-style tuple."""
|
|
207
|
+
if offset_s is None:
|
|
208
|
+
return time.localtime()
|
|
209
|
+
return gmtime(time.time() + offset_s)
|
|
210
|
+
|
|
211
|
+
|
|
212
|
+
def clock_time():
|
|
213
|
+
"""Return the local ``(hour, minute, second)``."""
|
|
214
|
+
t = now()
|
|
215
|
+
return t[3], t[4], t[5]
|
deskkit/localtime.pyi
ADDED
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
# SPDX-FileCopyrightText: 2026 Brad Barnett
|
|
2
|
+
#
|
|
3
|
+
# SPDX-License-Identifier: MIT
|
|
4
|
+
"""deskkit.localtime: keep the board's clock right, and read it in local time."""
|
|
5
|
+
from collections.abc import Callable
|
|
6
|
+
from typing import Any
|
|
7
|
+
|
|
8
|
+
gmtime: Callable[..., tuple[int, ...]]
|
|
9
|
+
offset_s: int | None
|
|
10
|
+
zone: str | None
|
|
11
|
+
|
|
12
|
+
def is_set() -> bool:
|
|
13
|
+
"""Return True once the clock holds a real date."""
|
|
14
|
+
def parse_http_date(text: str) -> tuple[int, int, int, int, int, int]:
|
|
15
|
+
"""Return `(year, month, day, hour, minute, second)` from a `Date` header."""
|
|
16
|
+
def sync() -> bool:
|
|
17
|
+
"""Set the clock from the network. It blocks: call it from a worker."""
|
|
18
|
+
def due() -> bool:
|
|
19
|
+
"""Return True when the clock is unset, or this program hasn't set it in a day."""
|
|
20
|
+
def parse_ip_zone(reply: dict[str, Any]) -> tuple[str, int]:
|
|
21
|
+
"""Return `(zone, offset_s)` from an ipwho.is reply."""
|
|
22
|
+
def parse_ip_place(reply: dict[str, Any]) -> dict[str, Any] | None:
|
|
23
|
+
"""Return the place an ipwho.is reply points at, for Weather to start on."""
|
|
24
|
+
def follow_ip_zone() -> bool:
|
|
25
|
+
"""Take the timezone, and Weather's place until one is chosen, from the board's public IP address."""
|
|
26
|
+
def resync_if_due() -> None:
|
|
27
|
+
"""Set the clock, the timezone and the place from the IP when the clock is unset or a day has passed."""
|
|
28
|
+
def finding() -> bool:
|
|
29
|
+
"""Return True while a board hasn't yet tried to find where it is."""
|
|
30
|
+
def now() -> tuple[int, ...]:
|
|
31
|
+
"""Return the local time as a `time.gmtime`-style tuple."""
|
|
32
|
+
def clock_time() -> tuple[int, int, int]:
|
|
33
|
+
"""Return the local `(hour, minute, second)`."""
|
deskkit/py.typed
ADDED
|
File without changes
|