Subversion Repositories Kolibri OS

Rev

Rev 8589 | Rev 9651 | Go to most recent revision | Only display areas with differences | Regard whitespace | Details | Blame | Last modification | View Log | RSS feed

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