Bryan 2025-08-17 19:13:11 -06:00
commit 6ea0b8ec66
26 changed files with 1076 additions and 196 deletions

View File

@ -1 +1,2 @@
0.01: first release 0.01: First release
0.02: Add setting to make widgets optional

View File

@ -1,10 +1,14 @@
# Deko Clock # Deko Clock
A simple clock with an Art Deko font A simple clock with an Art Deko font.
The font was obtained from https://dafonttop.com/building.font and is free for personal use Widgets can be configured to be always on, always off, or only shown when unlocked.
The font was obtained from https://dafonttop.com/building.font and is free for personal use.
![](screenshot.png) ![](screenshot.png) ![](screenshot-no-widgets.png)
Written by: [Hugh Barney](https://github.com/hughbarney) For support and discussion please post in the [Bangle JS Forum](http://forum.espruino.com/microcosms/1424/) Written by: [Hugh Barney](https://github.com/hughbarney)
Optional widgets settings added by [Trippnology](https://github.com/trippnology)
For support and discussion please post in the [Bangle JS Forum](http://forum.espruino.com/microcosms/1424/)

File diff suppressed because one or more lines are too long

View File

@ -1,16 +1,21 @@
{ {
"id": "deko", "id": "deko",
"name": "Deko Clock", "name": "Deko Clock",
"version": "0.01", "version": "0.02",
"description": "Clock with Art Deko font", "description": "Clock with Art Deko font",
"readme": "README.md", "readme": "README.md",
"icon": "app.png", "icon": "app.png",
"screenshots": [{"url":"screenshot.png"}], "screenshots": [
{ "url": "screenshot.png" },
{ "url": "screenshot-no-widgets.png" }
],
"type": "clock", "type": "clock",
"tags": "clock", "tags": "clock",
"supports": ["BANGLEJS","BANGLEJS2"], "supports": ["BANGLEJS", "BANGLEJS2"],
"storage": [ "storage": [
{"name":"deko.app.js","url":"app.js"}, { "name": "deko.app.js", "url": "app.js" },
{"name":"deko.img","url":"app-icon.js","evaluate":true} { "name": "deko.settings.js", "url": "settings.js" },
] { "name": "deko.img", "url": "app-icon.js", "evaluate": true }
],
"data": [{ "name": "deko.settings.json" }]
} }

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.5 KiB

32
apps/deko/settings.js Normal file
View File

@ -0,0 +1,32 @@
(function (back) {
const storage = require('Storage');
const settingsFile = 'deko.settings.json';
const defaultSettings = {
loadWidgets: 1,
};
const settings = Object.assign(
defaultSettings,
storage.readJSON(settingsFile, 1) || {},
);
const loadWidgetsChoices = ['No', 'Yes', 'Unlocked'];
const save = () => storage.write(settingsFile, settings);
const appMenu = {
'': { title: 'Deko Clock' },
'< Back': back,
'Load widgets?': {
value: settings.loadWidgets,
min: 0,
max: 2,
step: 1,
format: (v) => loadWidgetsChoices[v],
onchange: (v) => {
settings.loadWidgets = v;
save();
},
},
};
E.showMenu(appMenu);
})

1
apps/smartbatt/ChangeLog Normal file
View File

@ -0,0 +1 @@
v0.01: New app!

48
apps/smartbatt/README.md Normal file
View File

@ -0,0 +1,48 @@
# Smart Battery Module
A module for providing a truly accurate battery life in terms of days. The module learns from daily usage and drainage patterns, and extrapolates that. As you use it more, and the battery keeps draining, the predictions should become more accurate.
Because the Bangle.js battery percent fluctuates naturally, it is highly recomended to use the `Power Manager` app and enable monotonic/stable percentage to stabilize the percentage, and reduce fluctuations. This may help provide more accurate readings.
## Upon Install
Use an app that needs this module, like `Smart Battery Widget`.
When this app is installed, <i><b>do not rely on it for the first 24-30 hours.</b></i>
The module might return different data than expected, or a severely low prediction. Give it time. It will learn from drainage rates, which needs the battery to drain. If your watch normally lasts for a long time on one charge, it will take longer for the module to return an accurate reading.
If you think something is wrong with the predictions after 3 days, try clearing the data, and let it rebuild again from scratch.
## Clock Infos
The module provides two clockInfos:
- Days left
- Learned drainage rate per hour
## Settings
### Clear Data - Clears all learned data.
Use this when you switch to a new clock or change the battery drainage in a fundamental way. The app averages drainage over time, and so you might just want to restart the learned data to be more accurate for the new configurations you have implemented.
### Logging - Enables logging for stats that this module uses.
To view the log file, go to the [Web IDE](https://www.espruino.com/ide/#), click on the storage icon (4 discs), and scroll to the file named `smartbattlog.json`. From there, you can view the file, copy to editor, or save it to your computer.
Logs:
* The time in a human-readable format (hh:mm:ss, mm:dd:yy) when the record event was triggered
* The current battery percentage
* The last saved battery percentage
* The change in hours between the time last recorded and now
* The average or learned drainage for battery per hour
* The status of that record event:
* Recorded
* Skipped due to battery fluctuations or no change
* Invalid time between the two periods (first record)
## Functions
From any app, you can call `require("smartbatt")` and then one of the functions below:
* `require("smartbatt").record()` - Attempts to record the battery and push it to the average.
* `require("smartbatt").get()` - Returns an object that contains:
* `hrsRemaining` - Hours remaining
* `avgDrainage` - Learned battery drainage per hour
* `totalCycles` - Total times the battery has been recorded and averaged
* `totalHours` - Total hours recorded
* `batt` - Current battery level
* `require("smartbatt").deleteData()` - Deletes all learned data. (Automatically re-learns)
## Creator
- RKBoss6
## Contributors
- RelapsingCertainly

84
apps/smartbatt/clkinfo.js Normal file
View File

@ -0,0 +1,84 @@
(function() {
var batt;
//updates values
function getHrsFormatted(hrsLeft){
var daysLeft = hrsLeft / 24;
daysLeft = Math.round(daysLeft);
if(daysLeft >= 1) {
return daysLeft+"d";
}
else {
return Math.round(hrsLeft)+"h";
}
}
//draws battery icon and fill bar
function drawBatt(){
batt =E.getBattery();
var s=24,g=Graphics.createArrayBuffer(24,24,1,{msb:true});
g.fillRect(0,6,s-3,18).clearRect(2,8,s-5,16).fillRect(s-2,10,s,15).fillRect(3,9,3+batt*(s-9)/100,15);
g.transparent=0;
return g.asImage("string");
}
//calls both updates for values and icons.
//might split in the future since values updates once every five minutes so we dont need to call it in every minute while the battery can be updated once a minute.
function updateDisplay(){
drawBatt();
}
return {
name: "SmartBatt",
items: [
{ name : "BattStatus",
get : () => {
var img = drawBatt();
var data=require("smartbatt").get();
//update clock info according to batt state
if (Bangle.isCharging()) {
return { text: batt+"%", img };
}
else{
return { text: getHrsFormatted(data.hrsLeft), img };
}
},
show : function() {
this.interval = setInterval(()=>{
updateDisplay();
this.emit('redraw');
}, 300000);
},
hide : function() {
clearInterval(this.interval);
this.interval = undefined;
}
},
{ name : "AvgDrainage",
get : () => {
var img = drawBatt()
var data=require("smartbatt").get();
return { text: data.avgDrainage.toFixed(2)+"/h", img };
},
show : function() {
this.interval = setInterval(()=>{
this.emit('redraw');
}, 300000);
},
hide : function() {
clearInterval(this.interval);
this.interval = undefined;
}
}
]
};
})

BIN
apps/smartbatt/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 403 KiB

View File

@ -0,0 +1,21 @@
{
"id": "smartbatt",
"name": "Smart Battery Module",
"shortName": "Smart Battery",
"version": "0.01",
"description": "Provides a `smartbatt` module that returns the battery in days, and learns from daily usage over time for accurate predictions.",
"icon": "icon.png",
"type": "module",
"tags": "tool,system,clkinfo",
"supports": ["BANGLEJS","BANGLEJS2"],
"provides_modules" : ["smartbatt"],
"readme": "README.md",
"storage": [
{"name":"smartbatt","url":"module.js"},
{"name":"smartbatt.settings.js","url":"settings.js"},
{"name":"smartbatt.clkinfo.js","url":"clkinfo.js"}
],
"data": [
{"name":"smartbatt.settings.json"}
]
}

136
apps/smartbatt/module.js Normal file
View File

@ -0,0 +1,136 @@
{
var dataFile = "smartbattdata.json";
var interval;
var storage = require("Storage");
var logFile = "smartbattlog.json";
function getSettings() {
return Object.assign({
//Record Interval stored in ms
doLogging: false
}, require('Storage').readJSON("smartbatt.settings.json", true) || {});
}
function logBatterySample(entry) {
let log = storage.readJSON(logFile, 1) || [];
//get human-readable time
let d = new Date();
entry.time = d.getFullYear() + "-" +
("0" + (d.getMonth() + 1)).slice(-2) + "-" +
("0" + d.getDate()).slice(-2) + " " +
("0" + d.getHours()).slice(-2) + ":" +
("0" + d.getMinutes()).slice(-2) + ":" +
("0" + d.getSeconds()).slice(-2);
log.push(entry);
if (log.length > 100) log = log.slice(-100);
storage.writeJSON(logFile, log);
}
// Record current battery reading into current average
function recordBattery() {
let now = Date.now();
let data = getData();
let batt = E.getBattery();
let battChange = data.battLastRecorded - batt;
let deltaHours = (now - data.timeLastRecorded) / (1000 * 60 * 60);
// Default reason (in case we skip)
let reason = "Recorded";
if (battChange <= 0) {
reason = "Skipped: battery fluctuated or no change";
if (Math.abs(battChange) < 5) {
//less than 6% difference, average percents
var newBatt = (batt + data.battLastRecorded) / 2;
data.battLastRecorded = newBatt;
} else {
//probably charged, ignore average
data.battLastRecorded = batt;
}
storage.writeJSON(dataFile, data);
} else if (deltaHours <= 0 || !isFinite(deltaHours)) {
reason = "Skipped: invalid time delta";
data.timeLastRecorded = now;
data.battLastRecorded = batt;
storage.writeJSON(dataFile, data);
} else {
let weightCoefficient = 1;
let currentDrainage = battChange / deltaHours;
let newAvg = weightedAverage(data.avgBattDrainage, data.totalHours, currentDrainage, deltaHours * weightCoefficient);
data.avgBattDrainage = newAvg;
data.timeLastRecorded = now;
data.totalCycles += 1;
data.totalHours += deltaHours;
data.battLastRecorded = batt;
storage.writeJSON(dataFile, data);
reason = "Drainage recorded: " + currentDrainage.toFixed(3) + "%/hr";
}
if (getSettings().doLogging) {
// Always log the sample
logBatterySample({
battNow: batt,
battLast: data.battLastRecorded,
battChange: battChange,
deltaHours: deltaHours,
timeLastRecorded: data.timeLastRecorded,
avgDrainage: data.avgBattDrainage,
reason: reason
});
}
}
function weightedAverage(oldValue, oldWeight, newValue, newWeight) {
return (oldValue * oldWeight + newValue * newWeight) / (oldWeight + newWeight);
}
function getData() {
return storage.readJSON(dataFile, 1) || {
avgBattDrainage: 0,
battLastRecorded: E.getBattery(),
timeLastRecorded: Date.now(),
totalCycles: 0,
totalHours: 0,
};
}
// Estimate hours remaining
function estimateBatteryLife() {
let data = getData();
var batt = E.getBattery();
var hrsLeft = Math.abs(batt / data.avgBattDrainage);
return {
batt: batt,
hrsLeft: hrsLeft,
avgDrainage:data.avgBattDrainage,
totalHours:data.totalHours,
cycles:data.totalCycles
};
}
function deleteData() {
storage.erase(dataFile);
storage.erase(logFile);
}
// Expose public API
exports.record = recordBattery;
exports.deleteData = deleteData;
exports.get = estimateBatteryLife;
exports.changeInterval = function (newInterval) {
clearInterval(interval);
interval = setInterval(recordBattery, newInterval);
};
// Start recording every 5 minutes
interval = setInterval(recordBattery, 600000);
recordBattery(); // Log immediately
}

View File

@ -0,0 +1,42 @@
(function(back) {
var FILE = "smartbatt.settings.json";
// Load settings
var settings = Object.assign({
//Record Interval stored in ms
doLogging:false
}, require('Storage').readJSON(FILE, true) || {});
function writeSettings() {
require('Storage').writeJSON(FILE, settings);
}
// Show the menu
E.showMenu({
"" : { "title" : "Smart Day Battery" },
"< Back" : () => back(),
'Clear Data': function () {
E.showPrompt("Are you sure you want to delete all learned data?", {title:"Confirm"})
.then(function(v) {
if (v) {
require("smartbatt").deleteData();
E.showMessage("Successfully cleared data!","Cleared");
} else {
eval(require("Storage").read("smartbatt.settings.js"))(()=>load());
}
});
},
'Log Battery': {
value: !!settings.doLogging, // !! converts undefined to false
onchange: v => {
settings.doLogging = v;
writeSettings();
}
// format: ... may be specified as a function which converts the value to a string
// if the value is a boolean, showMenu() will convert this automatically, which
// keeps settings menus consistent
},
});
})

View File

@ -26,3 +26,9 @@
0.27: Add UV index display 0.27: Add UV index display
0.28: Fix UV positioning, hide when 0 0.28: Fix UV positioning, hide when 0
0.29: Add feels-like temperature data and clock_info 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. 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 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: You can view the full report through the app:
![Screenshot](screenshot.png) ![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. 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 ## Android Setup
1. Install [Gadgetbridge for Android](https://f-droid.org/packages/nodomain.freeyourgadget.gadgetbridge/) on your phone. 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). 2. Set up [Gadgetbridge weather reporting](https://gadgetbridge.org/basics/features/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`).
### Android Weather Apps ### 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 * Tiny Weather Forecast Germany
* F-Droid - https://f-droid.org/en/packages/de.kaffeemitkoffein.tinyweatherforecastgermany/ * F-Droid - https://f-droid.org/en/packages/de.kaffeemitkoffein.tinyweatherforecastgermany/
* Source code - https://codeberg.org/Starfish/TinyWeatherForecastGermany * Source code - https://codeberg.org/Starfish/TinyWeatherForecastGermany
* QuickWeather * QuickWeather
* F-Droid - https://f-droid.org/en/packages/com.ominous.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 * Google Play - https://play.google.com/store/apps/details?id=com.ominous.quickweather
* Source code - https://github.com/TylerWilliamson/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 ### Tiny Weather Forecast Germany
Even though Tiny Weather Forecast Germany is made for Germany, it can be used around the world. To do this: 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 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. 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. 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 ### 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. 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 ### 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 ## Clock Infos
@ -67,7 +75,9 @@ Adds:
## Settings ## 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 * Widget can be hidden
* To change the units for wind speed, you can install the [`Languages app`](https://banglejs.com/apps/?id=locale) which * 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. allows you to choose the units used for speed/distance/temperature and so on.
@ -76,3 +86,44 @@ allows you to choose the units used for speed/distance/temperature and so on.
* BTN2: opens the launcher (Bangle.js 1) * BTN2: opens the launcher (Bangle.js 1)
* BTN: opens the launcher (Bangle.js 2) * 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);
}
```

View File

@ -16,24 +16,24 @@ var layout = new Layout({type:"v", bgCol: g.theme.bg, c: [
render: l => { render: l => {
if (!current || current.uv === undefined) return; if (!current || current.uv === undefined) return;
const uv = Math.min(parseInt(current.uv), 11); // Cap at 11 const uv = Math.min(parseInt(current.uv), 11); // Cap at 11
// UV color thresholds: [max_value, color] based on WHO standards // UV color thresholds: [max_value, color] based on WHO standards
const colors = [[2,"#0F0"], [5,"#FF0"], [7,"#F80"], [10,"#F00"], [11,"#F0F"]]; const colors = [[2,"#0F0"], [5,"#FF0"], [7,"#F80"], [10,"#F00"], [11,"#F0F"]];
const color = colors.find(c => uv <= c[0])[1]; const color = colors.find(c => uv <= c[0])[1];
// Setup and measure label // Setup and measure label
g.setFont("6x8").setFontAlign(-1, 0); g.setFont("6x8").setFontAlign(-1, 0);
const label = "UV: "; const label = "UV: ";
const labelW = g.stringWidth(label); const labelW = g.stringWidth(label);
// Calculate centered position (4px block + 1px spacing) * blocks - last spacing // Calculate centered position (4px block + 1px spacing) * blocks - last spacing
const totalW = labelW + uv * 5 - (uv > 0 ? 1 : 0); const totalW = labelW + uv * 5 - (uv > 0 ? 1 : 0);
const x = l.x + (l.w - totalW) / 2; const x = l.x + (l.w - totalW) / 2;
const y = l.y + l.h+6; const y = l.y + l.h+6;
// Draw label // Draw label
g.setColor(g.theme.fg).drawString(label, x, y); g.setColor(g.theme.fg).drawString(label, x, y);
// Draw UV blocks // Draw UV blocks
g.setColor(color); g.setColor(color);
for (let i = 0; i < uv; i++) { for (let i = 0; i < uv; i++) {
@ -58,7 +58,7 @@ var layout = new Layout({type:"v", bgCol: g.theme.bg, c: [
{type: "txt", font: "6x8", pad: 2, halign: 1, label: /*LANG*/"Hum:"}, {type: "txt", font: "6x8", pad: 2, halign: 1, label: /*LANG*/"Hum:"},
{type: "txt", font: "9%", pad: 2, halign: 1, id: "hum", label: "000%"}, {type: "txt", font: "9%", pad: 2, halign: 1, id: "hum", label: "000%"},
]}, ]},
{filly: 1}, {filly: 1},
{type: "txt", font: "6x8", pad: 2, halign: -1, label: /*LANG*/"Wind"}, {type: "txt", font: "6x8", pad: 2, halign: -1, label: /*LANG*/"Wind"},
{type: "h", halign: -1, c: [ {type: "h", halign: -1, c: [
@ -79,7 +79,7 @@ var layout = new Layout({type:"v", bgCol: g.theme.bg, c: [
]}, {lazy: true}); ]}, {lazy: true});
function formatDuration(millis) { 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 < 60000) return /*LANG*/"< 1 minute";
if (millis < 3600000) return pluralize(Math.floor(millis/60000), /*LANG*/"minute"); if (millis < 3600000) return pluralize(Math.floor(millis/60000), /*LANG*/"minute");
if (millis < 86400000) return pluralize(Math.floor(millis/3600000), /*LANG*/"hour"); if (millis < 86400000) return pluralize(Math.floor(millis/3600000), /*LANG*/"hour");
@ -98,11 +98,11 @@ function draw() {
}else{ }else{
layout.feelslike.label = feelsLikeTemp[1]+feelsLikeTemp[2]; layout.feelslike.label = feelsLikeTemp[1]+feelsLikeTemp[2];
} }
layout.hum.label = current.hum+"%"; layout.hum.label = `${current.hum}%`;
const wind = locale.speed(current.wind).match(/^(\D*\d*)(.*)$/); const wind = locale.speed(current.wind).match(/^(\D*\d*)(.*)$/);
layout.wind.label = wind[1]; 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.cond.label = current.txt.charAt(0).toUpperCase()+(current.txt||'').slice(1);
layout.loc.label = current.loc; layout.loc.label = current.loc;
layout.updateTime.label = `${formatDuration(Date.now() - current.time)} ago`; // How to autotranslate this and similar? layout.updateTime.label = `${formatDuration(Date.now() - current.time)} ago`; // How to autotranslate this and similar?

View File

@ -1,5 +1,4 @@
(() => {
(function() {
var weather; var weather;
var weatherLib = require("weather"); var weatherLib = require("weather");
@ -8,9 +7,9 @@
if(weather){ if(weather){
weather.temp = require("locale").temp(weather.temp-273.15); weather.temp = require("locale").temp(weather.temp-273.15);
weather.feels = require("locale").temp(weather.feels-273.15); weather.feels = require("locale").temp(weather.feels-273.15);
weather.hum = weather.hum + "%"; weather.hum = `${weather.hum}%`;
weather.wind = require("locale").speed(weather.wind).match(/^(\D*\d*)(.*)$/); 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 { } else {
weather = { weather = {
temp: "?", temp: "?",

View File

@ -1,115 +1,357 @@
const storage = require('Storage'); const storage = require("Storage");
const B2 = process.env.HWVERSION===2; const B2 = process.env.HWVERSION === 2;
let expiryTimeout; let expiryTimeout;
function scheduleExpiry(json) { function scheduleExpiry() {
if (expiryTimeout) { if (expiryTimeout) {
clearTimeout(expiryTimeout); clearTimeout(expiryTimeout);
expiryTimeout = undefined; expiryTimeout = undefined;
} }
let expiry = "expiry" in json ? json.expiry : 2*3600000;
if (json.weather && json.weather.time && expiry) { const json = storage.readJSON("weatherSetting.json") || {};
let t = json.weather.time + expiry - Date.now(); const expiry = "expiry" in json ? json.expiry : 2 * 3600000;
expiryTimeout = setTimeout(update, t); 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) { 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(); weather.time = Date.now();
if (weather.wdir != null) { if (weather.wdir != null) {
// Convert numeric direction into human-readable label weather.wrose = windDirection(weather.wdir);
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; storage.write("weather.json", json);
} exports.emit("update", weather);
else {
delete json.weather;
}
// Request extended/forecast if supported by Weather Provider and set in settings
if (weatherEvent.v != null && (weatherSetting.dataType ?? "basic") !== "basic") {
updateWeather(true);
}
storage.write('weather.json', json); // Either Weather Provider doesn't support v2 and/or we don't need extended/forecast, so we use this event for refresh scheduling
scheduleExpiry(json); if (weatherEvent.v == null || (weatherSetting.dataType ?? "basic") === "basic") {
exports.emit("update", json.weather); 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);
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) + 273;
storage.write("weather.json", weather1);
exports.emit("update", weather1);
}
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(""); // 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);
return decoded;
}
}
exports.update = update; exports.update = update;
const _GB = global.GB; const _GB = global.GB;
global.GB = (event) => { global.GB = (event) => {
if (event.t==="weather") update(event); if (event.t === "weather") update(event);
if (_GB) setTimeout(_GB, 0, event); if (_GB) setTimeout(_GB, 0, event);
}; };
exports.get = function() { exports.updateWeather = updateWeather;
return (storage.readJSON('weather.json')||{}).weather; 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 + 273,
};
return json;
}
function getPalette(monochrome, ovr) { function getPalette(monochrome, ovr) {
var palette; var palette;
if(monochrome) { if (monochrome) {
palette = { palette = {
sun: '#FFF', sun: "#FFF",
cloud: '#FFF', cloud: "#FFF",
bgCloud: '#FFF', bgCloud: "#FFF",
rain: '#FFF', rain: "#FFF",
lightning: '#FFF', lightning: "#FFF",
snow: '#FFF', snow: "#FFF",
mist: '#FFF', mist: "#FFF",
background: '#000' background: "#000",
}; };
} else { } else {
if (B2) { if (B2) {
if (ovr.theme.dark) { if (ovr.theme.dark) {
palette = { palette = {
sun: '#FF0', sun: "#FF0",
cloud: '#FFF', cloud: "#FFF",
bgCloud: '#777', // dithers on B2, but that's ok bgCloud: "#777", // dithers on B2, but that's ok
rain: '#0FF', rain: "#0FF",
lightning: '#FF0', lightning: "#FF0",
snow: '#FFF', snow: "#FFF",
mist: '#FFF' mist: "#FFF",
}; };
} else { } else {
palette = { palette = {
sun: '#FF0', sun: "#FF0",
cloud: '#777', // dithers on B2, but that's ok cloud: "#777", // dithers on B2, but that's ok
bgCloud: '#000', bgCloud: "#000",
rain: '#00F', rain: "#00F",
lightning: '#FF0', lightning: "#FF0",
snow: '#0FF', snow: "#0FF",
mist: '#0FF' mist: "#0FF",
}; };
} }
} else { } else {
if (ovr.theme.dark) { if (ovr.theme.dark) {
palette = { palette = {
sun: '#FE0', sun: "#FE0",
cloud: '#BBB', cloud: "#BBB",
bgCloud: '#777', bgCloud: "#777",
rain: '#0CF', rain: "#0CF",
lightning: '#FE0', lightning: "#FE0",
snow: '#FFF', snow: "#FFF",
mist: '#FFF' mist: "#FFF",
}; };
} else { } else {
palette = { palette = {
sun: '#FC0', sun: "#FC0",
cloud: '#000', cloud: "#000",
bgCloud: '#777', bgCloud: "#777",
rain: '#07F', rain: "#07F",
lightning: '#FC0', lightning: "#FC0",
snow: '#CCC', snow: "#CCC",
mist: '#CCC' mist: "#CCC",
}; };
} }
} }
@ -117,10 +359,10 @@ function getPalette(monochrome, ovr) {
return palette; return palette;
} }
exports.getColor = function(code) { exports.getColor = (code) => {
const codeGroup = Math.round(code / 100); const codeGroup = Math.round(code / 100);
const palette = getPalette(0, g); 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) { switch (codeGroup) {
case 2: return g.blendColor(cloud, palette.lightning, .5); case 2: return g.blendColor(cloud, palette.lightning, .5);
case 3: return palette.rain; case 3: return palette.rain;
@ -144,7 +386,7 @@ exports.getColor = function(code) {
} }
default: return cloud; default: return cloud;
} }
} };
/** /**
* *
@ -158,9 +400,9 @@ exports.getColor = function(code) {
* @param ovr Graphics instance (or undefined for g) * @param ovr Graphics instance (or undefined for g)
* @param monochrome If true, produce a monochromatic icon * @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; var palette;
if(!ovr) ovr = g; if (!ovr) ovr = g;
palette = getPalette(monochrome, ovr); palette = getPalette(monochrome, ovr);
@ -257,7 +499,7 @@ exports.drawIcon = function(cond, x, y, r, ovr, monochrome) {
function drawSnow(x, y, r) { function drawSnow(x, y, r) {
function rotatePoints(points, pivotX, pivotY, angle) { function rotatePoints(points, pivotX, pivotY, angle) {
for(let i = 0; i<points.length; i += 2) { for (let i = 0; i < points.length; i += 2) {
const x = points[i]; const x = points[i];
const y = points[i+1]; const y = points[i+1];
points[i] = Math.cos(angle)*(x-pivotX)-Math.sin(angle)*(y-pivotY)+ points[i] = Math.cos(angle)*(x-pivotX)-Math.sin(angle)*(y-pivotY)+
@ -269,7 +511,7 @@ exports.drawIcon = function(cond, x, y, r, ovr, monochrome) {
ovr.setColor(palette.snow); ovr.setColor(palette.snow);
const w = 1/12*r; const w = 1/12*r;
for(let i = 0; i<=6; ++i) { for (let i = 0; i <= 6; ++i) {
const points = [ const points = [
x+w, y, x+w, y,
x-w, y, x-w, y,
@ -279,7 +521,7 @@ exports.drawIcon = function(cond, x, y, r, ovr, monochrome) {
rotatePoints(points, x, y, i/3*Math.PI); rotatePoints(points, x, y, i/3*Math.PI);
ovr.fillPoly(points); ovr.fillPoly(points);
for(let j = -1; j<=1; j += 2) { for (let j = -1; j <= 1; j += 2) {
const points = [ const points = [
x+w, y+7/12*r, x+w, y+7/12*r,
x-w, y+7/12*r, x-w, y+7/12*r,
@ -317,8 +559,8 @@ exports.drawIcon = function(cond, x, y, r, ovr, monochrome) {
} }
/* /*
* Choose weather icon to display based on weather description * Choose weather icon to display based on weather description
*/ */
function chooseIconByTxt(txt) { function chooseIconByTxt(txt) {
if (!txt) return () => {}; if (!txt) return () => {};
txt = txt.toLowerCase(); 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("few clouds")) return drawFewClouds;
if (txt.includes("scattered clouds")) return drawCloud; if (txt.includes("scattered clouds")) return drawCloud;
if (txt.includes("clouds")) return drawBrokenClouds; if (txt.includes("clouds")) return drawBrokenClouds;
if (txt.includes("mist") || if (
txt.includes("mist") ||
txt.includes("smoke") || txt.includes("smoke") ||
txt.includes("haze") || txt.includes("haze") ||
txt.includes("sand") || txt.includes("sand") ||
@ -344,16 +587,17 @@ exports.drawIcon = function(cond, x, y, r, ovr, monochrome) {
txt.includes("fog") || txt.includes("fog") ||
txt.includes("ash") || txt.includes("ash") ||
txt.includes("squalls") || txt.includes("squalls") ||
txt.includes("tornado")) { txt.includes("tornado")
) {
return drawMist; return drawMist;
} }
return drawUnknown; return drawUnknown;
} }
/* /*
* Choose weather icon to display based on weather conditition code * Choose weather icon to display based on weather condition code
* https://openweathermap.org/weather-conditions#Weather-Condition-Codes-2 * https://openweathermap.org/weather-conditions#Weather-Condition-Codes-2
*/ */
function chooseIconByCode(code) { function chooseIconByCode(code) {
const codeGroup = Math.round(code / 100); const codeGroup = Math.round(code / 100);
switch (codeGroup) { switch (codeGroup) {
@ -382,16 +626,15 @@ exports.drawIcon = function(cond, x, y, r, ovr, monochrome) {
} }
function chooseIcon(cond) { function chooseIcon(cond) {
if (typeof (cond)==="object") { if (typeof cond === "object") {
if ("code" in cond) return chooseIconByCode(cond.code); if ("code" in cond) return chooseIconByCode(cond.code);
if ("txt" in cond) return chooseIconByTxt(cond.txt); if ("txt" in cond) return chooseIconByTxt(cond.txt);
} else if (typeof (cond)==="number") { } else if (typeof cond === "number") {
return chooseIconByCode(cond.code); return chooseIconByCode(cond.code);
} else if (typeof (cond)==="string") { } else if (typeof cond === "string") {
return chooseIconByTxt(cond.txt); return chooseIconByTxt(cond.txt);
} }
return drawUnknown; return drawUnknown;
} }
chooseIcon(cond)(x, y, r); chooseIcon(cond)(x, y, r);
}; };

View File

@ -1,7 +1,7 @@
{ {
"id": "weather", "id": "weather",
"name": "Weather", "name": "Weather",
"version": "0.29", "version": "0.30",
"description": "Show Gadgetbridge/iOS weather report", "description": "Show Gadgetbridge/iOS weather report",
"icon": "icon.png", "icon": "icon.png",
"screenshots": [{"url":"screenshot.png"}], "screenshots": [{"url":"screenshot.png"}],
@ -16,5 +16,5 @@
{"name":"weather.settings.js","url":"settings.js"}, {"name":"weather.settings.js","url":"settings.js"},
{"name":"weather.clkinfo.js","url":"clkinfo.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,31 +1,87 @@
(function(back) { (function (back) {
const storage = require('Storage'); 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) { function save(key, value) {
settings[key] = value; settings[key] = value;
storage.write('weather.json', settings); storage.write("weatherSetting.json", settings);
} }
E.showMenu({
'': { 'title': 'Weather' }, const DATA_TYPE = ["basic", "extended", "forecast"];
'Expiry': {
value: "expiry" in settings ? settings["expiry"] : 2*3600000, let menuItems = {
"": { "title": "Weather" },
"Expiry": {
value: "expiry" in settings ? settings.expiry : 2 * 3600000,
min: 0, min: 0,
max : 24*3600000, max: 24 * 3600000,
step: 15*60000, step: 15 * 60000,
format: x => { format: (x) => {
if (x == 0) return "none"; if (x === 0) return "none";
if (x < 3600000) return Math.floor(x/60000) + "m"; if (x < 3600000) return `${Math.floor(x / 60000)}m`;
if (x < 86400000) return Math.floor(x/36000)/100 + "h"; if (x < 86400000) return `${Math.floor(x / 36000) / 100}h`;
}, },
onchange: x => save('expiry', x), onchange: (x) => save("expiry", x),
}, },
'Hide Widget': { "Hide Widget": {
value: "hide" in settings ? settings.hide : false, value: "hide" in settings ? settings.hide : false,
onchange: () => { onchange: () => {
settings.hide = !settings.hide settings.hide = !settings.hide;
save('hide', settings.hide); save("hide", settings.hide);
}, },
}, },
'< Back': back, "< Back": back,
}); };
// Add android only settings
let android = false;
try {
if (require("android") != null) {
android = true;
}
} catch (_) {}
if (android) {
menuItems["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),
};
menuItems["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);
},
};
menuItems["Force refresh"] = () => {
require("weather").updateWeather(true);
};
}
E.showMenu(menuItems);
}) })

View File

@ -1,53 +1,53 @@
(() => { (() => {
const weather = require('weather'); const weather = require("weather");
var dirty = false; var dirty = false;
let settings; let settings;
function loadSettings() { function loadSettings() {
settings = require('Storage').readJSON('weather.json', 1) || {}; settings = require("Storage").readJSON("weatherSetting.json", 1) || {};
} }
function setting(key) { function setting(key) {
if (!settings) { loadSettings(); } if (!settings) { loadSettings(); }
const DEFAULTS = { const DEFAULTS = {
'expiry': 2*3600000, "expiry": 2*3600000,
'hide': false "hide": false
}; };
return (key in settings) ? settings[key] : DEFAULTS[key]; return (key in settings) ? settings[key] : DEFAULTS[key];
} }
weather.on("update", w => { weather.on("update", w => {
if (setting('hide')) return; if (setting("hide")) return;
if (w) { if (w) {
if (!WIDGETS["weather"].width) { if (!WIDGETS.weather.width) {
WIDGETS["weather"].width = 20; WIDGETS.weather.width = 20;
Bangle.drawWidgets(); Bangle.drawWidgets();
} else if (Bangle.isLCDOn()) { } else if (Bangle.isLCDOn()) {
WIDGETS["weather"].draw(); WIDGETS.weather.draw();
} else { } else {
dirty = true; dirty = true;
} }
} }
else { else {
WIDGETS["weather"].width = 0; WIDGETS.weather.width = 0;
Bangle.drawWidgets(); Bangle.drawWidgets();
} }
}); });
Bangle.on('lcdPower', on => { Bangle.on("lcdPower", on => {
if (on && dirty && !setting('hide')) { if (on && dirty && !setting("hide")) {
WIDGETS["weather"].draw(); WIDGETS.weather.draw();
dirty = false; dirty = false;
} }
}); });
WIDGETS["weather"] = { WIDGETS.weather = {
area: "tl", area: "tl",
width: weather.get() && !setting('hide') ? 20 : 0, width: weather.get() && !setting("hide") ? 20 : 0,
draw: function() { draw: function() {
if (setting('hide')) return; if (setting("hide")) return;
const w = weather.get(); const w = weather.get();
if (!w) return; if (!w) return;
g.reset(); g.reset();
@ -56,17 +56,17 @@
weather.drawIcon(w, this.x+10, this.y+8, 7.5); weather.drawIcon(w, this.x+10, this.y+8, 7.5);
} }
if (w.temp) { 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 t = t.match(/[\d\-]*/)[0]; // but we have no room for units
g.reset(); g.reset();
g.setFontAlign(0, 1); // center horizontally at bottom of widget 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); g.drawString(t, this.x+10, this.y+24);
} }
}, },
reload:function() { reload:() => {
loadSettings(); loadSettings();
WIDGETS["weather"].redraw(); WIDGETS.weather.redraw();
}, },
}; };
})(); })();

View File

@ -0,0 +1 @@
v0.01: New app!

View File

@ -0,0 +1,12 @@
# Smart Battery Widget
Shows battery in terms of days (21 days, 12 hours), and uses the [`smartbatt`](https://banglejs.com/apps/?id=smartbatt) module to learn from daily battery drainage and provide accurate estimations.
This app was modified from `wid_a_battery_widget`, by @alainsaas
When you install this widget for the first time, or clear the data, it will also install the [`smartbatt`](https://banglejs.com/apps/?id=smartbatt) module as a dependency. As it learns your battery usage for the first time the forecast will fluctate, and will not be reliable for a while. As it compunds many drainage values together, it will keep learning, and provide better predictions.
The module learns by averaging all the battery drainage over a period of time, and saves it to a json, averaging it with many others, providing an accurate prediction. The module gives the best forecast when you use the watch relatively similar per day.
Tap on the widget to show the battery percentage. It will go back to the days left after 3 seconds.
When charging, only the percentage is shown.
## Creator
RKBoss6

BIN
apps/widsmartbatt/icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

View File

@ -0,0 +1,17 @@
{
"id": "widsmartbatt",
"name": "Smart Battery Widget",
"shortName":"Smart Batt Wid",
"icon": "icon.png",
"version":"0.01",
"type": "widget",
"supports": ["BANGLEJS", "BANGLEJS2"],
"readme": "README.md",
"dependencies" : { "smartbatt":"module" },
"description": "Simple and slim battery widget that shows days remaining, and uses the `smartbatt` module to learm from your usage and provide accurate predictions.",
"tags": "widget,battery",
"provides_widgets" : ["battery"],
"storage": [
{"name":"widsmartbatt.wid.js","url":"widget.js"}
]
}

View File

@ -0,0 +1,90 @@
(function(){
var showPercent = false;
const width = 40;
const height = 24;
let COLORS = {
'bg': g.theme.bg,
'fg': g.theme.fg,
'charging': "#08f",
'high': g.theme.dark ? "#fff" : "#000",
'low': "#f00",
};
const levelColor = (l) => {
if (Bangle.isCharging()) return COLORS.charging;
if (l >= 30) return COLORS.high;
return COLORS.low;
};
function draw() {
let batt=E.getBattery();
let data = require("smartbatt").get();
let hrsLeft=data.hrsLeft;
let days = hrsLeft / 24;
let txt = showPercent
? batt
: (days >= 1
? Math.round(Math.min(days, 99)) + "d"
: Math.round(hrsLeft) + "h");
if(Bangle.isCharging()) txt=E.getBattery();
let s = 29;
let x = this.x, y = this.y;
let xl = x + 4 + batt * (s - 12) / 100;
// Drawing code follows...
g.setColor(COLORS.bg);
g.fillRect(x + 2, y + 5, x + s - 6, y + 18);
g.setColor(levelColor(batt));
g.fillRect(x + 1, y + 3, x + s - 5, y + 4);
g.fillRect(x + 1, y + 19, x + s - 5, y + 20);
g.fillRect(x, y + 4, x + 1, y + 19);
g.fillRect(x + s - 5, y + 4, x + s - 4, y + 19);
g.fillRect(x + s - 3, y + 8, x + s - 2, y + 16);
g.fillRect(x + 4, y + 15, xl, y + 16);
g.setColor(COLORS.fg);
g.setFontAlign(0, 0);
g.setFont('6x8');
g.drawString(txt, x + 14, y + 10);
}
WIDGETS["widsmartbatt"] = {
area: "tr",
width: 30,
draw: draw
};
// Touch to temporarily show battery percent
Bangle.on("touch", function (_btn, xy) {
if (WIDGETS["back"] || !xy) return;
var oversize = 5;
var w = WIDGETS["widsmartbatt"];
var x = xy.x, y = xy.y;
if (w.x - oversize <= x && x < w.x + width + oversize
&& w.y - oversize <= y && y < w.y + height + oversize) {
E.stopEventPropagation && E.stopEventPropagation();
showPercent = true;
setTimeout(() => {
showPercent = false;
w.draw(w);
}, 3000);
w.draw(w);
}
});
// Update widget on charging state change
Bangle.on('charging', function () {
WIDGETS["widsmartbatt"].draw();
});
setInterval(() => WIDGETS["widsmartbatt"].draw(), 60000);
})();