diff --git a/apps/weather/ChangeLog b/apps/weather/ChangeLog index c51459fe04..c40fb81950 100644 --- a/apps/weather/ChangeLog +++ b/apps/weather/ChangeLog @@ -23,4 +23,10 @@ 0.24: Redraw clock_info on update and provide color field for condition 0.25: Added monochrome parameter to drawIcon in lib 0.26: Expose update function (for use by iOS integration) -0.27: Add UV index display \ No newline at end of file +0.27: Add UV index display +0.28: 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 diff --git a/apps/weather/README.md b/apps/weather/README.md index a90c02b96b..a5b97d5837 100644 --- a/apps/weather/README.md +++ b/apps/weather/README.md @@ -8,35 +8,38 @@ You can view the full report through the app: ![Screenshot](screenshot.png) ## iOS Setup + Use the iOS shortcut [here](https://www.icloud.com/shortcuts/dbf7159200d945179e0938c15e64f102). 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). +## Android Setup -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 @@ -47,6 +50,14 @@ 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. @@ -60,9 +71,12 @@ Adds: * Wind speed ClockInfo. * Chance of rain ClockInfo. * Temperature ClockInfo without condition icon. + ## 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+) +* Extended or forecast weather data can be enabled (this requires other App to use this 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. @@ -71,3 +85,44 @@ 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 + +Note: except `getWeather()` and `get()` it is android only for now + +Weather App can provide weather and forecast data to other Apps. + +* Get weather data without forecast/extended: + ```javascript + const weather = require("weather"); + weatherData = weather.getWeather(false); // or weather.get() + ``` + +* Get weather data with forecast/extended (needs forecast/extended 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); + } + ``` diff --git a/apps/weather/app.js b/apps/weather/app.js index 4875a3877a..46aeb82457 100644 --- a/apps/weather/app.js +++ b/apps/weather/app.js @@ -16,24 +16,24 @@ var layout = new Layout({type:"v", bgCol: g.theme.bg, c: [ render: l => { if (!current || current.uv === undefined) return; const uv = Math.min(parseInt(current.uv), 11); // Cap at 11 - + // UV color thresholds: [max_value, color] based on WHO standards const colors = [[2,"#0F0"], [5,"#FF0"], [7,"#F80"], [10,"#F00"], [11,"#F0F"]]; const color = colors.find(c => uv <= c[0])[1]; - + // Setup and measure label g.setFont("6x8").setFontAlign(-1, 0); const label = "UV: "; const labelW = g.stringWidth(label); - + // Calculate centered position (4px block + 1px spacing) * blocks - last spacing const totalW = labelW + uv * 5 - (uv > 0 ? 1 : 0); const x = l.x + (l.w - totalW) / 2; const y = l.y + l.h; - + // Draw label g.setColor(g.theme.fg).drawString(label, x, y); - + // Draw UV blocks g.setColor(color); for (let i = 0; i < uv; i++) { @@ -70,7 +70,7 @@ var layout = new Layout({type:"v", bgCol: g.theme.bg, c: [ ]}, {lazy: true}); function formatDuration(millis) { - let pluralize = (n, w) => n + " " + w + (n == 1 ? "" : "s"); + let pluralize = (n, w) => `${n} ${w}${n === 1 ? "" : "s"}`; if (millis < 60000) return /*LANG*/"< 1 minute"; if (millis < 3600000) return pluralize(Math.floor(millis/60000), /*LANG*/"minute"); if (millis < 86400000) return pluralize(Math.floor(millis/3600000), /*LANG*/"hour"); @@ -83,10 +83,10 @@ function draw() { const temp = locale.temp(current.temp-273.15).match(/^(\D*\d*)(.*)$/); layout.temp.label = temp[1]; layout.tempUnit.label = temp[2]; - layout.hum.label = current.hum+"%"; + layout.hum.label = `${current.hum}%`; const wind = locale.speed(current.wind).match(/^(\D*\d*)(.*)$/); layout.wind.label = wind[1]; - layout.windUnit.label = wind[2] + " " + (current.wrose||'').toUpperCase(); + layout.windUnit.label = `${wind[2]} ${(current.wrose||'').toUpperCase()}`; layout.cond.label = current.txt.charAt(0).toUpperCase()+(current.txt||'').slice(1); layout.loc.label = current.loc; layout.updateTime.label = `${formatDuration(Date.now() - current.time)} ago`; // How to autotranslate this and similar? @@ -140,4 +140,4 @@ Bangle.setUI("clock"); // This matters for widgets that hide themselves for clocks, like widclk or widclose delete Bangle.CLOCK; -Bangle.drawWidgets(); \ No newline at end of file +Bangle.drawWidgets(); diff --git a/apps/weather/clkinfo.js b/apps/weather/clkinfo.js index 2f36a600cd..a288bb8ef1 100644 --- a/apps/weather/clkinfo.js +++ b/apps/weather/clkinfo.js @@ -1,4 +1,4 @@ -(function() { +(() => { var weather; var weatherLib = require("weather"); @@ -6,9 +6,9 @@ weather = weatherLib.get(); if(weather){ weather.temp = require("locale").temp(weather.temp-273.15); - weather.hum = weather.hum + "%"; + weather.hum = `${weather.hum}%`; weather.wind = require("locale").speed(weather.wind).match(/^(\D*\d*)(.*)$/); - weather.wind = Math.round(weather.wind[1]) + "kph"; + weather.wind = `${Math.round(weather.wind[1])}kph`; } else { weather = { temp: "?", diff --git a/apps/weather/lib.js b/apps/weather/lib.js index 9505cbafef..1f854fe0cc 100644 --- a/apps/weather/lib.js +++ b/apps/weather/lib.js @@ -1,115 +1,357 @@ -const storage = require('Storage'); -const B2 = process.env.HWVERSION===2; +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 == null) { + return; + } + + 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; - 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)]; + weather.wrose = windDirection(weather.wdir); + } + + storage.write("weather.json", json); + exports.emit("update", weather); + + // Request extended/forecast if supported by Weather Provider and set in settings + if (weatherEvent.v != null && (weatherSetting.dataType ?? "basic") !== "basic") { + updateWeather(true); + } + + // Either Weather Provider doesn't support v2 and/or we don't need extended/forecast, so we use this event for refresh scheduling + if (weatherEvent.v == null || (weatherSetting.dataType ?? "basic") === "basic") { + 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); - json.weather = weather; + // 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); + exports.emit("update", weather); + } else if (weather1.weather != null && weather1.weather.feels === undefined) { + // Grab feels like temperature as we have it in v2 + weather1.weather.feels = decodeWeatherV2FeelsLike(weatherEvent); + storage.write("weather.json", weather); + exports.emit("update", weather); + } + + cloned = undefined; // Clear memory + + scheduleExpiry(); + scheduleRefresh(); + + exports.emit("update2"); } - else { - delete json.weather; +} + +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(""); // This empty line is important for correct communication with Weather Provider + Bluetooth.println(JSON.stringify({ t: "weather", v: 2, f: settings.dataType === "forecast" })); } +} + +function getWeather(extended) { + const weatherSetting = storage.readJSON("weatherSetting.json") || {}; + + if (extended === false || (weatherSetting.dataType ?? "basic") === "basic") { + // 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); - storage.write('weather.json', json); - scheduleExpiry(json); - exports.emit("update", json.weather); + return decoded; + } } + exports.update = update; const _GB = global.GB; global.GB = (event) => { - if (event.t==="weather") update(event); + if (event.t === "weather") update(event); if (_GB) setTimeout(_GB, 0, event); }; -exports.get = function() { - return (storage.readJSON('weather.json')||{}).weather; +exports.updateWeather = updateWeather; +exports.get = () => getWeather(false); +exports.getWeather = getWeather; + +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 Weather Provider + 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), + feels: 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; } -scheduleExpiry(storage.readJSON('weather.json')||{}); +function decodeWeatherV2FeelsLike(jsonData) { + if (jsonData == null || jsonData.d == null) { + return undefined; + } + + const buffer = E.toArrayBuffer(atob(jsonData.d)); + + return new DataView(buffer).getInt8(37, true); +} + +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, + feels: weather2.feels, + }; + + return json; +} function getPalette(monochrome, ovr) { var palette; - if(monochrome) { + if (monochrome) { palette = { - sun: '#FFF', - cloud: '#FFF', - bgCloud: '#FFF', - rain: '#FFF', - lightning: '#FFF', - snow: '#FFF', - mist: '#FFF', - background: '#000' + sun: "#FFF", + cloud: "#FFF", + bgCloud: "#FFF", + rain: "#FFF", + lightning: "#FFF", + snow: "#FFF", + mist: "#FFF", + background: "#000", }; } else { if (B2) { if (ovr.theme.dark) { palette = { - sun: '#FF0', - cloud: '#FFF', - bgCloud: '#777', // dithers on B2, but that's ok - rain: '#0FF', - lightning: '#FF0', - snow: '#FFF', - mist: '#FFF' + sun: "#FF0", + cloud: "#FFF", + bgCloud: "#777", // dithers on B2, but that's ok + rain: "#0FF", + lightning: "#FF0", + snow: "#FFF", + mist: "#FFF", }; } else { palette = { - sun: '#FF0', - cloud: '#777', // dithers on B2, but that's ok - bgCloud: '#000', - rain: '#00F', - lightning: '#FF0', - snow: '#0FF', - mist: '#0FF' + sun: "#FF0", + cloud: "#777", // dithers on B2, but that's ok + bgCloud: "#000", + rain: "#00F", + lightning: "#FF0", + snow: "#0FF", + mist: "#0FF", }; } } else { if (ovr.theme.dark) { palette = { - sun: '#FE0', - cloud: '#BBB', - bgCloud: '#777', - rain: '#0CF', - lightning: '#FE0', - snow: '#FFF', - mist: '#FFF' + sun: "#FE0", + cloud: "#BBB", + bgCloud: "#777", + rain: "#0CF", + lightning: "#FE0", + snow: "#FFF", + mist: "#FFF", }; } else { palette = { - sun: '#FC0', - cloud: '#000', - bgCloud: '#777', - rain: '#07F', - lightning: '#FC0', - snow: '#CCC', - mist: '#CCC' + sun: "#FC0", + cloud: "#000", + bgCloud: "#777", + rain: "#07F", + lightning: "#FC0", + snow: "#CCC", + mist: "#CCC", }; } } @@ -117,10 +359,10 @@ function getPalette(monochrome, ovr) { return palette; } -exports.getColor = function(code) { +exports.getColor = (code) => { const codeGroup = Math.round(code / 100); const palette = getPalette(0, g); - const cloud = g.blendColor(palette.cloud, palette.bgCloud, .5); //theme independent + const cloud = g.blendColor(palette.cloud, palette.bgCloud, 0.5); //theme independent switch (codeGroup) { case 2: return g.blendColor(cloud, palette.lightning, .5); case 3: return palette.rain; @@ -144,7 +386,7 @@ exports.getColor = function(code) { } default: return cloud; } -} +}; /** * @@ -158,9 +400,9 @@ exports.getColor = function(code) { * @param ovr Graphics instance (or undefined for g) * @param monochrome If true, produce a monochromatic icon */ -exports.drawIcon = function(cond, x, y, r, ovr, monochrome) { +exports.drawIcon = (cond, x, y, r, ovr, monochrome) => { var palette; - if(!ovr) ovr = g; + if (!ovr) ovr = g; palette = getPalette(monochrome, ovr); @@ -257,7 +499,7 @@ exports.drawIcon = function(cond, x, y, r, ovr, monochrome) { function drawSnow(x, y, r) { function rotatePoints(points, pivotX, pivotY, angle) { - for(let i = 0; i {}; txt = txt.toLowerCase(); @@ -336,7 +578,8 @@ exports.drawIcon = function(cond, x, y, r, ovr, monochrome) { if (txt.includes("few clouds")) return drawFewClouds; if (txt.includes("scattered clouds")) return drawCloud; if (txt.includes("clouds")) return drawBrokenClouds; - if (txt.includes("mist") || + if ( + txt.includes("mist") || txt.includes("smoke") || txt.includes("haze") || txt.includes("sand") || @@ -344,16 +587,17 @@ exports.drawIcon = function(cond, x, y, r, ovr, monochrome) { txt.includes("fog") || txt.includes("ash") || txt.includes("squalls") || - txt.includes("tornado")) { + txt.includes("tornado") + ) { return drawMist; } return drawUnknown; } /* - * Choose weather icon to display based on weather conditition code - * https://openweathermap.org/weather-conditions#Weather-Condition-Codes-2 - */ + * Choose weather icon to display based on weather condition code + * https://openweathermap.org/weather-conditions#Weather-Condition-Codes-2 + */ function chooseIconByCode(code) { const codeGroup = Math.round(code / 100); switch (codeGroup) { @@ -382,16 +626,15 @@ exports.drawIcon = function(cond, x, y, r, ovr, monochrome) { } function chooseIcon(cond) { - if (typeof (cond)==="object") { + if (typeof cond === "object") { if ("code" in cond) return chooseIconByCode(cond.code); if ("txt" in cond) return chooseIconByTxt(cond.txt); - } else if (typeof (cond)==="number") { + } else if (typeof cond === "number") { return chooseIconByCode(cond.code); - } else if (typeof (cond)==="string") { + } else if (typeof cond === "string") { return chooseIconByTxt(cond.txt); } return drawUnknown; } chooseIcon(cond)(x, y, r); - }; diff --git a/apps/weather/metadata.json b/apps/weather/metadata.json index ccefac8c03..7bd8ca3056 100644 --- a/apps/weather/metadata.json +++ b/apps/weather/metadata.json @@ -1,7 +1,7 @@ { "id": "weather", "name": "Weather", - "version": "0.27", + "version": "0.28", "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"}] } diff --git a/apps/weather/settings.js b/apps/weather/settings.js index 7e0bb24c82..443ef898fb 100644 --- a/apps/weather/settings.js +++ b/apps/weather/settings.js @@ -1,31 +1,72 @@ -(function(back) { - const storage = require('Storage'); - let settings = storage.readJSON('weather.json', 1) || {}; +(back) => { + const storage = require("Storage"); + 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); } + + const DATA_TYPE = ["basic", "extended", "forecast"]; + E.showMenu({ - '': { 'title': 'Weather' }, - 'Expiry': { - value: "expiry" in settings ? settings["expiry"] : 2*3600000, + "": { "title": "Weather" }, + "Expiry": { + value: "expiry" in settings ? settings.expiry : 2 * 3600000, + min: 0, + max: 24 * 3600000, + step: 15 * 60000, + format: (x) => { + if (x === 0) return "none"; + if (x < 3600000) return `${Math.floor(x / 60000)}m`; + if (x < 86400000) return `${Math.floor(x / 36000) / 100}h`; + }, + 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 "none"; - if (x < 3600000) return Math.floor(x/60000) + "m"; - if (x < 86400000) return Math.floor(x/36000)/100 + "h"; + 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('expiry', x), + onchange: (x) => save("refresh", x), }, - 'Hide Widget': { + "Data type": { + value: DATA_TYPE.indexOf(settings.dataType ?? "basic"), + format: (v) => DATA_TYPE[v], + min: 0, + max: DATA_TYPE.length - 1, + onchange: (v) => { + settings.dataType = DATA_TYPE[v]; + save("dataType", settings.dataType); + }, + }, + "Hide Widget": { value: "hide" in settings ? settings.hide : false, onchange: () => { - settings.hide = !settings.hide - save('hide', settings.hide); + settings.hide = !settings.hide; + save("hide", settings.hide); }, }, - '< Back': back, + "Force refresh": () => { + require("weather").updateWeather(true); + }, + "< Back": back, }); -}) +}; diff --git a/apps/weather/widget.js b/apps/weather/widget.js index 2905d776b4..7e4d2c6dd6 100644 --- a/apps/weather/widget.js +++ b/apps/weather/widget.js @@ -1,53 +1,53 @@ (() => { - const weather = require('weather'); - + const weather = require("weather"); + var dirty = false; - + let settings; function loadSettings() { - settings = require('Storage').readJSON('weather.json', 1) || {}; + settings = require("Storage").readJSON("weatherSetting.json", 1) || {}; } function setting(key) { if (!settings) { loadSettings(); } const DEFAULTS = { - 'expiry': 2*3600000, - 'hide': false + "expiry": 2*3600000, + "hide": false }; return (key in settings) ? settings[key] : DEFAULTS[key]; } weather.on("update", w => { - if (setting('hide')) return; + if (setting("hide")) return; if (w) { - if (!WIDGETS["weather"].width) { - WIDGETS["weather"].width = 20; + if (!WIDGETS.weather.width) { + WIDGETS.weather.width = 20; Bangle.drawWidgets(); } else if (Bangle.isLCDOn()) { - WIDGETS["weather"].draw(); + WIDGETS.weather.draw(); } else { dirty = true; } } else { - WIDGETS["weather"].width = 0; + WIDGETS.weather.width = 0; Bangle.drawWidgets(); } }); - Bangle.on('lcdPower', on => { - if (on && dirty && !setting('hide')) { - WIDGETS["weather"].draw(); + Bangle.on("lcdPower", on => { + if (on && dirty && !setting("hide")) { + WIDGETS.weather.draw(); dirty = false; } }); - WIDGETS["weather"] = { + WIDGETS.weather = { area: "tl", - width: weather.get() && !setting('hide') ? 20 : 0, + width: weather.get() && !setting("hide") ? 20 : 0, draw: function() { - if (setting('hide')) return; + if (setting("hide")) return; const w = weather.get(); if (!w) return; g.reset(); @@ -56,17 +56,17 @@ weather.drawIcon(w, this.x+10, this.y+8, 7.5); } if (w.temp) { - let t = require('locale').temp(w.temp-273.15); // applies conversion + let t = require("locale").temp(w.temp-273.15); // applies conversion t = t.match(/[\d\-]*/)[0]; // but we have no room for units g.reset(); g.setFontAlign(0, 1); // center horizontally at bottom of widget - g.setFont('6x8', 1); + g.setFont("6x8", 1); g.drawString(t, this.x+10, this.y+24); } }, - reload:function() { + reload:() => { loadSettings(); - WIDGETS["weather"].redraw(); + WIDGETS.weather.redraw(); }, }; })();