Subversion Repositories Kolibri OS

Rev

Rev 8589 | Rev 9651 | Go to most recent revision | Show entire file | Ignore whitespace | Details | Blame | Last modification | View Log | RSS feed

Rev 8589 Rev 8735
Line 6... Line 6...
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: 
Line 8... Line 8...
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)
Line 19... Line 19...
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 
Line 28... Line 27...
28
 
27
 
Line 29... Line 28...
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,
Line 46... Line 45...
46
  
45
  
47
Image *blend=NULL;
46
Image *blend=NULL;
Line 48... Line 47...
48
const char *config_name = "/sys/Settings/weather.json";
47
const char *config_name = "/sys/Settings/weather.json";
49
 
48
 
Line 50... Line 49...
50
unsigned char char_size=1;
49
unsigned char char_size=1;
Line 51... Line 50...
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
        
Line 55... Line 54...
55
char lang[3]="en";
54
char lang[3]="en";
Line 56... Line 55...
56
char format_temp_str[6];
55
char format_temp_str[6];
Line 57... Line 56...
57
char full_url[512];
56
char full_url[512];
Line 58... Line 57...
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
 
Line 76... Line 75...
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)
Line 80... Line 79...
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);
Line 84... Line 82...
84
}
82
}
85
 
83
 
86
void* safe_malloc(size_t size)
84
void* safe_malloc(size_t size)
Line 92... Line 90...
92
    }else{
90
    }else{
93
        return p;
91
        return p;
94
    }
92
    }
95
}
93
}
Line 96... Line 94...
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);
Line 105... Line 103...
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"
Line 117... Line 115...
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);
Line 150... Line 148...
150
            free(errmsg);
148
            free(errmsg);
151
        }
149
        }
152
    }
150
    }
153
}
151
}
Line 154... Line 152...
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;
Line 192... Line 190...
192
    if(h!=NULL){
190
    if(h!=NULL){
193
        http_free(h);
191
        http_free(h);
194
    }
192
    }
195
}
193
}
Line 196... Line 194...
196
 
194
 
197
void RedrawGUI() // Перересовываем интерфейс
195
void redraw_gui() // Перересовываем интерфейс
198
{
196
{
Line 199... Line 197...
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
    // Выводим жирным шрифтом название локации и временной зоны
Line 220... Line 218...
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
}
Line 229... Line 227...
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
    }
-
 
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);    
234
    }
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);
-
 
272
    fclose(config_j);
264
    free(config_j.data);
Line 273... Line 265...
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){
Line 323... Line 315...
323
    }
315
    }
324
}
316
}
Line 325... Line 317...
325
 
317
 
326
int main()
318
int main()
327
{
319
{
Line 328... Line 320...
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);
Line 333... Line 325...
333
    }
325
    }
Line 334... Line 326...
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; // Указатели на токен, название города, систему мер
Line 337... Line 329...
337
 
329
 
Line 338... Line 330...
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)();
Line 343... Line 335...
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: