Subversion Repositories Kolibri OS

Rev

Rev 8586 | Rev 8735 | Go to most recent revision | Blame | Compare with Previous | Last modification | View Log | Download | RSS feed

  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.
  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.  
  17. */
  18.  
  19. #include <stdio.h>
  20. #include <string.h>
  21. #include <time.h>
  22. #include <stdbool.h>
  23. #include "json/json.h"
  24. #include <kos32sys1.h>
  25. #include <kolibrisys.h>
  26. #include <clayer/http.h>
  27. #include <clayer/libimg.h>
  28.  
  29. #define VERSION  "Weather 1.5"
  30.  
  31. enum BUTTONS{
  32.     BTN_QUIT = 1,
  33.     BTN_UPDATE = 2
  34. };
  35.  
  36. #define START_YPOS 34
  37. #define UTF8_W 8
  38. #define CP866_W 6
  39. #define JSON_OBJ(X) value->u.object.values[X]
  40. #define OK 200
  41.  
  42. unsigned WINDOW_W = 230;
  43.  
  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"
  46.  
  47. Image *blend=NULL;
  48. const char *config_name = "/sys/Settings/weather.json";
  49.  
  50. unsigned char char_size=1;
  51. uint64_t AutoUpdateTime = 0;
  52.  
  53. char *wind_speed_str, *pressure_str, *visibility_str, *humidity_str, *update_str, *wind_deg_str;
  54.        
  55. char lang[3]="en";
  56. char format_temp_str[6];
  57. char full_url[512];
  58. char full_url_image[256];
  59.  
  60. char temp_char='K';
  61.  
  62. struct kolibri_system_colors sys_color_table;
  63.  
  64. pos_t win_pos;
  65.  
  66. #pragma pack(push,1)
  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;
  79. #pragma pack(pop)
  80.  
  81. void notify_show(char *text)
  82. {
  83.    start_app("/sys/@notify", text);
  84. }
  85.  
  86. void* safe_malloc(size_t size)
  87. {
  88.     void *p=malloc(size);
  89.     if(p==NULL){
  90.        notify_show("'Memory allocation error!' -E");
  91.        exit(0);
  92.     }else{
  93.         return p;
  94.     }
  95. }
  96.  
  97. void draw_format_text_sys(int x, int y, color_t color, const char *format_str, ... ) // Форматированный вывод в окно
  98. {
  99.     char tmp_buff[100];
  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.  
  107. void find_and_set(json_value *value, struct open_weather_data* weather) // Ищем значения в json и заполняем структуру "myw"
  108. {
  109.     for(int i=0; i<value->u.object.length; i++){
  110.         if(!strcmp(JSON_OBJ(i).name, "main")){
  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.             }
  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")){
  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.             }
  126.         }
  127.         if(!strcmp(JSON_OBJ(i).name, "weather")){
  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);
  130.         }
  131.         if(!strcmp(JSON_OBJ(i).name, "wind")){
  132.             weather->wind_deg = JSON_OBJ(i).value->u.object.values[1].value->u.integer;
  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.             }  
  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);
  150.             free(errmsg);
  151.         }
  152.     }
  153. }
  154.  
  155. http_msg* get_json(char *City, char *Token, char* Units)
  156. {
  157.     sprintf(full_url, API, City, Token, Units, lang);
  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) {
  161.         return h;
  162.     } else {
  163.         http_free(h);
  164.         return NULL;
  165.     }
  166. }
  167.  
  168. void get_image() // Функция загрузки изображения
  169. {
  170.     sprintf(full_url_image, IMAGE_URL, myw.image_code);
  171.     http_msg *h= http_get(full_url_image, 0, HTTP_FLAG_BLOCK, "");
  172.     http_long_receive(h);
  173.    
  174.     if (h->status == OK) {
  175.         Image *image = img_decode(h->content_ptr, h->content_length, 0); // Декодирование RAW данных в данные изображения
  176.         if (image->Type != IMAGE_BPP32) {
  177.             image = img_convert(image, NULL, IMAGE_BPP32, 0, 0); // Конвертируем картику в BPP32
  178.                 if (!image) {
  179.                 notify_show("'Convetring image error!' -E");  
  180.                 exit(0);
  181.             }
  182.         }
  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); // Уничтажаем растянутую картинку  
  189.     }else{
  190.        notify_show("'Image not loaded!!' -W");
  191.     }
  192.     if(h!=NULL){
  193.         http_free(h);
  194.     }
  195. }
  196.  
  197. void RedrawGUI() // Перересовываем интерфейс
  198. {
  199.     begin_draw();   // Начинам прорисовку
  200.  
  201.     int new_win_w = (strlen(myw.City)/char_size+10)*(UTF8_W+char_size-1); // Если название города не влезает в окно
  202.     if(new_win_w<WINDOW_W){
  203.         new_win_w=WINDOW_W;
  204.     }
  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.     // Выводим жирным шрифтом название локации и временной зоны
  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);
  210.     // Выводим изображение
  211.     img_draw(blend, 10, START_YPOS+30, 64,64,0,0);
  212.     // Выводим жирным шрифтом название локации и временной зоны
  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);
  215.     // Выводим жирным шрифтом название локации и временной зоны
  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);
  218.     // Выводим обычным шрифтом
  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);
  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);
  227.     end_draw();
  228. }
  229.  
  230. void get_config(char **City, char **Token, char **Units) // Загружаем конфиг
  231. {
  232.     FILE *config_j = fopen(config_name, "rb");
  233.     if(config_j==NULL){
  234.         notify_show("'Configuration file not found!' -E");
  235.         exit(0);
  236.     }
  237.     size_t size = _ksys_get_filesize((char*)config_name); // Получаем размер файла
  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.     }
  243.     json_value* value =json_parse (config_buff, size); // Парсим конфиг
  244.     for(int i=0; i<value->u.object.length; i++){
  245.         if(!strcmp(JSON_OBJ(i).name, "Location") && JSON_OBJ(i).value->type==json_string){  
  246.             *City = JSON_OBJ(i).value->u.string.ptr;  // Получаем название города
  247.         }
  248.         else if(!strcmp(JSON_OBJ(i).name, "Token") && JSON_OBJ(i).value->type==json_string){
  249.             *Token = JSON_OBJ(i).value->u.string.ptr; // Получаем токен
  250.         }
  251.         else if(!strcmp(JSON_OBJ(i).name, "Celsius") && JSON_OBJ(i).value->type==json_boolean){
  252.             if(JSON_OBJ(i).value->u.boolean){
  253.                 *Units = "metric";
  254.                 temp_char = 'C';
  255.             }else{
  256.                 *Units = "imperial";
  257.                 temp_char = 'F';
  258.             }
  259.         }
  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); // Получаем язык
  262.         }
  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.         }
  266.     }
  267.     if(*City==NULL || *Token ==NULL){
  268.          notify_show("'Invalid config!' -E");
  269.          exit(0);
  270.     }
  271.     free(config_buff);
  272.     fclose(config_j);
  273. }
  274.  
  275. void Update(char* city, char* token, char* units) // Обновление данных
  276. {
  277.     if(blend!=NULL){
  278.         img_destroy(blend); // Уничтожение картинику с прозрачностью
  279.         blend = NULL;
  280.     }
  281.     memset(&myw, 0, sizeof myw); // Обнуляем структуру
  282.     strcpy(myw.City,"None");
  283.     strcpy(myw.weath_desc,"unknown");
  284.     http_msg *json_file = get_json(city, token, units); // Получаем данные о погоде в формате json
  285.     if(json_file != NULL){
  286.         json_value* value=json_parse(json_file->content_ptr, json_file->content_length); // Парсим json файл
  287.         find_and_set(value, &myw);  //  Ищем значения в json
  288.         sprintf(format_temp_str, "%s°%c","%d",temp_char); // Формируем строку для вывода температуры
  289.         get_image(); // Получаем картинку
  290.         json_value_free(value); // Уничтожаем полученные json значения
  291.         http_free(json_file);
  292.     }else{
  293.        notify_show("'Connection error!' -E");
  294.     }
  295. }
  296.  
  297. void set_lang()
  298. {
  299.     if(!strcmp(lang, "ru")){
  300.         wind_speed_str = "Скорость ветра:    %d м/с";
  301.         pressure_str   = "Давление:          %d гПa";
  302.         visibility_str = "Видимость:         %d м";
  303.         humidity_str   = "Влажность:         %d %s";
  304.         update_str     = "Обновить";
  305.         wind_deg_str   = "Направление ветра: %d°";
  306.         WINDOW_W = 250;
  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";
  312.         humidity_str   = "Luftfeuchtigkeit:    %d %s";
  313.         wind_deg_str   = "Windrichtung         %d°";
  314.         WINDOW_W = 270;
  315.         update_str     = "Aktualisieren";
  316.     }else{
  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°";
  322.         update_str     = "Refresh";
  323.     }
  324. }
  325.  
  326. int main()
  327. {
  328.     win_pos = get_mouse_pos(0); // Получаем позицию курсора
  329.  
  330.     if(!kolibri_libimg_init()){ // Загружаем libimg.obj
  331.         notify_show("Libimg.obj not loaded!' -E");  
  332.         exit(0);
  333.     }
  334.     get_system_colors(&sys_color_table); // Получаем таблица цветов
  335.  
  336.     char *City=NULL, *Token=NULL, *Units=NULL; // Указатели на токен, название города, систему мер
  337.  
  338.     get_config(&City, &Token, &Units); // Загружаем конфиг
  339.     set_lang();  // Установить язык приложения
  340.     Update(City, Token, Units);
  341.  
  342.     uint32_t (*event)();
  343.  
  344.     if(AutoUpdateTime<=0){
  345.         event = get_os_event;
  346.     }else{
  347.         event = wait_for_event;
  348.     }
  349.    
  350.     while(1){
  351.         switch(event(6000*AutoUpdateTime)){ // Получаем системное событие
  352.             case KOLIBRI_EVENT_NONE:        // Нет события
  353.                 Update(City, Token, Units);
  354.                 debug_printf("Weather: Update\n");
  355.                 break;
  356.             case KOLIBRI_EVENT_REDRAW:      // Событие перерисовки
  357.                 RedrawGUI();
  358.                 break;        
  359.             case KOLIBRI_EVENT_BUTTON:      // Событие кнопок
  360.                 switch (get_os_button()){
  361.                     case BTN_UPDATE:
  362.                         Update(City, Token, Units);
  363.                         RedrawGUI();
  364.                         break;
  365.                     case BTN_QUIT:          // Кнопка выхода
  366.                         exit(0);
  367.                         break;
  368.                 }
  369.                 break;
  370.         }  
  371.     }
  372.     return 0;
  373. }
  374.