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