Rev 8586 | Rev 8735 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed
Rev | Author | Line No. | Line |
---|---|---|---|
8553 | superturbo | 1 | /* Copyright (C) 2019-2021 Logaev Maxim (turbocat2001), GPLv2 */ |
2 | |||
3 | /* |
||
4 | Info: App uses api from openweathermap.org. |
||
5 | The standard configuration uses my token and the city of Moscow. |
||
6 | You can always change it in the weather.json file. |
||
8566 | superturbo | 7 | weather.json configuration example: |
8 | |||
9 | { |
||
10 | "Celsius": false, // Enabled fahrenheit (Optional) |
||
11 | "Location": "Berlin", // City Berlin |
||
12 | "Token": "19ffa14b3dc0e238175829461d1788b8", // OpenWeatherMap token |
||
13 | "Lang": "ru", // Language (Optional) |
||
14 | "AutoUpdate": 5 // In minutes. 0 - disabled (Optional) |
||
15 | } |
||
16 | |||
8553 | superturbo | 17 | */ |
18 | |||
19 | #include |
||
20 | #include |
||
8566 | superturbo | 21 | #include |
22 | #include |
||
8553 | superturbo | 23 | #include "json/json.h" |
24 | #include |
||
25 | #include |
||
26 | #include |
||
27 | #include |
||
28 | |||
8566 | superturbo | 29 | #define VERSION "Weather 1.5" |
8553 | superturbo | 30 | |
31 | enum BUTTONS{ |
||
32 | BTN_QUIT = 1, |
||
33 | BTN_UPDATE = 2 |
||
34 | }; |
||
35 | |||
8556 | superturbo | 36 | #define START_YPOS 34 |
8554 | superturbo | 37 | #define UTF8_W 8 |
38 | #define CP866_W 6 |
||
8555 | superturbo | 39 | #define JSON_OBJ(X) value->u.object.values[X] |
40 | #define OK 200 |
||
8553 | superturbo | 41 | |
8556 | superturbo | 42 | unsigned WINDOW_W = 230; |
8554 | superturbo | 43 | |
8555 | superturbo | 44 | #define API "api.openweathermap.org/data/2.5/weather?q=%s&appid=%s&units=%s&lang=%s" |
45 | #define IMAGE_URL "openweathermap.org/img/w/%s.png" |
||
8556 | superturbo | 46 | |
8566 | superturbo | 47 | Image *blend=NULL; |
8589 | turbocat | 48 | const char *config_name = "/sys/Settings/weather.json"; |
8555 | superturbo | 49 | |
50 | unsigned char char_size=1; |
||
8566 | superturbo | 51 | uint64_t AutoUpdateTime = 0; |
8554 | superturbo | 52 | |
8556 | superturbo | 53 | char *wind_speed_str, *pressure_str, *visibility_str, *humidity_str, *update_str, *wind_deg_str; |
8555 | superturbo | 54 | |
55 | char lang[3]="en"; |
||
56 | char format_temp_str[6]; |
||
8554 | superturbo | 57 | char full_url[512]; |
8553 | superturbo | 58 | char full_url_image[256]; |
8555 | superturbo | 59 | |
60 | char temp_char='K'; |
||
61 | |||
8553 | superturbo | 62 | struct kolibri_system_colors sys_color_table; |
63 | |||
8554 | superturbo | 64 | pos_t win_pos; |
65 | |||
8553 | superturbo | 66 | #pragma pack(push,1) |
8555 | superturbo | 67 | struct open_weather_data{ |
68 | char City[100]; |
||
69 | int wind_speed; |
||
70 | int wind_deg; |
||
71 | int pressure; |
||
72 | int humidity; |
||
73 | char weath_desc[100]; |
||
74 | int visibility; |
||
75 | int timezone; |
||
76 | char image_code[4]; |
||
77 | int temp; |
||
78 | }myw; |
||
8553 | superturbo | 79 | #pragma pack(pop) |
80 | |||
81 | void notify_show(char *text) |
||
82 | { |
||
83 | start_app("/sys/@notify", text); |
||
84 | } |
||
85 | |||
8555 | superturbo | 86 | void* safe_malloc(size_t size) |
8553 | superturbo | 87 | { |
8566 | superturbo | 88 | void *p=malloc(size); |
8553 | superturbo | 89 | if(p==NULL){ |
90 | notify_show("'Memory allocation error!' -E"); |
||
91 | exit(0); |
||
92 | }else{ |
||
93 | return p; |
||
94 | } |
||
95 | } |
||
96 | |||
8566 | superturbo | 97 | void draw_format_text_sys(int x, int y, color_t color, const char *format_str, ... ) // Форматированный вывод в окно |
8553 | superturbo | 98 | { |
8566 | superturbo | 99 | char tmp_buff[100]; |
8553 | superturbo | 100 | va_list ap; |
101 | va_start (ap, format_str); |
||
102 | vsnprintf(tmp_buff, sizeof tmp_buff ,format_str, ap); |
||
103 | va_end(ap); |
||
104 | draw_text_sys(tmp_buff, x, y , 0, color); |
||
105 | } |
||
106 | |||
8566 | superturbo | 107 | void find_and_set(json_value *value, struct open_weather_data* weather) // Ищем значения в json и заполняем структуру "myw" |
8553 | superturbo | 108 | { |
109 | for(int i=0; i |
||
110 | if(!strcmp(JSON_OBJ(i).name, "main")){ |
||
8554 | superturbo | 111 | if(JSON_OBJ(i).value->u.object.values[0].value->type==json_double) |
112 | { |
||
113 | weather->temp = (int)JSON_OBJ(i).value->u.object.values[0].value->u.dbl; |
||
114 | }else{ |
||
115 | weather->temp = JSON_OBJ(i).value->u.object.values[0].value->u.integer; |
||
116 | } |
||
8553 | superturbo | 117 | weather->pressure = JSON_OBJ(i).value->u.object.values[4].value->u.integer; |
118 | weather->humidity = JSON_OBJ(i).value->u.object.values[5].value->u.integer; |
||
119 | } |
||
120 | if(!strcmp(JSON_OBJ(i).name, "name")){ |
||
8566 | superturbo | 121 | if(!strcmp(&JSON_OBJ(i).value->u.string.ptr[JSON_OBJ(i).value->u.string.length-3], "’")){ |
122 | strncpy(weather->City, JSON_OBJ(i).value->u.string.ptr, JSON_OBJ(i).value->u.string.length-3); |
||
123 | }else{ |
||
124 | strcpy(weather->City, JSON_OBJ(i).value->u.string.ptr); |
||
125 | } |
||
8553 | superturbo | 126 | } |
127 | if(!strcmp(JSON_OBJ(i).name, "weather")){ |
||
8554 | superturbo | 128 | strcpy(weather->weath_desc, JSON_OBJ(i).value->u.array.values[0]->u.object.values[2].value->u.string.ptr); |
129 | strcpy(weather->image_code, JSON_OBJ(i).value->u.array.values[0]->u.object.values[3].value->u.string.ptr); |
||
8553 | superturbo | 130 | } |
131 | if(!strcmp(JSON_OBJ(i).name, "wind")){ |
||
8556 | superturbo | 132 | weather->wind_deg = JSON_OBJ(i).value->u.object.values[1].value->u.integer; |
8554 | superturbo | 133 | if(JSON_OBJ(i).value->u.object.values[0].value->type==json_double) |
134 | { |
||
135 | weather->wind_speed = (int)JSON_OBJ(i).value->u.object.values[0].value->u.dbl; |
||
136 | }else{ |
||
137 | weather->wind_speed = JSON_OBJ(i).value->u.object.values[0].value->u.integer; |
||
138 | } |
||
8553 | superturbo | 139 | } |
140 | if(!strcmp(JSON_OBJ(i).name, "visibility")){ |
||
141 | weather->visibility = JSON_OBJ(i).value->u.integer; |
||
142 | } |
||
143 | if(!strcmp(JSON_OBJ(i).name, "timezone")){ |
||
144 | weather->timezone = JSON_OBJ(i).value->u.integer/60/60; |
||
145 | } |
||
146 | if(!strcmp(JSON_OBJ(i).name, "message")){ |
||
147 | char *errmsg = safe_malloc(weather->timezone = JSON_OBJ(i).value->u.string.length+6); |
||
148 | sprintf(errmsg,"'%s!' -E", JSON_OBJ(i).value->u.string.ptr); |
||
149 | notify_show(errmsg); |
||
8566 | superturbo | 150 | free(errmsg); |
8553 | superturbo | 151 | } |
152 | } |
||
153 | } |
||
154 | |||
8555 | superturbo | 155 | http_msg* get_json(char *City, char *Token, char* Units) |
8553 | superturbo | 156 | { |
8555 | superturbo | 157 | sprintf(full_url, API, City, Token, Units, lang); |
8553 | superturbo | 158 | http_msg *h = http_get(full_url, 0, HTTP_FLAG_BLOCK, ""); |
159 | http_long_receive(h); |
||
160 | if (h->status == OK || h->status == 404) { |
||
8554 | superturbo | 161 | return h; |
8553 | superturbo | 162 | } else { |
8566 | superturbo | 163 | http_free(h); |
8553 | superturbo | 164 | return NULL; |
165 | } |
||
166 | } |
||
167 | |||
8566 | superturbo | 168 | void get_image() // Функция загрузки изображения |
169 | { |
||
8553 | superturbo | 170 | sprintf(full_url_image, IMAGE_URL, myw.image_code); |
8566 | superturbo | 171 | http_msg *h= http_get(full_url_image, 0, HTTP_FLAG_BLOCK, ""); |
8553 | superturbo | 172 | http_long_receive(h); |
173 | |||
174 | if (h->status == OK) { |
||
8566 | superturbo | 175 | Image *image = img_decode(h->content_ptr, h->content_length, 0); // Декодирование RAW данных в данные изображения |
8553 | superturbo | 176 | if (image->Type != IMAGE_BPP32) { |
8566 | superturbo | 177 | image = img_convert(image, NULL, IMAGE_BPP32, 0, 0); // Конвертируем картику в BPP32 |
8553 | superturbo | 178 | if (!image) { |
179 | notify_show("'Convetring image error!' -E"); |
||
180 | exit(0); |
||
181 | } |
||
182 | } |
||
8566 | superturbo | 183 | blend = img_create(64, 64, IMAGE_BPP32); // Создаём фон для картинки |
184 | img_fill_color(blend, 64, 64, sys_color_table.work_area); // Заливаем фон цветом окна |
||
185 | Image* image2 = img_scale(image, 0, 0, 50, 50, NULL, LIBIMG_SCALE_STRETCH , LIBIMG_INTER_BILINEAR, 64, 64); // Растягиваем изображение |
||
186 | img_blend(blend, image2, 0, 0, 0, 0, 64, 64); // Смешиваем растянутую картинку и фон для получения прозрачности |
||
187 | img_destroy(image); // Уничтожаем исходную картинку |
||
188 | img_destroy(image2); // Уничтажаем растянутую картинку |
||
8553 | superturbo | 189 | }else{ |
190 | notify_show("'Image not loaded!!' -W"); |
||
8566 | superturbo | 191 | } |
192 | if(h!=NULL){ |
||
193 | http_free(h); |
||
194 | } |
||
8553 | superturbo | 195 | } |
196 | |||
8556 | superturbo | 197 | void RedrawGUI() // Перересовываем интерфейс |
8553 | superturbo | 198 | { |
8556 | superturbo | 199 | begin_draw(); // Начинам прорисовку |
8566 | superturbo | 200 | |
201 | int new_win_w = (strlen(myw.City)/char_size+10)*(UTF8_W+char_size-1); // Если название города не влезает в окно |
||
8554 | superturbo | 202 | if(new_win_w |
203 | new_win_w=WINDOW_W; |
||
204 | } |
||
8556 | superturbo | 205 | // Рисуем окно |
206 | sys_create_window(win_pos.x, win_pos.y, new_win_w, START_YPOS+220, VERSION, sys_color_table.work_area, 0x14); |
||
207 | // Выводим жирным шрифтом название локации и временной зоны |
||
8554 | superturbo | 208 | draw_format_text_sys(20, START_YPOS, 0xB0000000 | sys_color_table.work_text, "%s (UTC%+d)", myw.City, myw.timezone); |
209 | draw_format_text_sys(21, START_YPOS, 0xB0000000 | sys_color_table.work_text, "%s (UTC%+d)", myw.City, myw.timezone); |
||
8556 | superturbo | 210 | // Выводим изображение |
8554 | superturbo | 211 | img_draw(blend, 10, START_YPOS+30, 64,64,0,0); |
8556 | superturbo | 212 | // Выводим жирным шрифтом название локации и временной зоны |
8554 | superturbo | 213 | draw_format_text_sys(20, START_YPOS+20, 0xb0000000 | sys_color_table.work_text, myw.weath_desc); |
214 | draw_format_text_sys(21, START_YPOS+20, 0xb0000000 | sys_color_table.work_text, myw.weath_desc); |
||
8556 | superturbo | 215 | // Выводим жирным шрифтом название локации и временной зоны |
8555 | superturbo | 216 | draw_format_text_sys(100, START_YPOS+45, 0xb1000000 | sys_color_table.work_text, format_temp_str, myw.temp); |
217 | draw_format_text_sys(101, START_YPOS+46, 0xb1000000 | sys_color_table.work_text, format_temp_str, myw.temp); |
||
8556 | superturbo | 218 | // Выводим обычным шрифтом |
8555 | superturbo | 219 | draw_format_text_sys(20, START_YPOS+80, 0xb0000000 | sys_color_table.work_text, pressure_str,myw.pressure); |
220 | draw_format_text_sys(20, START_YPOS+100, 0xb0000000 | sys_color_table.work_text, humidity_str, myw.humidity, "%"); |
||
221 | draw_format_text_sys(20, START_YPOS+120, 0xb0000000 | sys_color_table.work_text, wind_speed_str, myw.wind_speed); |
||
8556 | superturbo | 222 | draw_format_text_sys(20, START_YPOS+140, 0xb0000000 | sys_color_table.work_text, wind_deg_str, myw.wind_deg); |
223 | draw_format_text_sys(20, START_YPOS+160, 0xb0000000 | sys_color_table.work_text, visibility_str, myw.visibility); |
||
224 | // Определяем кнопку |
||
225 | define_button(X_W(new_win_w/2-60,120), Y_H(START_YPOS+180,30), BTN_UPDATE, sys_color_table.work_button); |
||
226 | draw_text_sys(update_str, (new_win_w/2)-(UTF8_W*strlen(update_str)/2/char_size), START_YPOS+190, 0, 0xb0000000 | sys_color_table.work_button_text); |
||
8553 | superturbo | 227 | end_draw(); |
228 | } |
||
229 | |||
8556 | superturbo | 230 | void get_config(char **City, char **Token, char **Units) // Загружаем конфиг |
8553 | superturbo | 231 | { |
8589 | turbocat | 232 | FILE *config_j = fopen(config_name, "rb"); |
8553 | superturbo | 233 | if(config_j==NULL){ |
234 | notify_show("'Configuration file not found!' -E"); |
||
235 | exit(0); |
||
236 | } |
||
8589 | turbocat | 237 | size_t size = _ksys_get_filesize((char*)config_name); // Получаем размер файла |
8553 | superturbo | 238 | char *config_buff = safe_malloc(size+1); |
239 | if(size != fread(config_buff, sizeof(char), size, config_j)){ |
||
240 | notify_show("'The configuration file was not fully read!' -E"); |
||
241 | exit(0); |
||
242 | } |
||
8556 | superturbo | 243 | json_value* value =json_parse (config_buff, size); // Парсим конфиг |
8553 | superturbo | 244 | for(int i=0; i |
8566 | superturbo | 245 | if(!strcmp(JSON_OBJ(i).name, "Location") && JSON_OBJ(i).value->type==json_string){ |
8556 | superturbo | 246 | *City = JSON_OBJ(i).value->u.string.ptr; // Получаем название города |
8553 | superturbo | 247 | } |
8566 | superturbo | 248 | else if(!strcmp(JSON_OBJ(i).name, "Token") && JSON_OBJ(i).value->type==json_string){ |
8556 | superturbo | 249 | *Token = JSON_OBJ(i).value->u.string.ptr; // Получаем токен |
8553 | superturbo | 250 | } |
8566 | superturbo | 251 | else if(!strcmp(JSON_OBJ(i).name, "Celsius") && JSON_OBJ(i).value->type==json_boolean){ |
8555 | superturbo | 252 | if(JSON_OBJ(i).value->u.boolean){ |
8556 | superturbo | 253 | *Units = "metric"; |
8555 | superturbo | 254 | temp_char = 'C'; |
255 | }else{ |
||
8556 | superturbo | 256 | *Units = "imperial"; |
8555 | superturbo | 257 | temp_char = 'F'; |
258 | } |
||
259 | } |
||
8566 | superturbo | 260 | else if(!strcmp(JSON_OBJ(i).name, "Lang") && JSON_OBJ(i).value->type==json_string){ |
261 | strncpy(lang, JSON_OBJ(i).value->u.string.ptr,2); // Получаем язык |
||
8555 | superturbo | 262 | } |
8566 | superturbo | 263 | else if(!strcmp(JSON_OBJ(i).name, "AutoUpdate") && JSON_OBJ(i).value->type==json_integer){ |
264 | AutoUpdateTime = JSON_OBJ(i).value->u.integer; // Получаем время автообновлений данных |
||
265 | } |
||
8553 | superturbo | 266 | } |
267 | if(*City==NULL || *Token ==NULL){ |
||
8555 | superturbo | 268 | notify_show("'Invalid config!' -E"); |
8553 | superturbo | 269 | exit(0); |
270 | } |
||
8566 | superturbo | 271 | free(config_buff); |
8554 | superturbo | 272 | fclose(config_j); |
8553 | superturbo | 273 | } |
274 | |||
8556 | superturbo | 275 | void Update(char* city, char* token, char* units) // Обновление данных |
8553 | superturbo | 276 | { |
8554 | superturbo | 277 | if(blend!=NULL){ |
8566 | superturbo | 278 | img_destroy(blend); // Уничтожение картинику с прозрачностью |
8555 | superturbo | 279 | blend = NULL; |
8554 | superturbo | 280 | } |
8556 | superturbo | 281 | memset(&myw, 0, sizeof myw); // Обнуляем структуру |
282 | strcpy(myw.City,"None"); |
||
8554 | superturbo | 283 | strcpy(myw.weath_desc,"unknown"); |
8556 | superturbo | 284 | http_msg *json_file = get_json(city, token, units); // Получаем данные о погоде в формате json |
8553 | superturbo | 285 | if(json_file != NULL){ |
8566 | superturbo | 286 | json_value* value=json_parse(json_file->content_ptr, json_file->content_length); // Парсим json файл |
8556 | superturbo | 287 | find_and_set(value, &myw); // Ищем значения в json |
288 | sprintf(format_temp_str, "%s°%c","%d",temp_char); // Формируем строку для вывода температуры |
||
8566 | superturbo | 289 | get_image(); // Получаем картинку |
290 | json_value_free(value); // Уничтожаем полученные json значения |
||
291 | http_free(json_file); |
||
8553 | superturbo | 292 | }else{ |
8554 | superturbo | 293 | notify_show("'Connection error!' -E"); |
8553 | superturbo | 294 | } |
295 | } |
||
296 | |||
8555 | superturbo | 297 | void set_lang() |
298 | { |
||
299 | if(!strcmp(lang, "ru")){ |
||
8556 | superturbo | 300 | wind_speed_str = "Скорость ветра: %d м/с"; |
301 | pressure_str = "Давление: %d гПa"; |
||
302 | visibility_str = "Видимость: %d м"; |
||
303 | humidity_str = "Влажность: %d %s"; |
||
8555 | superturbo | 304 | update_str = "Обновить"; |
8556 | superturbo | 305 | wind_deg_str = "Направление ветра: %d°"; |
306 | WINDOW_W = 250; |
||
8555 | superturbo | 307 | char_size = 2; |
308 | }else if(!strcmp(lang, "de")){ |
||
309 | wind_speed_str = "Windgeschwindigkeit: %d m/s"; |
||
310 | pressure_str = "Druck: %d hPa"; |
||
311 | visibility_str = "Sichtbarkeit: %d m"; |
||
8556 | superturbo | 312 | humidity_str = "Luftfeuchtigkeit: %d %s"; |
313 | wind_deg_str = "Windrichtung %d°"; |
||
8555 | superturbo | 314 | WINDOW_W = 270; |
315 | update_str = "Aktualisieren"; |
||
316 | }else{ |
||
8556 | superturbo | 317 | pressure_str = "Pressure: %d hPa"; |
318 | humidity_str = "Humidity: %d %s"; |
||
319 | visibility_str = "Visibility: %d m"; |
||
320 | wind_speed_str = "Wind speed: %d m/s"; |
||
321 | wind_deg_str = "Wind direction: %d°"; |
||
8555 | superturbo | 322 | update_str = "Refresh"; |
323 | } |
||
324 | } |
||
325 | |||
8566 | superturbo | 326 | int main() |
327 | { |
||
8556 | superturbo | 328 | win_pos = get_mouse_pos(0); // Получаем позицию курсора |
8566 | superturbo | 329 | |
8556 | superturbo | 330 | if(!kolibri_libimg_init()){ // Загружаем libimg.obj |
331 | notify_show("Libimg.obj not loaded!' -E"); |
||
8554 | superturbo | 332 | exit(0); |
333 | } |
||
8556 | superturbo | 334 | get_system_colors(&sys_color_table); // Получаем таблица цветов |
8555 | superturbo | 335 | |
8566 | superturbo | 336 | char *City=NULL, *Token=NULL, *Units=NULL; // Указатели на токен, название города, систему мер |
8554 | superturbo | 337 | |
8556 | superturbo | 338 | get_config(&City, &Token, &Units); // Загружаем конфиг |
339 | set_lang(); // Установить язык приложения |
||
8566 | superturbo | 340 | Update(City, Token, Units); |
8556 | superturbo | 341 | |
8566 | superturbo | 342 | uint32_t (*event)(); |
343 | |||
344 | if(AutoUpdateTime<=0){ |
||
345 | event = get_os_event; |
||
346 | }else{ |
||
347 | event = wait_for_event; |
||
348 | } |
||
349 | |||
8553 | superturbo | 350 | while(1){ |
8566 | superturbo | 351 | switch(event(6000*AutoUpdateTime)){ // Получаем системное событие |
352 | case KOLIBRI_EVENT_NONE: // Нет события |
||
353 | Update(City, Token, Units); |
||
354 | debug_printf("Weather: Update\n"); |
||
8553 | superturbo | 355 | break; |
8566 | superturbo | 356 | case KOLIBRI_EVENT_REDRAW: // Событие перерисовки |
8553 | superturbo | 357 | RedrawGUI(); |
358 | break; |
||
8566 | superturbo | 359 | case KOLIBRI_EVENT_BUTTON: // Событие кнопок |
8553 | superturbo | 360 | switch (get_os_button()){ |
8566 | superturbo | 361 | case BTN_UPDATE: |
8556 | superturbo | 362 | Update(City, Token, Units); |
8553 | superturbo | 363 | RedrawGUI(); |
364 | break; |
||
8566 | superturbo | 365 | case BTN_QUIT: // Кнопка выхода |
8553 | superturbo | 366 | exit(0); |
367 | break; |
||
368 | } |
||
8566 | superturbo | 369 | break; |
370 | } |
||
8553 | superturbo | 371 | } |
372 | return 0; |
||
373 | }=0){> |