├── resources ├── icon.psd ├── banner.png ├── banner.psd ├── icon~bw.png ├── img │ ├── bt.png │ ├── mute.png │ ├── mute.psd │ └── bt-disconnect.png └── icon~color.png ├── screenshot ├── composite_color.sh ├── snowy-red.png ├── steel-black.png ├── v1.14.0 │ ├── bw.png │ ├── color.png │ ├── bw-composite.png │ └── color-composite.png ├── v1.7.0 │ ├── bw.png │ ├── color.png │ ├── bw-composite.png │ └── color-composite.png └── composite_bw.sh ├── src ├── c │ ├── appendix │ │ ├── app_message.h │ │ ├── math.h │ │ ├── math.c │ │ ├── config.h │ │ ├── persist.h │ │ ├── config.c │ │ ├── persist.c │ │ └── app_message.c │ ├── windows │ │ ├── main_window.h │ │ └── main_window.c │ ├── layers │ │ ├── battery_layer.h │ │ ├── loading_layer.h │ │ ├── calendar_layer.h │ │ ├── forecast_layer.h │ │ ├── weather_status_layer.h │ │ ├── time_layer.h │ │ ├── calendar_status_layer.h │ │ ├── loading_layer.c │ │ ├── battery_layer.c │ │ ├── time_layer.c │ │ ├── calendar_status_layer.c │ │ ├── weather_status_layer.c │ │ ├── calendar_layer.c │ │ └── forecast_layer.c │ └── watchface.c └── pkjs │ ├── clay │ ├── inject.js │ └── config.js │ ├── weather │ ├── openweathermap.js │ ├── wunderground.js │ └── provider.js │ └── index.js ├── .gitignore ├── RELEASE.md ├── .travis.yml ├── wscript ├── package.json ├── README.md └── LICENSE /resources/icon.psd: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mattrossman/forecaswatch2/HEAD/resources/icon.psd -------------------------------------------------------------------------------- /resources/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mattrossman/forecaswatch2/HEAD/resources/banner.png -------------------------------------------------------------------------------- /resources/banner.psd: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mattrossman/forecaswatch2/HEAD/resources/banner.psd -------------------------------------------------------------------------------- /resources/icon~bw.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mattrossman/forecaswatch2/HEAD/resources/icon~bw.png -------------------------------------------------------------------------------- /resources/img/bt.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mattrossman/forecaswatch2/HEAD/resources/img/bt.png -------------------------------------------------------------------------------- /screenshot/composite_color.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | composite -gravity Center $1 snowy-red.png $2 4 | -------------------------------------------------------------------------------- /src/c/appendix/app_message.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | void app_message_init(); -------------------------------------------------------------------------------- /resources/img/mute.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mattrossman/forecaswatch2/HEAD/resources/img/mute.png -------------------------------------------------------------------------------- /resources/img/mute.psd: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mattrossman/forecaswatch2/HEAD/resources/img/mute.psd -------------------------------------------------------------------------------- /resources/icon~color.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mattrossman/forecaswatch2/HEAD/resources/icon~color.png -------------------------------------------------------------------------------- /screenshot/snowy-red.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mattrossman/forecaswatch2/HEAD/screenshot/snowy-red.png -------------------------------------------------------------------------------- /screenshot/steel-black.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mattrossman/forecaswatch2/HEAD/screenshot/steel-black.png -------------------------------------------------------------------------------- /screenshot/v1.14.0/bw.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mattrossman/forecaswatch2/HEAD/screenshot/v1.14.0/bw.png -------------------------------------------------------------------------------- /screenshot/v1.7.0/bw.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mattrossman/forecaswatch2/HEAD/screenshot/v1.7.0/bw.png -------------------------------------------------------------------------------- /screenshot/composite_bw.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | composite -gravity Center -geometry +0-15 $1 steel-black.png $2 4 | -------------------------------------------------------------------------------- /screenshot/v1.14.0/color.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mattrossman/forecaswatch2/HEAD/screenshot/v1.14.0/color.png -------------------------------------------------------------------------------- /screenshot/v1.7.0/color.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mattrossman/forecaswatch2/HEAD/screenshot/v1.7.0/color.png -------------------------------------------------------------------------------- /resources/img/bt-disconnect.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mattrossman/forecaswatch2/HEAD/resources/img/bt-disconnect.png -------------------------------------------------------------------------------- /screenshot/v1.14.0/bw-composite.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mattrossman/forecaswatch2/HEAD/screenshot/v1.14.0/bw-composite.png -------------------------------------------------------------------------------- /screenshot/v1.7.0/bw-composite.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mattrossman/forecaswatch2/HEAD/screenshot/v1.7.0/bw-composite.png -------------------------------------------------------------------------------- /screenshot/v1.14.0/color-composite.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mattrossman/forecaswatch2/HEAD/screenshot/v1.14.0/color-composite.png -------------------------------------------------------------------------------- /screenshot/v1.7.0/color-composite.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mattrossman/forecaswatch2/HEAD/screenshot/v1.7.0/color-composite.png -------------------------------------------------------------------------------- /src/c/appendix/math.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | void min_max(int16_t *array, int n, int *min, int *max); 6 | 7 | int f_to_c(int temp_f); -------------------------------------------------------------------------------- /src/c/windows/main_window.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | void main_window_create(); 6 | 7 | void main_window_refresh(); 8 | 9 | void main_window_destroy(); -------------------------------------------------------------------------------- /src/c/layers/battery_layer.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | void battery_layer_create(Layer* parent_layer, GRect frame); 6 | 7 | void battery_layer_refresh(); 8 | 9 | void battery_layer_destroy(); -------------------------------------------------------------------------------- /src/c/layers/loading_layer.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | void loading_layer_create(Layer* parent_layer, GRect frame); 6 | 7 | void loading_layer_refresh(); 8 | 9 | void loading_layer_destroy(); -------------------------------------------------------------------------------- /src/c/layers/calendar_layer.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | void calendar_layer_create(Layer* parent_layer, GRect frame); 6 | 7 | void calendar_layer_refresh(); 8 | 9 | void calendar_layer_destroy(); -------------------------------------------------------------------------------- /src/c/layers/forecast_layer.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | void forecast_layer_create(Layer *parent_layer, GRect frame); 6 | 7 | void forecast_layer_refresh(); 8 | 9 | void forecast_layer_destroy(); -------------------------------------------------------------------------------- /src/c/layers/weather_status_layer.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | void weather_status_layer_create(Layer* parent_layer, GRect frame); 6 | 7 | void weather_status_layer_refresh(); 8 | 9 | void weather_status_layer_destroy(); -------------------------------------------------------------------------------- /src/c/layers/time_layer.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | void time_layer_create(Layer* parent_layer, GRect frame); 6 | 7 | void time_layer_tick(); 8 | 9 | void time_layer_refresh(); 10 | 11 | void time_layer_destroy(); -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .* 2 | !.gitignore 3 | !.travis.yml 4 | build 5 | src/pkjs/dev-config.js 6 | screenshot/* 7 | !screenshot/snowy-red.png 8 | !screenshot/steel-black.png 9 | !screenshot/composite_bw.sh 10 | !screenshot/composite_color.sh 11 | !screenshot/**/ 12 | node_modules 13 | -------------------------------------------------------------------------------- /RELEASE.md: -------------------------------------------------------------------------------- 1 | ## Tagging 2 | ```bash 3 | git tag -a v1.0.0 -m "v1.0.0" 4 | ``` 5 | 6 | ```bash 7 | git push --atomic origin master v1.0.0 8 | ``` 9 | 10 | ## Publishing 11 | 12 | Clear `build/` folder before running build to prevent stale version appearing on config page. 13 | 14 | Watchface file is found at `build/forecaswatch2.pbw` 15 | 16 | To upload to Rebble store: 17 | https://dev-portal.rebble.io/ -------------------------------------------------------------------------------- /src/c/layers/calendar_status_layer.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | void calendar_status_layer_create(Layer* parent_layer, GRect frame); 6 | 7 | void status_icons_refresh(); 8 | 9 | void bluetooth_icons_refresh(bool connected); 10 | 11 | void bluetooth_callback(bool connected); 12 | 13 | bool show_qt_icon(); 14 | 15 | void calendar_status_layer_refresh(); 16 | 17 | void calendar_status_layer_destroy(); -------------------------------------------------------------------------------- /src/c/watchface.c: -------------------------------------------------------------------------------- 1 | #include 2 | #include "windows/main_window.h" 3 | #include "appendix/app_message.h" 4 | #include "appendix/persist.h" 5 | #include "appendix/config.h" 6 | 7 | 8 | static void init() { 9 | app_message_init(); 10 | persist_init(); 11 | config_load(); 12 | main_window_create(); 13 | } 14 | 15 | static void deinit() { 16 | config_unload(); 17 | main_window_destroy(); 18 | } 19 | 20 | int main(void) { 21 | init(); 22 | app_event_loop(); 23 | deinit(); 24 | } 25 | -------------------------------------------------------------------------------- /src/c/appendix/math.c: -------------------------------------------------------------------------------- 1 | #include "math.h" 2 | #include 3 | #include "config.h" 4 | #include "persist.h" 5 | 6 | void min_max(int16_t *array, int n, int *min, int *max) { 7 | // It is assumed that the array has at least one element 8 | *min = array[0]; 9 | *max = array[0]; 10 | for (int i = 1; i < n; ++i) { 11 | if (array[i] < *min) { 12 | *min = array[i]; 13 | } 14 | else if (array[i] > *max) { 15 | *max = array[i]; 16 | } 17 | } 18 | } 19 | 20 | int roundFloat(float num) 21 | { 22 | return num < 0 ? num - 0.5 : num + 0.5; 23 | } 24 | 25 | 26 | int f_to_c(int temp_f) { 27 | // Convert a fahrenheit temperature to celcius 28 | return roundFloat((temp_f - 32) * 5.0 / 9); 29 | } -------------------------------------------------------------------------------- /src/c/appendix/config.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | typedef struct { 6 | bool celsius; 7 | bool time_lead_zero; 8 | bool axis_12h; 9 | bool start_mon; 10 | bool prev_week; 11 | bool show_qt; 12 | bool show_bt; 13 | bool show_bt_disconnect; 14 | bool vibe; 15 | bool show_am_pm; 16 | int16_t time_font; 17 | GColor color_today; 18 | GColor color_saturday; 19 | GColor color_sunday; 20 | GColor color_us_federal; 21 | GColor color_time; 22 | } Config; 23 | 24 | Config *g_config; 25 | 26 | void config_load(); 27 | 28 | void config_refresh(); 29 | 30 | void config_unload(); 31 | 32 | int config_localize_temp(int temp_f); 33 | 34 | int config_format_time(char *s, size_t maxsize, const struct tm * tm_p); 35 | 36 | int config_axis_hour(int hour); 37 | 38 | int config_n_today(); 39 | 40 | GFont config_time_font(); 41 | 42 | bool config_highlight_holidays(); 43 | 44 | bool config_highlight_sundays(); 45 | 46 | bool config_highlight_saturdays(); -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: minimal 2 | 3 | services: 4 | - docker 5 | 6 | before_install: 7 | - docker pull dmorgan81/rebble 8 | 9 | script: 10 | - docker run -u $(id -u):$(id -g) --rm -it -v $(pwd):/work dmorgan81/rebble build 11 | 12 | before_deploy: 13 | - mv build/work.pbw build/forecaswatch2.pbw 14 | 15 | deploy: 16 | provider: releases 17 | api_key: 18 | secure: ljM3XjpVbVFciui3ZPR6KpgcHf3gwD6hAZ4PHpIW67rM2FrNjOtBXs0RArE71RJO8N6aVnDWOa0abtfZWcTN2c4/o9Xo4+T8puGWbMGGLVV4JpM5nUgokzRySXR41a4awsuLozW1BSFGaN34S41YLUOQ+eXOAanZ2JqZlYeRLaQDAYUWuFmfWYgStlvYaDkuSx5pmdq4Of3qLan+jeEo/f47hVBi7HkPHjAasDxP1fKmEYmwwMg2lXSXKiwkMvUdPqaUtmcEbtEMxpUwxqwZWa0O1VHOgx+r8/aE7R2ZXe1N8iexJKBFY1OYNlhajUKESwCBC5oiB8VKWyPqNyUb+tMEDYaHqBITbzJx0TsyN9ujLpvDYuKzvohMzBh5HXQcBIjgeeps0P/zottYFZgCqzzXKKvBJTeMajjJ7bmMZnph7aK+Dv2GFdE3/VZLghxO+2y9ITPdNYgFAcUwoK4jJ+2gu/X4eBp09s8A29Kmww343n03LDAV0YXTY0dKHH7zbhwmxfFQ5DwJUdb04j1hLBo3mvX3BUpTnd1THCSI6qZsi3MHNyhy/DT++HFXKs52+QLouvKM539QTz9B7D3XeOGU/crNFbBmDXA72gkxjWIUJql7b4Y2XOQeo6xCcK9C2KYi7KIGpfqEeJGQgu8EfSB96XIN73SAd7MiaHK0hns= 19 | file: build/forecaswatch2.pbw 20 | skip_cleanup: true 21 | draft: true 22 | on: 23 | tags: true -------------------------------------------------------------------------------- /src/c/appendix/persist.h: -------------------------------------------------------------------------------- 1 | #pragma once 2 | 3 | #include 4 | 5 | #include "config.h" 6 | 7 | void persist_init(); 8 | 9 | int persist_get_temp_lo(); 10 | 11 | int persist_get_temp_hi(); 12 | 13 | int persist_get_temp_trend(int16_t *buffer, const size_t buffer_size); 14 | 15 | int persist_get_precip_trend(uint8_t *buffer, const size_t buffer_size); 16 | 17 | time_t persist_get_forecast_start(); 18 | 19 | int persist_get_num_entries(); 20 | 21 | int persist_get_current_temp(); 22 | 23 | int persist_get_city(char *buffer, const size_t buffer_size); 24 | 25 | int persist_get_sun_event_start_type(); 26 | 27 | int persist_get_sun_event_times(time_t *buffer, const size_t buffer_size); 28 | 29 | int persist_get_config(Config *config); 30 | 31 | void persist_set_temp_lo(int val); 32 | 33 | void persist_set_temp_hi(int val); 34 | 35 | void persist_set_temp_trend(int16_t *data, const size_t size); 36 | 37 | void persist_set_precip_trend(uint8_t *data, const size_t size); 38 | 39 | void persist_set_forecast_start(time_t val); 40 | 41 | void persist_set_num_entries(int val); 42 | 43 | void persist_set_current_temp(int val); 44 | 45 | void persist_set_city(char *val); 46 | 47 | void persist_set_sun_event_start_type(int val); 48 | 49 | void persist_set_sun_event_times(time_t *data, const size_t size); 50 | 51 | void persist_set_config(Config config); -------------------------------------------------------------------------------- /src/c/layers/loading_layer.c: -------------------------------------------------------------------------------- 1 | #include "loading_layer.h" 2 | #include "c/appendix/persist.h" 3 | 4 | static Layer *s_loading_layer; 5 | static TextLayer *s_loading_text_layer; 6 | 7 | static void loading_update_proc(Layer *layer, GContext *ctx) { 8 | GRect bounds = layer_get_bounds(layer); 9 | int w = bounds.size.w; 10 | int h = bounds.size.h; 11 | 12 | // Black out the weather components 13 | graphics_context_set_fill_color(ctx, GColorBlack); 14 | graphics_fill_rect(ctx, GRect(0, 0, w, h), 0, GCornerNone); 15 | } 16 | 17 | void loading_layer_create(Layer* parent_layer, GRect frame) { 18 | s_loading_layer = layer_create(frame); 19 | 20 | GRect bounds = layer_get_bounds(s_loading_layer); 21 | int w = bounds.size.w; int h = bounds.size.h; 22 | s_loading_text_layer = text_layer_create(GRect(0, h / 3, w, h)); 23 | text_layer_set_background_color(s_loading_text_layer, GColorClear); 24 | text_layer_set_text_color(s_loading_text_layer, GColorWhite); 25 | text_layer_set_font(s_loading_text_layer, fonts_get_system_font(FONT_KEY_GOTHIC_18)); 26 | text_layer_set_text_alignment(s_loading_text_layer, GTextAlignmentCenter); 27 | text_layer_set_text(s_loading_text_layer, "No data :("); 28 | 29 | layer_set_update_proc(s_loading_layer, loading_update_proc); 30 | layer_add_child(s_loading_layer, text_layer_get_layer(s_loading_text_layer)); 31 | layer_add_child(parent_layer, s_loading_layer); 32 | } 33 | 34 | void loading_layer_refresh() { 35 | const time_t forecast_start = persist_get_forecast_start(); 36 | const time_t now = time(NULL); 37 | if (now - forecast_start > 60 * 60 * 12) // 60 sec/min * 60 min/h * 12h 38 | layer_set_hidden(s_loading_layer, false); // show the no data notice 39 | else 40 | layer_set_hidden(s_loading_layer, true); // hide the no data notice 41 | } 42 | 43 | void loading_layer_destroy() { 44 | layer_destroy(s_loading_layer); 45 | text_layer_destroy(s_loading_text_layer); 46 | } -------------------------------------------------------------------------------- /wscript: -------------------------------------------------------------------------------- 1 | # 2 | # This file is the default set of rules to compile a Pebble application. 3 | # 4 | # Feel free to customize this to your needs. 5 | # 6 | import os.path 7 | 8 | top = '.' 9 | out = 'build' 10 | 11 | 12 | def options(ctx): 13 | ctx.load('pebble_sdk') 14 | 15 | 16 | def configure(ctx): 17 | """ 18 | This method is used to configure your build. ctx.load(`pebble_sdk`) automatically configures 19 | a build for each valid platform in `targetPlatforms`. Platform-specific configuration: add your 20 | change after calling ctx.load('pebble_sdk') and make sure to set the correct environment first. 21 | Universal configuration: add your change prior to calling ctx.load('pebble_sdk'). 22 | """ 23 | ctx.load('pebble_sdk') 24 | 25 | 26 | def build(ctx): 27 | ctx.load('pebble_sdk') 28 | 29 | build_worker = os.path.exists('worker_src') 30 | binaries = [] 31 | 32 | cached_env = ctx.env 33 | for platform in ctx.env.TARGET_PLATFORMS: 34 | ctx.env = ctx.all_envs[platform] 35 | ctx.set_group(ctx.env.PLATFORM_NAME) 36 | app_elf = '{}/pebble-app.elf'.format(ctx.env.BUILD_DIR) 37 | ctx.pbl_build(source=ctx.path.ant_glob('src/c/**/*.c'), target=app_elf, bin_type='app') 38 | 39 | if build_worker: 40 | worker_elf = '{}/pebble-worker.elf'.format(ctx.env.BUILD_DIR) 41 | binaries.append({'platform': platform, 'app_elf': app_elf, 'worker_elf': worker_elf}) 42 | ctx.pbl_build(source=ctx.path.ant_glob('worker_src/c/**/*.c'), 43 | target=worker_elf, 44 | bin_type='worker') 45 | else: 46 | binaries.append({'platform': platform, 'app_elf': app_elf}) 47 | ctx.env = cached_env 48 | 49 | ctx.set_group('bundle') 50 | ctx.pbl_bundle(binaries=binaries, 51 | js=ctx.path.ant_glob(['src/pkjs/**/*.js', 52 | 'src/pkjs/**/*.json', 53 | 'src/common/**/*.js']), 54 | js_entry_file='src/pkjs/index.js') 55 | -------------------------------------------------------------------------------- /src/pkjs/clay/inject.js: -------------------------------------------------------------------------------- 1 | module.exports = function (minified) { 2 | clayConfig = this; 3 | var $ = minified.$; 4 | 5 | clayConfig.on(clayConfig.EVENTS.AFTER_BUILD, function() { 6 | var clayFetch = clayConfig.getItemByMessageKey('fetch'); 7 | clayFetch.set(false); 8 | 9 | // Save initial states to detect changes to provider 10 | var clayOwmApiKey = clayConfig.getItemByMessageKey('owmApiKey'); 11 | var clayProvider = clayConfig.getItemByMessageKey('provider'); 12 | var clayLocation = clayConfig.getItemByMessageKey('location'); 13 | var initProvider = clayProvider.get(); 14 | var initOwmApiKey = clayOwmApiKey.get(); 15 | var initLocation = clayLocation.get(); 16 | 17 | // Configure default provide section layout 18 | if (initProvider !== 'openweathermap') { 19 | clayOwmApiKey.hide() 20 | } 21 | 22 | // Configure logic for updating the provider section layout 23 | clayProvider.on('change', function() { 24 | if (this.get() === 'openweathermap') { 25 | clayOwmApiKey.show(); 26 | } 27 | else { 28 | clayOwmApiKey.hide(); 29 | } 30 | console.log('Provider set to ' + this.get()); 31 | }) 32 | 33 | // Show last weather fetch status 34 | var lastFetchSuccessString = clayConfig.meta.userData.lastFetchSuccess; 35 | if (lastFetchSuccessString !== null) { 36 | var lastFetchSuccess = JSON.parse(lastFetchSuccessString); 37 | var date = new Date(lastFetchSuccess.time); 38 | $('#lastFetchSpan').ht(date.toLocaleDateString() + ' ' + date.toLocaleTimeString() + ' with ' + lastFetchSuccess.name); 39 | } 40 | 41 | // Override submit handler to force re-fetch if provider config changed 42 | $('#main-form').on('submit', function() { 43 | if (clayProvider.get() !== initProvider 44 | || clayOwmApiKey.get() !== initOwmApiKey 45 | || clayLocation.get() !== initLocation) { 46 | clayFetch.set(true); 47 | } 48 | 49 | // Copied from original handler ($.off requires non-anonymous handler) 50 | var returnTo = window.returnTo || 'pebblejs://close#'; 51 | location.href = returnTo + 52 | encodeURIComponent(JSON.stringify(clayConfig.serialize())); 53 | }) 54 | }); 55 | }; -------------------------------------------------------------------------------- /src/c/layers/battery_layer.c: -------------------------------------------------------------------------------- 1 | #include "battery_layer.h" 2 | #include "c/appendix/persist.h" 3 | 4 | #define BATTERY_NUB_W 2 5 | #define BATTERY_NUB_H 6 6 | #define BATTERY_STROKE 1 7 | #define FILL_PADDING 1 8 | 9 | 10 | static Layer *s_battery_layer; 11 | 12 | static void battery_state_handler(BatteryChargeState charge) { 13 | battery_layer_refresh(); 14 | } 15 | 16 | static GColor get_battery_color(int level) { 17 | if (level >= 50) 18 | return GColorGreen; 19 | else if (level >= 30) 20 | return GColorYellow; 21 | else 22 | return GColorRed; 23 | } 24 | 25 | static void battery_update_proc(Layer *layer, GContext *ctx) { 26 | GRect bounds = layer_get_bounds(layer); 27 | int w = bounds.size.w; 28 | int h = bounds.size.h; 29 | int battery_w = w - BATTERY_NUB_W; 30 | BatteryChargeState battery_state = battery_state_service_peek(); 31 | int battery_level = battery_state.charge_percent; 32 | 33 | // Fill the battery level 34 | GRect color_bounds = GRect( 35 | BATTERY_STROKE + FILL_PADDING, BATTERY_STROKE + FILL_PADDING, 36 | battery_w - (BATTERY_STROKE + FILL_PADDING) * 2, h - (BATTERY_STROKE + FILL_PADDING) * 2); 37 | GRect color_area = GRect( 38 | color_bounds.origin.x, color_bounds.origin.y, 39 | color_bounds.size.w * (float) (battery_level + 10) / (100.0 + 10), color_bounds.size.h); 40 | graphics_context_set_fill_color(ctx, PBL_IF_COLOR_ELSE(get_battery_color(battery_level), GColorWhite)); 41 | graphics_fill_rect(ctx, color_area, 0, GCornerNone); 42 | 43 | // Draw the white battery outline 44 | graphics_context_set_stroke_color(ctx, GColorWhite); 45 | graphics_context_set_stroke_width(ctx, BATTERY_STROKE); 46 | graphics_draw_rect(ctx, GRect(0, 0, battery_w, h)); 47 | 48 | // Draw the battery nub on the right 49 | graphics_draw_rect(ctx, GRect(battery_w - 1, h / 2 - BATTERY_NUB_H / 2, BATTERY_NUB_W + 1, BATTERY_NUB_H)); 50 | } 51 | 52 | void battery_layer_create(Layer* parent_layer, GRect frame) { 53 | s_battery_layer = layer_create(frame); 54 | layer_set_update_proc(s_battery_layer, battery_update_proc); 55 | battery_state_service_subscribe(battery_state_handler); 56 | layer_add_child(parent_layer, s_battery_layer); 57 | } 58 | 59 | void battery_layer_refresh() { 60 | layer_mark_dirty(s_battery_layer); 61 | } 62 | 63 | void battery_layer_destroy() { 64 | battery_state_service_unsubscribe(); 65 | layer_destroy(s_battery_layer); 66 | } 67 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "forecaswatch2", 3 | "author": "Matt Rossman", 4 | "version": "1.24.0", 5 | "keywords": [ 6 | "pebble-app" 7 | ], 8 | "private": true, 9 | "scripts": { 10 | "start": "docker run -dit --name=forecaswatch2 --platform=linux/amd64 -v $PWD:/forecaswatch2 rebble/pebble-sdk", 11 | "stop": "docker rm -f forecaswatch2", 12 | "shell": "docker exec -it -w /forecaswatch2 forecaswatch2 bash", 13 | "build": "docker exec -w /forecaswatch2 forecaswatch2 bash -c \"pebble build\"" 14 | }, 15 | "dependencies": { 16 | "suncalc": "^1.9.0" 17 | }, 18 | "pebble": { 19 | "displayName": "FCW2", 20 | "uuid": "7ed9b053-1521-4e49-be8b-6e12c68978ae", 21 | "sdkVersion": "3", 22 | "enableMultiJS": true, 23 | "targetPlatforms": [ 24 | "aplite", 25 | "basalt", 26 | "diorite" 27 | ], 28 | "watchapp": { 29 | "watchface": true 30 | }, 31 | "resources": { 32 | "media": [ 33 | { 34 | "menuIcon": true, 35 | "type": "png", 36 | "name": "IMAGE_MENU_ICON", 37 | "file": "icon.png" 38 | }, 39 | { 40 | "type": "bitmap", 41 | "name": "IMAGE_MUTE", 42 | "file": "img/mute.png", 43 | "memoryFormat": "1BitPalette" 44 | }, 45 | { 46 | "type": "bitmap", 47 | "name": "IMAGE_BT_DISCONNECT", 48 | "file": "img/bt-disconnect.png", 49 | "memoryFormat": "1BitPalette" 50 | }, 51 | { 52 | "type": "bitmap", 53 | "name": "IMAGE_BT_CONNECT", 54 | "file": "img/bt.png", 55 | "memoryFormat": "1BitPalette" 56 | } 57 | ] 58 | }, 59 | "capabilities": [ 60 | "location", 61 | "configurable" 62 | ], 63 | "messageKeys": [ 64 | "TEMP_TREND_INT16", 65 | "PRECIP_TREND_UINT8", 66 | "FORECAST_START", 67 | "NUM_ENTRIES", 68 | "CURRENT_TEMP", 69 | "CITY", 70 | "SUN_EVENTS", 71 | "CLAY_CELSIUS", 72 | "CLAY_TIME_LEAD_ZERO", 73 | "CLAY_AXIS_12H", 74 | "CLAY_START_MON", 75 | "CLAY_COLOR_TODAY", 76 | "CLAY_PREV_WEEK", 77 | "CLAY_TIME_FONT", 78 | "CLAY_SHOW_QT", 79 | "CLAY_SHOW_BT", 80 | "CLAY_SHOW_BT_DISCONNECT", 81 | "CLAY_VIBE", 82 | "CLAY_SHOW_AM_PM", 83 | "CLAY_COLOR_SATURDAY", 84 | "CLAY_COLOR_SUNDAY", 85 | "CLAY_COLOR_US_FEDERAL", 86 | "CLAY_COLOR_TIME" 87 | ] 88 | } 89 | } 90 | -------------------------------------------------------------------------------- /src/c/appendix/config.c: -------------------------------------------------------------------------------- 1 | #include "config.h" 2 | #include "persist.h" 3 | #include "math.h" 4 | 5 | // NOTE: g_config is a global config variable 6 | 7 | void config_load() { 8 | g_config = (Config*) malloc(sizeof(Config)); 9 | persist_get_config(g_config); 10 | } 11 | 12 | void config_refresh() { 13 | free(g_config); // Clear out the old config 14 | g_config = (Config*) malloc(sizeof(Config)); 15 | persist_get_config(g_config); // Then reload 16 | } 17 | 18 | void config_unload() { 19 | free(g_config); 20 | } 21 | 22 | int config_localize_temp(int temp_f) { 23 | // Convert temperatures as desired 24 | int result; 25 | if (g_config->celsius) 26 | result = f_to_c(temp_f); 27 | else 28 | result = temp_f; 29 | return result; 30 | } 31 | 32 | int config_format_time(char *s, size_t maxsize, const struct tm * tm_p) { 33 | int res = strftime(s, maxsize, clock_is_24h_style() ? "%H:%M" : "%I:%M", tm_p); 34 | if (!g_config->time_lead_zero) { 35 | // Remove leading zero if configured as such 36 | if (s[0] == '0') 37 | memmove(s, s+1, strlen(s)); 38 | } 39 | return res; 40 | } 41 | 42 | int config_axis_hour(int hour) { 43 | if (g_config->axis_12h) { 44 | hour = hour % 12; 45 | hour = hour == 0 ? 12 : hour; 46 | } 47 | else 48 | hour = hour % 24; 49 | return hour; 50 | } 51 | 52 | int config_n_today() { 53 | // Returns the index of the calendar box that holds today's date 54 | 55 | time_t today = time(NULL); 56 | struct tm *tm_today = localtime(&today); 57 | int wday = tm_today->tm_wday; 58 | // Offset if user wants to start the week on monday 59 | wday = g_config->start_mon ? (wday + 6) % 7 : wday; 60 | // Offset if user wants to show the previous week first 61 | if (g_config->prev_week) 62 | wday += 7; 63 | return wday; 64 | } 65 | 66 | GFont config_time_font() { 67 | const char *font_keys[] = { 68 | FONT_KEY_ROBOTO_BOLD_SUBSET_49, 69 | FONT_KEY_LECO_42_NUMBERS, 70 | FONT_KEY_BITHAM_42_MEDIUM_NUMBERS 71 | }; 72 | int16_t font_index = g_config->time_font; 73 | return fonts_get_system_font(font_keys[font_index]); 74 | } 75 | 76 | bool config_highlight_holidays() { 77 | return !gcolor_equal(g_config->color_us_federal, GColorWhite); 78 | } 79 | 80 | bool config_highlight_sundays() { 81 | return !gcolor_equal(g_config->color_sunday, GColorWhite); 82 | } 83 | 84 | bool config_highlight_saturdays() { 85 | return !gcolor_equal(g_config->color_saturday, GColorWhite); 86 | } 87 | -------------------------------------------------------------------------------- /src/c/windows/main_window.c: -------------------------------------------------------------------------------- 1 | #include "main_window.h" 2 | #include "c/layers/time_layer.h" 3 | #include "c/layers/forecast_layer.h" 4 | #include "c/layers/weather_status_layer.h" 5 | #include "c/layers/calendar_layer.h" 6 | #include "c/layers/calendar_status_layer.h" 7 | #include "c/layers/loading_layer.h" 8 | #include "c/appendix/persist.h" 9 | 10 | #define FORECAST_HEIGHT 51 11 | #define WEATHER_STATUS_HEIGHT 14 12 | #define TIME_HEIGHT 45 13 | #define CALENDAR_HEIGHT 45 14 | #define CALENDAR_STATUS_HEIGHT 13 15 | 16 | static Window *s_main_window; 17 | 18 | static void main_window_load(Window *window) { 19 | // Get information about the Window 20 | Layer *window_layer = window_get_root_layer(window); 21 | GRect bounds = layer_get_bounds(window_layer); 22 | int w = bounds.size.w; 23 | int h = bounds.size.h; 24 | window_set_background_color(window, GColorBlack); 25 | 26 | forecast_layer_create(window_layer, 27 | GRect(0, h - FORECAST_HEIGHT, w, FORECAST_HEIGHT)); 28 | weather_status_layer_create(window_layer, 29 | GRect(0, h - FORECAST_HEIGHT - WEATHER_STATUS_HEIGHT, w, WEATHER_STATUS_HEIGHT)); 30 | time_layer_create(window_layer, 31 | GRect(0, h - FORECAST_HEIGHT - WEATHER_STATUS_HEIGHT - TIME_HEIGHT, 32 | bounds.size.w, TIME_HEIGHT)); 33 | calendar_layer_create(window_layer, 34 | GRect(0, CALENDAR_STATUS_HEIGHT, bounds.size.w, CALENDAR_HEIGHT)); 35 | calendar_status_layer_create(window_layer, 36 | GRect(0, 0, bounds.size.w, CALENDAR_STATUS_HEIGHT + 1)); // +1 to stop text clipping 37 | loading_layer_create(window_layer, 38 | GRect(0, h - FORECAST_HEIGHT - WEATHER_STATUS_HEIGHT, w, FORECAST_HEIGHT + WEATHER_STATUS_HEIGHT)); 39 | loading_layer_refresh(); 40 | } 41 | 42 | static void main_window_unload(Window *window) { 43 | time_layer_destroy(); 44 | weather_status_layer_destroy(); 45 | forecast_layer_destroy(); 46 | calendar_layer_destroy(); 47 | calendar_status_layer_destroy(); 48 | loading_layer_destroy(); 49 | } 50 | 51 | static void minute_handler(struct tm *tick_time, TimeUnits units_changed) { 52 | time_layer_tick(); 53 | if (tick_time->tm_hour == 0) { 54 | calendar_layer_refresh(); 55 | calendar_status_layer_refresh(); 56 | } 57 | status_icons_refresh(); 58 | loading_layer_refresh(); 59 | } 60 | 61 | /*---------------------------- 62 | -------- EXTERNAL ------------ 63 | ----------------------------*/ 64 | 65 | void main_window_create() { 66 | // Create main Window element and assign to pointer 67 | s_main_window = window_create(); 68 | 69 | // Set handlers to manage the elements inside the Window 70 | window_set_window_handlers(s_main_window, (WindowHandlers) { 71 | .load = main_window_load, 72 | .unload = main_window_unload 73 | }); 74 | 75 | // Register with TickTimerService 76 | tick_timer_service_subscribe(MINUTE_UNIT, minute_handler); 77 | 78 | // Show the window on the watch with animated=true 79 | window_stack_push(s_main_window, true); 80 | time_layer_refresh(); 81 | } 82 | 83 | void main_window_refresh() { 84 | time_layer_refresh(); 85 | weather_status_layer_refresh(); 86 | forecast_layer_refresh(); 87 | calendar_layer_refresh(); 88 | calendar_status_layer_refresh(); 89 | } 90 | 91 | void main_window_destroy() { 92 | // Interface for destroying the main window (implicitly unloads contents) 93 | window_destroy(s_main_window); 94 | } -------------------------------------------------------------------------------- /src/c/layers/time_layer.c: -------------------------------------------------------------------------------- 1 | #include "time_layer.h" 2 | #include "c/appendix/config.h" 3 | 4 | // MT = Margin Top 5 | #define MT_TIME 14 6 | #define MT_AM_PM 7 7 | 8 | 9 | static TextLayer *s_container_layer; 10 | static TextLayer *s_time_layer; 11 | static TextLayer *s_am_pm_layer; 12 | 13 | void time_layer_create(Layer* parent_layer, GRect frame) { 14 | s_container_layer = text_layer_create(frame); 15 | s_time_layer = text_layer_create(GRect(0, 0, frame.size.w, frame.size.h)); 16 | s_am_pm_layer = text_layer_create(GRect(0, 0, 30, frame.size.h)); 17 | 18 | text_layer_set_background_color(s_container_layer, GColorClear); 19 | 20 | // Main time formatting 21 | text_layer_set_background_color(s_time_layer, GColorClear); 22 | text_layer_set_text(s_time_layer, "00:00"); 23 | text_layer_set_text_alignment(s_time_layer, GTextAlignmentLeft); 24 | 25 | // AM/PM formatting 26 | text_layer_set_font(s_am_pm_layer, fonts_get_system_font(FONT_KEY_GOTHIC_18)); 27 | text_layer_set_background_color(s_am_pm_layer, GColorClear); 28 | text_layer_set_text_color(s_am_pm_layer, GColorWhite); 29 | text_layer_set_text(s_am_pm_layer, "PM"); 30 | text_layer_set_text_alignment(s_am_pm_layer, GTextAlignmentLeft); 31 | 32 | layer_add_child(text_layer_get_layer(s_container_layer), text_layer_get_layer(s_time_layer)); 33 | layer_add_child(text_layer_get_layer(s_time_layer), text_layer_get_layer(s_am_pm_layer)); 34 | layer_add_child(parent_layer, text_layer_get_layer(s_container_layer)); 35 | 36 | } 37 | 38 | // 12:30 -> 12:30 39 | // 13:30 -> 1:30 40 | // 00:30 -> 12:30 41 | 42 | static void text_layer_move_frame(TextLayer *text_layer, GRect frame) { 43 | layer_set_frame(text_layer_get_layer(text_layer), frame); 44 | } 45 | 46 | void time_layer_tick() { 47 | // Get a tm structure 48 | time_t temp = time(NULL); 49 | struct tm *tick_time = localtime(&temp); 50 | 51 | // Format the time into a buffer 52 | static char s_buffer[8]; 53 | config_format_time(s_buffer, 8, tick_time); 54 | 55 | // Update the time and AM/PM indicator 56 | text_layer_set_text(s_time_layer, s_buffer); 57 | if (g_config->show_am_pm) 58 | text_layer_set_text(s_am_pm_layer, tick_time->tm_hour < 12 ? "AM" : "PM"); 59 | 60 | // Reposition everything 61 | GRect bounds = layer_get_bounds(text_layer_get_layer(s_container_layer)); 62 | text_layer_move_frame(s_time_layer, GRect(0, 0, bounds.size.w, bounds.size.h)); // Reset for size calculation 63 | GSize time_size = text_layer_get_content_size(s_time_layer); 64 | GSize am_pm_size = text_layer_get_content_size(s_am_pm_layer); 65 | 66 | // Calculate some landmarks 67 | int content_w = time_size.w + (g_config->show_am_pm ? am_pm_size.w : 0); 68 | int text_h = time_size.h - MT_TIME; // Remove top margin, approximately 69 | int text_top = -MT_TIME + (bounds.size.h/2 - text_h/2); 70 | int text_left = bounds.size.w / 2 - content_w / 2; 71 | 72 | // Update layer positions and visibility 73 | text_layer_move_frame(s_time_layer, GRect(text_left, text_top, content_w, time_size.h)); 74 | if (g_config->show_am_pm) 75 | text_layer_move_frame(s_am_pm_layer, GRect(time_size.w, MT_TIME - MT_AM_PM, 30, time_size.h)); 76 | layer_set_hidden(text_layer_get_layer(s_am_pm_layer), !g_config->show_am_pm); 77 | } 78 | 79 | void time_layer_refresh() { 80 | text_layer_set_font(s_time_layer, config_time_font()); 81 | text_layer_set_text_color(s_time_layer, PBL_IF_COLOR_ELSE(g_config->color_time, GColorWhite)); 82 | time_layer_tick(); // Update main time text and layer positions 83 | } 84 | 85 | void time_layer_destroy() { 86 | text_layer_destroy(s_time_layer); 87 | text_layer_destroy(s_container_layer); 88 | } -------------------------------------------------------------------------------- /src/pkjs/weather/openweathermap.js: -------------------------------------------------------------------------------- 1 | var WeatherProvider = require('./provider.js'); 2 | 3 | function request(url, type, callback) { 4 | var xhr = new XMLHttpRequest(); 5 | xhr.onload = function () { 6 | callback(this.responseText); 7 | }; 8 | xhr.open(type, url); 9 | xhr.send(); 10 | } 11 | 12 | var OpenWeatherMapProvider = function (apiKey) { 13 | this._super.call(this); 14 | this.name = 'OpenWeatherMap'; 15 | this.id = 'openweathermap'; 16 | this.apiKey = apiKey; 17 | this.weatherDataCache = null; 18 | console.log('Constructed with ' + apiKey); 19 | } 20 | 21 | OpenWeatherMapProvider.prototype = Object.create(WeatherProvider.prototype); 22 | OpenWeatherMapProvider.prototype.constructor = OpenWeatherMapProvider; 23 | OpenWeatherMapProvider.prototype._super = WeatherProvider; 24 | 25 | OpenWeatherMapProvider.prototype.withOwmResponse = function (lat, lon, callback) { 26 | var url = 'https://api.openweathermap.org/data/3.0/onecall?appid=' + this.apiKey + '&lat=' + lat + '&lon=' + lon + '&units=imperial&exclude=alerts,minutely'; 27 | 28 | console.log("Requesting " + url) 29 | 30 | request(url, 'GET', function (response) { 31 | var weatherData = JSON.parse(response); 32 | console.log('Found timezone: ' + weatherData.timezone); 33 | // cache weather data (use same request for sun events and weather forecast) 34 | this.weatherDataCache = weatherData; 35 | callback(weatherData); 36 | }); 37 | } 38 | 39 | OpenWeatherMapProvider.prototype.withWeatherData = function (lat, lon, callback) { 40 | if (this.weatherDataCache === null) { 41 | this.withOwmResponse(lat, lon, function (owmResponse) { 42 | callback(owmResponse); 43 | }); 44 | } else { 45 | callback(this.weatherDataCache); 46 | } 47 | } 48 | 49 | // ============== IMPORTANT OVERRIDE ================ 50 | OpenWeatherMapProvider.prototype.withSunEvents = function (lat, lon, callback) { 51 | console.log('This is the overridden implementation of withSunEvents') 52 | this.withOwmResponse(lat, lon, (function (owmResponse) { 53 | var days = owmResponse.daily; 54 | var sunEvents = [ 55 | { 'type': 'sunrise', 'date': new Date(days[0].sunrise * 1000) }, 56 | { 'type': 'sunset', 'date': new Date(days[0].sunset * 1000) }, 57 | { 'type': 'sunrise', 'date': new Date(days[1].sunrise * 1000) }, 58 | { 'type': 'sunset', 'date': new Date(days[1].sunset * 1000) } 59 | ] 60 | var now = new Date(); 61 | var nextSunEvents = sunEvents.filter(function (sunEvent) { 62 | return sunEvent.date > now; 63 | }); 64 | var next24HourSunEvents = nextSunEvents.slice(0, 2); 65 | console.log('The next ' + sunEvents[0].type + ' is at ' + sunEvents[0].date.toTimeString()); 66 | console.log('The next ' + sunEvents[1].type + ' is at ' + sunEvents[1].date.toTimeString()); 67 | callback(next24HourSunEvents); 68 | }).bind(this)); 69 | } 70 | 71 | OpenWeatherMapProvider.prototype.withProviderData = function (lat, lon, force, callback) { 72 | // callBack expects that this.hasValidData() will be true 73 | console.log('This is the overridden implementation of withProviderData') 74 | this.withWeatherData(lat, lon, (function (weatherData) { 75 | this.tempTrend = weatherData.hourly.map(function (entry) { 76 | return entry.temp; 77 | }) 78 | this.precipTrend = weatherData.hourly.map(function (entry) { 79 | return entry.pop; 80 | }) 81 | this.startTime = weatherData.hourly[0].dt; 82 | this.currentTemp = weatherData.current.temp; 83 | callback(); 84 | }).bind(this)) 85 | } 86 | 87 | module.exports = OpenWeatherMapProvider; -------------------------------------------------------------------------------- /src/pkjs/weather/wunderground.js: -------------------------------------------------------------------------------- 1 | var WeatherProvider = require('./provider.js'); 2 | 3 | function request(url, type, callback) { 4 | var xhr = new XMLHttpRequest(); 5 | xhr.onload = function() { 6 | callback(this.responseText); 7 | }; 8 | xhr.open(type, url); 9 | xhr.send(); 10 | } 11 | 12 | var WundergroundProvider = function() { 13 | this._super.call(this); 14 | this.name = 'Weather Underground'; 15 | this.id = 'wunderground'; 16 | } 17 | 18 | WundergroundProvider.prototype = Object.create(WeatherProvider.prototype); 19 | WundergroundProvider.prototype.constructor = WundergroundProvider; 20 | WundergroundProvider.prototype._super = WeatherProvider; 21 | 22 | WundergroundProvider.prototype.withWundergroundForecast = function(lat, lon, apiKey, callback) { 23 | // callback(wundergroundResponse) 24 | var url = 'https://api.weather.com/v1/geocode/' + lat + '/' + lon + '/forecast/hourly/48hour.json?apiKey=' + apiKey + '&language=en-US'; 25 | 26 | console.log("Requesting " + url) 27 | 28 | request(url, 'GET', function (response) { 29 | try { 30 | var weatherData = JSON.parse(response); 31 | callback(weatherData.forecasts); 32 | } catch (e) { 33 | console.error("Failed to parse Weather Underground forecast response, clearing potentially stale API key"); 34 | this.clearApiKey() 35 | throw e 36 | } 37 | }); 38 | } 39 | 40 | WundergroundProvider.prototype.withWundergroundCurrent = function(lat, lon, apiKey, callback) { 41 | // callback(wundergroundResponse) 42 | var url = 'https://api.weather.com/v3/wx/observations/current?language=en-US&units=e&format=json' 43 | + '&apiKey=' + apiKey 44 | + '&geocode=' + lat + ',' + lon; 45 | 46 | console.log("Requesting " + url) 47 | 48 | request(url, 'GET', (function (response) { 49 | try { 50 | var weatherData = JSON.parse(response); 51 | callback(weatherData.temperature); 52 | } catch (e) { 53 | console.error("Failed to parse Weather Underground current weather response, clearing potentially stale API key"); 54 | this.clearApiKey() 55 | throw e 56 | } 57 | }).bind(this)); 58 | } 59 | 60 | WundergroundProvider.prototype.clearApiKey = function() { 61 | localStorage.removeItem('wundergroundApiKey'); 62 | console.log("Cleared API key"); 63 | } 64 | 65 | WundergroundProvider.prototype.withApiKey = function(callback) { 66 | // callback(apiKey) 67 | 68 | var apiKey = localStorage.getItem('wundergroundApiKey'); 69 | 70 | if (apiKey === null) { 71 | console.log("Fetching Weather Underground API key"); 72 | 73 | var url = "https://www.wunderground.com/"; 74 | 75 | request(url, 'GET', function (response) { 76 | apiKey = response.match(/observations\/current\?apiKey=([a-z0-9]*)/)[1] 77 | localStorage.setItem('wundergroundApiKey', apiKey); 78 | console.log("Fetched Weather Underground API key: " + apiKey); 79 | 80 | callback(apiKey); 81 | }); 82 | } else { 83 | console.log("Using saved API key for Weather Underground"); 84 | callback(apiKey) 85 | } 86 | } 87 | 88 | // ============== IMPORTANT OVERRIDE ================ 89 | 90 | WundergroundProvider.prototype.withProviderData = function(lat, lon, force, callback) { 91 | // callback expects that this.hasValidData() will be true 92 | 93 | if (force) { 94 | // In case the API key becomes invalid 95 | console.log("Clearing Weather Underground API key for forced update") 96 | this.clearApiKey() 97 | } 98 | 99 | this.withApiKey((function(apiKey) { 100 | this.withWundergroundCurrent(lat, lon, apiKey, (function(currentTemp) { 101 | this.withWundergroundForecast(lat, lon, apiKey, (function(forecast) { 102 | this.tempTrend = forecast.map(function(entry) { 103 | return entry.temp; 104 | }) 105 | this.precipTrend = forecast.map(function(entry) { 106 | return entry.pop / 100.0 107 | }) 108 | this.startTime = forecast[0].fcst_valid; 109 | this.currentTemp = currentTemp; 110 | callback(); 111 | }).bind(this)); 112 | }).bind(this)) 113 | }).bind(this)); 114 | } 115 | 116 | module.exports = WundergroundProvider; -------------------------------------------------------------------------------- /src/c/appendix/persist.c: -------------------------------------------------------------------------------- 1 | #include "persist.h" 2 | #include "config.h" 3 | 4 | enum key { 5 | TEMP_LO, TEMP_HI, TEMP_TREND, PRECIP_TREND, FORECAST_START, CITY, SUN_EVENT_START_TYPE, SUN_EVENT_TIMES, NUM_ENTRIES, 6 | CURRENT_TEMP, BATTERY_LEVEL, CONFIG 7 | }; // Deprecated: BATTERY_LEVEL 8 | 9 | void persist_init() { 10 | if (!persist_exists(TEMP_LO)) { 11 | persist_write_int(TEMP_LO, 2); 12 | } 13 | if (!persist_exists(TEMP_HI)) { 14 | persist_write_int(TEMP_HI, 12); 15 | } 16 | if (!persist_exists(TEMP_TREND)) { 17 | int16_t data[] = {2, 2, 2, 4, 7, 9, 11, 12, 12, 12, 11, 9}; 18 | persist_write_data(TEMP_TREND, (void*) data, 12*sizeof(int16_t)); 19 | } 20 | if (!persist_exists(PRECIP_TREND)) { 21 | uint8_t data[] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; 22 | persist_write_data(TEMP_TREND, (void*) data, 12*sizeof(uint8_t)); 23 | } 24 | if (!persist_exists(FORECAST_START)) { 25 | persist_write_int(FORECAST_START, 0); 26 | } 27 | if (!persist_exists(NUM_ENTRIES)) { 28 | persist_write_int(NUM_ENTRIES, 12); 29 | } 30 | if (!persist_exists(CURRENT_TEMP)) { 31 | persist_write_int(CURRENT_TEMP, 1); 32 | } 33 | if (!persist_exists(CITY)) { 34 | persist_write_string(CITY, "Koji"); 35 | } 36 | if (!persist_exists(SUN_EVENT_START_TYPE)) { 37 | persist_write_int(SUN_EVENT_START_TYPE, 0); 38 | } 39 | if (!persist_exists(SUN_EVENT_TIMES)) { 40 | uint32_t data[] = {0, 0}; 41 | persist_write_data(SUN_EVENT_TIMES, (void*) data, 2*sizeof(uint32_t)); 42 | } 43 | if (!persist_exists(CONFIG)) { 44 | Config config = (Config) { 45 | .celsius = false, 46 | .time_lead_zero = false, 47 | .axis_12h = false, 48 | .start_mon = false, 49 | .prev_week = true, 50 | .time_font = 0, 51 | .color_today = GColorBlack, 52 | .show_qt = true, 53 | .show_bt = true, 54 | .show_bt_disconnect = true, 55 | .vibe = false, 56 | .show_am_pm = false, 57 | .color_saturday = GColorWhite, 58 | .color_sunday = GColorWhite, 59 | .color_us_federal = GColorWhite, 60 | .color_time = GColorWhite 61 | }; 62 | persist_set_config(config); 63 | } 64 | } 65 | 66 | int persist_get_temp_lo() { 67 | return persist_read_int(TEMP_LO); 68 | } 69 | 70 | int persist_get_temp_hi() { 71 | return persist_read_int(TEMP_HI); 72 | } 73 | 74 | int persist_get_temp_trend(int16_t *buffer, const size_t buffer_size) { 75 | return persist_read_data(TEMP_TREND, (void*) buffer, buffer_size * sizeof(int16_t)); 76 | } 77 | 78 | int persist_get_precip_trend(uint8_t *buffer, const size_t buffer_size) { 79 | return persist_read_data(PRECIP_TREND, (void*) buffer, buffer_size * sizeof(uint8_t)); 80 | } 81 | 82 | time_t persist_get_forecast_start() { 83 | return (time_t) persist_read_int(FORECAST_START); 84 | } 85 | 86 | int persist_get_num_entries() { 87 | return persist_read_int(NUM_ENTRIES); 88 | } 89 | 90 | int persist_get_current_temp() { 91 | return persist_read_int(CURRENT_TEMP); 92 | } 93 | 94 | int persist_get_city(char *buffer, const size_t buffer_size) { 95 | return persist_read_string(CITY, buffer, buffer_size); 96 | } 97 | 98 | int persist_get_sun_event_start_type() { 99 | return persist_read_int(SUN_EVENT_START_TYPE); 100 | } 101 | 102 | int persist_get_sun_event_times(time_t *buffer, const size_t buffer_size) { 103 | return persist_read_data(SUN_EVENT_TIMES, (void*) buffer, buffer_size * sizeof(time_t)); 104 | } 105 | 106 | int persist_get_config(Config *config) { 107 | return persist_read_data(CONFIG, config, sizeof(Config)); 108 | } 109 | 110 | void persist_set_temp_lo(int val) { 111 | persist_write_int(TEMP_LO, val); 112 | } 113 | 114 | void persist_set_temp_hi(int val) { 115 | persist_write_int(TEMP_HI, val); 116 | } 117 | 118 | void persist_set_temp_trend(int16_t *data, const size_t size) { 119 | persist_write_data(TEMP_TREND, (void*) data, size * sizeof(int16_t)); 120 | } 121 | 122 | void persist_set_precip_trend(uint8_t *data, const size_t size) { 123 | persist_write_data(PRECIP_TREND, (void*) data, size * sizeof(uint8_t)); 124 | } 125 | 126 | void persist_set_forecast_start(time_t val) { 127 | persist_write_int(FORECAST_START, (int) val); 128 | } 129 | 130 | void persist_set_num_entries(int val) { 131 | persist_write_int(NUM_ENTRIES, val); 132 | } 133 | 134 | void persist_set_current_temp(int val) { 135 | persist_write_int(CURRENT_TEMP, val); 136 | } 137 | 138 | void persist_set_city(char *val) { 139 | persist_write_string(CITY, val); 140 | } 141 | 142 | void persist_set_sun_event_start_type(int val) { 143 | persist_write_int(SUN_EVENT_START_TYPE, val); 144 | } 145 | 146 | void persist_set_sun_event_times(time_t *data, const size_t size) { 147 | persist_write_data(SUN_EVENT_TIMES, (void*) data, size * sizeof(time_t)); 148 | } 149 | 150 | void persist_set_config(Config config) { 151 | persist_write_data(CONFIG, &config, sizeof(Config)); 152 | config_refresh(); // Refresh global config variable 153 | } 154 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![banner](https://i.imgur.com/snWbbf5.png) 2 | 3 | [![GitHub release (latest by date)](https://img.shields.io/github/v/release/mattrossman/forecaswatch2?label=latest&color=85C1E9&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAQAAABKfvVzAAAAAmJLR0QA/4ePzL8AAAC0SURBVDjLldLLCcJAFEbhP4oIE1xYhw1pA4JWYRGCVbhxoTshWIUNaAnBgB4XBiTJ3HncbALznXAZIpnDmHnnmSqAS470p2Fn8wrfNEzS+INX++ZS+J6CRZu4lGWWEgVPT2DsfmfFwbMSjiuxcXn8H5gX6Q+S+ZtRDofT7/uXRF5RSmJEncEliS2fDC5JrCPJjVn/lwglQx5M/NxMbO5NwnyQxHknSeOSxIaac+feo0lhn30BIXaN/u4MXmAAAAAASUVORK5CYII=)](https://github.com/mattrossman/forecaswatch2/releases/latest) 4 | [![GitHub All Releases](https://img.shields.io/github/downloads/mattrossman/forecaswatch2/total?label=downloads&logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAMAAADXqc3KAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAM1BMVEUAAAD///////////////v///z///z///z///v///v///v///v///v///3///z///z///xB67/PAAAAEHRSTlMAERwgPExhYouMjY6P1N7g8FyKngAAAF5JREFUKM/VjksOgCAMBR+IH0CB+59WEBpTPsYts+tM2hTIiLUgwFGhoKYN+xVxFFyatlx0qDhox3Cv32tm4FnR/CtL3lTvUmk8cCZvgW7p+lgG/j9yaZBP8KHBf4QbpMkNa908ZS8AAAAASUVORK5CYII=)](https://github.com/mattrossman/forecaswatch2/releases/latest/download/forecaswatch2.pbw) 5 | [![Platform](https://img.shields.io/badge/platform-aplite%20%7C%20basalt%20%7C%20diorite-red?logo=data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAQAAABKfvVzAAAAAmJLR0QA/4ePzL8AAAC1SURBVDjL1ZSxDoIwFEWbMOLE6qgYdlb5FUkMFEOMox8pJsJg/A4HmGqOkwZtoTRx8b7t5p6h6X1PCIMIiIgIxBQxo+GlGt8OHOhrb4t73D6AK944sONbxVg8p9OAjmwovuLBiRLZm5IKxdIMpMBacxNgYwYkEGtuDNyZuwEG3waEbsDR9Q3yb4AUSFw+LkRRadU4o1gMtSmj1crXsh3ra6EB+W8XyHlFhcCnfscvE46A7cw8Ab9fQsIsgqKzAAAAAElFTkSuQmCC)](https://developer.rebble.io/developer.pebble.com/guides/tools-and-resources/hardware-information/index.html) 6 | [![GitHub](https://img.shields.io/github/license/mattrossman/forecaswatch2?color=blue&logo=data%3Aimage%2Fpng%3Bbase64%2CiVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAAACXBIWXMAAAsTAAALEwEAmpwYAAAB7ElEQVRIie2TPWsUURSGnxsWjLosIgTJLpL8AbWwUKwjgpg%2FYEAQxCiCSLKgsAppBG38AFNolU72P4hlrLZQEwsVxSD4AWmyKFmLPBY5wWGys9ktBAtfGJh73o9z7p078K9ATeqkOqWmv9Fg0j84269vaIAelcx7u19TaSeBOgocBYaBlxE%2Bop4BWimlL32PqJ5Sj6hVdVZtqRsWYyM0dbUW3tNF4eM9gt6py5n1ctSKMF7U5IL6NkRN9ZxaC24uEzAXtVponkb9vTrd64h2qSshvpzjtjXIcBej%2FlkdznL5WzQNjALPgUZeXDQUcCs8B4BLRcI96lf1cXyPjjqz0w7Ua6EdU59Ext5uDa6rP9VqrB%2Bq39VyUQO1rH5TH8S6Ghk38uEVdVW9k6mNqG210aNBQ11TRzK%2Bu5FVASjFywKwH9id%2B4AfgLr6usuOJ4E68BG4om5Rw5G1oJ4vAevAsSCvbju7TYwV1PbFc7gLfxxYH0op%2FQJOAktdRB3gNvCoCzcfXKcLtwRMpJQ6JYCU0hvgkHoipqkAn4BnKaVVgMwREB6Bm%2Bp9YCJ2tAa8SiktbulKOdMisMgAiAGag3i2QZ2JG7WFdvYf6TlAj9CDwBSbt2IWKOckbeAe8ANoppRWBp26Zf94MVD4f2TxGzyXVgXKldOBAAAAAElFTkSuQmCC)](https://www.gnu.org/licenses/gpl-3.0) 7 | [![Tip jar](https://img.shields.io/badge/%24%20tip%20jar-PayPal-253B80)](https://paypal.me/mttrssmn) 8 | 9 | 10 | Once upon a time I relied on *ForecasWatch* as the daily driver watchface on my beloved red Pebble Time. Recently, the free tier of the Weather Underground API on which the watchface relied was discontinued, making a huge portion of the watchface unusable. 11 | 12 | The developer, RCY, is nowhere to be found in the Rebble era. I plan to continue using my Pebble(s) for years to come, so this is my attempt to revive this wonderful watchface—and this time it's open source! 13 | 14 | ## Screenshots 15 | 16 |
17 | Color screenshot 18 | Black and white screenshot 19 |
20 | 21 | ## Features 22 | 23 | * Current time 24 | * Battery indicator 25 | * 3 week calendar 26 | * 24 hour weather forecast (updates every 30 minutes) 27 | * Bluetooth connection indicator 28 | * Quiet time indicator 29 | * Multiple weather providers (Weather Underground*, OpenWeatherMap) 30 | * Current temperature 31 | * Temperature forecast (red line) 32 | * Precipitation probability forecast (blue area) 33 | * City where forecast was fetched 34 | * Next sunrise or sunset time 35 | * GPS or manual location entry 36 | * Fahrenheit and Celsius temperatures 37 | * Customize time font and color 38 | * Customize colors for Sundays, Saturdays, and US federal holidays 39 | * Offline configuration page 40 | 41 | *\* Using a hacky workaround* 42 | 43 | ## Platforms 44 | 45 | All rectangular watches are supported (Classic, Steel, Time, Time Steel, Pebble 2). 46 | 47 | ## Installation 48 | 49 | ### Rebble 50 | 51 | A stable release is was made available on the Rebble store thanks to @joshua. [Click here for the store page.](https://apps.rebble.io/en_US/application/5dcdca6ac393f50cf6dbc264) 52 | 53 | ### Manual install 54 | 55 | For more cutting-edge features, download the latest [`forecaswatch2.pbw`](https://github.com/mattrossman/forecaswatch2/releases/latest/download/forecaswatch2.pbw) release. On Android you can use [Cx File Explorer](https://play.google.com/store/apps/details?id=com.cxinventor.file.explorer) to open this file through the Pebble app. 56 | 57 | ## Developers 58 | 59 | ### Building 60 | 61 | Prerequisites: [Node.js](https://nodejs.org/en/) and [Docker Desktop](https://docs.docker.com/get-docker/) 62 | 63 | ```bash 64 | # Install JS dependencies 65 | npm install 66 | 67 | # Start the detached docker container 68 | npm start 69 | 70 | # Build within the container 71 | npm run build 72 | ``` 73 | 74 | This will build the project inside a docker container containing the Pebble SDK. The `.pbw` output can be found in the `build` directory on the host machine. 75 | 76 | You can also use `npm run shell` to access other Pebble CLI commands, for instance during development I often use: 77 | 78 | ```bash 79 | pebble clean && pebble build && pebble install --phone 80 | ``` 81 | 82 | ### Config 83 | You can create a file `src/pkjs/dev-config.js` to set values for Clay keys (for convenience), e.g. 84 | 85 | ```javascript 86 | var owmApiKey = 'abc123'; 87 | module.exports.owmApiKey = owmApiKey; 88 | ``` 89 | -------------------------------------------------------------------------------- /src/c/layers/calendar_status_layer.c: -------------------------------------------------------------------------------- 1 | #include "calendar_status_layer.h" 2 | #include "battery_layer.h" 3 | #include "c/appendix/config.h" 4 | 5 | #define MONTH_FONT_OFFSET 7 6 | #define BATTERY_W 20 7 | #define BATTERY_H 10 8 | #define PADDING 4 9 | #define ICON_SLOT_1 GRect(PADDING, 0, 10, 10) 10 | #define ICON_SLOT_2 GRect(PADDING * 2 + 10, 0, 10, 10) 11 | 12 | static Layer *s_calendar_status_layer; 13 | static TextLayer *s_calendar_month_layer; 14 | static TextLayer *s_calendar_month_layer; 15 | static GBitmap *s_mute_bitmap; 16 | static GBitmap *s_bt_bitmap; 17 | static GBitmap *s_bt_disconnect_bitmap; 18 | static BitmapLayer *s_mute_bitmap_layer; 19 | static BitmapLayer *s_bt_bitmap_layer; 20 | static BitmapLayer *s_bt_disconnect_bitmap_layer; 21 | static GColor *s_bt_palette; 22 | static GColor *s_bt_disconnect_palette; 23 | static GColor *s_mute_palette; 24 | 25 | 26 | static void bitmap_layer_move_frame(BitmapLayer *bitmap_layer, GRect frame) { 27 | layer_set_frame(bitmap_layer_get_layer(bitmap_layer), frame); 28 | } 29 | 30 | void calendar_status_layer_create(Layer* parent_layer, GRect frame) { 31 | s_calendar_status_layer = layer_create(frame); 32 | GRect bounds = layer_get_bounds(s_calendar_status_layer); 33 | int w = bounds.size.w; 34 | int h = bounds.size.h; 35 | 36 | // Set up icons 37 | s_mute_bitmap = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_MUTE); 38 | s_bt_bitmap = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_BT_CONNECT); 39 | s_bt_disconnect_bitmap = gbitmap_create_with_resource(RESOURCE_ID_IMAGE_BT_DISCONNECT); 40 | 41 | // Set up color palette 42 | s_bt_palette = malloc(2*sizeof(GColor)); 43 | s_bt_palette[0] = PBL_IF_COLOR_ELSE(GColorPictonBlue, GColorWhite); 44 | s_bt_palette[1] = GColorClear; 45 | gbitmap_set_palette(s_bt_bitmap, s_bt_palette, false); 46 | 47 | s_bt_disconnect_palette = malloc(2*sizeof(GColor)); 48 | s_bt_disconnect_palette[0] = PBL_IF_COLOR_ELSE(GColorRed, GColorWhite); 49 | s_bt_disconnect_palette[1] = GColorClear; 50 | gbitmap_set_palette(s_bt_disconnect_bitmap, s_bt_disconnect_palette, false); 51 | 52 | s_mute_palette = malloc(2*sizeof(GColor)); 53 | s_mute_palette[0] = GColorWhite; 54 | s_mute_palette[1] = GColorClear; 55 | gbitmap_set_palette(s_mute_bitmap, s_mute_palette, false); 56 | 57 | s_mute_bitmap_layer = bitmap_layer_create(ICON_SLOT_1); 58 | bitmap_layer_set_compositing_mode(s_mute_bitmap_layer, GCompOpSet); 59 | bitmap_layer_set_bitmap(s_mute_bitmap_layer, s_mute_bitmap); 60 | 61 | s_bt_bitmap_layer = bitmap_layer_create(ICON_SLOT_2); 62 | bitmap_layer_set_compositing_mode(s_bt_bitmap_layer, GCompOpSet); 63 | bitmap_layer_set_bitmap(s_bt_bitmap_layer, s_bt_bitmap); 64 | 65 | s_bt_disconnect_bitmap_layer = bitmap_layer_create(ICON_SLOT_2); 66 | bitmap_layer_set_compositing_mode(s_bt_disconnect_bitmap_layer, GCompOpSet); 67 | bitmap_layer_set_bitmap(s_bt_disconnect_bitmap_layer, s_bt_disconnect_bitmap); 68 | 69 | 70 | // Set up month text layer 71 | s_calendar_month_layer = text_layer_create(GRect(0, -MONTH_FONT_OFFSET, w, 25)); 72 | text_layer_set_background_color(s_calendar_month_layer, GColorClear); 73 | text_layer_set_text_alignment(s_calendar_month_layer, GTextAlignmentCenter); 74 | text_layer_set_text_color(s_calendar_month_layer, GColorWhite); 75 | text_layer_set_font(s_calendar_month_layer, fonts_get_system_font(FONT_KEY_GOTHIC_18)); 76 | 77 | // Set up bluetooth handler 78 | connection_service_subscribe((ConnectionHandlers) { 79 | .pebble_app_connection_handler = bluetooth_callback 80 | }); 81 | 82 | calendar_status_layer_refresh(); 83 | layer_add_child(s_calendar_status_layer, bitmap_layer_get_layer(s_mute_bitmap_layer)); 84 | layer_add_child(s_calendar_status_layer, bitmap_layer_get_layer(s_bt_bitmap_layer)); 85 | layer_add_child(s_calendar_status_layer, bitmap_layer_get_layer(s_bt_disconnect_bitmap_layer)); 86 | layer_add_child(s_calendar_status_layer, text_layer_get_layer(s_calendar_month_layer)); 87 | battery_layer_create(s_calendar_status_layer, GRect(w - BATTERY_W - PADDING, 1, BATTERY_W, BATTERY_H)); 88 | layer_add_child(parent_layer, s_calendar_status_layer); 89 | } 90 | 91 | void bluetooth_icons_refresh(bool connected) { 92 | bool show_bt = connected && g_config->show_bt; 93 | bool show_bt_disconnect = !connected && g_config->show_bt_disconnect; 94 | layer_set_hidden(bitmap_layer_get_layer(s_bt_bitmap_layer), !show_bt); 95 | layer_set_hidden(bitmap_layer_get_layer(s_bt_disconnect_bitmap_layer), !show_bt_disconnect); 96 | } 97 | 98 | void bluetooth_callback(bool connected) { 99 | bluetooth_icons_refresh(connected); 100 | if (!connected && g_config->vibe) 101 | vibes_double_pulse(); 102 | } 103 | 104 | bool show_qt_icon() { 105 | return g_config->show_qt && quiet_time_is_active(); 106 | } 107 | 108 | void status_icons_refresh() { 109 | bool show_qt = show_qt_icon(); 110 | layer_set_hidden(bitmap_layer_get_layer(s_mute_bitmap_layer), !show_qt); 111 | bitmap_layer_move_frame(s_bt_bitmap_layer, show_qt ? ICON_SLOT_2 : ICON_SLOT_1); 112 | bitmap_layer_move_frame(s_bt_disconnect_bitmap_layer, show_qt ? ICON_SLOT_2 : ICON_SLOT_1); 113 | 114 | // Ensure bt icons are correct at start 115 | bluetooth_icons_refresh(connection_service_peek_pebble_app_connection()); 116 | } 117 | 118 | void calendar_status_layer_refresh() { 119 | static char s_buffer_month[10]; 120 | time_t now = time(NULL); 121 | struct tm *tm_now = localtime(&now); 122 | 123 | strftime(s_buffer_month, sizeof(s_buffer_month), "%b %Y", tm_now); 124 | text_layer_set_text(s_calendar_month_layer, s_buffer_month); 125 | status_icons_refresh(); 126 | } 127 | 128 | void calendar_status_layer_destroy() { 129 | free(s_bt_palette); 130 | free(s_bt_disconnect_palette); 131 | free(s_mute_palette); 132 | gbitmap_destroy(s_mute_bitmap); 133 | gbitmap_destroy(s_bt_bitmap); 134 | gbitmap_destroy(s_bt_disconnect_bitmap); 135 | bitmap_layer_destroy(s_mute_bitmap_layer); 136 | bitmap_layer_destroy(s_bt_bitmap_layer); 137 | bitmap_layer_destroy(s_bt_disconnect_bitmap_layer); 138 | layer_destroy(s_calendar_status_layer); 139 | } -------------------------------------------------------------------------------- /src/c/appendix/app_message.c: -------------------------------------------------------------------------------- 1 | #include "app_message.h" 2 | #include "persist.h" 3 | #include "math.h" 4 | #include "c/layers/forecast_layer.h" 5 | #include "c/layers/weather_status_layer.h" 6 | #include "c/layers/loading_layer.h" 7 | #include "c/windows/main_window.h" 8 | 9 | static void inbox_received_callback(DictionaryIterator *iterator, void *context) { 10 | APP_LOG(APP_LOG_LEVEL_INFO, "Message received!"); 11 | // Weather data 12 | Tuple *temp_trend_tuple = dict_find(iterator, MESSAGE_KEY_TEMP_TREND_INT16); 13 | Tuple *precip_trend_tuple = dict_find(iterator, MESSAGE_KEY_PRECIP_TREND_UINT8); 14 | Tuple *forecast_start_tuple = dict_find(iterator, MESSAGE_KEY_FORECAST_START); 15 | Tuple *num_entries_tuple = dict_find(iterator, MESSAGE_KEY_NUM_ENTRIES); 16 | Tuple *current_temp_tuple = dict_find(iterator, MESSAGE_KEY_CURRENT_TEMP); 17 | Tuple *city_tuple = dict_find(iterator, MESSAGE_KEY_CITY); 18 | Tuple *sun_events_tuple = dict_find(iterator, MESSAGE_KEY_SUN_EVENTS); 19 | 20 | // Clay config options 21 | Tuple *clay_celsius_tuple = dict_find(iterator, MESSAGE_KEY_CLAY_CELSIUS); 22 | Tuple *clay_time_lead_zero_tuple = dict_find(iterator, MESSAGE_KEY_CLAY_TIME_LEAD_ZERO); 23 | Tuple *clay_axis_12h_tuple = dict_find(iterator, MESSAGE_KEY_CLAY_AXIS_12H); 24 | Tuple *clay_start_mon_tuple = dict_find(iterator, MESSAGE_KEY_CLAY_START_MON); 25 | Tuple *clay_prev_week_tuple = dict_find(iterator, MESSAGE_KEY_CLAY_PREV_WEEK); 26 | Tuple *clay_color_today_tuple = dict_find(iterator, MESSAGE_KEY_CLAY_COLOR_TODAY); 27 | Tuple *clay_time_font_tuple = dict_find(iterator, MESSAGE_KEY_CLAY_TIME_FONT); 28 | Tuple *clay_vibe_tuple = dict_find(iterator, MESSAGE_KEY_CLAY_VIBE); 29 | Tuple *clay_show_qt_tuple = dict_find(iterator, MESSAGE_KEY_CLAY_SHOW_QT); 30 | Tuple *clay_show_bt_tuple = dict_find(iterator, MESSAGE_KEY_CLAY_SHOW_BT); 31 | Tuple *clay_show_bt_disconnect_tuple = dict_find(iterator, MESSAGE_KEY_CLAY_SHOW_BT_DISCONNECT); 32 | Tuple *clay_show_am_pm_tuple = dict_find(iterator, MESSAGE_KEY_CLAY_SHOW_AM_PM); 33 | Tuple *clay_color_saturday_tuple = dict_find(iterator, MESSAGE_KEY_CLAY_COLOR_SATURDAY); 34 | Tuple *clay_color_sunday_tuple = dict_find(iterator, MESSAGE_KEY_CLAY_COLOR_SUNDAY); 35 | Tuple *clay_color_us_federal_tuple = dict_find(iterator, MESSAGE_KEY_CLAY_COLOR_US_FEDERAL); 36 | Tuple *clay_color_time_tuple = dict_find(iterator, MESSAGE_KEY_CLAY_COLOR_TIME); 37 | 38 | if(temp_trend_tuple && temp_trend_tuple && forecast_start_tuple && num_entries_tuple && city_tuple && sun_events_tuple) { 39 | // Weather data received 40 | APP_LOG(APP_LOG_LEVEL_INFO, "All tuples received!"); 41 | persist_set_forecast_start((time_t)forecast_start_tuple->value->int32); 42 | const int num_entries = ((int)num_entries_tuple->value->int32); 43 | persist_set_num_entries(num_entries); 44 | int16_t *temp_data = (int16_t*) temp_trend_tuple->value->data; 45 | persist_set_temp_trend(temp_data, num_entries); 46 | uint8_t *precip_data = (uint8_t*) precip_trend_tuple->value->data; 47 | persist_set_precip_trend(precip_data, num_entries); 48 | persist_set_city((char*)city_tuple->value->cstring); 49 | int lo, hi; 50 | min_max(temp_data, num_entries, &lo, &hi); 51 | persist_set_temp_lo(lo); 52 | persist_set_temp_hi(hi); 53 | persist_set_current_temp((int)current_temp_tuple->value->int32); 54 | uint8_t sun_event_start_type = (uint8_t) sun_events_tuple->value->uint8; 55 | time_t *sun_event_times = (time_t*) (sun_events_tuple->value->data + 1); 56 | persist_set_sun_event_start_type(sun_event_start_type); 57 | persist_set_sun_event_times(sun_event_times, 2); 58 | loading_layer_refresh(); 59 | forecast_layer_refresh(); 60 | weather_status_layer_refresh(); 61 | } 62 | else if (clay_celsius_tuple && clay_axis_12h_tuple && clay_start_mon_tuple && clay_prev_week_tuple && clay_color_today_tuple 63 | && clay_vibe_tuple && clay_show_qt_tuple && clay_show_bt_tuple && clay_show_bt_disconnect_tuple && clay_show_am_pm_tuple 64 | && clay_color_saturday_tuple && clay_color_sunday_tuple && clay_color_us_federal_tuple && clay_color_time_tuple) { 65 | // Clay config data received 66 | bool clay_celsius = (bool) (clay_celsius_tuple->value->int16); 67 | bool time_lead_zero = (bool) (clay_time_lead_zero_tuple->value->int16); 68 | bool axis_12h = (bool) (clay_axis_12h_tuple->value->int16); 69 | bool start_mon = (bool) (clay_start_mon_tuple->value->int16); 70 | bool prev_week = (bool) (clay_prev_week_tuple->value->int16); 71 | bool vibe = (bool) (clay_vibe_tuple->value->int16); 72 | bool show_qt = (bool) (clay_show_qt_tuple->value->int16); 73 | bool show_bt = (bool) (clay_show_bt_tuple->value->int16); 74 | bool show_bt_disconnect = (bool) (clay_show_bt_disconnect_tuple->value->int16); 75 | bool show_am_pm = (bool) (clay_show_am_pm_tuple->value->int16); 76 | int16_t time_font = clay_time_font_tuple->value->int16; 77 | GColor color_today = GColorFromHEX(clay_color_today_tuple->value->int32); 78 | GColor color_saturday = GColorFromHEX(clay_color_saturday_tuple->value->int32); 79 | GColor color_sunday = GColorFromHEX(clay_color_sunday_tuple->value->int32); 80 | GColor color_us_federal = GColorFromHEX(clay_color_us_federal_tuple->value->int32); 81 | GColor color_time = GColorFromHEX(clay_color_time_tuple->value->int32); 82 | Config config = (Config) { 83 | .celsius = clay_celsius, 84 | .time_lead_zero = time_lead_zero, 85 | .axis_12h = axis_12h, 86 | .start_mon = start_mon, 87 | .prev_week = prev_week, 88 | .time_font = time_font, 89 | .color_today = color_today, 90 | .vibe = vibe, 91 | .show_qt = show_qt, 92 | .show_bt = show_bt, 93 | .show_bt_disconnect = show_bt_disconnect, 94 | .show_am_pm = show_am_pm, 95 | .color_saturday = color_saturday, 96 | .color_sunday = color_sunday, 97 | .color_us_federal = color_us_federal, 98 | .color_time = color_time 99 | }; 100 | persist_set_config(config); 101 | main_window_refresh(); 102 | } 103 | else { 104 | APP_LOG(APP_LOG_LEVEL_WARNING, "Bad payload received in app_message.c"); 105 | } 106 | } 107 | 108 | static void inbox_dropped_callback(AppMessageResult reason, void *context) { 109 | APP_LOG(APP_LOG_LEVEL_ERROR, "Message dropped!"); 110 | } 111 | 112 | void app_message_init() { 113 | // Register callbacks 114 | app_message_register_inbox_received(inbox_received_callback); 115 | app_message_register_inbox_dropped(inbox_dropped_callback); 116 | 117 | // Open AppMessage 118 | const int inbox_size = 256; 119 | const int outbox_size = 0; 120 | app_message_open(inbox_size, outbox_size); 121 | } 122 | -------------------------------------------------------------------------------- /src/c/layers/weather_status_layer.c: -------------------------------------------------------------------------------- 1 | #include "weather_status_layer.h" 2 | #include "c/appendix/persist.h" 3 | #include "c/appendix/config.h" 4 | 5 | #define FONT_18_OFFSET 7 6 | #define FONT_14_OFFSET 3 7 | #define CITY_INIT_WIDTH 100 8 | #define ARROW_H 8 9 | #define ARROW_HEAD_H 3 10 | #define ARROW_HEAD_W 2 11 | #define ARROW_W 6 12 | #define MARGIN 2 13 | 14 | static GRect frame_curr_temp; 15 | static GRect frame_sun_event; 16 | 17 | static Layer *s_weather_status_layer; 18 | static TextLayer *s_city_layer; 19 | static TextLayer *s_current_temp_layer; 20 | static TextLayer *s_next_sun_event_layer; 21 | 22 | static GPath *s_arrow_path = NULL; 23 | static const GPathInfo ARROW_PATH_INFO = { 24 | // Downward facing arrow, centered at the origin 25 | .num_points = 6, 26 | .points = (GPoint[]){ 27 | {0, -ARROW_H/2}, 28 | {0, ARROW_H/2 - ARROW_HEAD_H}, 29 | {-ARROW_HEAD_W, ARROW_H/2 - ARROW_HEAD_H}, 30 | {0, ARROW_H/2}, 31 | {ARROW_HEAD_W, ARROW_H/2 - ARROW_HEAD_H}, 32 | {0, ARROW_H/2 - ARROW_HEAD_H} 33 | } 34 | }; 35 | 36 | static void text_layer_move_frame(TextLayer *text_layer, GRect frame) { 37 | layer_set_frame(text_layer_get_layer(text_layer), frame); 38 | } 39 | 40 | static void city_layer_refresh() { 41 | // Set the city text layer contents from storage 42 | static char s_city_buffer[20]; 43 | persist_get_city(s_city_buffer, sizeof(s_city_buffer)); 44 | text_layer_set_text(s_city_layer, s_city_buffer); 45 | 46 | // Dynamic resizing 47 | GRect bounds = layer_get_bounds(s_weather_status_layer); 48 | GSize size = text_layer_get_content_size(s_city_layer); 49 | int x = frame_curr_temp.origin.x + frame_curr_temp.size.w + MARGIN * 2; 50 | int y = -FONT_14_OFFSET; 51 | int w = bounds.size.w - frame_curr_temp.size.w - frame_sun_event.size.w - MARGIN * 4; 52 | int h = size.h + FONT_14_OFFSET; 53 | text_layer_move_frame(s_city_layer, GRect(x, y, w, h)); 54 | } 55 | 56 | static void current_temp_layer_refresh() { 57 | static char s_temp_buffer[8]; 58 | snprintf(s_temp_buffer, sizeof(s_temp_buffer), "• %d", config_localize_temp(persist_get_current_temp())); 59 | text_layer_set_text(s_current_temp_layer, s_temp_buffer); 60 | 61 | // Dynamic resizing 62 | text_layer_move_frame(s_current_temp_layer, GRect(0, 0, 100, 100)); // Make it big so content doesn't get clipped 63 | GSize size = text_layer_get_content_size(s_current_temp_layer); 64 | text_layer_move_frame(s_current_temp_layer, GRect(MARGIN, -FONT_18_OFFSET, size.w, size.h)); 65 | frame_curr_temp = GRect(0, -FONT_18_OFFSET, size.w + MARGIN, size.h); 66 | } 67 | 68 | static void sun_event_layer_refresh() { 69 | GRect bounds = layer_get_bounds(s_weather_status_layer); 70 | // Get the time of the first sun event 71 | time_t first_sun_event_time; 72 | persist_get_sun_event_times(&first_sun_event_time, 1); 73 | struct tm *sun_time = localtime(&first_sun_event_time); 74 | 75 | static char s_buffer[8]; 76 | config_format_time(s_buffer, 8, sun_time); 77 | 78 | // Display this time on the TextLayer 79 | text_layer_set_text(s_next_sun_event_layer, s_buffer); 80 | // text_layer_set_text(s_next_sun_event_layer, "17:42"); 81 | 82 | // Dynamic resizing 83 | text_layer_move_frame(s_next_sun_event_layer, GRect(0, 0, 100, 100)); // Make it big so content doesn't get clipped 84 | GSize size = text_layer_get_content_size(s_next_sun_event_layer); 85 | text_layer_move_frame(s_next_sun_event_layer, 86 | GRect(bounds.size.w - MARGIN - ARROW_W - size.w, -FONT_14_OFFSET, size.w + ARROW_W, size.h)); 87 | frame_sun_event = GRect(bounds.size.w - MARGIN - ARROW_W - size.w, -FONT_14_OFFSET, size.w + ARROW_W + MARGIN, size.h); 88 | } 89 | 90 | static void weather_status_layer_init(GRect bounds) { 91 | // Set up the city text layer properties 92 | int w = bounds.size.w; 93 | int h = bounds.size.h; 94 | 95 | // Current temperature 96 | s_current_temp_layer = text_layer_create(GRect(MARGIN, -FONT_18_OFFSET, 40, 25)); 97 | text_layer_set_background_color(s_current_temp_layer, GColorClear); 98 | text_layer_set_text_alignment(s_current_temp_layer, GTextAlignmentLeft); 99 | text_layer_set_text_color(s_current_temp_layer, GColorWhite); 100 | text_layer_set_font(s_current_temp_layer, fonts_get_system_font(FONT_KEY_GOTHIC_18)); 101 | 102 | // City where weather was fetched 103 | s_city_layer = text_layer_create(GRect(w/2 - CITY_INIT_WIDTH/2, -FONT_14_OFFSET, CITY_INIT_WIDTH, 25)); 104 | text_layer_set_background_color(s_city_layer, GColorClear); 105 | text_layer_set_text_alignment(s_city_layer, GTextAlignmentCenter); 106 | text_layer_set_text_color(s_city_layer, GColorWhite); 107 | text_layer_set_font(s_city_layer, fonts_get_system_font(FONT_KEY_GOTHIC_14)); 108 | 109 | // Time of next sun event (sunrise/sunset) 110 | s_next_sun_event_layer = text_layer_create(GRect(w - MARGIN - 6 - 40, 4 - FONT_18_OFFSET, 40, 25)); 111 | text_layer_set_background_color(s_next_sun_event_layer, GColorClear); 112 | text_layer_set_text_alignment(s_next_sun_event_layer, GTextAlignmentLeft); 113 | text_layer_set_text_color(s_next_sun_event_layer, GColorWhite); 114 | text_layer_set_font(s_next_sun_event_layer, fonts_get_system_font(FONT_KEY_GOTHIC_14)); 115 | 116 | current_temp_layer_refresh(); 117 | sun_event_layer_refresh(); 118 | city_layer_refresh(); 119 | } 120 | 121 | static void weather_status_update_proc(Layer *layer, GContext *ctx) { 122 | GRect bounds = layer_get_bounds(layer); 123 | int w = bounds.size.w; 124 | int h = bounds.size.h; 125 | s_arrow_path = gpath_create(&ARROW_PATH_INFO); 126 | // Translate to correct location in layer 127 | if (persist_get_sun_event_start_type() == 0) 128 | gpath_rotate_to(s_arrow_path, TRIG_MAX_ANGLE / 2); 129 | gpath_move_to(s_arrow_path, GPoint(w - 4, 6)); 130 | graphics_context_set_stroke_color(ctx, GColorWhite); 131 | gpath_draw_outline_open(ctx, s_arrow_path); 132 | graphics_context_set_fill_color(ctx, GColorWhite); 133 | gpath_draw_filled(ctx, s_arrow_path); 134 | gpath_destroy(s_arrow_path); 135 | } 136 | 137 | void weather_status_layer_create(Layer* parent_layer, GRect frame) { 138 | s_weather_status_layer = layer_create(frame); 139 | GRect bounds = layer_get_bounds(s_weather_status_layer); 140 | 141 | // Set up all the text layers 142 | weather_status_layer_init(bounds); 143 | layer_add_child(s_weather_status_layer, text_layer_get_layer(s_city_layer)); 144 | layer_add_child(s_weather_status_layer, text_layer_get_layer(s_current_temp_layer)); 145 | layer_add_child(s_weather_status_layer, text_layer_get_layer(s_next_sun_event_layer)); 146 | layer_set_update_proc(s_weather_status_layer, weather_status_update_proc); 147 | 148 | // Add the weather status bar to its parent 149 | layer_add_child(parent_layer, s_weather_status_layer); 150 | } 151 | 152 | void weather_status_layer_refresh() { 153 | layer_mark_dirty(s_weather_status_layer); 154 | current_temp_layer_refresh(); 155 | sun_event_layer_refresh(); 156 | city_layer_refresh(); 157 | } 158 | 159 | void weather_status_layer_destroy() { 160 | text_layer_destroy(s_city_layer); 161 | text_layer_destroy(s_current_temp_layer); 162 | text_layer_destroy(s_next_sun_event_layer); 163 | layer_destroy(s_weather_status_layer); 164 | } -------------------------------------------------------------------------------- /src/c/layers/calendar_layer.c: -------------------------------------------------------------------------------- 1 | #include "calendar_layer.h" 2 | #include "c/appendix/config.h" 3 | #include 4 | 5 | #define NUM_WEEKS 3 6 | #define DAYS_PER_WEEK 7 7 | #define FONT_OFFSET 5 8 | 9 | static Layer *s_calendar_layer; 10 | static TextLayer *s_calendar_text_layers[NUM_WEEKS * DAYS_PER_WEEK]; 11 | 12 | 13 | static struct tm *relative_tm(int days_from_today) 14 | { 15 | /* Get a time structure for n days from today (only accurate to the day) 16 | Use this function to avoid edge cases from daylight savings time 17 | */ 18 | time_t timestamp = time(NULL); 19 | tm *local_time = localtime(×tamp); 20 | // Set arbitrary hour so there's no daylight savings rounding error: 21 | local_time->tm_hour = 5; 22 | timestamp = mktime(local_time) + days_from_today * SECONDS_PER_DAY; 23 | return localtime(×tamp); 24 | } 25 | 26 | static int relative_day_of_month(int days_from_today) { 27 | // What is the day of the month n days from today? 28 | tm *local_time = relative_tm(days_from_today); 29 | return local_time->tm_mday; 30 | } 31 | 32 | static bool is_us_federal_holiday(struct tm *t) 33 | { 34 | // No holidays on weekends (ensures we don't register a false positive for special cases) 35 | if (t->tm_wday == 0 || t->tm_wday == 6) 36 | return false; 37 | 38 | // These holidays are on a specific weekday, so no special cases 39 | if ((t->tm_mon == 0 && t->tm_mday >= 15 && t->tm_mday <= 21 && t->tm_wday == 1) || // MLK Day 40 | (t->tm_mon == 1 && t->tm_mday >= 15 && t->tm_mday <= 21 && t->tm_wday == 1) || // Washington's Birthday 41 | (t->tm_mon == 4 && t->tm_mday >= 25 && t->tm_mday <= 31 && t->tm_wday == 1) || // Memorial Day 42 | (t->tm_mon == 8 && t->tm_mday >= 1 && t->tm_mday <= 7 && t->tm_wday == 1) || // Labor Day 43 | (t->tm_mon == 9 && t->tm_mday >= 8 && t->tm_mday <= 14 && t->tm_wday == 1) || // Columbus Day 44 | (t->tm_mon == 10 && t->tm_mday >= 22 && t->tm_mday <= 28 && t->tm_wday == 4)) // Thanksgiving 45 | return true; 46 | 47 | // These remaining holidays are on a specific day of the month, which get 48 | // moved if they fall on a weekend 49 | 50 | // Friday special cases 51 | if (t->tm_wday == 5 && ( 52 | (t->tm_mon == 11 && t->tm_mday == 31) || // New Years 53 | (t->tm_mon == 6 && t->tm_mday == 3) || // Independence Day 54 | (t->tm_mon == 10 && t->tm_mday == 10) || // Veterans Day 55 | (t->tm_mon == 11 && t->tm_mday == 24))) // Christmas 56 | return true; 57 | // Monday special cases 58 | if (t->tm_wday == 1 && ( 59 | (t->tm_mon == 0 && t->tm_mday == 2) || // New Years 60 | (t->tm_mon == 6 && t->tm_mday == 5) || // Independence Day 61 | (t->tm_mon == 10 && t->tm_mday == 12) || // Veterans Day 62 | (t->tm_mon == 11 && t->tm_mday == 26))) // Christmas 63 | return true; 64 | // Non special cases 65 | if ((t->tm_mon == 0 && t->tm_mday == 1) || // New Years 66 | (t->tm_mon == 6 && t->tm_mday == 4) || // Independence Day 67 | (t->tm_mon == 10 && t->tm_mday == 11) || // Veterans Day 68 | (t->tm_mon == 11 && t->tm_mday == 25)) // Christmas 69 | return true; 70 | 71 | // Default to no holiday 72 | return false; 73 | } 74 | 75 | static GColor date_color(struct tm *t) { 76 | // Get color for a date, considering weekends and holidays 77 | if (is_us_federal_holiday(t)) 78 | return g_config->color_us_federal; 79 | if (t->tm_wday == 0) 80 | return g_config->color_sunday; 81 | if (t->tm_wday == 6) 82 | return g_config->color_saturday; 83 | return GColorWhite; 84 | } 85 | 86 | static GColor today_color() { 87 | // Either follow the date color or override to configured value 88 | struct tm *t = relative_tm(0); 89 | return PBL_IF_COLOR_ELSE( 90 | gcolor_equal(g_config->color_today, GColorBlack) ? date_color(t) : g_config->color_today, 91 | GColorWhite 92 | ); 93 | } 94 | 95 | static void calendar_update_proc(Layer *layer, GContext *ctx) { 96 | GRect bounds = layer_get_bounds(layer); 97 | int w = bounds.size.w; 98 | int h = bounds.size.h; 99 | float box_w = (float) w / DAYS_PER_WEEK; 100 | float box_h = (float) h / NUM_WEEKS; 101 | 102 | // Calculate which box holds today's date 103 | const int i_today = config_n_today(); 104 | 105 | graphics_context_set_fill_color(ctx, today_color()); 106 | graphics_fill_rect(ctx, 107 | GRect((i_today % DAYS_PER_WEEK) * box_w, (i_today / DAYS_PER_WEEK) * box_h, 108 | box_w, box_h), 1, GCornersAll); 109 | } 110 | 111 | void calendar_layer_create(Layer* parent_layer, GRect frame) { 112 | s_calendar_layer = layer_create(frame); 113 | GRect bounds = layer_get_bounds(s_calendar_layer); 114 | int w = bounds.size.w; 115 | int h = bounds.size.h; 116 | float box_w = (float) w / DAYS_PER_WEEK; 117 | float box_h = (float) h / NUM_WEEKS; 118 | 119 | for (int i = 0; i < NUM_WEEKS * DAYS_PER_WEEK; ++i) { 120 | // Place a text box in that space 121 | TextLayer *s_box_text_layer = text_layer_create( 122 | GRect((i % DAYS_PER_WEEK) * box_w, (i / DAYS_PER_WEEK) * box_h - FONT_OFFSET, 123 | box_w, box_h + FONT_OFFSET)); 124 | text_layer_set_background_color(s_box_text_layer, GColorClear); 125 | text_layer_set_text_alignment(s_box_text_layer, GTextAlignmentCenter); 126 | s_calendar_text_layers[i] = s_box_text_layer; 127 | layer_add_child(s_calendar_layer, text_layer_get_layer(s_box_text_layer)); 128 | } 129 | layer_set_update_proc(s_calendar_layer, calendar_update_proc); 130 | calendar_layer_refresh(); 131 | layer_add_child(parent_layer, s_calendar_layer); 132 | } 133 | 134 | 135 | void calendar_layer_refresh() { 136 | static char s_calendar_box_buffers[NUM_WEEKS * DAYS_PER_WEEK][4]; 137 | // Request redraw (of today's highlight) 138 | layer_mark_dirty(s_calendar_layer); 139 | 140 | // Calculate which box holds today's date 141 | const int i_today = config_n_today(); 142 | 143 | // Fill each box with an appropriate relative day number 144 | for (int i = 0; i < NUM_WEEKS * DAYS_PER_WEEK; ++i) { 145 | char *buffer = s_calendar_box_buffers[i]; 146 | struct tm *t = relative_tm(i - i_today); 147 | 148 | // Set the text color 149 | if (i == i_today) { 150 | GColor text_color = gcolor_legible_over(today_color()); 151 | text_layer_set_text_color(s_calendar_text_layers[i], text_color); 152 | } 153 | else { 154 | GColor text_color = PBL_IF_COLOR_ELSE(date_color(t), GColorWhite); 155 | text_layer_set_text_color(s_calendar_text_layers[i], text_color); 156 | } 157 | 158 | // Use bold font for today, and holidays/weekends if colored 159 | bool highlight_holiday = (config_highlight_holidays() && is_us_federal_holiday(t)); 160 | bool highlight_sunday = (config_highlight_sundays() && t->tm_wday == 0); 161 | bool highlight_saturday = (config_highlight_saturdays() && t->tm_wday == 6); 162 | bool bold = (i == i_today) || highlight_holiday || highlight_sunday || highlight_saturday; 163 | text_layer_set_font(s_calendar_text_layers[i], 164 | fonts_get_system_font(bold ? FONT_KEY_GOTHIC_18_BOLD : FONT_KEY_GOTHIC_18)); 165 | 166 | snprintf(buffer, 4, "%d", t->tm_mday); 167 | text_layer_set_text(s_calendar_text_layers[i], buffer); 168 | } 169 | } 170 | 171 | void calendar_layer_destroy() { 172 | for (int i = 0; i < NUM_WEEKS * DAYS_PER_WEEK; ++i) { 173 | text_layer_destroy(s_calendar_text_layers[i]); 174 | } 175 | layer_destroy(s_calendar_layer); 176 | } 177 | -------------------------------------------------------------------------------- /src/pkjs/index.js: -------------------------------------------------------------------------------- 1 | 2 | var WundergroundProvider = require('./weather/wunderground.js'); 3 | var OpenWeatherMapProvider = require('./weather/openweathermap.js') 4 | var Clay = require('./clay/_source.js'); 5 | var clayConfig = require('./clay/config.js'); 6 | var customClay = require('./clay/inject.js'); 7 | var clay = new Clay(clayConfig, customClay, { autoHandleEvents: false }); 8 | var app = {}; // Namespace for global app variables 9 | 10 | Pebble.addEventListener('showConfiguration', function(e) { 11 | // Set the userData here rather than in the Clay() constructor so it's actually up to date 12 | clay.meta.userData.lastFetchSuccess = localStorage.getItem('lastFetchSuccess'); 13 | Pebble.openURL(clay.generateUrl()); 14 | console.log('Showing clay: ' + JSON.stringify(getClaySettings())); 15 | }); 16 | 17 | Pebble.addEventListener('webviewclosed', function(e) { 18 | if (e && !e.response) { 19 | return; 20 | } 21 | 22 | clay.getSettings(e.response, false); // This triggers the update in localStorage 23 | app.settings = getClaySettings(); // This reads from localStorage in sensible format 24 | refreshProvider(); 25 | sendClaySettings(); 26 | 27 | // Fetching goes last, after other settings have been handled 28 | if (app.settings.fetch === true) { 29 | console.log('Force fetch!'); 30 | fetch(app.provider, true); 31 | } 32 | console.log('Closing clay: ' + JSON.stringify(getClaySettings())); 33 | }); 34 | 35 | // Listen for when the watchface is opened 36 | Pebble.addEventListener('ready', 37 | function (e) { 38 | clayTryDefaults(); 39 | clayTryDevConfig(); 40 | console.log('PebbleKit JS ready!'); 41 | app.settings = getClaySettings(); 42 | refreshProvider(); 43 | startTick(); 44 | } 45 | ); 46 | 47 | function startTick() { 48 | console.log('Tick from PKJS!'); 49 | tryFetch(app.provider); 50 | setTimeout(startTick, 60 * 1000); // 60 * 1000 milsec = 1 minute 51 | } 52 | 53 | function sendClaySettings() { 54 | payload = { 55 | "CLAY_CELSIUS": app.settings.temperatureUnits === 'c', 56 | "CLAY_TIME_LEAD_ZERO": app.settings.timeLeadingZero, 57 | "CLAY_AXIS_12H": app.settings.axisTimeFormat === '12h', 58 | "CLAY_COLOR_TODAY": app.settings.hasOwnProperty('colorToday') ? app.settings.colorToday : 16777215, 59 | "CLAY_START_MON": app.settings.weekStartDay === 'mon', 60 | "CLAY_PREV_WEEK": app.settings.firstWeek === 'prev', 61 | "CLAY_TIME_FONT": ['roboto', 'leco', 'bitham'].indexOf(app.settings.timeFont), 62 | "CLAY_SHOW_QT": app.settings.showQt, 63 | "CLAY_SHOW_BT": app.settings.btIcons === "connected" || app.settings.btIcons === "both", 64 | "CLAY_SHOW_BT_DISCONNECT": app.settings.btIcons === "disconnected" || app.settings.btIcons === "both", 65 | "CLAY_VIBE": app.settings.vibe, 66 | "CLAY_SHOW_AM_PM": app.settings.timeShowAmPm, 67 | "CLAY_COLOR_SUNDAY": app.settings.hasOwnProperty('colorSunday') ? app.settings.colorSunday : 16777215, 68 | "CLAY_COLOR_SATURDAY": app.settings.hasOwnProperty('colorSaturday') ? app.settings.colorSaturday : 16777215, 69 | "CLAY_COLOR_US_FEDERAL": app.settings.hasOwnProperty('colorUSFederal') ? app.settings.colorUSFederal : 16777215, 70 | "CLAY_COLOR_TIME": app.settings.hasOwnProperty('colorTime') ? app.settings.colorTime : 16777215, 71 | } 72 | Pebble.sendAppMessage(payload, function() { 73 | console.log('Message sent successfully: ' + JSON.stringify(payload)); 74 | }, function(e) { 75 | console.log('Message failed: ' + JSON.stringify(e)); 76 | }); 77 | } 78 | 79 | function refreshProvider() { 80 | setProvider(app.settings.provider); 81 | app.provider.location = app.settings.location === '' ? null : app.settings.location 82 | } 83 | 84 | function setProvider(providerId) { 85 | switch (providerId) { 86 | case 'openweathermap': 87 | app.provider = new OpenWeatherMapProvider(app.settings.owmApiKey); 88 | break; 89 | case 'wunderground': 90 | app.provider = new WundergroundProvider(); 91 | break; 92 | default: 93 | console.log('Unknown provider: "' + providerId + '", defaulting to wunderground'); 94 | clay.setSettings("provider", "wunderground"); 95 | app.provider = new WundergroundProvider(); 96 | } 97 | console.log('Set provider: ' + app.provider.name); 98 | } 99 | 100 | function clayTryDefaults() { 101 | /* Clay only considers `defaultValue` upon first startup, but we need 102 | * defaults set even if the user has not made a custom config 103 | */ 104 | var persistClay = localStorage.getItem('clay-settings'); 105 | if (persistClay === null) { 106 | console.log('No clay settings found, setting defaults'); 107 | persistClay = { 108 | provider: 'wunderground', 109 | location: '' 110 | } 111 | localStorage.setItem('clay-settings', JSON.stringify(persistClay)); 112 | } 113 | } 114 | 115 | function clayTryDevConfig() { 116 | /* Use values from a dev-config.js file to configure clay settings 117 | * by iterating over the exported properties 118 | */ 119 | try { 120 | var devConfig = require('./dev-config.js'); 121 | var persistClay = getClaySettings(); 122 | for (var prop in devConfig) { 123 | if (Object.prototype.hasOwnProperty.call(devConfig, prop)) { 124 | persistClay[prop] = devConfig[prop]; 125 | console.log('Found dev setting: ' + prop + '=' + devConfig[prop]); 126 | } 127 | } 128 | localStorage.setItem('clay-settings', JSON.stringify(persistClay)); 129 | } 130 | catch (ex) { 131 | console.log("No developer configuration file found"); 132 | } 133 | } 134 | 135 | function getClaySettings() { 136 | return JSON.parse(localStorage.getItem('clay-settings')); 137 | } 138 | 139 | /** 140 | * @typedef {import("./weather/provider")} WeatherProvider 141 | * @param {WeatherProvider} provider 142 | * @param {boolean} force 143 | */ 144 | function fetch(provider, force) { 145 | console.log('Fetching from ' + provider.name); 146 | var fetchStatus = { 147 | time: new Date(), 148 | id: provider.id, 149 | name: provider.name 150 | } 151 | localStorage.setItem('lastFetchAttempt', JSON.stringify(fetchStatus)); 152 | provider.fetch( 153 | function() { 154 | // Sucess, update recent fetch time 155 | localStorage.setItem('lastFetchSuccess', JSON.stringify(fetchStatus)); 156 | console.log('Successfully fetched weather!') 157 | }, 158 | function() { 159 | // Failure 160 | console.log('[!] Provider failed to update weather') 161 | }, 162 | force 163 | ) 164 | } 165 | 166 | function tryFetch(provider) { 167 | if (needRefresh()) { 168 | fetch(provider, false); 169 | }; 170 | } 171 | 172 | function roundDownMinutes(date, minuteMod) { 173 | // E.g. with minuteMod=30, 3:52 would roll back to 3:30 174 | out = new Date(date); 175 | out.setMinutes(date.getMinutes() - (date.getMinutes() % minuteMod)); 176 | out.setSeconds(0); 177 | out.setMilliseconds(0); 178 | return out; 179 | } 180 | 181 | function needRefresh() { 182 | // If the weather has never been fetched 183 | var lastFetchSuccessString = localStorage.getItem('lastFetchSuccess'); 184 | if (lastFetchSuccessString === null) { 185 | return true; 186 | } 187 | var lastFetchSuccess = JSON.parse(lastFetchSuccessString); 188 | if (lastFetchSuccess.time === null) { 189 | // Just covering all my bases 190 | return true; 191 | } 192 | // If the most recent fetch is more than 30 minutes old 193 | return (Date.now() - roundDownMinutes(new Date(lastFetchSuccess.time), 30) > 1000 * 60 * 30); 194 | } 195 | -------------------------------------------------------------------------------- /src/c/layers/forecast_layer.c: -------------------------------------------------------------------------------- 1 | #include "forecast_layer.h" 2 | #include "c/appendix/persist.h" 3 | #include "c/appendix/math.h" 4 | #include "c/appendix/config.h" 5 | 6 | #define LEFT_AXIS_MARGIN_W 17 7 | #define BOTTOM_AXIS_FONT_OFFSET 4 // Adjustment for whitespace at top of font 8 | #define LABEL_PADDING 20 // Minimum width a label should cover 9 | #define BOTTOM_AXIS_H 10 // Height of the bottom axis (hour labels) 10 | #define MARGIN_TEMP_H 7 // Height of margins for the temperature plot 11 | 12 | static Layer *s_forecast_layer; 13 | static TextLayer *s_hi_layer; 14 | static TextLayer *s_lo_layer; 15 | 16 | static void forecast_update_proc(Layer *layer, GContext *ctx) { 17 | GRect bounds = layer_get_bounds(layer); 18 | GRect graph_bounds = GRect(LEFT_AXIS_MARGIN_W, 0, bounds.size.w - LEFT_AXIS_MARGIN_W, bounds.size.h); 19 | int w = graph_bounds.size.w; 20 | int h = graph_bounds.size.h; 21 | 22 | // Load data from storage 23 | const int num_entries = persist_get_num_entries(); 24 | const time_t forecast_start = persist_get_forecast_start(); 25 | struct tm *forecast_start_local = localtime(&forecast_start); 26 | int16_t temps[num_entries]; 27 | uint8_t precips[num_entries]; 28 | persist_get_temp_trend(temps, num_entries); 29 | persist_get_precip_trend(precips, num_entries); 30 | 31 | // Allocate point arrays for plots 32 | GPoint points_temp[num_entries]; 33 | GPoint points_precip[num_entries + 2]; // We need 2 more to complete the area 34 | 35 | // Calculate the temperature range 36 | int lo, hi; 37 | min_max(temps, num_entries, &lo, &hi); 38 | int range = hi - lo; 39 | 40 | // Draw a bounding box for each data entry (the -1 is since we don't want a gap on either side) 41 | float entry_w = (float) graph_bounds.size.w / (num_entries - 1); 42 | graphics_context_set_text_color(ctx, GColorWhite); 43 | graphics_context_set_stroke_color(ctx, GColorLightGray); 44 | 45 | // Round this division up by adding (divisor - 1) to the dividend 46 | const int entries_per_label = ((float) LABEL_PADDING + (entry_w - 1)) / entry_w; 47 | for (int i = 0; i < num_entries; ++i) { 48 | int entry_x = graph_bounds.origin.x + i * entry_w; 49 | 50 | // Save a point for the precipitation probability 51 | int precip = precips[i]; 52 | int precip_h = (float) precip / 100.0 * (h - BOTTOM_AXIS_H); 53 | points_precip[i] = GPoint(entry_x, h - BOTTOM_AXIS_H - precip_h); 54 | 55 | // Save a point for the temperature reading 56 | int temp = temps[i]; 57 | int temp_h = (float) (temp - lo) / range * (h - MARGIN_TEMP_H * 2 - BOTTOM_AXIS_H); 58 | points_temp[i] = GPoint(entry_x, h - temp_h - MARGIN_TEMP_H - BOTTOM_AXIS_H); 59 | 60 | if (i % entries_per_label == 0) { 61 | // Draw a text hour label at the appropriate interval 62 | char buf[4]; 63 | snprintf(buf, sizeof(buf), "%d", config_axis_hour(forecast_start_local->tm_hour + i)); 64 | graphics_draw_text(ctx, buf, 65 | fonts_get_system_font(FONT_KEY_GOTHIC_14), 66 | GRect(entry_x - 20, h - BOTTOM_AXIS_H - BOTTOM_AXIS_FONT_OFFSET, 40, BOTTOM_AXIS_H), 67 | GTextOverflowModeWordWrap, 68 | GTextAlignmentCenter, 69 | NULL 70 | ); 71 | } 72 | else if ((i + entries_per_label/2) % entries_per_label == 0) { 73 | // Just draw a tick between hour labels 74 | graphics_draw_line(ctx, 75 | GPoint(entry_x, h - BOTTOM_AXIS_H - 0), 76 | GPoint(entry_x, h - BOTTOM_AXIS_H + 4)); 77 | } 78 | } 79 | 80 | // Complete the area under the precipitation 81 | points_precip[num_entries] = GPoint(graph_bounds.origin.x + w, h - BOTTOM_AXIS_H); 82 | points_precip[num_entries + 1] = GPoint(graph_bounds.origin.x, h - BOTTOM_AXIS_H); 83 | 84 | // Fill the precipitation area 85 | GPathInfo path_info_precip = { 86 | .num_points = num_entries + 2, 87 | .points = points_precip 88 | }; 89 | GPath *path_precip_area_under = gpath_create(&path_info_precip); 90 | graphics_context_set_fill_color(ctx, PBL_IF_COLOR_ELSE(GColorCobaltBlue, GColorLightGray)); 91 | gpath_draw_filled(ctx, path_precip_area_under); 92 | gpath_destroy(path_precip_area_under); 93 | 94 | 95 | // Draw the precipitation line 96 | path_info_precip.num_points = num_entries; 97 | GPath *path_precip_top = gpath_create(&path_info_precip); 98 | graphics_context_set_stroke_color(ctx, GColorPictonBlue); 99 | graphics_context_set_stroke_width(ctx, 1); 100 | gpath_draw_outline_open(ctx, path_precip_top); 101 | gpath_destroy(path_precip_top); 102 | 103 | // Draw the temperature line 104 | GPathInfo path_info_temp = { 105 | .num_points = num_entries, 106 | .points = points_temp 107 | }; 108 | GPath *path_temp = gpath_create(&path_info_temp); 109 | graphics_context_set_stroke_color(ctx, PBL_IF_COLOR_ELSE(GColorRed, GColorWhite)); 110 | graphics_context_set_stroke_width(ctx, 3); // Only odd stroke width values supported 111 | gpath_draw_outline_open(ctx, path_temp); 112 | gpath_destroy(path_temp); 113 | 114 | // Draw a line for the bottom axis 115 | graphics_context_set_stroke_color(ctx, PBL_IF_COLOR_ELSE(GColorOrange, GColorWhite)); 116 | graphics_context_set_stroke_width(ctx, 1); 117 | graphics_draw_line(ctx, GPoint(graph_bounds.origin.x, h - BOTTOM_AXIS_H), GPoint(graph_bounds.origin.x + w, h - BOTTOM_AXIS_H)); 118 | // And for the left side axis 119 | graphics_context_set_fill_color(ctx, GColorBlack); 120 | graphics_fill_rect(ctx, GRect(0, 0, LEFT_AXIS_MARGIN_W, h - BOTTOM_AXIS_H), 0, GCornerNone); // Paint over plot bleeding 121 | graphics_draw_line(ctx, GPoint(graph_bounds.origin.x, 0), GPoint(graph_bounds.origin.x, h - BOTTOM_AXIS_H)); 122 | } 123 | 124 | static void text_layers_refresh() { 125 | static char s_buffer_lo[4], s_buffer_hi[4]; 126 | 127 | snprintf(s_buffer_hi, sizeof(s_buffer_hi), "%d", config_localize_temp(persist_get_temp_hi())); 128 | text_layer_set_text(s_hi_layer, s_buffer_hi); 129 | 130 | snprintf(s_buffer_lo, sizeof(s_buffer_lo), "%d", config_localize_temp(persist_get_temp_lo())); 131 | text_layer_set_text(s_lo_layer, s_buffer_lo); 132 | } 133 | 134 | void forecast_layer_create(Layer *parent_layer, GRect frame) { 135 | s_forecast_layer = layer_create(frame); 136 | GRect bounds = layer_get_bounds(s_forecast_layer); 137 | 138 | // Temperature HIGH 139 | s_hi_layer = text_layer_create(GRect(0, -3, 15, 20)); 140 | text_layer_set_background_color(s_hi_layer, GColorClear); 141 | text_layer_set_text_alignment(s_hi_layer, GTextAlignmentRight); 142 | text_layer_set_text_color(s_hi_layer, GColorWhite); 143 | text_layer_set_font(s_hi_layer, fonts_get_system_font(FONT_KEY_GOTHIC_18)); 144 | layer_add_child(s_forecast_layer, text_layer_get_layer(s_hi_layer)); 145 | 146 | // Temperature LOW 147 | s_lo_layer = text_layer_create(GRect(0, 22, 15, 20)); 148 | text_layer_set_background_color(s_lo_layer, GColorClear); 149 | text_layer_set_text_alignment(s_lo_layer, GTextAlignmentRight); 150 | text_layer_set_text_color(s_lo_layer, GColorWhite); 151 | text_layer_set_font(s_lo_layer, fonts_get_system_font(FONT_KEY_GOTHIC_18)); 152 | layer_add_child(s_forecast_layer, text_layer_get_layer(s_lo_layer)); 153 | 154 | // Fill the contents with values 155 | 156 | layer_set_update_proc(s_forecast_layer, forecast_update_proc); 157 | text_layers_refresh(); 158 | 159 | // Add it as a child layer to the Window's root layer 160 | layer_add_child(parent_layer, s_forecast_layer); 161 | } 162 | 163 | void forecast_layer_refresh() { 164 | layer_mark_dirty(s_forecast_layer); 165 | text_layers_refresh(); 166 | } 167 | 168 | void forecast_layer_destroy() { 169 | text_layer_destroy(s_hi_layer); 170 | text_layer_destroy(s_lo_layer); 171 | layer_destroy(s_forecast_layer); 172 | } -------------------------------------------------------------------------------- /src/pkjs/clay/config.js: -------------------------------------------------------------------------------- 1 | var meta = require('../../../package.json'); 2 | module.exports = [ 3 | { 4 | "type": "heading", 5 | "defaultValue": "ForecasWatch2" 6 | }, 7 | { 8 | "type": "text", 9 | "defaultValue": "Contribute on GitHub!" 10 | }, 11 | { 12 | "type": "section", 13 | "items": [ 14 | { 15 | "type": "heading", 16 | "defaultValue": "Time", 17 | }, 18 | { 19 | "type": "toggle", 20 | "label": "Leading zero", 21 | "messageKey": "timeLeadingZero", 22 | }, 23 | { 24 | "type": "toggle", 25 | "label": "Show AM/PM", 26 | "messageKey": "timeShowAmPm", 27 | }, 28 | { 29 | "type": "select", 30 | "label": "Axis time format", 31 | "messageKey": "axisTimeFormat", 32 | "defaultValue": "24h", 33 | "description": "Tip: go to Settings > Date & Time > Time Format on your watch to change the main time format", 34 | "options": [ 35 | { 36 | "label": "12h", 37 | "value": "12h" 38 | }, 39 | { 40 | "label": "24h", 41 | "value": "24h" 42 | } 43 | ] 44 | }, 45 | { 46 | "type": "select", 47 | "label": "Main time font", 48 | "messageKey": "timeFont", 49 | "defaultValue": "roboto", 50 | "options": [ 51 | { 52 | "label": "Roboto", 53 | "value": "roboto" 54 | }, 55 | { 56 | "label": "Leco", 57 | "value": "leco" 58 | }, 59 | { 60 | "label": "Bitham", 61 | "value": "bitham" 62 | }, 63 | ] 64 | }, 65 | { 66 | "type": "color", 67 | "label": "Main time color", 68 | "messageKey": "colorTime", 69 | "defaultValue": "#FFFFFF", 70 | "sunlight": false, 71 | "capabilities": ["COLOR"] 72 | }, 73 | ] 74 | }, 75 | { 76 | "type": "section", 77 | "items": [ 78 | { 79 | "type": "heading", 80 | "defaultValue": "Calendar", 81 | }, 82 | { 83 | "type": "select", 84 | "label": "Start week on", 85 | "messageKey": "weekStartDay", 86 | "defaultValue": "sun", 87 | "options": [ 88 | { 89 | "label": "Sunday", 90 | "value": "sun" 91 | }, 92 | { 93 | "label": "Monday", 94 | "value": "mon" 95 | } 96 | ] 97 | }, 98 | { 99 | "type": "select", 100 | "label": "First week to display", 101 | "messageKey": "firstWeek", 102 | "defaultValue": "prev", 103 | "options": [ 104 | { 105 | "label": "Previous week", 106 | "value": "prev" 107 | }, 108 | { 109 | "label": "Current week", 110 | "value": "curr" 111 | } 112 | ] 113 | }, 114 | { 115 | "type": "color", 116 | "label": "Today highlight", 117 | "messageKey": "colorToday", 118 | "defaultValue": "#000000", 119 | "description": "Black (default) means match date color, any other value overrides this.", 120 | "sunlight": false, 121 | "capabilities": ["COLOR"] 122 | }, 123 | { 124 | "type": "color", 125 | "label": "Sunday color", 126 | "messageKey": "colorSunday", 127 | "defaultValue": "#FFFFFF", 128 | "sunlight": false, 129 | "capabilities": ["COLOR"] 130 | }, 131 | { 132 | "type": "color", 133 | "label": "Saturday color", 134 | "messageKey": "colorSaturday", 135 | "defaultValue": "#FFFFFF", 136 | "sunlight": false, 137 | "capabilities": ["COLOR"] 138 | }, 139 | { 140 | "type": "color", 141 | "label": "US federal holidays color", 142 | "messageKey": "colorUSFederal", 143 | "defaultValue": "#FFFFFF", 144 | "description": "White (default) means disable", 145 | "sunlight": false, 146 | "capabilities": ["COLOR"] 147 | }, 148 | ] 149 | }, 150 | { 151 | "type": "section", 152 | "items": [ 153 | { 154 | "type": "heading", 155 | "defaultValue": "Weather" 156 | }, 157 | { 158 | "type": "select", 159 | "defaultValue": "f", 160 | "messageKey": "temperatureUnits", 161 | "label": "Temperature Units", 162 | "options": [ 163 | { 164 | "label": "°F", 165 | "value": "f" 166 | }, 167 | { 168 | "label": "°C", 169 | "value": "c" 170 | } 171 | ] 172 | }, 173 | { 174 | "type": "radiogroup", 175 | "label": "Provider", 176 | "messageKey": "provider", 177 | "defaultValue": "wunderground", 178 | "options": [ 179 | { 180 | "label": "Weather Underground", 181 | "value": "wunderground" 182 | }, 183 | { 184 | "label": "OpenWeatherMap", 185 | "value": "openweathermap" 186 | } 187 | ] 188 | }, 189 | { 190 | "type": "input", 191 | "label": "OpenWeatherMap API key", 192 | "messageKey": "owmApiKey", 193 | "description": "Register an OpenWeatherMap account and paste your API key here" 194 | }, 195 | { 196 | "type": "toggle", 197 | "label": "Force weather fetch", 198 | "messageKey": "fetch", 199 | "description": "Last successful fetch:
Never :(" 200 | }, 201 | { 202 | "type": "input", 203 | "label": "Location override", 204 | "messageKey": "location", 205 | "description": "Example: \"Manhattan\" or \"123 Oak St Plainsville KY\".
Click here to test out your location query.
To use GPS, leave this blank and ensure GPS is enabled on your device.", 206 | "attributes": { 207 | "placeholder": "Using GPS", 208 | } 209 | } 210 | ] 211 | }, 212 | { 213 | "type": "section", 214 | "items": [ 215 | { 216 | "type": "heading", 217 | "defaultValue": "Misc" 218 | }, 219 | { 220 | "type": "toggle", 221 | "label": "Show quiet time icon", 222 | "messageKey": "showQt", 223 | "defaultValue": true 224 | }, 225 | { 226 | "type": "toggle", 227 | "label": "Vibrate on bluetooth disconnect", 228 | "messageKey": "vibe", 229 | "defaultValue": false 230 | }, 231 | { 232 | "type": "select", 233 | "defaultValue": "both", 234 | "messageKey": "btIcons", 235 | "label": "Show icon for bluetooth", 236 | "options": [ 237 | { 238 | "label": "Disconnected", 239 | "value": "disconnected" 240 | }, 241 | { 242 | "label": "Connected", 243 | "value": "connected" 244 | }, 245 | { 246 | "label": "Both", 247 | "value": "both" 248 | }, 249 | { 250 | "label": "None", 251 | "value": "none" 252 | } 253 | ] 254 | }, 255 | ] 256 | }, 257 | { 258 | "type": "submit", 259 | "defaultValue": "Save Settings" 260 | }, 261 | { 262 | "type": "text", 263 | "defaultValue": "v" + meta.version 264 | } 265 | ] 266 | -------------------------------------------------------------------------------- /src/pkjs/weather/provider.js: -------------------------------------------------------------------------------- 1 | const SunCalc = require('suncalc') 2 | 3 | function request(url, type, callback) { 4 | var xhr = new XMLHttpRequest(); 5 | xhr.onload = function() { 6 | callback(this.responseText); 7 | }; 8 | xhr.open(type, url); 9 | xhr.send(); 10 | } 11 | 12 | var WeatherProvider = function() { 13 | this.numEntries = 24; 14 | this.name = 'Template'; 15 | this.id = 'interface'; 16 | this.location = null; // Address query used for overriding the GPS 17 | } 18 | 19 | WeatherProvider.prototype.gpsEnable = function() { 20 | this.location = null; 21 | } 22 | 23 | WeatherProvider.prototype.gpsOverride = function(location) { 24 | this.location = location; 25 | } 26 | 27 | WeatherProvider.prototype.withSunEvents = function(lat, lon, callback) { 28 | /* The callback runs with an array of the next two sun events (i.e. 24 hours worth), 29 | * where each sun event contains a 'type' ('sunrise' or 'sunset') and a 'date' (of type Date) 30 | */ 31 | const dateNow = new Date() 32 | const dateTomorrow = new Date().setDate(dateNow.getDate() + 1) 33 | 34 | const resultsToday = SunCalc.getTimes(dateNow, lat, lon) 35 | const resultsTomorrow = SunCalc.getTimes(dateTomorrow, lat, lon) 36 | 37 | /** 38 | * @param {SunCalc.GetTimesResult} results 39 | * @returns {{ type: 'sunrise'|'sunset', date: Date }[]} 40 | */ 41 | var processResults = function(results) { 42 | return [ 43 | { 44 | 'type': 'sunrise', 45 | 'date': results.sunrise 46 | }, 47 | { 48 | 'type': 'sunset', 49 | 'date': results.sunset 50 | } 51 | ] 52 | } 53 | 54 | var sunEvents = processResults(resultsToday).concat(processResults(resultsTomorrow)) 55 | var nextSunEvents = sunEvents.filter(function (sunEvent) { 56 | return sunEvent.date > dateNow; 57 | }); 58 | var next24HourSunEvents = nextSunEvents.slice(0, 2); 59 | console.log('The next ' + sunEvents[0].type + ' is at ' + sunEvents[0].date.toTimeString()); 60 | console.log('The next ' + sunEvents[1].type + ' is at ' + sunEvents[1].date.toTimeString()); 61 | callback(next24HourSunEvents); 62 | } 63 | 64 | WeatherProvider.prototype.withCityName = function(lat, lon, callback) { 65 | // callback(cityName) 66 | var url = 'https://geocode.arcgis.com/arcgis/rest/services/World/GeocodeServer/reverseGeocode?f=json&langCode=EN&location=' 67 | + lon + ',' + lat; 68 | request(url, 'GET', function (response) { 69 | var address = JSON.parse(response).address; 70 | var name = address.District ? address.District : address.City; 71 | console.log('Running callback with city: ' + name); 72 | callback(name); 73 | }); 74 | } 75 | 76 | // https://github.com/mattrossman/forecaswatch2/issues/59#issue-1317582743 77 | const r_lat_long = new RegExp(/([-+]?[\d\.]*),([-+]?[\d\.]*)/gm); 78 | 79 | WeatherProvider.prototype.withGeocodeCoordinates = function(callback) { 80 | // callback(lattitude, longtitude) 81 | var locationiq_key = 'pk.5a61972cde94491774bcfaa0705d5a0d'; 82 | var url = 'https://us1.locationiq.com/v1/search.php?key=' + locationiq_key 83 | + '&q=' + this.location 84 | + '&format=json'; 85 | var m = r_lat_long.exec(this.location); 86 | 87 | console.log('WeatherProvider.prototype.withGeocodeCoordinates lets regex, this.location: ' + JSON.stringify(this.location)); 88 | if (m != null) { 89 | var latitude = m[1]; 90 | var longitude = m[2]; 91 | 92 | console.log('regex matched, override is lat/long') 93 | callback(latitude, longitude); 94 | } 95 | else { 96 | console.log('regex failed, about to look up lat/long for override') 97 | request(url, 'GET', function (response) { 98 | var locations = JSON.parse(response); 99 | if (locations.length === 0) { 100 | console.log('[!] No geocoding results') 101 | } 102 | else { 103 | var closest = locations[0]; 104 | console.log('Query ' + this.location + ' geocoded to ' + closest.lat + ', ' + closest.lon); 105 | JSON.stringify('closest.lat ' + JSON.stringify(closest.lat)); 106 | JSON.stringify('closest ' + JSON.stringify(closest)); 107 | callback(closest.lat, closest.lon); 108 | } 109 | }); 110 | } 111 | 112 | } 113 | 114 | WeatherProvider.prototype.withGpsCoordinates = function(callback) { 115 | // callback(lattitude, longtitude) 116 | var options = { 117 | enableHighAccuracy: true, 118 | maximumAge: 10000, 119 | timeout: 10000 120 | }; 121 | function success(pos) { 122 | console.log('FOUND LOCATION: lat= ' + pos.coords.latitude + ' lon= ' + pos.coords.longitude); 123 | callback(pos.coords.latitude, pos.coords.longitude); 124 | } 125 | function error(err) { 126 | console.log('location error (' + err.code + '): ' + err.message); 127 | } 128 | navigator.geolocation.getCurrentPosition(success, error, options); 129 | } 130 | 131 | WeatherProvider.prototype.withCoordinates = function(callback) { 132 | if (this.location === null) { 133 | console.log('Using GPS') 134 | this.withGpsCoordinates(callback); 135 | } 136 | else { 137 | console.log('Using geocoded coordinates') 138 | this.withGeocodeCoordinates(callback); 139 | } 140 | } 141 | 142 | WeatherProvider.prototype.withProviderData = function(lat, lon, force, callback) { 143 | console.log('This is the fallback implementation of withProviderData') 144 | callback(); 145 | } 146 | 147 | WeatherProvider.prototype.fetch = function(onSuccess, onFailure, force) { 148 | this.withCoordinates((function(lat, lon) { 149 | this.withCityName(lat, lon, (function(cityName) { 150 | this.withSunEvents(lat, lon, (function(sunEvents) { 151 | this.withProviderData(lat, lon, force, (function() { 152 | // if `this` (the provider) contains valid weather details, 153 | // then we can safely call this.getPayload() 154 | if (this.hasValidData()) { 155 | console.log('Lets get the payload for ' + cityName); 156 | // Send to Pebble 157 | this.cityName = cityName; 158 | this.sunEvents = sunEvents; 159 | payload = this.getPayload(); 160 | Pebble.sendAppMessage(payload, 161 | function (e) { 162 | console.log('Weather info sent to Pebble successfully!'); 163 | onSuccess(); 164 | }, 165 | function (e) { 166 | console.log('Error sending weather info to Pebble!'); 167 | onFailure(); 168 | } 169 | ); 170 | } 171 | else { 172 | console.log('Fetch cancelled: insufficient data.') 173 | onFailure(); 174 | } 175 | }).bind(this)); 176 | }).bind(this)); 177 | }).bind(this)); 178 | }).bind(this)); 179 | } 180 | 181 | WeatherProvider.prototype.hasValidData = function() { 182 | // all fields are set 183 | if (this.hasOwnProperty('tempTrend') && this.hasOwnProperty('precipTrend') && this.hasOwnProperty('startTime') && this.hasOwnProperty('currentTemp')) { 184 | // trends are filled with enough data 185 | if (this.tempTrend.length >= this.numEntries && this.precipTrend.length >= this.numEntries) { 186 | console.log('Data from ' + this.name + ' is good, ready to fetch.'); 187 | return true; 188 | } 189 | } 190 | else { 191 | if (!this.hasOwnProperty('tempTrend')) { 192 | console.log('Temperature trend array was not set properly'); 193 | } 194 | if (!this.hasOwnProperty('precipTrend')) { 195 | console.log('Precipitation trend array was not set properly'); 196 | } 197 | if (!this.hasOwnProperty('startTime')) { 198 | console.log('Start time value was not set properly'); 199 | } 200 | if (!this.hasOwnProperty('currentTemp')) { 201 | console.log('Current temperature value was not set properly'); 202 | } 203 | console.log('Data does not pass the checks.'); 204 | return false; 205 | } 206 | } 207 | 208 | WeatherProvider.prototype.getPayload = function() { 209 | // Get the rounded (integer) temperatures for those hours 210 | var temps = this.tempTrend.slice(0, this.numEntries).map(function(temperature) { 211 | return Math.round(temperature); 212 | }); 213 | var precips = this.precipTrend.slice(0, this.numEntries).map(function(probability) { 214 | return Math.round(probability * 100); 215 | }); 216 | var tempsIntView = new Int16Array(temps); 217 | var tempsByteArray = Array.prototype.slice.call(new Uint8Array(tempsIntView.buffer)) 218 | var sunEventsIntView = new Int32Array(this.sunEvents.map(function(sunEvent) { 219 | return sunEvent.date.getTime() / 1000; // Seconds since epoch 220 | })); 221 | var sunEventsByteArray = Array.prototype.slice.call(new Uint8Array(sunEventsIntView.buffer)) 222 | var payload = { 223 | 'TEMP_TREND_INT16': tempsByteArray, 224 | 'PRECIP_TREND_UINT8': precips, // Holds values within [0,100] 225 | 'FORECAST_START': this.startTime, 226 | 'NUM_ENTRIES': this.numEntries, 227 | 'CURRENT_TEMP': Math.round(this.currentTemp), 228 | 'CITY': this.cityName, 229 | // The first byte determines whether the list of events starts on a sunrise (0) or sunset (1) 230 | 'SUN_EVENTS': [this.sunEvents[0].type == 'sunrise' ? 0 : 1].concat(sunEventsByteArray) 231 | } 232 | return payload; 233 | } 234 | 235 | module.exports = WeatherProvider; -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------