Weather: Add new weather parsing in Weather App

master^2
Rengyr 2025-05-17 18:29:26 +02:00
parent dcec8ead09
commit 42bf5b3cbd
No known key found for this signature in database
6 changed files with 372 additions and 54 deletions

View File

@ -26,3 +26,9 @@
0.27: Add UV index display
0.28: Fix UV positioning, hide when 0
0.29: Add feels-like temperature data and clock_info
0.30: Refactor code to more modern javascript style
Split settings and weather data into two files in storage
Add support for new version of weather data and forecast from GadgetBridge (requires version 0.86.0 or higher)
Add support to automatically fetch weather at time interval defined in settings (requires GadgetBridge version 0.86.0 or higher)
Add button to settings to force fetch weather data (requires GadgetBridge version 0.86.0 or higher)
Add new API to get weather from Weather App for other Apps

View File

@ -3,7 +3,7 @@
This allows your Bangle.js to display weather reports from the Gadgetbridge app for an Android phone, or by using the iOS shortcut below to push weather information.
It adds a widget with a weather pictogram and the temperature.
It also adds a ClockInfo list to Bangle.js.
It also adds a ClockInfo list to Bangle.js.
You can view the full report through the app:
![Screenshot](screenshot.png)
@ -12,35 +12,35 @@ You can view the full report through the app:
Use the iOS shortcut [here](https://www.icloud.com/shortcuts/73be0ce1076446f3bdc45a5707de5c4d). The shortcut uses Apple Weather for weather updates, and sends a notification, which is read by Bangle.js. To push weather every hour, or interval, you will need to create a shortcut automation for every time you want to push the weather.
## Android Setup
1. Install [Gadgetbridge for Android](https://f-droid.org/packages/nodomain.freeyourgadget.gadgetbridge/) on your phone.
2. Set up [Gadgetbridge weather reporting](https://codeberg.org/Freeyourgadget/Gadgetbridge/wiki/Weather).
If using the `Bangle.js Gadgetbridge` app on your phone (as opposed to the standard F-Droid `Gadgetbridge`) you need to set the package name
to `com.espruino.gadgetbridge.banglejs` in the settings of the weather app (`settings -> gadgetbridge support -> package name`).
1. Install [Gadgetbridge for Android](https://f-droid.org/packages/nodomain.freeyourgadget.gadgetbridge/) on your phone
2. Set up [Gadgetbridge weather reporting](https://gadgetbridge.org/basics/features/weather/)
### Android Weather Apps
There are two weather apps for Android that can connect with Gadgetbridge:
There are multiple weather apps for Android that can connect with Gadgetbridge:
* Tiny Weather Forecast Germany
* F-Droid - https://f-droid.org/en/packages/de.kaffeemitkoffein.tinyweatherforecastgermany/
* Source code - https://codeberg.org/Starfish/TinyWeatherForecastGermany
* F-Droid - https://f-droid.org/en/packages/de.kaffeemitkoffein.tinyweatherforecastgermany/
* Source code - https://codeberg.org/Starfish/TinyWeatherForecastGermany
* QuickWeather
* F-Droid - https://f-droid.org/en/packages/com.ominous.quickweather/
* Google Play - https://play.google.com/store/apps/details?id=com.ominous.quickweather
* Source code - https://github.com/TylerWilliamson/QuickWeather
* F-Droid - https://f-droid.org/en/packages/com.ominous.quickweather/
* Google Play - https://play.google.com/store/apps/details?id=com.ominous.quickweather
* Source code - https://github.com/TylerWilliamson/QuickWeather
* Breezy Weather
* F-Droid - https://f-droid.org/en/packages/org.breezyweather/
* Source code - https://github.com/breezy-weather/breezy-weather
### Tiny Weather Forecast Germany
Even though Tiny Weather Forecast Germany is made for Germany, it can be used around the world. To do this:
1. Tap on the three dots in the top right hand corner and go to settings
2. Go down to Location and tap on the checkbox labeled "Use location services". You may also want to check on the "Check Location checkbox". Alternatively, you may select the "manual" checkbox and choose your location.
3. Scroll down further to the "other" section and tap "Gadgetbridge support". Then tap on "Enable". You may also choose to tap on "Send current time".
3. Scroll down further to the "other" section and tap "Gadgetbridge support". Then tap on "Enable". You may also choose to tap on "Send current time".
4. If you're using the specific Gadgetbridge for Bangle.JS app, you'll want to tap on "Package name." In the dialog box that appears, you'll want to put in "com.espruino.gadgetbridge.banglejs" without the quotes. If you're using the original Gadgetbridge, leave this as the default.
### QuickWeather
@ -51,9 +51,17 @@ If you're using OpenWeatherMap you will need the "One Call By Call" plan, which
When you first load QuickWeather, it will take you through the setup process. You will fill out all the required information as well as put your API key in. If you do not have the "One Call By Call", or commonly known as "One Call", API, you will need to sign up for that. QuickWeather will work automatically with both the main version of Gadgetbridge and Gadgetbridge for Bangle.JS.
### Breezy Weather
Enabling connection to Gadgetbridge:
1. Tap on the three dots in the top right hand corner and go to settings
2. Find "Widgets & Live wallpaper" settings
3. Under "Data sharing" tap on "Send Gadgetbridge data" and enable for Gadgetbridge flavor you are using
### Weather Notification
**Note:** at one time, the Weather Notification app also worked with Gadgetbridge. However, many users are reporting it's no longer seeing the OpenWeatherMap API key as valid. The app has not received any updates since August of 2020, and may be unmaintained.
**Note:** at one time, the Weather Notification app also worked with Gadgetbridge. However, many users are reporting it's no longer seeing the OpenWeatherMap API key as valid. The app has not received any updates since August of 2020, and may be unmaintained.
## Clock Infos
@ -67,7 +75,9 @@ Adds:
## Settings
* Expiration timespan can be set after which the local weather data is considered as invalid
* Expiration time span can be set after which the local weather data is considered as invalid
* Automatic weather data request interval can be set (weather data are pushed to Bangle automatically, but this can help in cases when it fails) (requires Gadgetbridge v0.86+)
* Forecast weather data can be enabled (this requires other App to use the data, Weather App itself doesn't show the forecast data) (requires Gadgetbridge v0.86+)
* Widget can be hidden
* To change the units for wind speed, you can install the [`Languages app`](https://banglejs.com/apps/?id=locale) which
allows you to choose the units used for speed/distance/temperature and so on.
@ -76,3 +86,42 @@ allows you to choose the units used for speed/distance/temperature and so on.
* BTN2: opens the launcher (Bangle.js 1)
* BTN: opens the launcher (Bangle.js 2)
## Weather App API
Weather App can provide weather and forecast data to other Apps.
* Get weather data without forecast:
```javascript
const weather = require("weather");
weatherData = weather.getWeather(false); // or weather.get()
```
* Get weather data with forecast (needs forecast enabled in settings):
```javascript
const weather = require("weather");
weatherData = weather.getWeather(true);
```
* Fetch new data from Gadgetbridge:
```javascript
const weather = require("weather");
weather.updateWeather(false); // Can set to true if we want to ignore debounce
```
* React to updated weather data:
```javascript
const weather = require("weather");
// For weather data without forecast
weather.on("update", () => {
currentData = weather.getWeather(false);
// console.log(currentData);
}
// For weather data with forecast
weather.on("update2", () => {
currentData = weather.getWeather(true);
// console.log(currentData);
}
```

View File

@ -2,43 +2,147 @@ const storage = require("Storage");
const B2 = process.env.HWVERSION === 2;
let expiryTimeout;
function scheduleExpiry(json) {
function scheduleExpiry() {
if (expiryTimeout) {
clearTimeout(expiryTimeout);
expiryTimeout = undefined;
}
let expiry = "expiry" in json ? json.expiry : 2 * 3600000;
if (json.weather && json.weather.time && expiry) {
let t = json.weather.time + expiry - Date.now();
expiryTimeout = setTimeout(update, t);
const json = storage.readJSON("weatherSetting.json") || {};
const expiry = "expiry" in json ? json.expiry : 2 * 3600000;
expiryTimeout = setTimeout(() => {
storage.write("weather.json", { t: "weather", weather: undefined });
storage.write("weather2.json", {});
}, expiry);
}
let refreshTimeout;
function scheduleRefresh() {
if (refreshTimeout) {
clearTimeout(refreshTimeout);
refreshTimeout = undefined;
}
const json = storage.readJSON("weatherSetting.json") || {};
const refresh = "refresh" in json ? json.refresh : 0;
if (refresh === 0) {
return;
}
refreshTimeout = setTimeout(() => {
updateWeather(false);
scheduleRefresh();
}, refresh);
}
const angles = ["n", "ne", "e", "se", "s", "sw", "w", "nw", "n"];
function windDirection(angle) {
return angles[Math.floor((angle + 22.5) / 45)];
}
function update(weatherEvent) {
let json = storage.readJSON("weather.json") || {};
if (weatherEvent) {
let weather = weatherEvent.clone();
delete weather.t;
weather.time = Date.now();
if (weather.wdir != null) {
// Convert numeric direction into human-readable label
let deg = weather.wdir;
while (deg < 0 || deg > 360) {
deg = (deg + 360) % 360;
}
weather.wrose = ["n", "ne", "e", "se", "s", "sw", "w", "nw", "n"][Math.floor((deg + 22.5) / 45)];
}
json.weather = weather;
} else {
delete json.weather;
if (weatherEvent == null) {
return;
}
storage.write("weather.json", json);
scheduleExpiry(json);
exports.emit("update", json.weather);
if (weatherEvent.t !== "weather") {
return;
}
const weatherSetting = storage.readJSON("weatherSetting.json") || {};
if (weatherEvent.v == null || weatherEvent.v === 1) {
let json = { "t": "weather", "weather": weatherEvent.clone() };
let weather = json.weather;
weather.time = Date.now();
if (weather.wdir != null) {
weather.wrose = windDirection(weather.wdir);
}
storage.write("weather.json", json);
exports.emit("update", weather);
// Request forecast if supported by GadgetBridge and set in settings
if (weatherEvent.v != null && (weatherSetting.forecast ?? false)) {
updateWeather(true);
}
// Either GadgetBridge doesn't support v2 and/or we don't need forecast, so we use this event for refresh scheduling
if (weatherEvent.v == null || (weatherSetting.forecast ?? false) === false) {
weatherSetting.time = Date.now();
storage.write("weatherSetting.json", weatherSetting);
scheduleExpiry();
scheduleRefresh();
}
} else if (weatherEvent.v === 2) {
weatherSetting.time = Date.now();
storage.write("weatherSetting.json", weatherSetting);
// Store binary data for parsing when requested by other apps later
let cloned = weatherEvent.clone();
cloned.time = weatherSetting.time;
storage.write("weather2.json", cloned);
// If we stored weather v1 recently, we don't need to parse non-forecast from v2
// Otherwise we need to parse part of it to refresh weather1.json
let weather1 = storage.readJSON("weather.json") ?? {};
if (weather1.weather == null || weather1.weather.time == null || Date.now() - weather1.weather.time >= 60 * 1000) {
weather1 = undefined; // Clear memory
const weather2 = decodeWeatherV2(weatherEvent, true, false);
// Store simpler weather for apps that doesn't need forecast or backward compatibility
const weather = downgradeWeatherV2(weather2);
storage.write("weather.json", weather);
}
cloned = undefined; // Clear memory
scheduleExpiry();
scheduleRefresh();
exports.emit("update2");
}
}
function updateWeather(force) {
const settings = storage.readJSON("weatherSetting.json") || {};
let lastFetch = settings.time ?? 0;
// More than 5 minutes
if (force || Date.now() - lastFetch >= 5 * 60 * 1000) {
Bluetooth.println("");
Bluetooth.println(JSON.stringify({ t: "weather", v: 2, f: settings.forecast ?? false }));
}
}
function getWeather(forecast) {
const weatherSetting = storage.readJSON("weatherSetting.json") || {};
if (forecast === false || !(weatherSetting.forecast ?? false)) {
// biome-ignore lint/complexity/useOptionalChain: not supported by Espruino
return (storage.readJSON("weather.json") ?? {}).weather;
} else {
const json2 = storage.readJSON("weather2.json");
if (json2 == null) {
// Fallback in case no weather v2 exists, but we have weather v1
// biome-ignore lint/complexity/useOptionalChain: not supported by Espruino
return (storage.readJSON("weather.json") ?? {}).weather;
}
if (json2.d == null) {
// We have already parsed weather v2
return json2;
}
// We have weather v2, but not decoded
const decoded = decodeWeatherV2(json2, true, true);
storage.write("weather2.json", decoded);
return decoded;
}
}
exports.update = update;
const _GB = global.GB;
global.GB = (event) => {
@ -46,11 +150,134 @@ global.GB = (event) => {
if (_GB) setTimeout(_GB, 0, event);
};
exports.get = () => {
return (storage.readJSON("weather.json") || {}).weather;
};
exports.updateWeather = updateWeather;
exports.get = () => getWeather(false);
exports.getWeather = getWeather;
scheduleExpiry(storage.readJSON("weather.json") || {});
scheduleRefresh();
function decodeWeatherV2(jsonData, canDestroyArgument, parseForecast) {
let time;
if (jsonData != null && jsonData.time != null) {
time = Math.round(jsonData.time);
} else {
time = Math.round(Date.now());
}
// Check if we have data to parse
if (jsonData == null || jsonData.d == null) {
return { t: "weather2", v: 2, time: time };
}
// This needs to be kept in sync with GadgetBridge
const weatherCodes = [
[200, 201, 202, 210, 211, 212, 221, 230, 231, 232],
[300, 301, 302, 310, 311, 312, 313, 314, 321],
[],
[500, 501, 502, 503, 504, 511, 520, 521, 522, 531],
[600, 601, 602, 611, 612, 613, 615, 616, 620, 621, 622],
[701, 711, 721, 731, 741, 751, 761, 762, 771, 781],
[800, 801, 802, 803, 804],
];
const mapWCode = (code) => {
return weatherCodes[code >> 5][code & 0x1f];
};
const buffer = E.toArrayBuffer(atob(jsonData.d));
const dataView = new DataView(buffer);
if (canDestroyArgument) {
delete jsonData.d; // Free some memory if we can
}
const weather = {
t: "weather2",
v: 2,
time: time,
temp: dataView.getInt8(0),
hi: dataView.getInt8(1),
lo: dataView.getInt8(2),
hum: dataView.getUint8(3),
rain: dataView.getUint8(4),
uv: dataView.getUint8(5) / 10,
code: mapWCode(dataView.getUint8(6)),
txt: jsonData.c,
wind: dataView.getUint16(7, true) / 100,
wdir: dataView.getUint16(9, true),
loc: jsonData.l,
dew: dataView.getInt8(11),
pres: dataView.getUint16(12, true) / 10,
cloud: dataView.getUint8(14),
visib: dataView.getUint32(15, true) / 10,
sunrise: dataView.getUint32(19, true),
sunset: dataView.getUint32(23, true),
moonrise: dataView.getUint32(27, true),
moonset: dataView.getUint32(31, true),
moonphase: dataView.getUint16(35, true),
feel: dataView.getInt8(37, true),
};
weather.wrose = windDirection(weather.wdir);
let offset = 38;
if (offset < buffer.length && parseForecast) {
// We have forecast data
// Hourly forecast
const hoursAmount = dataView.getUint8(offset++);
const timestampBase = dataView.getUint32(offset, true);
offset += 4;
weather.hourfcast = {
time: [].map.call(new Uint8Array(buffer, offset, hoursAmount), (v) => timestampBase + (v / 10) * 3600),
temp: new Int8Array(buffer, offset + hoursAmount, hoursAmount),
code: [].map.call(new Uint8Array(buffer, offset + hoursAmount * 2, hoursAmount), mapWCode),
wind: new Uint8Array(buffer, offset + hoursAmount * 3, hoursAmount),
wdir: [].map.call(new Uint8Array(buffer, offset + hoursAmount * 4, hoursAmount), (v) => v * 2),
wrose: [].map.call(new Uint8Array(buffer, offset + hoursAmount * 4, hoursAmount), (v) => windDirection(v * 2)),
rain: new Uint8Array(buffer, offset + hoursAmount * 5, hoursAmount),
};
offset += hoursAmount * 6;
// Daily forecast
const daysAmount = dataView.getUint8(offset++);
weather.dayfcast = {
hi: new Int8Array(buffer, offset, daysAmount),
lo: new Int8Array(buffer, offset + daysAmount, daysAmount),
code: [].map.call(new Uint8Array(buffer, offset + daysAmount * 2, daysAmount), mapWCode),
wind: new Uint8Array(buffer, offset + daysAmount * 3, daysAmount),
wdir: [].map.call(new Uint8Array(buffer, offset + daysAmount * 4, daysAmount), (v) => v * 2),
wrose: [].map.call(new Uint8Array(buffer, offset + daysAmount * 4, daysAmount), (v) => windDirection(v * 2)),
rain: new Uint8Array(buffer, offset + daysAmount * 5, daysAmount),
};
}
return weather;
}
function downgradeWeatherV2(weather2) {
const json = { t: "weather" };
json.weather = {
v: 1,
time: weather2.time,
temp: weather2.temp + 273,
hi: weather2.hi + 273,
lo: weather2.lo + 273,
hum: weather2.hum,
rain: weather2.rain,
uv: weather2.uv,
code: weather2.code,
txt: weather2.txt,
wind: weather2.wind,
wdir: weather2.wdir,
wrose: weather2.wrose,
loc: weather2.loc,
};
return json;
}
function getPalette(monochrome, ovr) {
var palette;

View File

@ -1,7 +1,7 @@
{
"id": "weather",
"name": "Weather",
"version": "0.29",
"version": "0.30",
"description": "Show Gadgetbridge/iOS weather report",
"icon": "icon.png",
"screenshots": [{"url":"screenshot.png"}],
@ -16,5 +16,5 @@
{"name":"weather.settings.js","url":"settings.js"},
{"name":"weather.clkinfo.js","url":"clkinfo.js"}
],
"data": [{"name":"weather.json"}]
"data": [{"name":"weatherSetting.json"},{"name":"weather.json"},{"name":"weather2.json"}]
}

View File

@ -1,10 +1,24 @@
(back) => {
const storage = require("Storage");
let settings = storage.readJSON("weather.json", 1) || {};
let settings = storage.readJSON("weatherSetting.json", 1);
// Handle transition from old weather.json to new weatherSetting.json
if (settings == null) {
const settingsOld = storage.readJSON("weather.json", 1) || {};
settings = {
expiry: "expiry" in settingsOld ? settingsOld.expiry : 2 * 3600000,
hide: "hide" in settingsOld ? settingsOld.hide : false,
};
if (settingsOld != null && settingsOld.weather != null && settingsOld.weather.time != null) {
settings.time = settingsOld.weather.time;
}
}
function save(key, value) {
settings[key] = value;
storage.write("weather.json", settings);
storage.write("weatherSetting.json", settings);
}
E.showMenu({
"": { "title": "Weather" },
"Expiry": {
@ -19,6 +33,25 @@
},
onchange: (x) => save("expiry", x),
},
"Refresh Rate": {
value: "refresh" in settings ? settings.refresh : 0,
min: 0,
max: 24 * 3600000,
step: 15 * 60000,
format: (x) => {
if (x === 0) return "never";
if (x < 3600000) return `${Math.floor(x / 60000)}m`;
if (x < 86400000) return `${Math.floor(x / 36000) / 100}h`;
},
onchange: (x) => save("refresh", x),
},
Forecast: {
value: "forecast" in settings ? settings.forecast : false,
onchange: () => {
settings.forecast = !settings.forecast;
save("forecast", settings.forecast);
},
},
"Hide Widget": {
value: "hide" in settings ? settings.hide : false,
onchange: () => {
@ -26,6 +59,9 @@
save("hide", settings.hide);
},
},
"Force refresh": () => {
require("weather").updateWeather(true);
},
"< Back": back,
});
};

View File

@ -6,7 +6,7 @@
let settings;
function loadSettings() {
settings = require("Storage").readJSON("weather.json", 1) || {};
settings = require("Storage").readJSON("weatherSetting.json", 1) || {};
}
function setting(key) {