Advertisement
dimonml

Acaia save data- acaia_ios_process

Oct 5th, 2018
214
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 16.97 KB | None | 0 0
  1. #!/bin/bash
  2. #
  3. # acaia_ios_process.sh 'J:/tmp/20180723_2'
  4. # Формат ячеек даты в экселе
  5. #   ДД.ММ.ГГГГ ч:мм:сс,0
  6. #
  7. # Файлы с iphone экспортировать, например, iMazing, см https://imazing.com
  8. # Для работы используется sqlite3 command-line shell, см https://www.sqlite.org/download.html
  9. #
  10. script_dir=`dirname "$0"`; script_dir=`(cd "$script_dir"; pwd)`
  11.  
  12. export brewmaster_root="$1/co.acaia.iphone.brewmaster/Documents"
  13. export acaiacoffee_root="$1/acaiacoffee/Documents"
  14. export work_dir="$script_dir/../_temp/acaia"
  15.  
  16. mkdir -p "$work_dir"
  17.  
  18. (
  19.     echo '--brewmaster';
  20.     "$script_dir/sqlite3.exe" -batch -readonly "$brewmaster_root/Test.sqlite" <<EOF
  21. .separator "\t"
  22. select round(zbrewedat*5,0)/5
  23.       ,zname
  24.       ,zbean
  25.       ,zbeanweight
  26.       ,ztemp
  27.       ,zgrind
  28.       ,zdripper
  29.       ,zpot
  30.       ,ztasty
  31.       ,replace(znote, char(10), ' ')
  32.       ,replace(replace(replace(replace(zweightdata, char(10), ''),' ', ''), '[', ''), ']', '')
  33.       from zbrewprint;
  34. EOF
  35.     echo '--acaiacoffee';
  36.     "$script_dir/sqlite3.exe" -batch -readonly "$acaiacoffee_root/Test.sqlite" <<EOF
  37. .separator "\t"
  38. select round(zstarttime*5,0)/5-0.2
  39.       ,zbeanweight
  40.       ,zstarcount
  41.       ,zgrind
  42.       ,ztemp
  43.       ,replace(znote, char(10), ' ')
  44.       ,zuuid
  45.       from zcoffeerecord;
  46.    
  47. EOF
  48. ) | awk "-F\t" '
  49.    BEGIN {
  50.        split("", g_union_table_result);
  51.  
  52.        g_smooth_step = 5;
  53.        g_union_table_result[0]= "Дата";
  54.        g_union_table_result[1]= "Время";
  55.        g_union_table_result[2]= "Вода"; # Всего
  56.        g_union_table_result[3]= "Воронка";
  57.        g_union_table_result[4]= "Кофе";
  58.        g_union_table_result[5]= "Кофе2, г/с";
  59.    }
  60.    "--brewmaster" == $0 {state="brewmaster"; next;}
  61.    "--acaiacoffee" == $0 {state="acaiacoffee"; next;}
  62.    BEGIN {
  63.        split("", data);
  64.        split("", data_w);
  65.    }
  66.    "brewmaster" == state {
  67.        start_time_ios = $1;
  68.        start_time_posix = get_posixtime_by_iostime(start_time_ios);
  69.        filename_only_name = "brewmaster_" get_timestamp_by_posix_time(start_time_posix) "_" $2;
  70.        filename = ENVIRON["work_dir"] "/" filename_only_name ".txt";
  71.  
  72.        header_init(start_time_posix, filename, "brewmaster");
  73.        header_add("Назначение", "Кофе");
  74.        header_add("Приложение", "Brewmaster");
  75.        header_add("Имя файла", filename_only_name);
  76.        header_add("Формат даты", "ДД.ММ.ГГГГ ч:мм:сс,0");
  77.        header_add("Начало", get_timestamp_by_posix_time(start_time_posix));
  78.        header_add("Масса зерен", $4);
  79.        header_add("Температура воды", $5);
  80.        header_add("Вкус", $9);
  81.        header_add("Помол", $6);
  82.        header_add("Примечания", $10);
  83.        
  84.        header_add("Имя", $2);
  85.        header_add("Зерна", $3);
  86.        header_add("Воронка", $7);
  87.        header_add("Чайник", $8);
  88.        
  89.        data_init();
  90.        weight_size = split($11, weight, ",");
  91.        for (i = 0; i < weight_size; ++i) {
  92.            data_add(start_time_posix + i*0.2, weight[i+1]);
  93.        }
  94.    }
  95.    "acaiacoffee" == state {
  96.        start_time_ios = $1;
  97.        start_time_posix = get_posixtime_by_iostime(start_time_ios);
  98.        filename_only_name = "acaiacoffee_" get_timestamp_by_posix_time(start_time_posix);
  99.        filename = ENVIRON["work_dir"] "/" filename_only_name ".txt";
  100.  
  101.        header_init(start_time_posix, filename, "acaiacoffee");
  102.        if (index($6 , "Total")) {
  103.            header_add("Назначение", "Вода");
  104.        }
  105.        else {
  106.            header_add("Назначение", "Воронка");
  107.        }
  108.      
  109.        header_add("Приложение", "Acaia coffee");
  110.        header_add("Имя файла", filename_only_name);
  111.        header_add("Формат даты", "ДД.ММ.ГГГГ ч:мм:сс,0");
  112.        header_add("Начало", get_timestamp_by_posix_time(start_time_posix));
  113.        header_add("Масса зерен", $2);
  114.        header_add("Температура воды", $5);
  115.        header_add("Вкус", $3);
  116.        header_add("Помол", $4);
  117.        header_add("Примечания", $6);
  118.  
  119.        data_init();
  120.        uuid = $7;
  121.        filename_weight = ENVIRON["acaiacoffee_root"] "/" uuid "_weight.csv";
  122.        i = 0;
  123.        while (1 == getline_result=getline < filename_weight) {
  124.            if (match($0, "<real>([0-9.]+)</real>", m)) {
  125.                data_add(start_time_posix + i++*0.2, m[1]);
  126.            }
  127.        }
  128.        close(filename_weight);
  129.    }
  130.    END {
  131.        # Находим пересечения
  132.        last_ids = "empty";
  133.        
  134.        data_w_num = asorti(data_w, data_w_indices);
  135.        for (j=1; j <= data_w_num; ++j) {
  136.            time_posix_str = data_w_indices[j];
  137.            size = length(data_w[time_posix_str]);
  138.            if (size > 1) {
  139.                ids = "";
  140.                for (i = 0; i < size; ++i) {
  141.                    ids = (length(ids) ? ids "_" : "") data_w[time_posix_str][i]["data_id"];
  142.                }
  143.                if (last_ids != ids) {
  144.                    if ("empty" != last_ids) {
  145.                        union_fini();
  146.                    }
  147.                    union_init(time_posix_str);
  148.                    last_ids = ids;
  149.                }
  150.                union_add(time_posix_str);
  151.            }
  152.        }
  153.        if ("empty" != last_ids) {
  154.            union_fini();
  155.        }
  156.    }
  157.    
  158.    # Работа с заголовками
  159.    function header_init(start_time_posix, filename, type) {
  160.        g_header_index = 0;
  161.        g_filename = filename;
  162.        g_item_index = g_item_last_index++;
  163.        
  164.        data[g_item_index]["start_time_posix"] = start_time_posix;
  165.        data[g_item_index]["type"] = type;
  166.    }
  167.    function header_add(header_name, header_value, _header_item) {
  168.        _header_item = sprintf("%s\t%s", header_name, header_value);
  169.        data[g_item_index]["header"][g_header_index] = _header_item;
  170.        data[g_item_index]["header_map"][header_name] = header_value;
  171.        ++g_header_index;
  172.  
  173.        # Запись в файл
  174.        if (1 == g_header_index) {
  175.            printf("%s\r\n", _header_item) > g_filename;
  176.        }
  177.        else {
  178.            printf("%s\r\n", _header_item) >> g_filename;
  179.        }
  180.    }
  181.    
  182.    # Работа с данными
  183.    function data_init() {
  184.    }
  185.    function data_add(time_posix, weight, _time_posix_str, _excel_time_str, _data_w_id, _text) {
  186.            _time_posix_str = sprintf("%.1f", time_posix);
  187.            _excel_time_str = get_exceltime_by_posixtime(time_posix);
  188.            
  189.            _data_w_id = 0;
  190.            if (_time_posix_str in data_w) {
  191.                _data_w_id = length(data_w[_time_posix_str]);
  192.            }
  193.            data_w[_time_posix_str][_data_w_id]["data_id"] = g_item_index;
  194.            data_w[_time_posix_str][_data_w_id]["excel_time"] = _excel_time_str;
  195.            data_w[_time_posix_str][_data_w_id]["time_posix"] = time_posix;
  196.            data_w[_time_posix_str][_data_w_id]["weight"] = weight;
  197.  
  198.            # Запись в файл
  199.            _text = sprintf("%s\t%s\r\n", _excel_time_str, weight);
  200.            gsub("\\.", ",", _text);
  201.            printf("%s", _text) >> g_filename;
  202.    }
  203.    
  204.    # работа с объединениями
  205.    function union_init(time_posix_str, _i, _size, _data_id, _empty_size, _header_index, _header, _header_arr, _header_result, _header_main) {
  206.        g_union_timespamp = get_timestamp_by_posix_time(data_w[time_posix_str][0]["time_posix"]);
  207.        union_filename_full = ENVIRON["work_dir"] "/" "union_" g_union_timespamp ".txt";
  208.        union_filename_inited = 0;
  209.        
  210.        ##Add BOM to the new file
  211.        #union_write("\xEF\xBB\xBF");
  212.  
  213.        _size = length(data_w[time_posix_str]);
  214.        
  215.        split("", _header_main);
  216.        for (_i = 0; _i < _size; ++_i) {
  217.            union_write(sprintf("%s%s", _i ? "\t" : "", "Время общего начала"));
  218.        }
  219.        for (; _i < _size * 2; ++_i) {
  220.            union_write(sprintf("%s%s", _i ? "\t" : "", g_union_timespamp));
  221.        }        
  222.        union_write("\r\n");
  223.        
  224.        for (_header_index = 0; ; ++_header_index) {
  225.            _empty_size = 0;
  226.            split("", _header_result);
  227.            for (_i = 0; _i < _size; ++_i) {
  228.                _header = "\t";
  229.                _data_id = data_w[time_posix_str][_i]["data_id"];
  230.                if (length(data[_data_id]["header"]) > _header_index) {
  231.                    _header = data[_data_id]["header"][_header_index];
  232.                }
  233.                else {
  234.                    ++_empty_size;
  235.                }
  236.                #union_write(sprintf("%s%s", _i ? "\t" : "", _header));
  237.                split(_header, _header_arr, "\t");
  238.                _header_result[_i] = _header_arr[1];
  239.                _header_result[_i+_size] = _header_arr[2];
  240.                if (!_header_index) {
  241.                    _header_main[_i] = g_union_timespamp " " _header_arr[2];
  242.                }
  243.            }
  244.            
  245.            for (_i = 0; _i < length(_header_result); ++_i) {
  246.                union_write(sprintf("%s%s", _i ? "\t" : "", _header_result[_i]));
  247.            }
  248.            union_write(sprintf("\r\n"));
  249.            
  250.            # Допускаем печать пустой строчки
  251.            if (_empty_size >= _size) {
  252.                break;
  253.            }
  254.        }
  255.        g_union_item_id = 0;
  256.        
  257.        split("", g_union_table_order);
  258.        split("", g_union_table);
  259.        
  260.        g_union_table_row_post_process_type = 0;
  261.    }
  262.    function union_add(time_posix_str, _i, _size, _text) {
  263.        union_table_row_init();
  264.        union_table_row_add("Дата", data_w[time_posix_str][0]["excel_time"]);
  265.        union_table_row_add("Время", sprintf("%.1f", g_union_item_id * 0.2));
  266.        
  267.        _size = length(data_w[time_posix_str]);
  268.        for (_i = 0; _i < _size; ++_i) {
  269.            _weight = data_w[time_posix_str][_i]["weight"];
  270.            _data_id = data_w[time_posix_str][_i]["data_id"];
  271.            _purpose = data[_data_id]["header_map"]["Назначение"];
  272.            union_table_row_add(_purpose, _weight);
  273.        }
  274.        union_table_row_fini();
  275.        ++g_union_item_id;
  276.    }
  277.    function union_fini(_i) {
  278.        union_table_smooth_and_derivative();
  279.        union_table_print_header();
  280.        union_table_print_data();
  281.    }
  282.    function union_write(str) {
  283.        if (union_filename_inited) {
  284.            printf("%s", str) >> union_filename_full;
  285.        }
  286.        else {
  287.            printf("%s", str) > union_filename_full;
  288.            union_filename_inited = 1;
  289.        }
  290.    }
  291.    
  292.    function union_table_row_init() {
  293.    }
  294.    function union_table_row_add(column_name, value) {
  295.        if (!(column_name in g_union_table)) {
  296.            g_union_table_order[length(g_union_table_order)] = column_name;
  297.        }
  298.        g_union_table[column_name][g_union_item_id] = value;
  299.    }
  300.    function union_table_row_fini() {
  301.        union_table_row_post_process();
  302.    }
  303.    function union_table_print_header(_i, _is_not_first) {
  304.        # Печатаем заголовок
  305.        _is_not_first = 0;
  306.        if (length(g_union_table_result)) {
  307.            for (_i = 0; _i < length(g_union_table_result); ++_i) {
  308.                if (g_union_table_result[_i] in g_union_table) {
  309.                    union_write(sprintf("%s%s %s", _is_not_first++ ? "\t" : "", g_union_timespamp, g_union_table_result[_i]));
  310.                }
  311.            }
  312.        } else {
  313.            for (_i = 0; _i < length(g_union_table_order); ++_i) {
  314.                union_write(sprintf("%s%s %s", _is_not_first++ ? "\t" : "", g_union_timespamp, g_union_table_order[_i]));
  315.            }
  316.        }
  317.        union_write(sprintf("\r\n"));
  318.    }
  319.    function union_table_print_data(_c, _i, _value, _out_line) {
  320.        # Печатаем данные
  321.        if (length(g_union_table_order) <= 0) return;
  322.        for (_c = 0; _c < length(g_union_table[g_union_table_order[0]]); ++_c) {
  323.            _out_line = "";
  324.            if (length(g_union_table_result)) {
  325.                for (_i = 0; _i < length(g_union_table_result); ++_i) {
  326.                    if (g_union_table_result[_i] in g_union_table) {
  327.                        _value = g_union_table[g_union_table_result[_i]][_c];
  328.                        gsub("\\.", ",", _value);
  329.                        _out_line = ("" == _out_line ? "" : _out_line "\t") _value;
  330.                    }
  331.                }
  332.            } else {
  333.                for (_i = 0; _i < length(g_union_table_order); ++_i) {
  334.                    _value = g_union_table[g_union_table_order[_i]][_c];
  335.                    gsub("\\.", ",", _value);
  336.                    _out_line = ("" == _out_line ? "" : _out_line "\t") _value;
  337.                }
  338.            }
  339.            union_write(_out_line "\r\n");
  340.        }
  341.    }
  342.    
  343.    # Обработка данных
  344.    function union_table_row_post_process() {
  345.        if (!g_union_table_row_post_process_type) {
  346.            if ("Кофе" in g_union_table && "Вода" in g_union_table) {
  347.                g_union_table_row_post_process_type = 1;
  348.            }
  349.            else if ("Кофе" in g_union_table && "Воронка" in g_union_table) {
  350.                g_union_table_row_post_process_type = 2;
  351.            }
  352.        }
  353.        
  354.        if (1 == g_union_table_row_post_process_type) {
  355.            # Считаю разницу между весами - получаю, какая масса осталась в воронке
  356.            union_table_row_add("Воронка", g_union_table["Вода"][g_union_item_id] - g_union_table["Кофе"][g_union_item_id]);
  357.        }
  358.        else if (2 == g_union_table_row_post_process_type) {
  359.            # Считаю общую массу
  360.            union_table_row_add("Вода", g_union_table["Воронка"][g_union_item_id] + g_union_table["Кофе"][g_union_item_id]);
  361.        }
  362.    }
  363.    function union_table_smooth_and_derivative(_c, _i, _union_table_order_size, _union_table_size, _column_header, _column_header_new, _column_header_derivative, _value_old, _smooth_time_step, _value, _value_derivative, _column2_header_time, _column2_header_new, _column2_header_derivative) {
  364.        # Укрупняю данные, чтобы уменьшить случайные колебания
  365.        _union_table_order_size = length(g_union_table_order);
  366.        if (_union_table_order_size <= 0) return;
  367.        if (!("Время" in g_union_table)) return;
  368.        _union_table_size = length(g_union_table[g_union_table_order[0]]);
  369.        if (_union_table_size <= g_smooth_step) return;
  370.        _smooth_time_step = g_union_table["Время"][g_smooth_step] - g_union_table["Время"][0];
  371.  
  372.        # Цикл по всем столбцам
  373.        for (_i = 2; _i < _union_table_order_size; ++_i) {
  374.            _column_header = g_union_table_order[_i];
  375.            _column_header_new = _column_header ", г";
  376.            _column_header_derivative = _column_header ", г/с";
  377.            _value_old = 0.0;
  378.            
  379.            # Новые столбцы без повторений
  380.            _column2_header_time = "Время2";
  381.            _column2_header_new = _column_header "2, г";
  382.            _column2_header_derivative = _column_header "2, г/с";
  383.            
  384.            
  385.            for (_c = g_smooth_step - 1; _c < _union_table_size; _c += g_smooth_step) {
  386.                _value = g_union_table[g_union_table_order[_i]][_c];
  387.                _value_derivative = _value - _value_old / _smooth_time_step;
  388.                _value_old = _value;
  389.                for (g_union_item_id = _c + 1 - g_smooth_step; g_union_item_id <= _c; ++g_union_item_id) {
  390.                    union_table_row_add(_column_header_new, _value);
  391.                    union_table_row_add(_column_header_derivative, _value_derivative);
  392.                }
  393.                
  394.                # Новые столбцы без повторений
  395.                g_union_item_id = (_c + 1) / g_smooth_step - 1;
  396.                union_table_row_add(_column2_header_time, g_union_item_id * _smooth_time_step);
  397.                union_table_row_add(_column2_header_new, _value);
  398.                union_table_row_add(_column2_header_derivative, _value_derivative);
  399.            }            
  400.        }
  401.    }
  402.    
  403.    # разные функции
  404.    function get_posixtime_by_iostime(ios_time) {
  405.        return ios_time + 975715200 + 30*24*60*60 ;
  406.    }
  407.    function get_exceltime_by_posixtime(posix_time) {
  408.        return sprintf("%.10f", posix_time/(24*60*60) + 25569.125);
  409.    }
  410.    function get_timestamp_by_posix_time(posix_time) {
  411.        return strftime("%Y%m%dT%H%M%S",sprintf("%.0f", posix_time));
  412.    }
  413. '
  414. exit 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement