diff --git a/.gitignore b/.gitignore deleted file mode 100644 index 65469d13..00000000 --- a/.gitignore +++ /dev/null @@ -1,7 +0,0 @@ -.pio -.vscode/.browse.c_cpp.db* -.vscode/c_cpp_properties.json -.vscode/launch.json -.vscode/ipch -lib/libraies-master - diff --git a/.vscode/extensions.json b/.vscode/extensions.json deleted file mode 100644 index e80666bf..00000000 --- a/.vscode/extensions.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - // See http://go.microsoft.com/fwlink/?LinkId=827846 - // for the documentation about the extensions.json format - "recommendations": [ - "platformio.platformio-ide" - ] -} diff --git a/LICENSE b/LICENSE deleted file mode 100644 index f8f7d0eb..00000000 --- a/LICENSE +++ /dev/null @@ -1,21 +0,0 @@ -MIT License - -Copyright (c) 2021 Dmitry Borisenko - -Permission is hereby granted, free of charge, to any person obtaining a copy -of this software and associated documentation files (the "Software"), to deal -in the Software without restriction, including without limitation the rights -to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -copies of the Software, and to permit persons to whom the Software is -furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all -copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -SOFTWARE. diff --git a/README.md b/README.md deleted file mode 100644 index 99208207..00000000 --- a/README.md +++ /dev/null @@ -1,6 +0,0 @@ -# IoTManager -Это модульная система беспроводной автоматизации на базе ESP32/ESP8266 микроконтроллеров и приложения IoT Manager. -Телеграм канал обсуждения приложения и системы автоматизации https://t.me/IoTmanager -# [Инструкция](https://github.com/IoTManagerProject/IoTManager/wiki) - -![](https://github.com/IoTManagerProject/IoTManager/blob/beta/doc/pictures/007%20iot%20manager.jpg) diff --git a/bin/esp8266_1mb/firmware.bin b/bin/esp8266_1mb/firmware.bin deleted file mode 100644 index 817f8ff3..00000000 Binary files a/bin/esp8266_1mb/firmware.bin and /dev/null differ diff --git a/bin/esp8266_1mb/spiffs.bin b/bin/esp8266_1mb/spiffs.bin deleted file mode 100644 index 8cbb8b67..00000000 Binary files a/bin/esp8266_1mb/spiffs.bin and /dev/null differ diff --git a/bin/esp8266_mysensors_4mb/firmware.bin b/bin/esp8266_mysensors_4mb/firmware.bin deleted file mode 100644 index 9ce4258a..00000000 Binary files a/bin/esp8266_mysensors_4mb/firmware.bin and /dev/null differ diff --git a/bin/esp8266_mysensors_4mb/littlefs.bin b/bin/esp8266_mysensors_4mb/littlefs.bin deleted file mode 100644 index 910c9f95..00000000 Binary files a/bin/esp8266_mysensors_4mb/littlefs.bin and /dev/null differ diff --git a/data_esp/config.json b/data_esp/config.json deleted file mode 100644 index 88b2d187..00000000 --- a/data_esp/config.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "IoTmanager", - "chipID": "", - "apssid": "IoTmanager", - "appass": "", - "routerssid": "XChangeWIFI", - "routerpass": "XCh@WIFI", - "timezone": 1, - "ntp": "pool.ntp.org", - "mqttServer": "91.204.228.124", - "mqttPort": 1883, - "mqttPrefix": "/iotTest3", - "mqttUser": "rise", - "mqttPass": "23ri22se32", - "mqttServer2": "M2.WQTT.RU", - "mqttPort2": 8021, - "mqttPrefix2": "/iotTest3", - "mqttUser2": "rise", - "mqttPass2": "hostel3333", - "scen": 1, - "telegramApi": "1416711569:AAEI0j83GmXqwzb_gnK1B0Am0gDwZoJt5xo", - "telegonof": 0, - "teleginput": 0, - "autos": 1, - "weblogin": "admin", - "webpass": "admin", - "MqttIn": 0, - "MqttOut": 0, - "blink": 1, - "oneWirePin": 2, - "serverip": "http://206.189.49.244", - "uart": 0, - "uartS": 9600, - "uartTX": 12, - "uartRX": 13, - "grafmax": 0 -} \ No newline at end of file diff --git a/data_esp/css/build.css.gz b/data_esp/css/build.css.gz deleted file mode 100644 index 138a767b..00000000 Binary files a/data_esp/css/build.css.gz and /dev/null differ diff --git a/data_esp/dev_conf.txt b/data_esp/dev_conf.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/data_esp/edit.htm.gz b/data_esp/edit.htm.gz deleted file mode 100644 index 5786121f..00000000 Binary files a/data_esp/edit.htm.gz and /dev/null differ diff --git a/data_esp/favicon.ico b/data_esp/favicon.ico deleted file mode 100644 index 50d908fa..00000000 Binary files a/data_esp/favicon.ico and /dev/null differ diff --git a/data_esp/index.htm.gz b/data_esp/index.htm.gz deleted file mode 100644 index 073ff4ab..00000000 Binary files a/data_esp/index.htm.gz and /dev/null differ diff --git a/data_esp/index.json.gz b/data_esp/index.json.gz deleted file mode 100644 index 25eebb26..00000000 Binary files a/data_esp/index.json.gz and /dev/null differ diff --git a/data_esp/items/items.txt b/data_esp/items/items.txt deleted file mode 100644 index b75f01f0..00000000 --- a/data_esp/items/items.txt +++ /dev/null @@ -1,34 +0,0 @@ -0;button-out;btnid;toggleBtn;Кнопки;Освещение;order;gpio* -0;button-out;btnid;toggleBtn;Кнопки;Освещение;order;gpio;inv[1]* -0;button-out;btnid;toggleBtn;Кнопки;Освещение;order* -0;button-in;btnid;toggleBtn;Кнопки;Освещение;order;gpio;db[20]* -0;pwm-out;pwmid;range;Ползунки;Яркость;order;gpio* -0;input-value;dgtid;inputDigit;Ввод;Введите#цифру;order* -0;input-value;tmid;inputTime;Ввод;Введите#время;order* -0;output-value;txtid;anydata;Вывод;Сигнализация;order* -0;analog-adc;adcid;fillgauge;Сенсоры;Аналоговый;order;pin[0];map[0,1024,0,100];c[1];int[10]* -0;dallas-temp;tmpid;anydataTemp;Сенсоры;Температура;order;pin[2];index[0];int[10]* -0;ultrasonic-cm;cmid;anydata;Сенсоры;Расстояние;order;pin[12,13];map[0,500,0,100];c[1];int[10]* -0;dht;tmpid;anydataTemp;Сенсоры;Температура;1;c[1] -0;dht;humid;anydataHum;Сенсоры;Влажность;2;c[1];pin[2];type[dht11];int[10]* -0;dht;tmpid;anydataTemp;Сенсоры;Температура;1;c[1] -0;dht;humid;anydataHum;Сенсоры;Влажность;2;c[1];pin[2];type[dht22];int[10]* -0;bme280;tmpid;anydataTemp;Сенсоры;Температура;1;c[1] -0;bme280;humid;anydataHum;Сенсоры;Влажность;2;c[1] -0;bme280;prsid;anydataPress;Сенсоры;Давление;3;c[1];addr[0x76];int[10]* -0;bmp280;tmpid;anydataTemp;Сенсоры;Температура;1;c[1] -0;bmp280;prsid;anydataPress;Сенсоры;Давление;3;c[1];addr[0x76];int[10]* -0;pzem;Vltid;anydataVlt;Сенсоры;Напряжение;1;c[1];k[0] -0;pzem;Ampid;anydataAmp;Сенсоры;Сила#тока;2;c[1];k[0] -0;pzem;Wttid;anydataWtt;Сенсоры;Мощность;3;c[1];k[0] -0;pzem;Whrid;anydataWhr;Сенсоры;Энергия;4;c[1];k[0] -0;pzem;Htzid;anydataHtz;Сенсоры;Частота;5;c[1];k[0];addr[0xF8];int[10]* -0;ccs811;ppmid;anydataPpm;Сенсоры;Содержание#CO2;1;c[1] -0;ccs811;ppbid;anydataPpb;Сенсоры;Содержание#орг#соед;2;c[1];addr[0x76];int[10]* -0;impuls-out;impid;na;na;na;order;gpio* -0;impuls-in;impid;anydata;Сенсоры;Количество#импульсов;order;pin[0];c[1];k[0]* -0;count-down;cntid;anydata;Таймер;Обратный#отчет;order* -0;output-value;txtid;anydata;Вывод;Температура;order* -0;logging;crtid;chart;Графики;История;order;val[any];int[60];cnt[100]* -0;logging;crtid;chart3;Графики;История;order;val[any];int[23:30];cnt[100];st[0]* -0;uptime;uptid;anydataTime;Системные;%name%#uptime;order;int[60]* \ No newline at end of file diff --git a/data_esp/js/build.chart.js.gz b/data_esp/js/build.chart.js.gz deleted file mode 100644 index 654707fd..00000000 Binary files a/data_esp/js/build.chart.js.gz and /dev/null differ diff --git a/data_esp/js/function.js.gz b/data_esp/js/function.js.gz deleted file mode 100644 index 87c9dd01..00000000 Binary files a/data_esp/js/function.js.gz and /dev/null differ diff --git a/data_esp/lang/lang.ru.json b/data_esp/lang/lang.ru.json deleted file mode 100644 index 2c089bcb..00000000 --- a/data_esp/lang/lang.ru.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "SetDevConf": "Конфигурация устройства", - "SetDevPreset": "Выберите из списка подходящий пресет кофигурации", - - "ButSave":"Сохранить", - "ButMainPage":"Главная", - - - "SetUDPList": "Список других устройств в сети:", - "SetUDPWarn1": "После нажатия на кнопку переформировать список устройств ждите примерно минуту, а затем обновите страницу и список появится вновь", - - "SetUDPUpdateList":"Переформировать список устройств", - "SetUDPUpdatePage":"Обновить страницу", - "SetUDPNameOfDev":"Имя этого устройства:", - "SetUDPDateExchange":"Включить обмен данными между устройствами", - "SetUDPWarn2":"Если обмен данными включен, то устройства будут обмениваться широковещательными пакетами udp для формирования списка устройств и для осуществления посылки настроек mqtt. Данный обмен создает дополнительную нагрузку на wifi сеть.", - - "SetWiFiNameOfDev":"Имя устройства:", - "SetWiFiRouterConnect":"Подключение к WiFi роутеру:", - "SetWiFiAccessPoint":"Точка доступа:", - "SetWiFiWeb":"Логин и пароль web interface:", - "SetWiFiTimeZone":"Временная зона:", - "SetWiFiNTP":"Сервер NTP:", - "SetWiFiWarn1":"Имя устройства должно состоять из английских букв и иметь длинну от 6 до 12 символов", - "SetWiFiWarn2":"После того как вы введете логин пароль от вашего wifi роутера необходимо нажать кнопку сохранить, а затем обязательно нажать кнопку перезагрузить устройство внизу этой страницы", - "SetWiFiWarn3":"Устройство постоянно сканирует сеть на наличие wifi. Если роутер отключен, то устройство автоматически перейдет в режим точки доступа. Когда wifi появится устройство автоматически подключится к роутеру снова, и выключит точку доступа", - "SetWiFiWarn4":"После изменения поля NTP сервер необходимо перезагрузить устройство", - "SetWiFiWarn5":"Светодиод статуса подключения показывает четыре состояния подключения:
1. мигает редко - идет подключение к wifi
2. мигает часто - идет подключение к серверу mqtt
3. горит постоянно - модуль в режиме точки доступа,
4. не горит - модуль подключен к wifi и к mqtt.
Светодиод подключен к gpio2. Если галочка стоит - то использовать этот пин нельзя", - - "SetMQTTServerName":"Имя сервера:", - "SetMQTTPort":"Номер порта:", - "SetMQTTPrefix":"Префикс:", - "SetMQTTUserName":"Имя пользователя:", - "SetMQTTPassword":"Пароль:", - - "SetMQTTSendSettings":"Отправить настройки MQTT с этого устройства на все остальные", - "SetMQTTWarn1":"Обратите внимание что поле префикс может состоять только из одного слова и одного разделителя: /prefix, вариант вида: /prefix1/prefix2 работать не будет. После изменения поля prefix необходимо перезагрузить устройство", - "SetMQTTWarn2":"Прежде чем нажимать на кнопку Отправить настройки MQTT сохрание их, если Вы их меняли. Настройки получат и перезапишут все устройства в локальной сети" -} \ No newline at end of file diff --git a/data_esp/presets/presets.c.txt b/data_esp/presets/presets.c.txt deleted file mode 100644 index b8944e5a..00000000 --- a/data_esp/presets/presets.c.txt +++ /dev/null @@ -1,54 +0,0 @@ -0;dallas-temp;t1;anydataTemp;Термостат;Температура;1;pin[2];index[0];int[10] -0;logging;log1;chart;Термостат;История;2;val[t1];int[60];cnt[100] -0;input-value;tUp1;inputDigitTemp;Термостат;Верхний#порог;3 -0;input-value;tLow1;inputDigitTemp;Термостат;Нижний#порог;4 -0;button-out;btn1;toggleBtn;Термостат;Нагрев;5;pin[12]* -0;dallas-temp;t2;anydataTemp;Главная;Температура;1;pin[2];index[0];int[10] -0;logging;log2;chart;Главная;История;2;val[t2];int[10];cnt[100] -0;input-value;threshold;inputDigitTemp;Главная;Заданная#температура;3 -0;button-out;heater2;toggleBtn;Главная;Нагреватель;7;pin[5] -0;input-value;time21;inputTimeClock;Расписание;Утренний#период;8 -0;input-value;threshold1;inputDigitTemp;Расписание;Температура;9 -0;input-value;time22;inputTimeClock;Расписание;Дневной#период;10 -0;input-value;threshold2;inputDigitTemp;Расписание;Температура;11 -0;input-value;time23;inputTimeClock;Расписание;Вечерний#период;12 -0;input-value;threshold3;inputDigitTemp;Расписание;Температура;13 -0;input-value;time24;inputTimeClock;Расписание;Ночной#период;14 -0;input-value;threshold4;inputDigitTemp;Расписание;Температура;15* -0;dht;t3;anydataTemp;Теплица;Температура;1;c[1] -0;dht;h3;anydataHum;Теплица;Влажность;2;c[1];pin[2];type[dht11];int[10] -0;logging;log3;chart;Теплица;История;3;val[h3];int[60];cnt[100] -0;input-value;hUp3;inputDigit;Теплица;Верхний#порог;4 -0;input-value;hLow3;inputDigit;Теплица;Нижний#порог;5 -0;button-out;btn3;toggleBtn;Теплица;Полив;6;pin[12]* -0;button-out;btn41;toggleBtn;Реле;Реле1;1;pin[12] -0;input-value;time41;inputTimeClock;Реле;Введите#время#включения;2 -0;button-out;btn42;toggleBtn;Реле;Реле2;3;pin[13] -0;input-value;time42;inputTimeClock;Реле;Введите#время#выключения;4* -0;button-out;btn51;toggleBtn;Сценарии;Выключить#все;1 -0;button-out;btn52;toggleBtn;Сценарии;Гостинная;2;pin[12] -0;button-out;btn53;toggleBtn;Сценарии;Спальня;3;pin[13] -0;button-out;btn54;toggleBtn;Сценарии;Прихожая;4;pin[14] -0;pwm-out;pwm51;range;Сценарии;Яркость;5;pin[15] -0;pwm-out;pwm52;range;Сценарии;Яркость;6;pin[16] -0;output-value;txt5;anydata;Сценарии;Статус;7* -0;button-out;btn6;toggleBtn;Таймер;Освещение;1;pin[12] -0;count-down;cnt6;anydata;Таймер;Обратный#отчет;2 -0;input-value;sec6;inputDigit;Таймер;Введите#цифру;3* -0;button-out;start;toggleBtn;Цикл;Запустить#цикл;1 -0;count-down;cnt71;anydata;Цикл;Осталось#секунд;3 -0;input-value;sec71;inputDigit;Цикл;Период#включения;4 -0;count-down;cnt72;anydata;Цикл;Осталось#секунд;5 -0;input-value;sec72;inputDigit;Цикл;Период#выключения;6 -0;button-out;btn7;toggleBtn;Цикл;Реле;7;pin[12]* -0;output-value;txt81;anydataAlarm;Сигнализация;Движение:;1 -0;output-value;txt82;anydataTime;Сигнализация;Время:;2 -0;button-in;sens8;na;na;na;3;pin[0];db[20] -0;button-out;rst8;toggleBtn;Сигнализация;Сбросить;4 -0;button-out;on8;toggleBtn;Сигнализация;Включить;5* -0;button-in;sens9;na;na;na;1;pin[0];db[20] -0;button-out;btn9;toggleBtn;Освещение;Освещение;2;pin[13] -0;count-down;cnt9;anydata;Освещение;Обратный#отчет;3 -0;input-value;sec9;inputDigit;Освещение;Период#включения;4* -0;button-out;btn10;toggleBtn;Кнопки;Освещение;1;pin[13] -0;button-in;sw10;na;na;na;2;pin[0];db[20]* \ No newline at end of file diff --git a/data_esp/presets/presets.s.txt b/data_esp/presets/presets.s.txt deleted file mode 100644 index 481ac0a9..00000000 --- a/data_esp/presets/presets.s.txt +++ /dev/null @@ -1,105 +0,0 @@ -t1 > tUp1 -btn1 0 -telegram msg1 нагрев#выключен -end -t1 < tLow1 -btn1 1 -telegram msg1 нагрев#включен -end* -t2 > threshold+-2 -heater2 0 -end -t2 < threshold+-2 -heater2 1 -end -timenow = time21 -threshold threshold1 -end -timenow = time22 -threshold threshold2 -end -timenow = time23 -threshold threshold3 -end -timenow = time24 -threshold threshold4 -end* -h3 > hUp3 -btn3 0 -telegram msg3 полив#выключен -end -h3 < hLow3 -btn3 1 -telegram msg3 полив#включен -end* -timenow = time41 -btn41 1 -btn42 0 -end -timenow = time42 -btn41 0 -btn42 1 -end* -btn51 = 1 -btn52 1 -btn53 1 -btn54 1 -pwm51 200 -pwm52 800 -txt5 включено -end -btn51 = 0 -btn52 0 -btn53 0 -btn54 0 -pwm51 800 -pwm52 200 -txt5 выключено -end -pwm51 > 900 && pwm52 > 900 -btn52 0 -btn53 0 -btn54 0 -end* -btn6 = 1 -cnt6 sec6 -end -cnt6 = 0 -btn6 0 -end* -start = 1 -cnt71 sec71 -btn7 1 -end -cnt71 = 0 -btn7 0 -cnt72 sec72 -end -cnt72 = 0 -btn7 1 -cnt71 sec71 -end -start = 0 -cnt71 0 -cnt72 0 -end* -sens8 = 1 && on8b = 1 -txt81 обнаружено -txt82 %date% -telegram often Обнаружено#движение -end -rst8 = 1 -txt81 не#обнаружено -txt82 %date% -rst8 0 -end* -sens9 = 1 -btn9 1 -cnt9 sec9 -end -cnt9 = 0 -btn9 0 -end* -sw10 = 1 -btn10 change -end* \ No newline at end of file diff --git a/data_esp/s.conf.csv b/data_esp/s.conf.csv deleted file mode 100644 index 40b35ae1..00000000 --- a/data_esp/s.conf.csv +++ /dev/null @@ -1 +0,0 @@ -Удалить;Тип элемента;Id;Виджет;Имя вкладки;Имя виджета;Позиция виджета \ No newline at end of file diff --git a/data_esp/s.scen.txt b/data_esp/s.scen.txt deleted file mode 100644 index ab0c0141..00000000 --- a/data_esp/s.scen.txt +++ /dev/null @@ -1 +0,0 @@ -// \ No newline at end of file diff --git a/data_esp/set.developer.json.gz b/data_esp/set.developer.json.gz deleted file mode 100644 index baa9834e..00000000 Binary files a/data_esp/set.developer.json.gz and /dev/null differ diff --git a/data_esp/set.device.json.gz b/data_esp/set.device.json.gz deleted file mode 100644 index 87d9244b..00000000 Binary files a/data_esp/set.device.json.gz and /dev/null differ diff --git a/data_esp/set.manual.json.gz b/data_esp/set.manual.json.gz deleted file mode 100644 index 17584676..00000000 Binary files a/data_esp/set.manual.json.gz and /dev/null differ diff --git a/data_esp/set.mqtt.json.gz b/data_esp/set.mqtt.json.gz deleted file mode 100644 index 7e48784f..00000000 Binary files a/data_esp/set.mqtt.json.gz and /dev/null differ diff --git a/data_esp/set.telegram.json.gz b/data_esp/set.telegram.json.gz deleted file mode 100644 index e8810e9b..00000000 Binary files a/data_esp/set.telegram.json.gz and /dev/null differ diff --git a/data_esp/set.udp.json.gz b/data_esp/set.udp.json.gz deleted file mode 100644 index 6091765c..00000000 Binary files a/data_esp/set.udp.json.gz and /dev/null differ diff --git a/data_esp/set.utilities.json.gz b/data_esp/set.utilities.json.gz deleted file mode 100644 index 5356db03..00000000 Binary files a/data_esp/set.utilities.json.gz and /dev/null differ diff --git a/data_esp/set.wifi.json.gz b/data_esp/set.wifi.json.gz deleted file mode 100644 index d5cab6bf..00000000 Binary files a/data_esp/set.wifi.json.gz and /dev/null differ diff --git a/data_esp/widgets.json b/data_esp/widgets.json deleted file mode 100644 index acf59ff9..00000000 --- a/data_esp/widgets.json +++ /dev/null @@ -1,34 +0,0 @@ -{ - "undef": "Ошибка", - "toggleBtn": "Кнопка переключатель", - "range": "Ползунок", - "inputDate": "Окно ввода даты", - "inputTime": "Окно ввода времени 1", - "inputTimeClock": "Окно ввода времени 2", - "inputDigit": "Окно ввода цифры", - "inputDigitTemp": "Окно ввода температуры", - "inputText": "Окно ввода текста", - "select": "Выпадающий список", - "chart": "График без точек", - "chart2": "График с точками", - "chart3": "График дневного расхода (столбики)", - "chart4": "График дневного расхода (плавный)", - "fillgauge": "Бочка", - "progress-line": "Линия", - "progress-round": "Круг", - "anydata": "Текст", - "anydataHum": "Влажность (%)", - "anydataPress": "Давление (mm)", - "anydataTemp": "Температура (°С)", - "anydataPpb": "Части на миллиард (ppb)", - "anydataPpm": "Части на миллион (ppm)", - "anydataVlt": "Напряжение (Vlt)", - "anydataAmp": "Сила тока (Amp)", - "anydataWtt": "Мощность (Wtt)", - "anydataWhr": "Энергия (Whr)", - "anydataHtz": "Частота (Htz)", - "anydataTime": "Манометр", - "alarm": "Тревожное сообщение 1", - "anydataAlarm": "Тревожное сообщение 2", - "na": "Без виджета" -} \ No newline at end of file diff --git a/data_esp/widgets/alarm.json b/data_esp/widgets/alarm.json deleted file mode 100644 index e0e636c3..00000000 --- a/data_esp/widgets/alarm.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "widget": "anydata", - "icon": "body", - "color": "red", - "descrColor": "red" -} \ No newline at end of file diff --git a/data_esp/widgets/anydata.json b/data_esp/widgets/anydata.json deleted file mode 100644 index 4157b9c9..00000000 --- a/data_esp/widgets/anydata.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "anydata", - "after": "", - "icon": "" -} \ No newline at end of file diff --git a/data_esp/widgets/anydataAlarm.json b/data_esp/widgets/anydataAlarm.json deleted file mode 100644 index d793d350..00000000 --- a/data_esp/widgets/anydataAlarm.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "widget": "anydata", - "after": "", - "color":"red", - "icon": "walk" -} \ No newline at end of file diff --git a/data_esp/widgets/anydataAmp.json b/data_esp/widgets/anydataAmp.json deleted file mode 100644 index 0cc40403..00000000 --- a/data_esp/widgets/anydataAmp.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "anydata", - "after": "Amp", - "icon": "speedometer" -} \ No newline at end of file diff --git a/data_esp/widgets/anydataHtz.json b/data_esp/widgets/anydataHtz.json deleted file mode 100644 index 4836a81a..00000000 --- a/data_esp/widgets/anydataHtz.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "anydata", - "after": "Htz", - "icon": "speedometer" -} \ No newline at end of file diff --git a/data_esp/widgets/anydataHum.json b/data_esp/widgets/anydataHum.json deleted file mode 100644 index ebc5b5af..00000000 --- a/data_esp/widgets/anydataHum.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "anydata", - "after": "%", - "icon": "water" -} \ No newline at end of file diff --git a/data_esp/widgets/anydataPpb.json b/data_esp/widgets/anydataPpb.json deleted file mode 100644 index 037e77d3..00000000 --- a/data_esp/widgets/anydataPpb.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "anydata", - "after": "ppb", - "icon": "body" - } \ No newline at end of file diff --git a/data_esp/widgets/anydataPpm.json b/data_esp/widgets/anydataPpm.json deleted file mode 100644 index e4d134e7..00000000 --- a/data_esp/widgets/anydataPpm.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "anydata", - "after": "ppm", - "icon": "body" - } \ No newline at end of file diff --git a/data_esp/widgets/anydataPress.json b/data_esp/widgets/anydataPress.json deleted file mode 100644 index e67af2c8..00000000 --- a/data_esp/widgets/anydataPress.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "anydata", - "after": "mm", - "icon": "speedometer" -} \ No newline at end of file diff --git a/data_esp/widgets/anydataTemp.json b/data_esp/widgets/anydataTemp.json deleted file mode 100644 index 112da222..00000000 --- a/data_esp/widgets/anydataTemp.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "anydata", - "after": "°С", - "icon": "thermometer" -} \ No newline at end of file diff --git a/data_esp/widgets/anydataTime.json b/data_esp/widgets/anydataTime.json deleted file mode 100644 index 821c4dab..00000000 --- a/data_esp/widgets/anydataTime.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "anydata", - "after": "", - "icon": "speedometer" -} \ No newline at end of file diff --git a/data_esp/widgets/anydataVlt.json b/data_esp/widgets/anydataVlt.json deleted file mode 100644 index f2a10747..00000000 --- a/data_esp/widgets/anydataVlt.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "anydata", - "after": "Vlt", - "icon": "speedometer" -} \ No newline at end of file diff --git a/data_esp/widgets/anydataWhr.json b/data_esp/widgets/anydataWhr.json deleted file mode 100644 index e523bedd..00000000 --- a/data_esp/widgets/anydataWhr.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "anydata", - "after": "Whr", - "icon": "speedometer" -} \ No newline at end of file diff --git a/data_esp/widgets/anydataWtt.json b/data_esp/widgets/anydataWtt.json deleted file mode 100644 index c1211050..00000000 --- a/data_esp/widgets/anydataWtt.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "anydata", - "after": "Wtt", - "icon": "speedometer" -} \ No newline at end of file diff --git a/data_esp/widgets/btn.json b/data_esp/widgets/btn.json deleted file mode 100644 index 67dcc0d3..00000000 --- a/data_esp/widgets/btn.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "widget": "btn", - "size": "large", - "color": "green", - "send": "test" -} \ No newline at end of file diff --git a/data_esp/widgets/chart.json b/data_esp/widgets/chart.json deleted file mode 100644 index 878ce0e4..00000000 --- a/data_esp/widgets/chart.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "chart", - "dateFormat": "HH:mm", - "pointRadius": 0 -} \ No newline at end of file diff --git a/data_esp/widgets/chart2.json b/data_esp/widgets/chart2.json deleted file mode 100644 index 9ecc61e3..00000000 --- a/data_esp/widgets/chart2.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "widget": "chart", - "dateFormat": "HH:mm" -} \ No newline at end of file diff --git a/data_esp/widgets/chart3.json b/data_esp/widgets/chart3.json deleted file mode 100644 index e2783cea..00000000 --- a/data_esp/widgets/chart3.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "chart", - "dateFormat": "DD.MM.YYYY", - "type":"bar" -} \ No newline at end of file diff --git a/data_esp/widgets/chart4.json b/data_esp/widgets/chart4.json deleted file mode 100644 index 11d05d24..00000000 --- a/data_esp/widgets/chart4.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "widget": "chart", - "dateFormat": "DD.MM.YYYY" -} \ No newline at end of file diff --git a/data_esp/widgets/fillgauge.json b/data_esp/widgets/fillgauge.json deleted file mode 100644 index 34315ea8..00000000 --- a/data_esp/widgets/fillgauge.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "widget": "fillgauge", - "circleColor": "#00FFFF", - "textColor": "#FFFFFF", - "waveTextColor": "#000000", - "waveColor": "#00FFFF" -} \ No newline at end of file diff --git a/data_esp/widgets/inputDate.json b/data_esp/widgets/inputDate.json deleted file mode 100644 index ecc3113d..00000000 --- a/data_esp/widgets/inputDate.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "widget" : "input", - "size" : "small", - "color" : "orange", - "type" : "date" -} \ No newline at end of file diff --git a/data_esp/widgets/inputDigit.json b/data_esp/widgets/inputDigit.json deleted file mode 100644 index 20196c6a..00000000 --- a/data_esp/widgets/inputDigit.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget" : "input", - "color" : "blue", - "type" : "number" -} \ No newline at end of file diff --git a/data_esp/widgets/inputDigitTemp.json b/data_esp/widgets/inputDigitTemp.json deleted file mode 100644 index 28f19081..00000000 --- a/data_esp/widgets/inputDigitTemp.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "widget" : "input", - "color" : "green", - "type" : "number", - "size" : "small", - "icon": "thermometer" -} \ No newline at end of file diff --git a/data_esp/widgets/inputText.json b/data_esp/widgets/inputText.json deleted file mode 100644 index 3484d53b..00000000 --- a/data_esp/widgets/inputText.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "widget" : "input", - "size" : "small", - "color" : "orange", - "type" : "text" -} \ No newline at end of file diff --git a/data_esp/widgets/inputTime.json b/data_esp/widgets/inputTime.json deleted file mode 100644 index e39942a4..00000000 --- a/data_esp/widgets/inputTime.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget" : "input", - "color" : "blue", - "type" : "time" -} \ No newline at end of file diff --git a/data_esp/widgets/inputTimeClock.json b/data_esp/widgets/inputTimeClock.json deleted file mode 100644 index ab3186f8..00000000 --- a/data_esp/widgets/inputTimeClock.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "widget" : "input", - "color" : "orange", - "type" : "time", - "size" : "small", - "icon": "alarm-outline" -} \ No newline at end of file diff --git a/data_esp/widgets/progress-line.json b/data_esp/widgets/progress-line.json deleted file mode 100644 index b2a95529..00000000 --- a/data_esp/widgets/progress-line.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "widget": "progress-line", - "icon": "sunny", - "descrColor": "", - "color": "", - "max": "100", - "background": "", - "stroke": "10", - "disabled": "", - "before": "", - "after": "" -} \ No newline at end of file diff --git a/data_esp/widgets/progress-round.json b/data_esp/widgets/progress-round.json deleted file mode 100644 index bf3ddae5..00000000 --- a/data_esp/widgets/progress-round.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "widget": "progress-round", - "descrColor": "", - "max": "100", - "stroke": "20", - "color": "#45ccce", - "background": "#777", - "before": "", - "semicircle": "1", - "after": "" -} \ No newline at end of file diff --git a/data_esp/widgets/range.json b/data_esp/widgets/range.json deleted file mode 100644 index 4d1e0ff3..00000000 --- a/data_esp/widgets/range.json +++ /dev/null @@ -1,9 +0,0 @@ - { - "widget" : "range", - "descrColor": "red", - "after" : "%", - "k" : 0.0977, - "min" : 0, - "max" : 100, - "debounce": 500 -} \ No newline at end of file diff --git a/data_esp/widgets/select.json b/data_esp/widgets/select.json deleted file mode 100644 index bad018fd..00000000 --- a/data_esp/widgets/select.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "widget": "select", - "options": [ - "Выключен", - "Включен" - ], - "status": 0 -} \ No newline at end of file diff --git a/data_esp/widgets/toggleBtn.json b/data_esp/widgets/toggleBtn.json deleted file mode 100644 index 4e9eed5e..00000000 --- a/data_esp/widgets/toggleBtn.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "toggle", - "icon": "", - "iconOff": "" -} \ No newline at end of file diff --git a/data_esp/widgets/toggleSunMoon.json b/data_esp/widgets/toggleSunMoon.json deleted file mode 100644 index 5501aa75..00000000 --- a/data_esp/widgets/toggleSunMoon.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "toggle", - "icon": "sunny", - "iconOff": "moon" -} \ No newline at end of file diff --git a/data_ms/config.json b/data_ms/config.json deleted file mode 100644 index c9b7441c..00000000 --- a/data_ms/config.json +++ /dev/null @@ -1,38 +0,0 @@ -{ - "name": "IoTmanager", - "chipID": "", - "apssid": "IoTmanager", - "appass": "", - "routerssid": "rise2", - "routerpass": "hostel3333", - "timezone": 1, - "ntp": "pool.ntp.org", - "mqttServer": "91.204.228.124", - "mqttPort": 1883, - "mqttPrefix": "/iotTest4", - "mqttUser": "rise", - "mqttPass": "23ri22se32", - "mqttServer2": "", - "mqttPort2": 0, - "mqttPrefix2": "", - "mqttUser2": "", - "mqttPass2": "", - "scen": "1", - "telegramApi": "1416711569:AAEI0j83GmXqwzb_gnK1B0Am0gDwZoJt5xo", - "telegonof": "0", - "teleginput": "0", - "autos": "1", - "weblogin": "admin", - "webpass": "admin", - "MqttIn": "0", - "MqttOut": "0", - "blink": "0", - "oneWirePin": "2", - "serverip": "http://206.189.49.244", - "uart": "0", - "uartS": "9600", - "uartTX": "12", - "uartRX": "13", - "grafmax": "0", - "gateAuto": "0" -} \ No newline at end of file diff --git a/data_ms/css/build.css.gz b/data_ms/css/build.css.gz deleted file mode 100644 index 138a767b..00000000 Binary files a/data_ms/css/build.css.gz and /dev/null differ diff --git a/data_ms/dev_conf.txt b/data_ms/dev_conf.txt deleted file mode 100644 index e69de29b..00000000 diff --git a/data_ms/edit.htm.gz b/data_ms/edit.htm.gz deleted file mode 100644 index 5786121f..00000000 Binary files a/data_ms/edit.htm.gz and /dev/null differ diff --git a/data_ms/favicon.ico b/data_ms/favicon.ico deleted file mode 100644 index 50d908fa..00000000 Binary files a/data_ms/favicon.ico and /dev/null differ diff --git a/data_ms/index.htm.gz b/data_ms/index.htm.gz deleted file mode 100644 index 073ff4ab..00000000 Binary files a/data_ms/index.htm.gz and /dev/null differ diff --git a/data_ms/index.json.gz b/data_ms/index.json.gz deleted file mode 100644 index 25eebb26..00000000 Binary files a/data_ms/index.json.gz and /dev/null differ diff --git a/data_ms/items/items.txt b/data_ms/items/items.txt deleted file mode 100644 index 2a853275..00000000 --- a/data_ms/items/items.txt +++ /dev/null @@ -1,10 +0,0 @@ -0;button-out;btnid;toggleBtn;Кнопки;Освещение;order* -0;button-out;100-0;toggleBtn;Кнопки;Освещение;order;type[ms]* -0;input;dgtid;inputDigit;Ввод;Введите#цифру;order* -0;input;tmid;inputTime;Ввод;Введите#время;order* -0;output;txtid;anydata;Вывод;Сигнализация;order* -0;count-down;cntid;anydata;Таймер;Обратный#отчет;order* -0;sensor-node;100-0;anydataTemp;MySensors;Температура;order;tm1[30];tm2[60];c[1];k[0]* -0;logging;crtid;chart;Графики;История;order;val[any];int[60];cnt[100]* -0;logging;crtid;chart3;Графики;История;order;val[any];int[23:30];cnt[100];st[0]* -0;uptime;uptid;anydataTime;Системные;%name%#uptime;order;int[60]* \ No newline at end of file diff --git a/data_ms/items/itemsAuto.txt b/data_ms/items/itemsAuto.txt deleted file mode 100644 index 22092348..00000000 --- a/data_ms/items/itemsAuto.txt +++ /dev/null @@ -1,2 +0,0 @@ -0;sensor-node;id;file;MySensors;descr;order;tm1[30];tm2[60];c[1];k[0]* -0;button-out;id;toggleBtn;Кнопки;descr;order;type[ms]* \ No newline at end of file diff --git a/data_ms/js/build.chart.js.gz b/data_ms/js/build.chart.js.gz deleted file mode 100644 index 654707fd..00000000 Binary files a/data_ms/js/build.chart.js.gz and /dev/null differ diff --git a/data_ms/js/function.js.gz b/data_ms/js/function.js.gz deleted file mode 100644 index 87c9dd01..00000000 Binary files a/data_ms/js/function.js.gz and /dev/null differ diff --git a/data_ms/lang/lang.ru.json b/data_ms/lang/lang.ru.json deleted file mode 100644 index 2c089bcb..00000000 --- a/data_ms/lang/lang.ru.json +++ /dev/null @@ -1,39 +0,0 @@ -{ - "SetDevConf": "Конфигурация устройства", - "SetDevPreset": "Выберите из списка подходящий пресет кофигурации", - - "ButSave":"Сохранить", - "ButMainPage":"Главная", - - - "SetUDPList": "Список других устройств в сети:", - "SetUDPWarn1": "После нажатия на кнопку переформировать список устройств ждите примерно минуту, а затем обновите страницу и список появится вновь", - - "SetUDPUpdateList":"Переформировать список устройств", - "SetUDPUpdatePage":"Обновить страницу", - "SetUDPNameOfDev":"Имя этого устройства:", - "SetUDPDateExchange":"Включить обмен данными между устройствами", - "SetUDPWarn2":"Если обмен данными включен, то устройства будут обмениваться широковещательными пакетами udp для формирования списка устройств и для осуществления посылки настроек mqtt. Данный обмен создает дополнительную нагрузку на wifi сеть.", - - "SetWiFiNameOfDev":"Имя устройства:", - "SetWiFiRouterConnect":"Подключение к WiFi роутеру:", - "SetWiFiAccessPoint":"Точка доступа:", - "SetWiFiWeb":"Логин и пароль web interface:", - "SetWiFiTimeZone":"Временная зона:", - "SetWiFiNTP":"Сервер NTP:", - "SetWiFiWarn1":"Имя устройства должно состоять из английских букв и иметь длинну от 6 до 12 символов", - "SetWiFiWarn2":"После того как вы введете логин пароль от вашего wifi роутера необходимо нажать кнопку сохранить, а затем обязательно нажать кнопку перезагрузить устройство внизу этой страницы", - "SetWiFiWarn3":"Устройство постоянно сканирует сеть на наличие wifi. Если роутер отключен, то устройство автоматически перейдет в режим точки доступа. Когда wifi появится устройство автоматически подключится к роутеру снова, и выключит точку доступа", - "SetWiFiWarn4":"После изменения поля NTP сервер необходимо перезагрузить устройство", - "SetWiFiWarn5":"Светодиод статуса подключения показывает четыре состояния подключения:
1. мигает редко - идет подключение к wifi
2. мигает часто - идет подключение к серверу mqtt
3. горит постоянно - модуль в режиме точки доступа,
4. не горит - модуль подключен к wifi и к mqtt.
Светодиод подключен к gpio2. Если галочка стоит - то использовать этот пин нельзя", - - "SetMQTTServerName":"Имя сервера:", - "SetMQTTPort":"Номер порта:", - "SetMQTTPrefix":"Префикс:", - "SetMQTTUserName":"Имя пользователя:", - "SetMQTTPassword":"Пароль:", - - "SetMQTTSendSettings":"Отправить настройки MQTT с этого устройства на все остальные", - "SetMQTTWarn1":"Обратите внимание что поле префикс может состоять только из одного слова и одного разделителя: /prefix, вариант вида: /prefix1/prefix2 работать не будет. После изменения поля prefix необходимо перезагрузить устройство", - "SetMQTTWarn2":"Прежде чем нажимать на кнопку Отправить настройки MQTT сохрание их, если Вы их меняли. Настройки получат и перезапишут все устройства в локальной сети" -} \ No newline at end of file diff --git a/data_ms/presets/presets.c.txt b/data_ms/presets/presets.c.txt deleted file mode 100644 index c26c03b7..00000000 --- a/data_ms/presets/presets.c.txt +++ /dev/null @@ -1,4 +0,0 @@ -0;output;100-0;anydataTemp;MySensors;Температура;order -0;output;100-1;anydataPress;MySensors;Давление;order -0;output;100-2;anydataHum;MySensors;Влажность;order -0;input;dgt;inputDigit;MySensors;Введите#цифру;order* \ No newline at end of file diff --git a/data_ms/presets/presets.s.txt b/data_ms/presets/presets.s.txt deleted file mode 100644 index cccfdfca..00000000 --- a/data_ms/presets/presets.s.txt +++ /dev/null @@ -1,6 +0,0 @@ -100-0 > dgt -telegram Гостинная Повышение#температуры -end -100-0 < dgt -telegram Гостинная Понижение#температуры -end* \ No newline at end of file diff --git a/data_ms/s.conf.csv b/data_ms/s.conf.csv deleted file mode 100644 index 40b35ae1..00000000 --- a/data_ms/s.conf.csv +++ /dev/null @@ -1 +0,0 @@ -Удалить;Тип элемента;Id;Виджет;Имя вкладки;Имя виджета;Позиция виджета \ No newline at end of file diff --git a/data_ms/s.scen.txt b/data_ms/s.scen.txt deleted file mode 100644 index ab0c0141..00000000 --- a/data_ms/s.scen.txt +++ /dev/null @@ -1 +0,0 @@ -// \ No newline at end of file diff --git a/data_ms/set.developer.json.gz b/data_ms/set.developer.json.gz deleted file mode 100644 index baa9834e..00000000 Binary files a/data_ms/set.developer.json.gz and /dev/null differ diff --git a/data_ms/set.device.json.gz b/data_ms/set.device.json.gz deleted file mode 100644 index e0bb935d..00000000 Binary files a/data_ms/set.device.json.gz and /dev/null differ diff --git a/data_ms/set.manual.json.gz b/data_ms/set.manual.json.gz deleted file mode 100644 index 17584676..00000000 Binary files a/data_ms/set.manual.json.gz and /dev/null differ diff --git a/data_ms/set.mqtt.json.gz b/data_ms/set.mqtt.json.gz deleted file mode 100644 index f6c1c7c4..00000000 Binary files a/data_ms/set.mqtt.json.gz and /dev/null differ diff --git a/data_ms/set.telegram.json.gz b/data_ms/set.telegram.json.gz deleted file mode 100644 index e8810e9b..00000000 Binary files a/data_ms/set.telegram.json.gz and /dev/null differ diff --git a/data_ms/set.udp.json.gz b/data_ms/set.udp.json.gz deleted file mode 100644 index 6091765c..00000000 Binary files a/data_ms/set.udp.json.gz and /dev/null differ diff --git a/data_ms/set.utilities.json.gz b/data_ms/set.utilities.json.gz deleted file mode 100644 index 5356db03..00000000 Binary files a/data_ms/set.utilities.json.gz and /dev/null differ diff --git a/data_ms/set.wifi.json.gz b/data_ms/set.wifi.json.gz deleted file mode 100644 index d5cab6bf..00000000 Binary files a/data_ms/set.wifi.json.gz and /dev/null differ diff --git a/data_ms/widgets.json b/data_ms/widgets.json deleted file mode 100644 index 8b9190e1..00000000 --- a/data_ms/widgets.json +++ /dev/null @@ -1,33 +0,0 @@ -{ - "toggleBtn": "Кнопка переключатель", - "range": "Ползунок", - "inputDate": "Окно ввода даты", - "inputTime": "Окно ввода времени 1", - "inputTimeClock": "Окно ввода времени 2", - "inputDigit": "Окно ввода цифры", - "inputDigitTemp": "Окно ввода температуры", - "inputText": "Окно ввода текста", - "select": "Выпадающий список", - "chart": "График без точек", - "chart2": "График с точками", - "chart3": "График дневного расхода (столбики)", - "chart4": "График дневного расхода (плавный)", - "fillgauge": "Бочка", - "progress-line": "Линия", - "progress-round": "Круг", - "anydata": "Текст", - "anydataHum": "Влажность (%)", - "anydataPress": "Давление (mm)", - "anydataTemp": "Температура (°С)", - "anydataPpb": "Части на миллиард (ppb)", - "anydataPpm": "Части на миллион (ppm)", - "anydataVlt": "Напряжение (Vlt)", - "anydataAmp": "Сила тока (Amp)", - "anydataWtt": "Мощность (Wtt)", - "anydataWhr": "Энергия (Whr)", - "anydataHtz": "Частота (Htz)", - "anydataTime": "Манометр", - "alarm": "Тревожное сообщение 1", - "anydataAlarm": "Тревожное сообщение 2", - "na": "Без виджета" -} \ No newline at end of file diff --git a/data_ms/widgets/alarm.json b/data_ms/widgets/alarm.json deleted file mode 100644 index e0e636c3..00000000 --- a/data_ms/widgets/alarm.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "widget": "anydata", - "icon": "body", - "color": "red", - "descrColor": "red" -} \ No newline at end of file diff --git a/data_ms/widgets/anydata.json b/data_ms/widgets/anydata.json deleted file mode 100644 index 4157b9c9..00000000 --- a/data_ms/widgets/anydata.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "anydata", - "after": "", - "icon": "" -} \ No newline at end of file diff --git a/data_ms/widgets/anydataAlarm.json b/data_ms/widgets/anydataAlarm.json deleted file mode 100644 index d793d350..00000000 --- a/data_ms/widgets/anydataAlarm.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "widget": "anydata", - "after": "", - "color":"red", - "icon": "walk" -} \ No newline at end of file diff --git a/data_ms/widgets/anydataAmp.json b/data_ms/widgets/anydataAmp.json deleted file mode 100644 index 0cc40403..00000000 --- a/data_ms/widgets/anydataAmp.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "anydata", - "after": "Amp", - "icon": "speedometer" -} \ No newline at end of file diff --git a/data_ms/widgets/anydataHtz.json b/data_ms/widgets/anydataHtz.json deleted file mode 100644 index 4836a81a..00000000 --- a/data_ms/widgets/anydataHtz.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "anydata", - "after": "Htz", - "icon": "speedometer" -} \ No newline at end of file diff --git a/data_ms/widgets/anydataHum.json b/data_ms/widgets/anydataHum.json deleted file mode 100644 index ebc5b5af..00000000 --- a/data_ms/widgets/anydataHum.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "anydata", - "after": "%", - "icon": "water" -} \ No newline at end of file diff --git a/data_ms/widgets/anydataPpb.json b/data_ms/widgets/anydataPpb.json deleted file mode 100644 index 037e77d3..00000000 --- a/data_ms/widgets/anydataPpb.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "anydata", - "after": "ppb", - "icon": "body" - } \ No newline at end of file diff --git a/data_ms/widgets/anydataPpm.json b/data_ms/widgets/anydataPpm.json deleted file mode 100644 index e4d134e7..00000000 --- a/data_ms/widgets/anydataPpm.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "anydata", - "after": "ppm", - "icon": "body" - } \ No newline at end of file diff --git a/data_ms/widgets/anydataPress.json b/data_ms/widgets/anydataPress.json deleted file mode 100644 index e67af2c8..00000000 --- a/data_ms/widgets/anydataPress.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "anydata", - "after": "mm", - "icon": "speedometer" -} \ No newline at end of file diff --git a/data_ms/widgets/anydataTemp.json b/data_ms/widgets/anydataTemp.json deleted file mode 100644 index 112da222..00000000 --- a/data_ms/widgets/anydataTemp.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "anydata", - "after": "°С", - "icon": "thermometer" -} \ No newline at end of file diff --git a/data_ms/widgets/anydataTime.json b/data_ms/widgets/anydataTime.json deleted file mode 100644 index 821c4dab..00000000 --- a/data_ms/widgets/anydataTime.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "anydata", - "after": "", - "icon": "speedometer" -} \ No newline at end of file diff --git a/data_ms/widgets/anydataVlt.json b/data_ms/widgets/anydataVlt.json deleted file mode 100644 index f2a10747..00000000 --- a/data_ms/widgets/anydataVlt.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "anydata", - "after": "Vlt", - "icon": "speedometer" -} \ No newline at end of file diff --git a/data_ms/widgets/anydataWhr.json b/data_ms/widgets/anydataWhr.json deleted file mode 100644 index e523bedd..00000000 --- a/data_ms/widgets/anydataWhr.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "anydata", - "after": "Whr", - "icon": "speedometer" -} \ No newline at end of file diff --git a/data_ms/widgets/anydataWtt.json b/data_ms/widgets/anydataWtt.json deleted file mode 100644 index c1211050..00000000 --- a/data_ms/widgets/anydataWtt.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "anydata", - "after": "Wtt", - "icon": "speedometer" -} \ No newline at end of file diff --git a/data_ms/widgets/btn.json b/data_ms/widgets/btn.json deleted file mode 100644 index 67dcc0d3..00000000 --- a/data_ms/widgets/btn.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "widget": "btn", - "size": "large", - "color": "green", - "send": "test" -} \ No newline at end of file diff --git a/data_ms/widgets/chart.json b/data_ms/widgets/chart.json deleted file mode 100644 index 878ce0e4..00000000 --- a/data_ms/widgets/chart.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "chart", - "dateFormat": "HH:mm", - "pointRadius": 0 -} \ No newline at end of file diff --git a/data_ms/widgets/chart2.json b/data_ms/widgets/chart2.json deleted file mode 100644 index 9ecc61e3..00000000 --- a/data_ms/widgets/chart2.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "widget": "chart", - "dateFormat": "HH:mm" -} \ No newline at end of file diff --git a/data_ms/widgets/chart3.json b/data_ms/widgets/chart3.json deleted file mode 100644 index e2783cea..00000000 --- a/data_ms/widgets/chart3.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "chart", - "dateFormat": "DD.MM.YYYY", - "type":"bar" -} \ No newline at end of file diff --git a/data_ms/widgets/chart4.json b/data_ms/widgets/chart4.json deleted file mode 100644 index 11d05d24..00000000 --- a/data_ms/widgets/chart4.json +++ /dev/null @@ -1,4 +0,0 @@ -{ - "widget": "chart", - "dateFormat": "DD.MM.YYYY" -} \ No newline at end of file diff --git a/data_ms/widgets/fillgauge.json b/data_ms/widgets/fillgauge.json deleted file mode 100644 index 34315ea8..00000000 --- a/data_ms/widgets/fillgauge.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "widget": "fillgauge", - "circleColor": "#00FFFF", - "textColor": "#FFFFFF", - "waveTextColor": "#000000", - "waveColor": "#00FFFF" -} \ No newline at end of file diff --git a/data_ms/widgets/inputDate.json b/data_ms/widgets/inputDate.json deleted file mode 100644 index ecc3113d..00000000 --- a/data_ms/widgets/inputDate.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "widget" : "input", - "size" : "small", - "color" : "orange", - "type" : "date" -} \ No newline at end of file diff --git a/data_ms/widgets/inputDigit.json b/data_ms/widgets/inputDigit.json deleted file mode 100644 index 20196c6a..00000000 --- a/data_ms/widgets/inputDigit.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget" : "input", - "color" : "blue", - "type" : "number" -} \ No newline at end of file diff --git a/data_ms/widgets/inputDigitTemp.json b/data_ms/widgets/inputDigitTemp.json deleted file mode 100644 index 28f19081..00000000 --- a/data_ms/widgets/inputDigitTemp.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "widget" : "input", - "color" : "green", - "type" : "number", - "size" : "small", - "icon": "thermometer" -} \ No newline at end of file diff --git a/data_ms/widgets/inputText.json b/data_ms/widgets/inputText.json deleted file mode 100644 index 3484d53b..00000000 --- a/data_ms/widgets/inputText.json +++ /dev/null @@ -1,6 +0,0 @@ -{ - "widget" : "input", - "size" : "small", - "color" : "orange", - "type" : "text" -} \ No newline at end of file diff --git a/data_ms/widgets/inputTime.json b/data_ms/widgets/inputTime.json deleted file mode 100644 index e39942a4..00000000 --- a/data_ms/widgets/inputTime.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget" : "input", - "color" : "blue", - "type" : "time" -} \ No newline at end of file diff --git a/data_ms/widgets/inputTimeClock.json b/data_ms/widgets/inputTimeClock.json deleted file mode 100644 index ab3186f8..00000000 --- a/data_ms/widgets/inputTimeClock.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "widget" : "input", - "color" : "orange", - "type" : "time", - "size" : "small", - "icon": "alarm-outline" -} \ No newline at end of file diff --git a/data_ms/widgets/progress-line.json b/data_ms/widgets/progress-line.json deleted file mode 100644 index b2a95529..00000000 --- a/data_ms/widgets/progress-line.json +++ /dev/null @@ -1,12 +0,0 @@ -{ - "widget": "progress-line", - "icon": "sunny", - "descrColor": "", - "color": "", - "max": "100", - "background": "", - "stroke": "10", - "disabled": "", - "before": "", - "after": "" -} \ No newline at end of file diff --git a/data_ms/widgets/progress-round.json b/data_ms/widgets/progress-round.json deleted file mode 100644 index bf3ddae5..00000000 --- a/data_ms/widgets/progress-round.json +++ /dev/null @@ -1,11 +0,0 @@ -{ - "widget": "progress-round", - "descrColor": "", - "max": "100", - "stroke": "20", - "color": "#45ccce", - "background": "#777", - "before": "", - "semicircle": "1", - "after": "" -} \ No newline at end of file diff --git a/data_ms/widgets/range.json b/data_ms/widgets/range.json deleted file mode 100644 index 4d1e0ff3..00000000 --- a/data_ms/widgets/range.json +++ /dev/null @@ -1,9 +0,0 @@ - { - "widget" : "range", - "descrColor": "red", - "after" : "%", - "k" : 0.0977, - "min" : 0, - "max" : 100, - "debounce": 500 -} \ No newline at end of file diff --git a/data_ms/widgets/select.json b/data_ms/widgets/select.json deleted file mode 100644 index bad018fd..00000000 --- a/data_ms/widgets/select.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "widget": "select", - "options": [ - "Выключен", - "Включен" - ], - "status": 0 -} \ No newline at end of file diff --git a/data_ms/widgets/toggleBtn.json b/data_ms/widgets/toggleBtn.json deleted file mode 100644 index 4e9eed5e..00000000 --- a/data_ms/widgets/toggleBtn.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "toggle", - "icon": "", - "iconOff": "" -} \ No newline at end of file diff --git a/data_ms/widgets/toggleSunMoon.json b/data_ms/widgets/toggleSunMoon.json deleted file mode 100644 index 5501aa75..00000000 --- a/data_ms/widgets/toggleSunMoon.json +++ /dev/null @@ -1,5 +0,0 @@ -{ - "widget": "toggle", - "icon": "sunny", - "iconOff": "moon" -} \ No newline at end of file diff --git a/data_svelte/build/bundle.css b/data_svelte/build/bundle.css deleted file mode 100644 index 5c5c667a..00000000 --- a/data_svelte/build/bundle.css +++ /dev/null @@ -1,14 +0,0 @@ -*,::before,::after{box-sizing:border-box}html{-moz-tab-size:4;-o-tab-size:4;tab-size:4}html{line-height:1.15;-webkit-text-size-adjust:100%}body{margin:0}body{font-family:system-ui, - -apple-system, /* Firefox supports this but not yet `system-ui` */ - 'Segoe UI', - Roboto, - Helvetica, - Arial, - sans-serif, - 'Apple Color Emoji', - 'Segoe UI Emoji'}hr{height:0;color:inherit}abbr[title]{-webkit-text-decoration:underline dotted;text-decoration:underline dotted}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:ui-monospace, - SFMono-Regular, - Consolas, - 'Liberation Mono', - Menlo, - monospace;font-size:1em}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sub{bottom:-0.25em}sup{top:-0.5em}table{text-indent:0;border-color:inherit}button,input,optgroup,select,textarea{font-family:inherit;font-size:100%;line-height:1.15;margin:0}button,select{text-transform:none}button,[type='button']{-webkit-appearance:button}::-moz-focus-inner{border-style:none;padding:0}legend{padding:0}progress{vertical-align:baseline}::-webkit-inner-spin-button,::-webkit-outer-spin-button{height:auto}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-file-upload-button{-webkit-appearance:button;font:inherit}summary{display:list-item}blockquote,dl,dd,h1,h2,h3,h4,h5,h6,hr,figure,p,pre{margin:0}button{background-color:transparent;background-image:none}fieldset{margin:0;padding:0}ol,ul{list-style:none;margin:0;padding:0}html{font-family:ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";line-height:1.5}body{font-family:inherit;line-height:inherit}*,::before,::after{box-sizing:border-box;border-width:0;border-style:solid;border-color:currentColor}hr{border-top-width:1px}img{border-style:solid}textarea{resize:vertical}input::-moz-placeholder,textarea::-moz-placeholder{opacity:1;color:#9ca3af}input:-ms-input-placeholder,textarea:-ms-input-placeholder{opacity:1;color:#9ca3af}input::placeholder,textarea::placeholder{opacity:1;color:#9ca3af}button{cursor:pointer}table{border-collapse:collapse}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;text-decoration:inherit}button,input,optgroup,select,textarea{padding:0;line-height:inherit;color:inherit}pre,code,kbd,samp{font-family:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace}img,svg,video,canvas,audio,iframe,embed,object{display:block;vertical-align:middle}img,video{max-width:100%;height:auto}*,::before,::after{--tw-border-opacity:1;border-color:rgba(229, 231, 235, var(--tw-border-opacity))}.cards-grid{display:grid;grid-template-columns:repeat(1, minmax(0, 1fr));justify-items:center;gap:1rem}@media(min-width: 640px){.cards-grid{grid-template-columns:repeat(2, minmax(0, 1fr))}}@media(min-width: 1024px){.cards-grid{grid-template-columns:repeat(3, minmax(0, 1fr))}}@media(min-width: 1280px){.cards-grid{grid-template-columns:repeat(3, minmax(0, 1fr))}}@media(min-width: 1536px){.cards-grid{grid-template-columns:repeat(3, minmax(0, 1fr))}}.cards-grid-inline{display:grid;grid-template-columns:repeat(1, minmax(0, 1fr));justify-items:center}.card{width:100%;border-radius:0.5rem;--tw-bg-opacity:1;background-color:rgba(255, 255, 255, var(--tw-bg-opacity));padding:0.5rem;--tw-shadow:0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow)}@media(min-width: 640px){.card{padding:0.5rem}}@media(min-width: 768px){.card{padding:0.5rem}}@media(min-width: 1024px){.card{padding:0.5rem;--tw-shadow:0 10px 15px -3px rgba(0, 0, 0, 0.1), 0 4px 6px -2px rgba(0, 0, 0, 0.05);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow)}}@media(min-width: 1280px){.card{padding-left:2rem;padding-right:2rem;padding-top:1rem;padding-bottom:1rem}}@media(min-width: 1536px){.card{padding-left:2rem;padding-right:2rem;padding-top:1rem;padding-bottom:1rem}}.card-header{padding-bottom:1rem;text-align:center;font-size:1.125rem;line-height:1.75rem;font-weight:700;--tw-text-opacity:1;color:rgba(107, 114, 128, var(--tw-text-opacity))}.card-items-psn{margin-bottom:1rem;display:flex;height:2rem;align-items:center}.widget-descr-width{width:66.666667%}.widget-descr-style{padding-right:1rem;font-weight:700;--tw-text-opacity:1;color:rgba(107, 114, 128, var(--tw-text-opacity))}.widget-width{display:flex;width:33.333333%;justify-content:flex-end}.widget-input{width:100%;-webkit-appearance:none;-moz-appearance:none;appearance:none;align-content:center;border-radius:0.25rem;border-width:2px;--tw-border-opacity:1;border-color:rgba(229, 231, 235, var(--tw-border-opacity));--tw-bg-opacity:1;background-color:rgba(229, 231, 235, var(--tw-bg-opacity))}.widget-input:focus{--tw-bg-opacity:1;background-color:rgba(255, 255, 255, var(--tw-bg-opacity))}.widget-input{padding-top:0.25rem;padding-bottom:0.25rem;padding-right:1rem;text-align:right;line-height:1.25;--tw-text-opacity:1;color:rgba(55, 65, 81, var(--tw-text-opacity))}.widget-input:focus{outline:2px solid transparent;outline-offset:2px}.json-input{width:100%;-webkit-appearance:none;-moz-appearance:none;appearance:none;align-content:center;border-radius:0.25rem;border-width:2px;--tw-border-opacity:1;border-color:rgba(229, 231, 235, var(--tw-border-opacity))}.json-input:focus{--tw-border-opacity:1;border-color:rgba(99, 102, 241, var(--tw-border-opacity))}.json-input{--tw-bg-opacity:1;background-color:rgba(229, 231, 235, var(--tw-bg-opacity))}.json-input:focus{--tw-bg-opacity:1;background-color:rgba(255, 255, 255, var(--tw-bg-opacity))}.json-input{padding-top:0.25rem;padding-bottom:0.25rem;padding-right:1rem;line-height:1.25;--tw-text-opacity:1;color:rgba(55, 65, 81, var(--tw-text-opacity))}.json-input:focus{outline:2px solid transparent;outline-offset:2px}.widget-anydata-style{text-align:center;font-weight:700;--tw-text-opacity:1;color:rgba(107, 114, 128, var(--tw-text-opacity))}.table-head-element{width:25%;overflow-wrap:break-word;border-width:1px;--tw-border-opacity:1;border-color:rgba(209, 213, 219, var(--tw-border-opacity));text-align:center;font-weight:700;--tw-text-opacity:1;color:rgba(107, 114, 128, var(--tw-text-opacity))}.table-body-element{width:25%;overflow-wrap:break-word;border-width:1px;--tw-border-opacity:1;border-color:rgba(209, 213, 219, var(--tw-border-opacity));text-align:center}.table-input{width:100%;-webkit-appearance:none;-moz-appearance:none;appearance:none;align-content:center;border-width:2px;--tw-border-opacity:1;border-color:rgba(229, 231, 235, var(--tw-border-opacity))}.table-input:focus{--tw-border-opacity:1;border-color:rgba(99, 102, 241, var(--tw-border-opacity))}.table-input{--tw-bg-opacity:1;background-color:rgba(243, 244, 246, var(--tw-bg-opacity))}.table-input:focus{--tw-bg-opacity:1;background-color:rgba(255, 255, 255, var(--tw-bg-opacity))}.table-input{text-align:center;line-height:1.25;--tw-text-opacity:1;color:rgba(55, 65, 81, var(--tw-text-opacity))}.table-input:focus{outline:2px solid transparent;outline-offset:2px}.long-button{margin-top:1rem;display:flex;height:2rem;width:100%;align-content:center;justify-content:center;overflow-wrap:break-word;border-radius:0.25rem;border-width:1px;--tw-border-opacity:1;border-color:rgba(209, 213, 219, var(--tw-border-opacity));--tw-bg-opacity:1;background-color:rgba(219, 234, 254, var(--tw-bg-opacity))}.long-button:hover{--tw-bg-opacity:1;background-color:rgba(191, 219, 254, var(--tw-bg-opacity))}.long-button{font-weight:700;--tw-text-opacity:1;color:rgba(107, 114, 128, var(--tw-text-opacity))}.sr-only{position:absolute;width:1px;height:1px;padding:0;margin:-1px;overflow:hidden;clip:rect(0, 0, 0, 0);white-space:nowrap;border-width:0}.fixed{position:fixed}.absolute{position:absolute}.relative{position:relative}.top-1{top:0.25rem}.left-1{left:0.25rem}.m-0{margin:0px}.mt-4{margin-top:1rem}.mb-4{margin-bottom:1rem}.block{display:block}.flex{display:flex}.table{display:table}.grid{display:grid}.h-4{height:1rem}.h-6{height:1.5rem}.h-8{height:2rem}.h-10{height:2.5rem}.w-4{width:1rem}.w-8{width:2rem}.w-10{width:2.5rem}.w-1\/4{width:25%}.w-full{width:100%}.table-fixed{table-layout:fixed}.transform{--tw-translate-x:0;--tw-translate-y:0;--tw-rotate:0;--tw-skew-x:0;--tw-skew-y:0;--tw-scale-x:1;--tw-scale-y:1;transform:translateX(var(--tw-translate-x)) translateY(var(--tw-translate-y)) rotate(var(--tw-rotate)) skewX(var(--tw-skew-x)) skewY(var(--tw-skew-y)) scaleX(var(--tw-scale-x)) scaleY(var(--tw-scale-y))}@-webkit-keyframes spin{to{transform:rotate(360deg)}}@keyframes spin{to{transform:rotate(360deg)}}@-webkit-keyframes ping{75%,100%{transform:scale(2);opacity:0}}@keyframes ping{75%,100%{transform:scale(2);opacity:0}}@-webkit-keyframes pulse{50%{opacity:.5}}@keyframes pulse{50%{opacity:.5}}@-webkit-keyframes bounce{0%,100%{transform:translateY(-25%);-webkit-animation-timing-function:cubic-bezier(0.8,0,1,1);animation-timing-function:cubic-bezier(0.8,0,1,1)}50%{transform:none;-webkit-animation-timing-function:cubic-bezier(0,0,0.2,1);animation-timing-function:cubic-bezier(0,0,0.2,1)}}@keyframes bounce{0%,100%{transform:translateY(-25%);-webkit-animation-timing-function:cubic-bezier(0.8,0,1,1);animation-timing-function:cubic-bezier(0.8,0,1,1)}50%{transform:none;-webkit-animation-timing-function:cubic-bezier(0,0,0.2,1);animation-timing-function:cubic-bezier(0,0,0.2,1)}}.cursor-pointer{cursor:pointer}.appearance-none{-webkit-appearance:none;-moz-appearance:none;appearance:none}.grid-cols-1{grid-template-columns:repeat(1, minmax(0, 1fr))}.content-center{align-content:center}.items-center{align-items:center}.justify-end{justify-content:flex-end}.justify-center{justify-content:center}.gap-4{gap:1rem}.break-words{overflow-wrap:break-word}.rounded{border-radius:0.25rem}.rounded-lg{border-radius:0.5rem}.rounded-full{border-radius:9999px}.border-2{border-width:2px}.border{border-width:1px}.border-gray-200{--tw-border-opacity:1;border-color:rgba(229, 231, 235, var(--tw-border-opacity))}.border-gray-300{--tw-border-opacity:1;border-color:rgba(209, 213, 219, var(--tw-border-opacity))}.border-red-500{--tw-border-opacity:1;border-color:rgba(239, 68, 68, var(--tw-border-opacity))}.focus\:border-indigo-500:focus{--tw-border-opacity:1;border-color:rgba(99, 102, 241, var(--tw-border-opacity))}.bg-white{--tw-bg-opacity:1;background-color:rgba(255, 255, 255, var(--tw-bg-opacity))}.bg-gray-50{--tw-bg-opacity:1;background-color:rgba(249, 250, 251, var(--tw-bg-opacity))}.bg-gray-100{--tw-bg-opacity:1;background-color:rgba(243, 244, 246, var(--tw-bg-opacity))}.bg-gray-200{--tw-bg-opacity:1;background-color:rgba(229, 231, 235, var(--tw-bg-opacity))}.bg-gray-600{--tw-bg-opacity:1;background-color:rgba(75, 85, 99, var(--tw-bg-opacity))}.bg-red-100{--tw-bg-opacity:1;background-color:rgba(254, 226, 226, var(--tw-bg-opacity))}.bg-red-400{--tw-bg-opacity:1;background-color:rgba(248, 113, 113, var(--tw-bg-opacity))}.bg-green-100{--tw-bg-opacity:1;background-color:rgba(209, 250, 229, var(--tw-bg-opacity))}.bg-blue-100{--tw-bg-opacity:1;background-color:rgba(219, 234, 254, var(--tw-bg-opacity))}.bg-indigo-500{--tw-bg-opacity:1;background-color:rgba(99, 102, 241, var(--tw-bg-opacity))}.hover\:bg-blue-200:hover{--tw-bg-opacity:1;background-color:rgba(191, 219, 254, var(--tw-bg-opacity))}.hover\:bg-indigo-700:hover{--tw-bg-opacity:1;background-color:rgba(67, 56, 202, var(--tw-bg-opacity))}.focus\:bg-white:focus{--tw-bg-opacity:1;background-color:rgba(255, 255, 255, var(--tw-bg-opacity))}.bg-cover{background-size:cover}.p-2{padding:0.5rem}.px-4{padding-left:1rem;padding-right:1rem}.px-10{padding-left:2.5rem;padding-right:2.5rem}.py-1{padding-top:0.25rem;padding-bottom:0.25rem}.py-2{padding-top:0.5rem;padding-bottom:0.5rem}.pt-8{padding-top:2rem}.pr-4{padding-right:1rem}.text-center{text-align:center}.text-lg{font-size:1.125rem;line-height:1.75rem}.font-semibold{font-weight:600}.font-bold{font-weight:700}.leading-tight{line-height:1.25}.text-black{--tw-text-opacity:1;color:rgba(0, 0, 0, var(--tw-text-opacity))}.text-white{--tw-text-opacity:1;color:rgba(255, 255, 255, var(--tw-text-opacity))}.text-gray-500{--tw-text-opacity:1;color:rgba(107, 114, 128, var(--tw-text-opacity))}.text-gray-700{--tw-text-opacity:1;color:rgba(55, 65, 81, var(--tw-text-opacity))}.text-red-500{--tw-text-opacity:1;color:rgba(239, 68, 68, var(--tw-text-opacity))}.text-green-500{--tw-text-opacity:1;color:rgba(16, 185, 129, var(--tw-text-opacity))}*,::before,::after{--tw-shadow:0 0 #0000}.shadow-md{--tw-shadow:0 4px 6px -1px rgba(0, 0, 0, 0.1), 0 2px 4px -1px rgba(0, 0, 0, 0.06);box-shadow:var(--tw-ring-offset-shadow, 0 0 #0000), var(--tw-ring-shadow, 0 0 #0000), var(--tw-shadow)}.focus\:outline-none:focus{outline:2px solid transparent;outline-offset:2px}*,::before,::after{--tw-ring-inset:var(--tw-empty,/*!*/ /*!*/);--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-color:rgba(59, 130, 246, 0.5);--tw-ring-offset-shadow:0 0 #0000;--tw-ring-shadow:0 0 #0000}.focus\:ring-2:focus{--tw-ring-offset-shadow:var(--tw-ring-inset) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color);--tw-ring-shadow:var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width)) var(--tw-ring-color);box-shadow:var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 #0000)}.focus\:ring-indigo-400:focus{--tw-ring-opacity:1;--tw-ring-color:rgba(129, 140, 248, var(--tw-ring-opacity))}.transition{transition-property:background-color, border-color, color, fill, stroke, opacity, box-shadow, transform, filter, -webkit-backdrop-filter;transition-property:background-color, border-color, color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter;transition-property:background-color, border-color, color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter, -webkit-backdrop-filter;transition-timing-function:cubic-bezier(0.4, 0, 0.2, 1);transition-duration:150ms}#menu__toggle{opacity:0}#menu__toggle:checked~.menu__btn>span{transform:rotate(45deg)}#menu__toggle:checked~.menu__btn>span::before{top:0;transform:rotate(0)}#menu__toggle:checked~.menu__btn>span::after{top:0;transform:rotate(90deg)}#menu__toggle:checked~.menu__box{visibility:visible;left:0}#menu__toggle:checked~.menu__main{margin-left:150px;transition-duration:0.25s}.menu__btn{display:flex;align-items:center;position:fixed;z-index:1;top:10px;left:20px;width:20px;height:20px;cursor:pointer}.menu__btn>span,.menu__btn>span::before,.menu__btn>span::after{display:block;position:absolute;width:100%;height:2px;background-color:#616161;transition-duration:0.25s}.menu__btn>span::before{content:"";top:-8px}.menu__btn>span::after{content:"";top:8px}.menu__box{display:block;position:fixed;visibility:hidden;top:0;left:-100%;width:150px;height:100%;margin:0;padding:80px 0;list-style:none;background-color:#eceff1;box-shadow:1px 0px 6px rgba(0, 0, 0, 0.2);transition-duration:0.25s}.menu__item{display:block;padding:12px 24px;color:rgba(51, 51, 51, 0.788);font-family:"Roboto", sans-serif;font-size:15px;font-weight:600;text-decoration:none;transition-duration:0.25s}.menu__item:hover{background-color:#cfd8dc}.upper__bar{background-color:rgba(51, 51, 51, 0.144);height:70px;position:fixed;z-index:-1;top:0px;left:0;width:100%;margin:0;padding:0;box-shadow:1px 0px 3px rgba(0, 0, 0, 0.2)}input[type="date"]::-webkit-calendar-picker-indicator{margin-left:5px;margin-right:-8px}input[type="time"]::-webkit-calendar-picker-indicator{margin-left:5px;margin-right:-8px}input[type="number"]::-webkit-outer-spin-button,input[type="number"]::-webkit-inner-spin-button{margin-left:7px;margin-right:-6px;width:30px;height:30px;opacity:1}input:checked~.dot{transform:translateX(100%)}@media(min-width: 640px){.sm\:grid-cols-2{grid-template-columns:repeat(2, minmax(0, 1fr))}.sm\:p-2{padding:0.5rem}}@media(min-width: 768px){.md\:p-2{padding:0.5rem}}@media(min-width: 1024px){.lg\:grid-cols-3{grid-template-columns:repeat(3, minmax(0, 1fr))}.lg\:p-2{padding:0.5rem}}@media(min-width: 1280px){.xl\:grid-cols-3{grid-template-columns:repeat(3, minmax(0, 1fr))}.xl\:px-8{padding-left:2rem;padding-right:2rem}.xl\:py-4{padding-top:1rem;padding-bottom:1rem}}@media(min-width: 1536px){.\32xl\:grid-cols-3{grid-template-columns:repeat(3, minmax(0, 1fr))}.\32xl\:px-8{padding-left:2rem;padding-right:2rem}.\32xl\:py-4{padding-top:1rem;padding-bottom:1rem}} \ No newline at end of file diff --git a/data_svelte/build/bundle.js b/data_svelte/build/bundle.js deleted file mode 100644 index d9f1c682..00000000 --- a/data_svelte/build/bundle.js +++ /dev/null @@ -1,2 +0,0 @@ -var app=function(){"use strict";function t(){}function e(t){return t()}function n(){return Object.create(null)}function r(t){t.forEach(e)}function s(t){return"function"==typeof t}function o(t,e){return t!=t?e==e:t!==e||t&&"object"==typeof t||"function"==typeof t}function a(e,n,r){e.$$.on_destroy.push(function(e,...n){if(null==e)return t;const r=e.subscribe(...n);return r.unsubscribe?()=>r.unsubscribe():r}(n,r))}function i(t,e,n,r){if(t){const s=l(t,e,n,r);return t[0](s)}}function l(t,e,n,r){return t[1]&&r?function(t,e){for(const n in e)t[n]=e[n];return t}(n.ctx.slice(),t[1](r(e))):n.ctx}function c(t,e,n,r){if(t[2]&&r){const s=t[2](r(n));if(void 0===e.dirty)return s;if("object"==typeof s){const t=[],n=Math.max(e.dirty.length,s.length);for(let r=0;r32){const e=[],n=t.ctx.length/32;for(let t=0;tt.removeEventListener(e,n,r)}function v(t,e,n){null==n?t.removeAttribute(e):t.getAttribute(e)!==n&&t.setAttribute(e,n)}function _(t){return""===t?null:+t}function k(t,e){e=""+e,t.wholeText!==e&&(t.data=e)}function S(t,e){t.value=null==e?"":e}function E(t,e){for(let n=0;n{Y.delete(t),r&&(n&&t.d(1),r())})),t.o(e)}}function U(t,e,n){const r=t.$$.props[e];void 0!==r&&(t.$$.bound[r]=n,n(t.$$.ctx[r]))}function V(t){t&&t.c()}function tt(t,n,o,a){const{fragment:i,on_mount:l,on_destroy:c,after_update:u}=t.$$;i&&i.m(n,o),a||I((()=>{const n=l.map(e).filter(s);c?c.push(...n):r(n),t.$$.on_mount=[]})),u.forEach(I)}function et(t,e){const n=t.$$;null!==n.fragment&&(r(n.on_destroy),n.fragment&&n.fragment.d(e),n.on_destroy=n.fragment=null,n.ctx=[])}function nt(e,s,o,a,i,l,c,u=[-1]){const d=P;N(e);const p=e.$$={fragment:null,ctx:null,props:l,update:t,not_equal:i,bound:n(),on_mount:[],on_destroy:[],on_disconnect:[],before_update:[],after_update:[],context:new Map(s.context||(d?d.$$.context:[])),callbacks:n(),dirty:u,skip_bound:!1,root:s.target||d.$$.root};c&&c(p.root);let f=!1;if(p.ctx=o?o(e,s.props||{},((t,n,...r)=>{const s=r.length?r[0]:n;return p.ctx&&i(p.ctx[t],p.ctx[t]=s)&&(!p.skip_bound&&p.bound[t]&&p.bound[t](s),f&&function(t,e){-1===t.$$.dirty[0]&&(T.push(t),R(),t.$$.dirty.fill(0)),t.$$.dirty[e/31|0]|=1<{const t=n.indexOf(e);-1!==t&&n.splice(t,1)}}$set(t){var e;this.$$set&&(e=t,0!==Object.keys(e).length)&&(this.$$.skip_bound=!0,this.$$set(t),this.$$.skip_bound=!1)}}const st=[];function ot(e,n=t){let r;const s=new Set;function a(t){if(o(e,t)&&(e=t,r)){const t=!st.length;for(const t of s)t[1](),st.push(t,e);if(t){for(let t=0;t{s.delete(l),0===s.size&&(r(),r=null)}}}}function at(t,e=!1){return(t=t.slice(t.startsWith("/#")?2:0,t.endsWith("/*")?-2:void 0)).startsWith("/")||(t="/"+t),"/"===t&&(t=""),e&&!t.endsWith("/")&&(t+="/"),t}function it(t,e,n){if(""===n)return t;if("/"===n[0])return n;let r=t=>t.split("/").filter((t=>""!==t)),s=r(t);return"/"+(e?r(e):[]).map(((t,e)=>s[e])).join("/")+"/"+n}function lt(t,e,n,r){let s=[e,"data-"+e].reduce(((e,r)=>{let s=t.getAttribute(r);return n&&t.removeAttribute(r),null===s?e:s}),!1);return!r&&""===s||(s||r||!1)}function ct(t){let e=t.split("&").map((t=>t.split("="))).reduce(((t,e)=>{let n=e[0];if(!n)return t;let r=!(e.length>1)||e[e.length-1];return"string"==typeof r&&r.includes(",")&&(r=r.split(",")),void 0===t[n]?t[n]=[r]:t[n].push(r),t}),{});return Object.entries(e).reduce(((t,e)=>(t[e[0]]=e[1].length>1?e[1]:e[1][0],t)),{})}var ut,dt,pt={HISTORY:1,HASH:2,MEMORY:3,OFF:4,run:function(t,e,n,r){return 1===t?e&&e():2===t?n&&n():r&&r()},getDeafault:function(){return window&&"srcdoc"!==window.location.pathname?1:3}},ft=function(){let t,e=pt.getDeafault(),n=n=>t&&t(gt(e));function r(t){t&&(e=t),window.onhashchange=window.onpopstate=dt=null,e!==pt.OFF&&pt.run(e,(t=>window.onpopstate=n),(t=>window.onhashchange=n))&&n()}return{mode:t=>r(t),get:t=>gt(e),go(t,r){(function(t,e,n){let r=t=>history[n?"replaceState":"pushState"]({},"",t);pt.run(t,(t=>r(e)),(t=>r(`#${e}`)),(t=>dt=e))})(e,t,r),n()},start(e){t=e,r()},stop(){t=null,r(pt.OFF)}}}();function gt(t){let e=ut,n=ut=pt.run(t,(t=>window.location.pathname+window.location.search),(t=>String(window.location.hash.slice(1)||"/")),(t=>dt||"/")),r=n.match(/^([^?#]+)(?:\?([^#]+))?(?:\#(.+))?$/);return{url:n,from:e,path:r[1]||"",query:ct(r[2]||""),hash:r[3]||""}}function mt(t){let e=H("tinro");e&&(e.exact||e.fallback)&&function(t){throw new Error("[Tinro] "+t)}(`${t.fallback?"":``} can't be inside ${e.fallback?"":` with exact path`}`);let n=t.fallback?"fallbacks":"childs",r=ot({}),s={router:{},exact:!1,pattern:null,meta:{},parent:e,fallback:t.fallback,redirect:!1,firstmatch:!1,breadcrumb:null,matched:!1,childs:new Set,activeChilds:new Set,fallbacks:new Set,update(t){s.exact=!t.path.endsWith("/*"),s.pattern=at(`${s.parent&&s.parent.pattern||""}${t.path}`),s.redirect=t.redirect,s.firstmatch=t.firstmatch,s.breadcrumb=t.breadcrumb,s.match()},register:()=>{if(s.parent)return s.parent[n].add(s),()=>{s.parent[n].delete(s),s.router.un&&s.router.un()}},show:()=>{t.onShow(),!s.fallback&&s.parent&&s.parent.activeChilds.add(s)},hide:()=>{t.onHide(),!s.fallback&&s.parent&&s.parent.activeChilds.delete(s)},match:async()=>{s.matched=!1;let{path:e,url:n,from:o,query:a}=s.router,i=function(t,e){t=at(t,!0),e=at(e,!0);let n=[],r={},s=!0,o=t.split("/").map((t=>t.startsWith(":")?(n.push(t.slice(1)),"([^\\/]+)"):t)).join("\\/"),a=e.match(new RegExp(`^${o}$`));return a||(s=!1,a=e.match(new RegExp(`^${o}`))),a?(n.forEach(((t,e)=>r[t]=a[e+1])),{exact:s,params:r,part:a[0].slice(0,-1)}):null}(s.pattern,e);if(!s.fallback&&i&&s.redirect&&(!s.exact||s.exact&&i.exact)){await z();let t=it(e,s.parent&&s.parent.pattern,s.redirect);return $t.goto(t,!0)}if(s.meta=i&&{from:o,url:n,query:a,match:i.part,pattern:s.pattern,breadcrumbs:s.parent&&s.parent.meta&&s.parent.meta.breadcrumbs.slice()||[],params:i.params,subscribe:r.subscribe},s.breadcrumb&&s.meta&&s.meta.breadcrumbs.push({name:s.breadcrumb,path:i.part}),r.set(s.meta),!i||s.fallback||!(!s.exact||s.exact&&i.exact)||s.parent&&s.parent.firstmatch&&s.parent.matched?s.hide():(t.onMeta(s.meta),s.parent&&(s.parent.matched=!0),s.show()),await z(),i&&!s.fallback&&(s.childs.size>0&&0==s.activeChilds.size||0==s.childs.size&&s.fallbacks.size>0)){let t=s;for(;0==t.fallbacks.size;)if(t=t.parent,!t)return;t&&t.fallbacks.forEach((t=>{if(t.redirect){let e=it("/",t.parent&&t.parent.pattern,t.redirect);$t.goto(e,!0)}else t.show()}))}}};return o="tinro",a=s,O().$$.context.set(o,a),A((()=>s.register())),s.router.un=$t.subscribe((t=>{s.router.path=t.path,s.router.url=t.url,s.router.query=t.query,s.router.from=t.from,null!==s.pattern&&s.match()})),s;var o,a}function ht(){return H("tinro").meta}var $t=function(){let{subscribe:t}=ot(ft.get(),(t=>{ft.start(t);let e=function(t){let e=e=>{let n=e.target.closest("a[href]"),r=n&<(n,"target",!1,"_self"),s=n&<(n,"tinro-ignore"),o=e.ctrlKey||e.metaKey||e.altKey||e.shiftKey;if("_self"==r&&!s&&!o&&n){let r=n.getAttribute("href").replace(/^\/#/,"");/^\/\/|^[a-zA-Z]+:/.test(r)||(e.preventDefault(),t(r.startsWith("/")?r:n.href.replace(window.location.origin,"")))}};return addEventListener("click",e),()=>removeEventListener("click",e)}(ft.go);return()=>{ft.stop(),e()}}));return{subscribe:t,goto:ft.go,params:bt,meta:ht,useHashNavigation:t=>ft.mode(t?pt.HASH:pt.HISTORY),mode:{hash:()=>ft.mode(pt.HASH),history:()=>ft.mode(pt.HISTORY),memory:()=>ft.mode(pt.MEMORY)}}}();function bt(){return H("tinro").meta.params}const wt=t=>({params:2&t,meta:4&t}),yt=t=>({params:t[1],meta:t[2]});function xt(t){let e;const n=t[9].default,r=i(n,t,t[8],yt);return{c(){r&&r.c()},m(t,n){r&&r.m(t,n),e=!0},p(t,s){r&&r.p&&(!e||262&s)&&u(r,n,t,t[8],e?c(n,t[8],s,wt):d(t[8]),yt)},i(t){e||(X(r,t),e=!0)},o(t){G(r,t),e=!1},d(t){r&&r.d(t)}}}function vt(t){let e,n,r=t[0]&&xt(t);return{c(){r&&r.c(),e=y()},m(t,s){r&&r.m(t,s),f(t,e,s),n=!0},p(t,[n]){t[0]?r?(r.p(t,n),1&n&&X(r,1)):(r=xt(t),r.c(),X(r,1),r.m(e.parentNode,e)):r&&(Z(),G(r,1,1,(()=>{r=null})),Q())},i(t){n||(X(r),n=!0)},o(t){G(r),n=!1},d(t){r&&r.d(t),t&&g(e)}}}function _t(t,e,n){let{$$slots:r={},$$scope:s}=e,{path:o="/*"}=e,{fallback:a=!1}=e,{redirect:i=!1}=e,{firstmatch:l=!1}=e,{breadcrumb:c=null}=e,u=!1,d={},p={};const f=mt({fallback:a,onShow(){n(0,u=!0)},onHide(){n(0,u=!1)},onMeta(t){n(2,p=t),n(1,d=p.params)}});return t.$$set=t=>{"path"in t&&n(3,o=t.path),"fallback"in t&&n(4,a=t.fallback),"redirect"in t&&n(5,i=t.redirect),"firstmatch"in t&&n(6,l=t.firstmatch),"breadcrumb"in t&&n(7,c=t.breadcrumb),"$$scope"in t&&n(8,s=t.$$scope)},t.$$.update=()=>{232&t.$$.dirty&&f.update({path:o,redirect:i,firstmatch:l,breadcrumb:c})},[u,d,p,o,a,i,l,c,s,r]}class kt extends rt{constructor(t){super(),nt(this,t,_t,vt,o,{path:3,fallback:4,redirect:5,firstmatch:6,breadcrumb:7})}}function St(t){let e,n,r,s,o;const a=t[2].default,l=i(a,t,t[1],null);return{c(){e=h("div"),n=h("h1"),r=b(t[0]),s=w(),l&&l.c(),v(n,"class","card-header"),v(e,"class","card")},m(t,a){f(t,e,a),p(e,n),p(n,r),p(e,s),l&&l.m(e,null),o=!0},p(t,[e]){(!o||1&e)&&k(r,t[0]),l&&l.p&&(!o||2&e)&&u(l,a,t,t[1],o?c(a,t[1],e,null):d(t[1]),null)},i(t){o||(X(l,t),o=!0)},o(t){G(l,t),o=!1},d(t){t&&g(e),l&&l.d(t)}}}function Et(t,e,n){let{$$slots:r={},$$scope:s}=e,{title:o}=e;return t.$$set=t=>{"title"in t&&n(0,o=t.title),"$$scope"in t&&n(1,s=t.$$scope)},[o,s,r]}class Pt extends rt{constructor(t){super(),nt(this,t,Et,St,o,{title:0})}}function Nt(t){let e,n,s,o;return{c(){e=h("input"),v(e,"class",n=1==t[0].send?"widget-input border-red-500":"widget-input focus:border-indigo-500"),v(e,"step","0.1"),v(e,"type","number")},m(n,r){f(n,e,r),S(e,t[0].status),s||(o=[x(e,"change",t[2]),x(e,"input",t[3])],s=!0)},p(t,r){1&r&&n!==(n=1==t[0].send?"widget-input border-red-500":"widget-input focus:border-indigo-500")&&v(e,"class",n),1&r&&_(e.value)!==t[0].status&&S(e,t[0].status)},d(t){t&&g(e),s=!1,r(o)}}}function Ot(t){let e,n,s,o;return{c(){e=h("input"),v(e,"class",n=1==t[0].send?"widget-input border-red-500":"widget-input focus:border-indigo-500"),v(e,"type","text")},m(n,r){f(n,e,r),S(e,t[0].status),s||(o=[x(e,"change",t[4]),x(e,"input",t[5])],s=!0)},p(t,r){1&r&&n!==(n=1==t[0].send?"widget-input border-red-500":"widget-input focus:border-indigo-500")&&v(e,"class",n),1&r&&e.value!==t[0].status&&S(e,t[0].status)},d(t){t&&g(e),s=!1,r(o)}}}function At(t){let e,n,s,o;return{c(){e=h("input"),v(e,"class",n=1==t[0].send?"widget-input border-red-500":"widget-input focus:border-indigo-500"),v(e,"type","date")},m(n,r){f(n,e,r),S(e,t[0].status),s||(o=[x(e,"change",t[6]),x(e,"input",t[7])],s=!0)},p(t,r){1&r&&n!==(n=1==t[0].send?"widget-input border-red-500":"widget-input focus:border-indigo-500")&&v(e,"class",n),1&r&&S(e,t[0].status)},d(t){t&&g(e),s=!1,r(o)}}}function Ht(t){let e,n,s,o;return{c(){e=h("input"),v(e,"class",n=1==t[0].send?"widget-input border-red-500":"widget-input focus:border-indigo-500"),v(e,"type","time")},m(n,r){f(n,e,r),S(e,t[0].status),s||(o=[x(e,"change",t[8]),x(e,"input",t[9])],s=!0)},p(t,r){1&r&&n!==(n=1==t[0].send?"widget-input border-red-500":"widget-input focus:border-indigo-500")&&v(e,"class",n),1&r&&S(e,t[0].status)},d(t){t&&g(e),s=!1,r(o)}}}function Tt(e){let n,r,s,o,a,i,l,c,u,d=(e[0].descr?e[0].descr:"")+"",m="number"==e[0].type&&Nt(e),$="text"==e[0].type&&Ot(e),y="date"==e[0].type&&At(e),x="time"==e[0].type&&Ht(e);return{c(){n=h("div"),r=h("div"),s=h("label"),o=b(d),a=w(),i=h("div"),m&&m.c(),l=w(),$&&$.c(),c=w(),y&&y.c(),u=w(),x&&x.c(),v(s,"class","widget-descr-style"),v(r,"class","widget-descr-width"),v(i,"class","widget-width"),v(n,"class","card-items-psn")},m(t,e){f(t,n,e),p(n,r),p(r,s),p(s,o),p(n,a),p(n,i),m&&m.m(i,null),p(i,l),$&&$.m(i,null),p(i,c),y&&y.m(i,null),p(i,u),x&&x.m(i,null)},p(t,[e]){1&e&&d!==(d=(t[0].descr?t[0].descr:"")+"")&&k(o,d),"number"==t[0].type?m?m.p(t,e):(m=Nt(t),m.c(),m.m(i,l)):m&&(m.d(1),m=null),"text"==t[0].type?$?$.p(t,e):($=Ot(t),$.c(),$.m(i,c)):$&&($.d(1),$=null),"date"==t[0].type?y?y.p(t,e):(y=At(t),y.c(),y.m(i,u)):y&&(y.d(1),y=null),"time"==t[0].type?x?x.p(t,e):(x=Ht(t),x.c(),x.m(i,null)):x&&(x.d(1),x=null)},i:t,o:t,d(t){t&&g(n),m&&m.d(),$&&$.d(),y&&y.d(),x&&x.d()}}}function Ct(t,e,n){let{widget:r}=e,{wsPushProp:s=((t,e,n)=>{})}=e;return t.$$set=t=>{"widget"in t&&n(0,r=t.widget),"wsPushProp"in t&&n(1,s=t.wsPushProp)},[r,s,()=>(n(0,r.send=!0,r),s(r.ws,r.topic,r.status)),function(){r.status=_(this.value),n(0,r)},()=>(n(0,r.send=!0,r),s(r.ws,r.topic,r.status)),function(){r.status=this.value,n(0,r)},()=>(n(0,r.send=!0,r),s(r.ws,r.topic,r.status)),function(){r.status=this.value,n(0,r)},()=>(n(0,r.send=!0,r),s(r.ws,r.topic,r.status)),function(){r.status=this.value,n(0,r)}]}class Lt extends rt{constructor(t){super(),nt(this,t,Ct,Tt,o,{widget:0,wsPushProp:1})}}function Mt(e){let n,s,o,a,i,l,c,u,d,m,$,y,_,E,P,N,O,A,H=(e[0].descr?e[0].descr:"")+"";return{c(){n=h("div"),s=h("div"),o=h("label"),a=b(H),i=w(),l=h("div"),c=h("label"),u=h("div"),d=h("input"),$=w(),y=h("div"),_=w(),E=h("div"),v(o,"class","widget-descr-style"),v(s,"class","widget-descr-width"),v(d,"id",m=e[0].topic),v(d,"type","checkbox"),v(d,"class","sr-only"),v(y,"class","block bg-gray-600 w-10 h-6 rounded-full"),v(E,"class",P="dot "+(1==e[0].send?"bg-red-400":"bg-white")+" absolute left-1 top-1 w-4 h-4 rounded-full transition"),v(u,"class","relative"),v(c,"for",N=e[0].topic),v(c,"class","items-center cursor-pointer"),v(l,"class","widget-width"),v(n,"class","card-items-psn")},m(t,r){f(t,n,r),p(n,s),p(s,o),p(o,a),p(n,i),p(n,l),p(l,c),p(c,u),p(u,d),S(d,e[0].status),p(u,$),p(u,y),p(u,_),p(u,E),O||(A=[x(d,"change",e[2]),x(d,"change",e[3])],O=!0)},p(t,[e]){1&e&&H!==(H=(t[0].descr?t[0].descr:"")+"")&&k(a,H),1&e&&m!==(m=t[0].topic)&&v(d,"id",m),1&e&&S(d,t[0].status),1&e&&P!==(P="dot "+(1==t[0].send?"bg-red-400":"bg-white")+" absolute left-1 top-1 w-4 h-4 rounded-full transition")&&v(E,"class",P),1&e&&N!==(N=t[0].topic)&&v(c,"for",N)},i:t,o:t,d(t){t&&g(n),O=!1,r(A)}}}function jt(t,e,n){let{widget:r}=e,{wsPushProp:s=((t,e,n)=>{})}=e;return t.$$set=t=>{"widget"in t&&n(0,r=t.widget),"wsPushProp"in t&&n(1,s=t.wsPushProp)},[r,s,()=>(n(0,r.send=!0,r),s(r.ws,r.topic,r.status)),function(){r.status=this.value,n(0,r)}]}class qt extends rt{constructor(t){super(),nt(this,t,jt,Mt,o,{widget:0,wsPushProp:1})}}function Rt(e){let n,r,s,o,a,i,l,c,u,d,m,$,y=(e[0].descr?e[0].descr:"")+"",x=(e[0].status?e[0].status:"")+"",_=(e[0].after?e[0].after:"")+"";return{c(){n=h("div"),r=h("div"),s=h("label"),o=b(y),a=w(),i=h("div"),l=h("label"),c=b(x),u=w(),d=h("label"),m=b(" "),$=b(_),v(s,"class","widget-descr-style"),v(r,"class","widget-descr-width"),v(l,"class","widget-anydata-style"),v(d,"class","widget-anydata-style"),v(i,"class","widget-width"),v(n,"class","card-items-psn")},m(t,e){f(t,n,e),p(n,r),p(r,s),p(s,o),p(n,a),p(n,i),p(i,l),p(l,c),p(i,u),p(i,d),p(d,m),p(d,$)},p(t,[e]){1&e&&y!==(y=(t[0].descr?t[0].descr:"")+"")&&k(o,y),1&e&&x!==(x=(t[0].status?t[0].status:"")+"")&&k(c,x),1&e&&_!==(_=(t[0].after?t[0].after:"")+"")&&k($,_)},i:t,o:t,d(t){t&&g(n)}}}function zt(t,e,n){let{widget:r}=e;return t.$$set=t=>{"widget"in t&&n(0,r=t.widget)},[r]}class It extends rt{constructor(t){super(),nt(this,t,zt,Rt,o,{widget:0})}}function Ft(t,e,n){const r=t.slice();return r[45]=e[n],r}function Jt(t,e,n){const r=t.slice();return r[48]=e[n],r[50]=n,r}function Wt(t,e,n){const r=t.slice();return r[51]=e[n],r}function Bt(t,e,n){const r=t.slice();return r[54]=e[n],r[50]=n,r}function Dt(t,e,n){const r=t.slice();return r[56]=e[n],r[57]=e,r[50]=n,r}function Yt(t,e,n){const r=t.slice();return r[45]=e[n],r}function Kt(t){let e,n,r,s,o=t[45].name+"";return{c(){e=h("option"),n=b(o),r=w(),e.__value=s=t[45],e.value=e.__value},m(t,s){f(t,e,s),p(e,n),p(e,r)},p(t,r){64&r[0]&&o!==(o=t[45].name+"")&&k(n,o),64&r[0]&&s!==(s=t[45])&&(e.__value=s,e.value=e.__value)},d(t){t&&g(e)}}}function Zt(t){let e,n,r,s,o="input"===t[56].widget&&Qt(t),a="toggle"===t[56].widget&&Xt(t),i="anydata"===t[56].widget&&Gt(t);return{c(){o&&o.c(),e=w(),a&&a.c(),n=w(),i&&i.c(),r=y()},m(t,l){o&&o.m(t,l),f(t,e,l),a&&a.m(t,l),f(t,n,l),i&&i.m(t,l),f(t,r,l),s=!0},p(t,s){"input"===t[56].widget?o?(o.p(t,s),2&s[0]&&X(o,1)):(o=Qt(t),o.c(),X(o,1),o.m(e.parentNode,e)):o&&(Z(),G(o,1,1,(()=>{o=null})),Q()),"toggle"===t[56].widget?a?(a.p(t,s),2&s[0]&&X(a,1)):(a=Xt(t),a.c(),X(a,1),a.m(n.parentNode,n)):a&&(Z(),G(a,1,1,(()=>{a=null})),Q()),"anydata"===t[56].widget?i?(i.p(t,s),2&s[0]&&X(i,1)):(i=Gt(t),i.c(),X(i,1),i.m(r.parentNode,r)):i&&(Z(),G(i,1,1,(()=>{i=null})),Q())},i(t){s||(X(o),X(a),X(i),s=!0)},o(t){G(o),G(a),G(i),s=!1},d(t){o&&o.d(t),t&&g(e),a&&a.d(t),t&&g(n),i&&i.d(t),t&&g(r)}}}function Qt(t){let e,n,r;function s(e){t[17](e,t[56])}let o={widget:t[56],wsPushProp:t[16]};return void 0!==t[56].status&&(o.value=t[56].status),e=new Lt({props:o}),C.push((()=>U(e,"value",s))),{c(){V(e.$$.fragment)},m(t,n){tt(e,t,n),r=!0},p(r,s){t=r;const o={};2&s[0]&&(o.widget=t[56]),!n&&2&s[0]&&(n=!0,o.value=t[56].status,F((()=>n=!1))),e.$set(o)},i(t){r||(X(e.$$.fragment,t),r=!0)},o(t){G(e.$$.fragment,t),r=!1},d(t){et(e,t)}}}function Xt(t){let e,n,r;function s(e){t[19](e,t[56])}let o={widget:t[56],wsPushProp:t[18]};return void 0!==t[56].status&&(o.value=t[56].status),e=new qt({props:o}),C.push((()=>U(e,"value",s))),{c(){V(e.$$.fragment)},m(t,n){tt(e,t,n),r=!0},p(r,s){t=r;const o={};2&s[0]&&(o.widget=t[56]),!n&&2&s[0]&&(n=!0,o.value=t[56].status,F((()=>n=!1))),e.$set(o)},i(t){r||(X(e.$$.fragment,t),r=!0)},o(t){G(e.$$.fragment,t),r=!1},d(t){et(e,t)}}}function Gt(t){let e,n,r;function s(e){t[20](e,t[56])}let o={widget:t[56]};return void 0!==t[56].status&&(o.value=t[56].status),e=new It({props:o}),C.push((()=>U(e,"value",s))),{c(){V(e.$$.fragment)},m(t,n){tt(e,t,n),r=!0},p(r,s){t=r;const o={};2&s[0]&&(o.widget=t[56]),!n&&2&s[0]&&(n=!0,o.value=t[56].status,F((()=>n=!1))),e.$set(o)},i(t){r||(X(e.$$.fragment,t),r=!0)},o(t){G(e.$$.fragment,t),r=!1},d(t){et(e,t)}}}function Ut(t){let e,n,r=t[56].page===t[54].page&&Zt(t);return{c(){r&&r.c(),e=y()},m(t,s){r&&r.m(t,s),f(t,e,s),n=!0},p(t,n){t[56].page===t[54].page?r?(r.p(t,n),6&n[0]&&X(r,1)):(r=Zt(t),r.c(),X(r,1),r.m(e.parentNode,e)):r&&(Z(),G(r,1,1,(()=>{r=null})),Q())},i(t){n||(X(r),n=!0)},o(t){G(r),n=!1},d(t){r&&r.d(t),t&&g(e)}}}function Vt(t){let e,n,r=t[1],s=[];for(let e=0;eG(s[t],1,1,(()=>{s[t]=null}));return{c(){for(let t=0;tG(a[t],1,1,(()=>{a[t]=null}));return r=new Pt({props:{title:"Редактор JSON",$$slots:{default:[ee]},$$scope:{ctx:t}}}),{c(){e=h("div");for(let t=0;tТип \n Подтип \n Id \n 4',r=w(),s=h("tbody");for(let t=0;tНазвание устройства \n IP адрес \n Идентификатор \n Состояние',r=w(),s=h("tbody");for(let t=0;t",P=w(),N=h("ul"),O=h("li"),A=h("a"),A.textContent="Управление",H=w(),T=h("li"),C=h("a"),C.textContent="Конфигуратор",L=w(),M=h("li"),j=h("a"),j.textContent="Подключение",q=w(),R=h("li"),z=h("a"),z.textContent="Утилиты",F=w(),J=h("li"),W=h("a"),W.textContent="Лог",B=w(),D=h("li"),Y=h("a"),Y.textContent="Устройства",K=w(),Z=h("li"),Q=h("a"),Q.textContent="О проекте",U=w(),nt=h("ul"),rt=h("div"),V(st.$$.fragment),ot=w(),V(at.$$.fragment),it=w(),V(lt.$$.fragment),ct=w(),V(ut.$$.fragment),dt=w(),V(pt.$$.fragment),ft=w(),V(gt.$$.fragment),mt=w(),V(ht.$$.fragment),void 0===t[5]&&I((()=>t[14].call(a))),v(o,"class","px-15 py-2"),v(u,"stroke","none"),v(u,"d","M0 0h24v24H0z"),v(d,"d","M7 18a4.6 4.4 0 0 1 0 -9h0a5 4.5 0 0 1 11 2h1a3.5 3.5 0 0 1 0 7h-12"),v(c,"class",b="h-8 w-8 "+(!0===t[4]?"text-green-500":"text-red-500")),v(c,"width","24"),v(c,"height","24"),v(c,"viewBox","0 0 24 24"),v(c,"stroke-width","2"),v(c,"stroke","currentColor"),v(c,"fill","none"),v(c,"stroke-linecap","round"),v(c,"stroke-linejoin","round"),v(l,"class","px-10 py-1"),v(s,"class","flex justify-end content-center"),v(n,"class","fixed m-0 h-10 w-full bg-gray-100 shadow-md"),v(_,"id","menu__toggle"),v(_,"type","checkbox"),v(S,"class","menu__btn"),v(S,"for","menu__toggle"),v(A,"class","menu__item"),v(A,"href","/"),v(C,"class","menu__item"),v(C,"href","/config"),v(j,"class","menu__item"),v(j,"href","/connection"),v(z,"class","menu__item"),v(z,"href","/utilities"),v(W,"class","menu__item"),v(W,"href","/log"),v(Y,"class","menu__item"),v(Y,"href","/list"),v(Q,"class","menu__item"),v(Q,"href","/about"),v(N,"class","menu__box"),v(rt,"class","bg-cover bg-gray-50 pt-8 px-4"),v(nt,"class","menu__main")},m(r,g){f(r,e,g),p(e,n),p(n,s),p(s,o),p(o,a);for(let t=0;tn(30,r=t))),$t.mode.hash();let s=document.location.hostname,o=!1,i=[],l=[];i=[{widget:"input",type:"date",status:"2021-10-17",page:"Inputs",order:"4",descr:"Switch on boiler date",topic:"/prefix/00000-00004/date1",ws:0},{widget:"input",type:"time",status:"12:00",page:"Inputs",order:"1",descr:"Switch on boiler time",topic:"/prefix/00000-00001/time",ws:0},{widget:"input",type:"number",status:"30.5",after:"°С",page:"Inputs",order:"2",descr:"Boiler temperature",topic:"/prefix/00000-00002/temp",ws:0},{widget:"input",type:"text",status:"Hello",page:"Inputs",order:"3",descr:"Message to be send",topic:"/prefix/00000-00003/text",ws:0},{widget:"toggle",status:0,page:"Toggles",order:"3",descr:"Light in my room",topic:"/prefix/00000-00003/btn1",ws:0},{widget:"toggle",status:0,page:"Toggles",order:"3",descr:"Light in my room",topic:"/prefix/00000-00003/btn2",ws:0},{widget:"toggle",status:0,page:"Toggles",order:"3",descr:"Light in my room",topic:"/prefix/00000-00003/btn3",ws:0},{widget:"anydata",status:30.5,after:"°С",page:"Any data",order:"3",descr:"Temperature",topic:"/prefix/00000-00003/tmp10",ws:0},{widget:"anydata",status:1032,after:"mm",page:"Any data",order:"3",descr:"Pressure",topic:"/prefix/00000-00003/tmp10",ws:0},{widget:"anydata",status:50,after:"%",page:"Any data",order:"3",descr:"Level",topic:"/prefix/00000-00003/tmp10",ws:0},{widget:"anydata",status:"opened",page:"Any data",order:"3",descr:"Status",topic:"/prefix/00000-00003/tmp10",ws:0}];let c,u,d=[],p=[],f=!1,g={},m=[],h=!0,$={},b=[];function w(){let t=0;m.forEach((e=>{e.ws=t,e.status||(x(t),_(t)),t++})),n(6,m),n(4,f=g.status)}function y(t,e){m.forEach((n=>{n.ws===t&&(n.status=e,n.status?console.log("[i]",n.ip,"status online"):console.log("[i]",n.ip,"status offline"))})),n(6,m),n(4,f=g.status)}function x(t){let e=v(t);"error"===e?console.log("[e]","device list wrong"):(p[t]=new WebSocket("ws://"+e+"/ws"),console.log("[i]",e,"started connecting..."))}function v(t){let e="error";return m.forEach((n=>{t===n.ws&&(e=n.ip)})),e}function _(t){if(p[t]){let e=v(t);console.log("[i]",e,"web socket events added"),p[t].addEventListener("open",(function(n){console.log("[i]",e,"completed connecting"),y(t,!0),T()})),p[t].addEventListener("message",(function(t){let e=t.data.toString();console.log("[i]","data:",e),e.includes("[log]")?(e=e.replace("[log]",""),N(e)):e.includes("[config]")&&(console.log("[i]","config data:",e),e=e.replace("[config]",""),e=JSON.parse(e),d.push(e),n(3,d))})),p[t].addEventListener("close",(n=>{console.log("[e]",e,"connection closed"),y(t,!1)})),p[t].addEventListener("error",(function(n){console.log("[e]",e,"connection error"),y(t,!1)}))}else console.log("[e]","socket not exist")}function k(t,e,n){let r=e+" "+n;console.log("[i]","send to ws msg:",r),E(t,r)}function S(){setTimeout(S,1e4),console.log("[i]","----timer tick----"),h||m.forEach((t=>{!function(t){let e=!1;return m.forEach((n=>{t===n.ws&&(e=n.status)})),e}(t.ws)?(x(t.ws),_(t.ws)):E(t.ws,"tst")})),h=!1}function E(t,e){p[t]&&1===p[t].readyState?(p[t].send(e),console.log("[i]",v(t),"msg send success",e)):console.log("[e]",v(t),"msg not send",e)}function P(){n(2,l=[]);Array.from(new Set(Array.from(i,(({page:t})=>t)))).forEach((function(t,e,r){n(2,l=[...l,JSON.parse(JSON.stringify({page:t}))])})),l.sort((function(t,e){return t.pagee.page?1:0}))}m=[{name:"Устройство 1",id:"987654321",ip:"192.168.88.235",status:!1}],$t.subscribe((function(){n(3,d=[]),u=r.path.toString(),console.log("[i]","user on page:",u),T()}));const N=t=>{b.length>Number(10)&&n(8,b=b.slice(0));const e=(new Date).getTime();n(8,b=[...b,{time:e,msg:t}]),b.sort((function(t,e){return t.time>e.time?-1:t.time{console.log("[i]","mounted"),w(),S(),n(4,f=g.status),O(),P()}));return[o,i,l,d,f,g,m,$,b,k,function(){n(1,i=JSON.parse(document.getElementById("text1").value)),P()},O,H,t=>{try{t=JSON.stringify(JSON.parse(t),null,4)}catch(e){return t}return t=(t=t.replace(/&/g,"&").replace(//g,">")).replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g,(function(t){return t}))},function(){g=function(t){const e=t.querySelector(":checked")||t.options[0];return e&&e.__value}(this),n(5,g),n(6,m)},()=>O(),(t,e,n)=>k(t,e,n),function(e,r){t.$$.not_equal(r.status,e)&&(r.status=e,n(1,i))},(t,e,n)=>k(t,e,n),function(e,r){t.$$.not_equal(r.status,e)&&(r.status=e,n(1,i))},function(e,r){t.$$.not_equal(r.status,e)&&(r.status=e,n(1,i))},()=>function(t,e,n){console.log("[i]","request for edit file");var r=new XMLHttpRequest,s=new FormData;s.append("data",new Blob([e],{type:"text/json"}),"/"+n),r.open("POST","http://"+t+"/edit"),r.onload=function(){},r.send(s)}("192.168.88.235","data data data data","file.json"),function(){$.name=this.value,n(7,$)},function(){$.ip=this.value,n(7,$)},function(){$.id=this.value,n(7,$)},()=>(n(0,o=!o),H())]}return new class extends rt{constructor(t){super(),nt(this,t,me,ge,o,{},null,[-1,-1])}}({target:document.body,props:{name:"world"}})}(); -//# sourceMappingURL=bundle.js.map diff --git a/data_svelte/config.json b/data_svelte/config.json deleted file mode 100644 index cc6024be..00000000 --- a/data_svelte/config.json +++ /dev/null @@ -1,37 +0,0 @@ -{ - "name": "IoTmanager", - "chipID": "", - "apssid": "IoTmanager", - "appass": "", - "routerssid": "rise", - "routerpass": "hostel3333", - "timezone": 1, - "ntp": "pool.ntp.org", - "mqttServer": "M2.WQTT.RU", - "mqttPort": 8021, - "mqttPrefix": "/iotTest3", - "mqttUser": "rise", - "mqttPass": "hostel3333", - "mqttServer2": "", - "mqttPort2": 0, - "mqttPrefix2": "", - "mqttUser2": "", - "mqttPass2": "", - "scen": 1, - "telegramApi": "1416711569:AAEI0j83GmXqwzb_gnK1B0Am0gDwZoJt5xo", - "telegonof": 0, - "teleginput": 0, - "autos": 1, - "weblogin": "admin", - "webpass": "admin", - "MqttIn": 0, - "MqttOut": 0, - "blink": 0, - "oneWirePin": 2, - "serverip": "http://206.189.49.244", - "uart": 0, - "uartS": 9600, - "uartTX": 12, - "uartRX": 13, - "grafmax": 0 -} \ No newline at end of file diff --git a/data_svelte/favicon.png b/data_svelte/favicon.png deleted file mode 100644 index 7e6f5eb5..00000000 Binary files a/data_svelte/favicon.png and /dev/null differ diff --git a/data_svelte/index.html b/data_svelte/index.html deleted file mode 100644 index a9c8fd65..00000000 --- a/data_svelte/index.html +++ /dev/null @@ -1,17 +0,0 @@ - - - - - - - Svelte app - - - - - - - - - - diff --git a/data_svelte/lile.json b/data_svelte/lile.json deleted file mode 100644 index 5f0dfdf2..00000000 --- a/data_svelte/lile.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "type": "binary", - "subtype": "button-out", - "id": "btn1", - "gpio": 1, - "inv": false -} \ No newline at end of file diff --git a/data_svelte/setup.json b/data_svelte/setup.json deleted file mode 100644 index efa38a10..00000000 --- a/data_svelte/setup.json +++ /dev/null @@ -1,559 +0,0 @@ -[ - { - "type": "binary", - "subtype": "button-out", - "id": "btn1", - "gpio": 1, - "inv": false - }, - { - "type": "sensor1", - "subtype": "bme280", - "units": "temp", - "id": "tmp1", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor2", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor3", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor4", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor5", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor6", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor7", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor8", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor9", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor10", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor11", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor12", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor13", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor14", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor15", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor16", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor17", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor18", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor19", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor20", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor21", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor22", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor23", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor24", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor25", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor26", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor27", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor28", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor29", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor30", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor31", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor32", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor33", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor34", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor35", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor36", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor37", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor38", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor39", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor40", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor41", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor42", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor43", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor44", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor45", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor46", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor47", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor48", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor49", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor50", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor51", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor52", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor53", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor54", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - }, - { - "type": "sensor55", - "subtype": "bme280", - "units": "temp", - "id": "tmp2", - "addr": "0x48", - "int": 10, - "c": 1, - "s": 0 - } -] \ No newline at end of file diff --git a/data_svelte/sync.ffs_db b/data_svelte/sync.ffs_db deleted file mode 100644 index cd5cdf88..00000000 Binary files a/data_svelte/sync.ffs_db and /dev/null differ diff --git a/doc/calculator.xlsx b/doc/calculator.xlsx deleted file mode 100644 index dc077bcd..00000000 Binary files a/doc/calculator.xlsx and /dev/null differ diff --git a/doc/eagle.txt b/doc/eagle.txt deleted file mode 100644 index 8a590610..00000000 --- a/doc/eagle.txt +++ /dev/null @@ -1,24 +0,0 @@ -eagle.flash.512k0.ld 512K (no SPIFFS) -eagle.flash.512k64.ld 512K (64K SPIFFS) -eagle.flash.512k128.ld 512K (128K SPIFFS) -eagle.flash.1m0.ld 1M (no SPIFFS) -eagle.flash.1m64.ld 1M (64K SPIFFS) -eagle.flash.1m128.ld 1M (128K SPIFFS) -eagle.flash.1m144.ld 1M (144K SPIFFS) -eagle.flash.1m160.ld 1M (160K SPIFFS) -eagle.flash.1m192.ld 1M (192K SPIFFS) -eagle.flash.1m256.ld 1M (256K SPIFFS) -eagle.flash.1m512.ld 1M (512K SPIFFS) -eagle.flash.2m.ld 2M (1M SPIFFS) -eagle.flash.4m1m.ld 4M (1M SPIFFS) -eagle.flash.4m2m.ld 4M (2M SPIFFS) -eagle.flash.4m.ld 4M (3M SPIFFS) -eagle.flash.8m.ld 8M (7M SPIFFS) -eagle.flash.16m.ld 16M (15M SPIFFS) - -# Name, Type, SubType, Offset, Size, Flags -nvs, data, nvs, 0x9000, 0x5000, -otadata, data, ota, 0xe000, 0x2000, -app0, app, ota_0, 0x10000, 0x1F0000, -app1, app, ota_1, 0x200000, 0x1F0000, -spiffs, data, spiffs, 0x3F0000,0x10000, \ No newline at end of file diff --git a/doc/orders.xlsm b/doc/orders.xlsm deleted file mode 100644 index d86f040e..00000000 Binary files a/doc/orders.xlsm and /dev/null differ diff --git a/doc/pictures/001 iot manager.jpeg b/doc/pictures/001 iot manager.jpeg deleted file mode 100644 index 39914774..00000000 Binary files a/doc/pictures/001 iot manager.jpeg and /dev/null differ diff --git a/doc/pictures/002 iot manager.jpeg b/doc/pictures/002 iot manager.jpeg deleted file mode 100644 index 80b9d67c..00000000 Binary files a/doc/pictures/002 iot manager.jpeg and /dev/null differ diff --git a/doc/pictures/003 iot manager.jpeg b/doc/pictures/003 iot manager.jpeg deleted file mode 100644 index 3f23d111..00000000 Binary files a/doc/pictures/003 iot manager.jpeg and /dev/null differ diff --git a/doc/pictures/007 iot manager.jpg b/doc/pictures/007 iot manager.jpg deleted file mode 100644 index 2178d634..00000000 Binary files a/doc/pictures/007 iot manager.jpg and /dev/null differ diff --git a/doc/pictures/008 flash.jpg b/doc/pictures/008 flash.jpg deleted file mode 100644 index 65be639f..00000000 Binary files a/doc/pictures/008 flash.jpg and /dev/null differ diff --git a/doc/pictures/009 flash.jpg b/doc/pictures/009 flash.jpg deleted file mode 100644 index 14341646..00000000 Binary files a/doc/pictures/009 flash.jpg and /dev/null differ diff --git a/doc/pictures/010 flash.jpg b/doc/pictures/010 flash.jpg deleted file mode 100644 index c26de4bc..00000000 Binary files a/doc/pictures/010 flash.jpg and /dev/null differ diff --git a/doc/pictures/011 flash.jpg b/doc/pictures/011 flash.jpg deleted file mode 100644 index 7329b0c0..00000000 Binary files a/doc/pictures/011 flash.jpg and /dev/null differ diff --git a/doc/pictures/012 wifi.jpg b/doc/pictures/012 wifi.jpg deleted file mode 100644 index 13c4c9d3..00000000 Binary files a/doc/pictures/012 wifi.jpg and /dev/null differ diff --git a/doc/pictures/013 wifi.jpg b/doc/pictures/013 wifi.jpg deleted file mode 100644 index c2938a8a..00000000 Binary files a/doc/pictures/013 wifi.jpg and /dev/null differ diff --git a/doc/pictures/014 wifi.jpg b/doc/pictures/014 wifi.jpg deleted file mode 100644 index 411b7a4d..00000000 Binary files a/doc/pictures/014 wifi.jpg and /dev/null differ diff --git a/doc/pictures/015 wifi.jpg b/doc/pictures/015 wifi.jpg deleted file mode 100644 index 394d00d7..00000000 Binary files a/doc/pictures/015 wifi.jpg and /dev/null differ diff --git a/doc/pictures/016 wifi.jpg b/doc/pictures/016 wifi.jpg deleted file mode 100644 index 4369c37f..00000000 Binary files a/doc/pictures/016 wifi.jpg and /dev/null differ diff --git a/doc/pictures/017.jpg b/doc/pictures/017.jpg deleted file mode 100644 index 68b210e2..00000000 Binary files a/doc/pictures/017.jpg and /dev/null differ diff --git a/doc/pictures/018.jpg b/doc/pictures/018.jpg deleted file mode 100644 index e8c0cc93..00000000 Binary files a/doc/pictures/018.jpg and /dev/null differ diff --git a/doc/pictures/019.jpg b/doc/pictures/019.jpg deleted file mode 100644 index 5667ee58..00000000 Binary files a/doc/pictures/019.jpg and /dev/null differ diff --git a/doc/pictures/020.jpg b/doc/pictures/020.jpg deleted file mode 100644 index 13fc001e..00000000 Binary files a/doc/pictures/020.jpg and /dev/null differ diff --git a/include/BufferExecute.h b/include/BufferExecute.h deleted file mode 100644 index 2398bdb6..00000000 --- a/include/BufferExecute.h +++ /dev/null @@ -1,20 +0,0 @@ -#pragma once -#include - -extern void loopCmdAdd(const String& cmdStr); -extern void fileCmdExecute(const String& filename); -extern void csvCmdExecute(String& cmdStr); -extern void spaceCmdExecute(String& cmdStr); -extern void loopCmdExecute(); -extern void addKey(String& key, String& keyNumberTable, int number); -extern int getKeyNum(String& key, String& keyNumberTable); - -extern void buttonIn(); -extern void buttonInSet(); - - - - - - - diff --git a/include/Bus.h b/include/Bus.h deleted file mode 100644 index 11edd50b..00000000 --- a/include/Bus.h +++ /dev/null @@ -1,4 +0,0 @@ -#pragma once -#include -void busInit(); -String i2c_scan(); \ No newline at end of file diff --git a/include/Class/CallBackTest.h b/include/Class/CallBackTest.h deleted file mode 100644 index 6632bfe0..00000000 --- a/include/Class/CallBackTest.h +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once -#include -#include -#include - -// Декларируем тип - сигнатуру метода , который мы готовы принять в данном случае это -// должен быть метод без результата и без параметров. -// Новый тип мы называем AsynсActionCb - хотя можешь назвать вообще как нравиться а что значит callBack - -typedef std::function AsyncActionCb; //метод без результата и параметров -typedef std::function AsyncParamActionCb; //метод без результата и параметров - -class CallBackTest { - private: - long count; - AsyncActionCb _cb; - AsyncParamActionCb _pcb; - - - public: - CallBackTest(); - void loop(); - void setCallback(AsyncActionCb cb); - void setCallback(AsyncParamActionCb pcb); -}; -//extern CallBackTest* CB; \ No newline at end of file diff --git a/include/Class/LineParsing.h b/include/Class/LineParsing.h deleted file mode 100644 index ff8a3965..00000000 --- a/include/Class/LineParsing.h +++ /dev/null @@ -1,291 +0,0 @@ -#pragma once - -#include - -#include "Global.h" -#include "ItemsList.h" -#include "Utils/JsonUtils.h" - -class LineParsing { - protected: - String _key; - String _file; - String _page; - String _descr; - String _order; - String _addr; - String _reg; - String _pin; - String _map; - String _c; - String _k; - String _inv; - String _state; - String _db; - String _type; - String _int; - String _cnt; - String _val; - String _index; - String _tm1; - String _tm2; - - int pinErrors; - - public: - LineParsing() : - - _key{""}, - _file{""}, - _page{""}, - _descr{""}, - _order{""}, - _addr{""}, - _reg{""}, - _pin{""}, - _map{""}, - _c{""}, - _k{""}, - _inv{""}, - _state{""}, - _db{""}, - _type{""}, - _int{""}, - _cnt{""}, - _val{""}, - _index{""}, - _tm1{""}, - _tm2{""}, - - pinErrors{0} - - {}; - - void update() { - //String order = sCmd.order(); - //SerialPrint("I","module","create '" + order + "'"); - for (int i = 1; i < 12; i++) { - if (i == 1) _key = sCmd.next(); - if (i == 2) _file = sCmd.next(); - if (i == 3) _page = sCmd.next(); - if (i == 4) _descr = sCmd.next(); - if (i == 5) _order = sCmd.next(); - } - - for (int i = 1; i < 10; i++) { - String arg = sCmd.next(); - if (arg != "") { - if (arg.indexOf("pin[") != -1) { - _pin = extractInner(arg); - } - if (arg.indexOf("inv[") != -1) { - _inv = extractInner(arg); - } - if (arg.indexOf("st[") != -1) { - _state = extractInner(arg); - } - if (arg.indexOf("db[") != -1) { - _db = extractInner(arg); - } - if (arg.indexOf("map[") != -1) { - _map = extractInner(arg); - } - if (arg.indexOf("c[") != -1) { - _c = extractInner(arg); - } - if (arg.indexOf("k[") != -1) { - _k = extractInner(arg); - } - if (arg.indexOf("type[") != -1) { - _type = extractInner(arg); - } - if (arg.indexOf("addr[") != -1) { - _addr = extractInner(arg); - } - if (arg.indexOf("reg[") != -1) { - _reg = extractInner(arg); - } - if (arg.indexOf("int[") != -1) { - _int = extractInner(arg); - } - if (arg.indexOf("cnt[") != -1) { - _cnt = extractInner(arg); - } - if (arg.indexOf("val[") != -1) { - _val = extractInner(arg); - } - if (arg.indexOf("index[") != -1) { - _index = extractInner(arg); - } - if (arg.indexOf("tm1[") != -1) { - _tm1 = extractInner(arg); - } - if (arg.indexOf("tm2[") != -1) { - _tm2 = extractInner(arg); - } - } - } - - if (_pin != "") { - if (_pin.indexOf(",") == -1) { - if (!isPinExist(_pin.toInt()) || !isDigitStr(_pin)) { - pinErrors++; - _pin = ""; - } - } else { - String pin1 = selectToMarker(_pin, ","); - String pin2 = deleteBeforeDelimiter(_pin, ","); - if (!isPinExist(pin1.toInt()) || !isDigitStr(pin1) || !isPinExist(pin2.toInt()) || !isDigitStr(pin2)) { - pinErrors++; - _pin = ""; - } - } - } - - _page.replace("#", " "); - _descr.replace("#", " "); - _descr.replace("%ver%", String(FIRMWARE_VERSION)); - _descr.replace("%name%", jsonReadStr(configSetupJson, F("name"))); - - createWidget(_descr, _page, _order, _file, _key); - } - - String gkey() { - return _key; - } - String gfile() { - return _file; - } - String gpage() { - return _page; - } - String gdescr() { - return _descr; - } - String gorder() { - return _order; - } - String gpin() { - return _pin; - } - String ginv() { - return _inv; - } - String gstate() { - return _state; - } - String gmap() { - return _map; - } - String gc() { - return _c; - } - String gk() { - return _k; - } - String gtype() { - return _type; - } - String gaddr() { - return _addr; - } - String gregaddr() { - return _reg; - } - String gint() { - return _int; - } - String gcnt() { - return _cnt; - } - String gval() { - return _val; - } - String gindex() { - return _index; - } - String gtm1() { - return _tm1; - } - String gtm2() { - return _tm2; - } - - int getPinErrors() { - return pinErrors; - } - - void clearErrors() { - pinErrors = 0; - } - - void clear() { - _key = ""; - _file = ""; - _page = ""; - _descr = ""; - _order = ""; - _addr = ""; - _reg = ""; - _pin = ""; - _map = ""; - _c = ""; - _k = ""; - _inv = ""; - _state = ""; - _db = ""; - _type = ""; - _int = ""; - _cnt = ""; - _val = ""; - _index = ""; - } - - String extractInnerDigit(String str) { - int p1 = str.indexOf("["); - int p2 = str.indexOf("]"); - return str.substring(p1 + 1, p2); - } - - void createWidget(String descr, String page, String order, String filename, String topic) { - if (filename != "na") { - String buf = "{}"; - if (!loadWidget(filename, buf)) { - return; - } - if (_cnt != "") { - if (filename.indexOf("chart") != -1) jsonWriteStr(buf, "maxCount", _cnt); - } - -#ifdef GATE_MODE - jsonWriteStr(buf, "info", " "); -#endif - - jsonWriteStr(buf, "page", page); - jsonWriteStr(buf, "order", order); - jsonWriteStr(buf, "descr", descr); - jsonWriteStr(buf, "topic", prex + "/" + topic); - -#ifdef LAYOUT_IN_RAM - all_widgets += widget + "\r\n"; -#else - addFileLn("layout.txt", buf); -#endif - } - } - - bool loadWidget(const String& filename, String& buf) { - buf = readFile(getWidgetFile(filename), 2048); - bool res = !(buf == "Failed" || buf == "Large"); - if (!res) { - SerialPrint("E","module","on load" + filename); - } - return res; - } - - const String getWidgetFile(const String& name) { - return "/widgets/" + name + ".json"; - } -}; - -extern LineParsing myLineParsing; diff --git a/include/Class/NotAsync.h b/include/Class/NotAsync.h deleted file mode 100644 index 1d5278cc..00000000 --- a/include/Class/NotAsync.h +++ /dev/null @@ -1,32 +0,0 @@ -#pragma once -#include -#include - -#include - -typedef std::function NotAsyncCb; - -struct NotAsyncItem { - bool test; - NotAsyncCb cb; - void* cb_arg; - volatile bool is_used = false; -}; - -class NotAsync { - private: - uint8_t size; - uint8_t task = 0; - NotAsyncItem* items = NULL; - void handle(NotAsyncCb f, void* arg); - - public: - NotAsync(uint8_t size); - ~NotAsync(); - - void add(uint8_t i, NotAsyncCb, void* arg); - void make(uint8_t task); - void loop(); -}; - -extern NotAsync* myNotAsyncActions; \ No newline at end of file diff --git a/include/Class/ScenarioClass3.h b/include/Class/ScenarioClass3.h deleted file mode 100644 index 177fcdce..00000000 --- a/include/Class/ScenarioClass3.h +++ /dev/null @@ -1,257 +0,0 @@ -#pragma once -#include - -#include "Cmd.h" -#include "Global.h" - -class Scenario { - public: - void loop2() { - if (!jsonReadBool(configSetupJson, "scen")) { - return; - } - String allBlocks = scenario; - allBlocks += "\n"; - - String incommingEvent = selectToMarker(eventBuf, ","); - - String incommingEventKey = selectToMarker(incommingEvent, " "); - String incommingEventValue = selectToMarkerLast(incommingEvent, " "); - - while (allBlocks.length()) { - String oneBlock = selectToMarker(allBlocks, "end\n"); - String condition = selectToMarker(oneBlock, "\n"); - - //логическое и - if (condition.indexOf("&&") != -1) { - condition = condition += " && "; - - //посчитаем количество условий - int conditionCnt = itemsCount2(condition, "&&") - 1; - - //создадим и заполним динамический массив - bool *arr = new bool[conditionCnt]; - for (int i = 0; i < conditionCnt; i++) { - arr[i] = false; - } - - //есть ли входящее событие хотя бы в одном из условий и удавлетварено ли оно? - int evenInConditionNum = -1; - for (int i = 0; i < conditionCnt; i++) { - String buf = selectFromMarkerToMarker(condition, " && ", i); - if (isScenarioNeedToDo(buf, incommingEventKey, incommingEventValue, 1)) { - arr[i] = true; - evenInConditionNum = i; - } - } - - //если да то проверяем остальные условия по json - if (evenInConditionNum >= 0) { - for (int i = 0; i < conditionCnt; i++) { - String buf = selectFromMarkerToMarker(condition, " && ", i); - if (i != evenInConditionNum) { - if (isScenarioNeedToDoJson(buf)) { - arr[i] = true; - } - } - } - } - - //все элементы массива должны быть true - bool result = true; - for (int i = 0; i < conditionCnt; i++) { - if (!arr[i]) { - result = false; - } - } - - delete[] arr; - - if (result) { - oneBlock = deleteBeforeDelimiter(oneBlock, "\n"); - oneBlock.replace("end", ""); - - //SerialPrint("I", "Event done", incommingEvent); - SerialPrint("I", F("Scenario"), F("All conditions are matched")); - spaceCmdExecute(oneBlock); - } - - //логическое или - } else if (condition.indexOf("||") != -1) { - condition = condition += " || "; - - //посчитаем количество условий - int conditionCnt = itemsCount2(condition, "||") - 1; - - //создадим и заполним динамический массив - bool *arr = new bool[conditionCnt]; - for (int i = 0; i < conditionCnt; i++) { - arr[i] = false; - } - - //есть ли входящее событие хотя бы в одном из условий и удавлетварено ли оно? - int evenInConditionNum = -1; - for (int i = 0; i < conditionCnt; i++) { - String buf = selectFromMarkerToMarker(condition, " || ", i); - if (isScenarioNeedToDo(buf, incommingEventKey, incommingEventValue, 1)) { - arr[i] = true; - evenInConditionNum = i; - } - } - - //если да то проверяем остальные условия по json - if (evenInConditionNum >= 0) { - for (int i = 0; i < conditionCnt; i++) { - String buf = selectFromMarkerToMarker(condition, " || ", i); - if (i != evenInConditionNum) { - if (isScenarioNeedToDoJson(buf)) { - arr[i] = true; - } - } - } - } - - //хотя бы один элемент массива должн быть true - bool result = false; - for (int i = 0; i < conditionCnt; i++) { - if (arr[i]) { - result = true; - } - } - - delete[] arr; - - if (result) { - oneBlock = deleteBeforeDelimiter(oneBlock, "\n"); - oneBlock.replace("end", ""); - - //SerialPrint("I", "Event done", incommingEvent); - SerialPrint("I", F("Scenario"), F("One of all condition are matched")); - spaceCmdExecute(oneBlock); - } - - //если гистерезис - } else if (condition.indexOf("+-") != -1) { - if (isScenarioNeedToDo(condition, incommingEventKey, incommingEventValue, 2)) { - oneBlock = deleteBeforeDelimiter(oneBlock, "\n"); - oneBlock.replace("end", ""); - - //SerialPrint("I", "Event done", incommingEvent); - SerialPrint("I", F("Scenario"), "Condition are matched: " + condition); - spaceCmdExecute(oneBlock); - } - - //остальные случаи - } else { - if (isScenarioNeedToDo(condition, incommingEventKey, incommingEventValue, 1)) { - oneBlock = deleteBeforeDelimiter(oneBlock, "\n"); - oneBlock.replace("end", ""); - - //SerialPrint("I", "Event done", incommingEvent); - SerialPrint("I", F("Scenario"), "Condition are matched: " + condition); - spaceCmdExecute(oneBlock); - } - } - allBlocks = deleteBeforeDelimiter(allBlocks, "end\n"); - } - eventBuf = deleteBeforeDelimiter(eventBuf, ","); - } - - private: - bool isScenarioNeedToDo(String &condition, String &incommingEventKey, String &incommingEventValue, int type) { - bool res = false; - String setEventKey = selectFromMarkerToMarker(condition, " ", 0); - if (isEventExist(incommingEventKey, setEventKey)) { - String setEventSign; - String setEventValue; - if (type == 1) preCalculation(condition, setEventSign, setEventValue); - if (type == 2) preCalculationGisteresis(condition, setEventSign, setEventValue); - if (isConditionMatch(setEventSign, incommingEventValue, setEventValue)) { - res = true; - } - } - return res; - } - - bool isScenarioNeedToDoJson(String &condition) { - bool res = false; - String setEventKey = selectFromMarkerToMarker(condition, " ", 0); - String setEventSign; - String setEventValue; - preCalculation(condition, setEventSign, setEventValue); - String jsonValue = getValue(setEventKey); - if (isConditionMatch(setEventSign, jsonValue, setEventValue)) { - res = true; - } - return res; - } - - //bool isScenarioNeedToDoJson2(String &condition, String &incommingEventKey, String &incommingEventValue) { - // bool res = false; - // String setEventKey = selectFromMarkerToMarker(condition, " ", 0); - // if (isEventExist(incommingEventKey, setEventKey)) { - // String setEventSign; - // String setEventValue; - // preCalculation(condition, setEventSign, setEventValue); - // if (isConditionMatch(setEventSign, incommingEventValue, setEventValue)) { - // res = true; - // } - // } - // return res; - //} - - void preCalculation(String &condition, String &setEventSign, String &setEventValue) { - setEventSign = selectFromMarkerToMarker(condition, " ", 1); - setEventValue = selectFromMarkerToMarker(condition, " ", 2); - if (!isDigitDotCommaStr(setEventValue)) { - setEventValue = getValue(setEventValue); - } - } - - void preCalculationGisteresis(String &condition, String &setEventSign, String &setEventValue) { - setEventSign = selectFromMarkerToMarker(condition, " ", 1); - setEventValue = selectFromMarkerToMarker(condition, " ", 2); - if (!isDigitDotCommaStr(setEventValue)) { - String setEventValueName = selectToMarker(setEventValue, "+-"); - String gisteresisValue = selectToMarkerLast(setEventValue, "+-"); - gisteresisValue.replace("+-", ""); - String value = getValue(setEventValueName); - String upValue = String(value.toFloat() + gisteresisValue.toFloat()); - String lowValue = String(value.toFloat() - gisteresisValue.toFloat()); - if (setEventSign == ">") { - setEventValue = upValue; - } else if (setEventSign == "<") { - setEventValue = lowValue; - } - } - } - - bool isEventExist(String &incommingEventKey, String &setEventKey) { - bool res = false; - if (incommingEventKey == setEventKey) { - res = true; - } - return res; - } - - bool isConditionMatch(String &setEventSign, String &incommingEventValue, String &setEventValue) { - boolean flag = false; - if (setEventSign == "=") { - flag = incommingEventValue == setEventValue; - } else if (setEventSign == "!=") { - flag = incommingEventValue != setEventValue; - } else if (setEventSign == "<") { - flag = incommingEventValue.toFloat() < setEventValue.toFloat(); - } else if (setEventSign == ">") { - flag = incommingEventValue.toFloat() > setEventValue.toFloat(); - } else if (setEventSign == ">=") { - flag = incommingEventValue.toFloat() >= setEventValue.toFloat(); - } else if (setEventSign == "<=") { - flag = incommingEventValue.toFloat() <= setEventValue.toFloat(); - } - return flag; - } -}; - -extern Scenario *myScenario; -extern void streamEventUDP(String event); \ No newline at end of file diff --git a/include/Class/TCircularBuffer.h b/include/Class/TCircularBuffer.h deleted file mode 100644 index 33cdb81a..00000000 --- a/include/Class/TCircularBuffer.h +++ /dev/null @@ -1,107 +0,0 @@ -#pragma once - -#include - -template - -class TCircularBuffer { - public: - TCircularBuffer() : _head{0}, _tail{0}, _full{false} {} - - ~TCircularBuffer() {} - - void reset() { - _head = _tail = _full = 0; - } - - bool empty() const { - return _head == _tail && !_full; - } - - bool full() const { - return _full; - } - - /** - * Get the number of elements currently stored in the circular_buffer. - */ - size_t size() const { - size_t res = 0; - if (!_full) { - if (_head < _tail) - res = BUFFER_SIZE + _head - _tail; - else - res = _head - _tail; - } else { - res = BUFFER_SIZE; - } - return res; - } - - /** Push the transaction to the buffer. This overwrites the buffer if it's full. - * Загрузить данные в буфер - * @param data item to be pushed to the buffer. - */ - void push(const T &item) { - if (_full) { - _tail++; - if (_tail == BUFFER_SIZE) - _tail = 0; - } - _pool[_head++] = item; - if (_head == BUFFER_SIZE) - _head = 0; - if (_head == _tail) - _full = true; - } - - /** Pop from the buffer. - * Забрать данные из буфера - * @param data item to store the data to be popped from the buffer. - * @return True if data popped. - */ - bool pop(T &item) { - bool res = false; - if (!empty()) { - item = _pool[_tail++]; - if (_tail == BUFFER_SIZE) _tail = 0; - _full = false; - res = true; - } - return res; - } - - bool pop_back(T &item) { - bool res = false; - if (!empty()) { - item = _pool[--_head]; - _full = false; - res = true; - } - return res; - } - - /** Peek into circular buffer without popping. - * - * @param data item to be peeked from the buffer. - * @return True if the buffer is not empty and data contains a transaction, false otherwise. - */ - bool peek(T &item) const { - bool res = false; - if (!empty()) { - item = _pool[_tail]; - - res = true; - } - return res; - } - - private: - T _pool[BUFFER_SIZE]; - size_t _head; - size_t _tail; - bool _full; -}; - -extern TCircularBuffer *myTCircularBuffer; -extern TCircularBuffer *myWsBuffer; diff --git a/include/Clock.h b/include/Clock.h deleted file mode 100644 index cd7038af..00000000 --- a/include/Clock.h +++ /dev/null @@ -1,178 +0,0 @@ -#pragma once - -#include "Clock.h" -#include "Global.h" -#include "Utils/TimeUtils.h" -#include "Utils\SerialPrint.h" - -extern void clockInit(); - -#ifdef ESP8266 -#include "sntp.h" -#endif - - - -class Clock { - private: - Time_t _time_local; - Time_t _time_utc; - unsigned long _uptime; - unsigned long _unixtime; - int _timezone; - String _ntp; - bool _hasSynced; - bool _configured; - - public: - Clock() : _uptime{0}, _timezone{0}, _ntp{""}, _hasSynced{false}, _configured{false} {}; - - void loop() { - unsigned long passed = millis_since(_uptime); - if (passed < ONE_SECOND_ms) { - return; - } - _uptime += passed; - - // world time - time_t now = getSystemTime(); - time_t estimated = _unixtime + (passed / ONE_SECOND_ms); - double drift = difftime(now, estimated); - if (drift > 1) { - // Обработать ситуации c дрифтом времени на значительные величины - } - - _unixtime = now; - - breakEpochToTime(_unixtime, _time_utc); - - breakEpochToTime(_unixtime + getOffsetInSeconds(_timezone), _time_local); - } - - bool hasSync() { - if (!_hasSynced) { - startSync(); - } - return _hasSynced; - } - - void setNtpPool(String ntp) { - if (!_ntp.equals(ntp)) { - _ntp = ntp; - _configured = false; - } - } - - void setTimezone(int timezone) { - if (_timezone != timezone) { - _timezone = timezone; - _configured = false; - } - } - - void startSync() { - if (!_configured) { - SerialPrint("I", "NTP", "sync to: " + _ntp + " timezone: " + String(_timezone)); - setupSntp(); - _configured = true; - return; - } - _hasSynced = hasTimeSynced(); - if (_hasSynced) { - SerialPrint("I", "NTP", "synced " + getDateDotFormated() + " " + getTime()); - } else { - SerialPrint("E", "NTP", F("failed to obtain time")); - } - } - - void setupSntp() { -#ifdef ESP8266 - sntp_setservername(0, _ntp.c_str()); - sntp_setservername(1, "ru.pool.ntp.org"); - sntp_setservername(2, "pool.ntp.org"); - sntp_stop(); - sntp_set_timezone(0); - sntp_init(); -#else - configTime(0, 0, _ntp.c_str(), "ru.pool.ntp.org", "pool.ntp.org"); -#endif - } - - bool hasTimeSynced() const { - return _unixtime > MIN_DATETIME; - } - - time_t getSystemTime() const { - timeval tv{0, 0}; - timezone tz = timezone{0, 0}; - time_t epoch = 0; - if (gettimeofday(&tv, &tz) != -1) { - epoch = tv.tv_sec; - } - return epoch; - } - - const String getTimeUnix() { - return String(_unixtime); - } - - /* - * Локальное время "дд.ММ.гг" - */ - const String getDateDotFormated() { - char buf[32]; - sprintf(buf, "%02d.%02d.%02d", _time_local.day_of_month, _time_local.month, _time_local.year); - return String(buf); - } - - /* - * Локальное дата время "дд.ММ.гг чч.мм.cc" - */ - const String getDateTimeDotFormated() { - char buf[32]; - sprintf(buf, "%02d.%02d.%02d %02d:%02d:%02d", _time_local.day_of_month, _time_local.month, _time_local.year, _time_local.hour, _time_local.minute, _time_local.second); - return String(buf); - } - - /* - * Локальное дата время "дд.ММ.гг чч.мм.cc" - */ - const String getDateTimeDotFormated(Time_t timeNow) { - char buf[32]; - sprintf(buf, "%02d.%02d.%02d %02d:%02d:%02d", timeNow.day_of_month, timeNow.month, timeNow.year, timeNow.hour, timeNow.minute, timeNow.second); - return String(buf); - } - - - /* - * Локальное время "чч:мм:cc" - */ - const String getTime() { - char buf[32]; - sprintf(buf, "%02d:%02d:%02d", _time_local.hour, _time_local.minute, _time_local.second); - return String(buf); - } - - const String getTimeJson() { - char buf[32]; - sprintf(buf, "%02d-%02d-%02d", _time_local.hour, _time_local.minute, _time_local.second); - return String(buf); - } - - /* - * Локальное время "чч:мм" - */ - const String getTimeWOsec() { - char buf[32]; - sprintf(buf, "%02d:%02d", _time_local.hour, _time_local.minute); - return String(buf); - } - - /* - * Время с момента запуска "чч:мм:cc" далее "дд чч:мм" - */ - const String getUptime() { - return prettyMillis(_uptime); - } -}; -extern Clock* timeNow; \ No newline at end of file diff --git a/include/Cmd.h b/include/Cmd.h deleted file mode 100644 index f19f54d1..00000000 --- a/include/Cmd.h +++ /dev/null @@ -1,64 +0,0 @@ -#pragma once - -#include - -extern void cmd_init(); - - -//extern void levelPr(); -//extern void ultrasonicCm(); -//extern void ultrasonic_reading(); - -extern void analog_reading1(); -extern void analog_reading2(); -extern void dallas_reading(); -extern void dhtT_reading(); - -//extern void dallas(); - -extern void bmp280T(); -extern void bmp280P(); -extern void bmp280T_reading(); -extern void bmp280P_reading(); - -extern void bme280T(); -extern void bme280P(); -extern void bme280H(); -extern void bme280A(); - -extern void bme280T_reading(); -extern void bme280P_reading(); -extern void bme280H_reading(); -extern void bme280A_reading(); - -//extern void dhtT(); -//extern void dhtH(); -//extern void dhtP(); -//extern void dhtC(); -//extern void dhtD(); -//extern void dhtH_reading(); -//extern void dhtP_reading(); -//extern void dhtC_reading(); -//extern void dhtD_reading(); - -extern void timeInit(); -extern void stepper(); -extern void stepperSet(); -extern void servo_(); -extern void servoSet(); -extern void serialBegin(); -extern void serialWrite(); -extern void logging(); - -extern void button(); -extern void timeSet(); - -extern void mqttOrderSend(); -extern void httpOrderSend(); -extern void firmwareVersion(); -extern void firmwareUpdate(); -extern void loadScenario(); - -extern void fileCmdExecute(const String& filename); -extern void csvCmdExecute(String& cmdStr); -extern void spaceCmdExecute(String& cmdStr); \ No newline at end of file diff --git a/include/Consts.h b/include/Consts.h deleted file mode 100644 index 7cd34240..00000000 --- a/include/Consts.h +++ /dev/null @@ -1,161 +0,0 @@ -#pragma once - -#define FIRMWARE_VERSION 400 - -#define svelte - -#ifdef esp8266_4mb -#define FIRMWARE_NAME "esp8266_4mb" -#define USE_LITTLEFS true -#define USE_OTA true -#define LED_PIN 2 -#define ESP_MODE -#endif - -#ifdef esp8266_1mb -#define FIRMWARE_NAME "esp8266_1mb" -#define USE_LITTLEFS true -#define USE_OTA false -#define LED_PIN 2 -#define ESP_MODE -#endif - -#ifdef esp32_4mb -#define FIRMWARE_NAME "esp32_4mb" -#define USE_LITTLEFS false -#define USE_OTA true -#define LED_PIN 22 -#define ESP_MODE -#endif - -#ifdef esp8266_mysensors_4mb -#define FIRMWARE_NAME "esp8266_mysensors_4mb" -#define USE_LITTLEFS true -#define USE_OTA true -#define LED_PIN 2 -#define GATE_MODE -#define MYSENSORS -#endif - -#ifdef esp32_mysensors_4mb -#define FIRMWARE_NAME "esp32_mysensors_4mb" -#define USE_LITTLEFS false -#define USE_OTA true -#define LED_PIN 22 -#define GATE_MODE -#define MYSENSORS -#endif - -#define JSON_BUFFER_SIZE 4096 -#define NUM_BUTTONS 6 -#define MQTT_RECONNECT_INTERVAL 20000 -#define CHANGE_BROKER_AFTER 5 -#define TELEMETRY_UPDATE_INTERVAL_MIN 60 -#define DEVICE_CONFIG_FILE "s.conf.csv" -#define DEVICE_SCENARIO_FILE "s.scen.txt" -//#define OTA_UPDATES_ENABLED -//#define MDNS_ENABLED -#define WEBSOCKET_ENABLED -//#define LAYOUT_IN_RAM -//#define UDP_ENABLED -//#define SSDP_ENABLED - -#ifdef ESP_MODE -#define EnableButtonIn -#define EnableButtonOut -#define EnableCountDown -#define EnableImpulsOut -#define EnableInput -#define EnableLogging -#define EnableOutput -#define EnablePwmOut -#define EnableSensorAnalog -#define EnableSensorBme280 -#define EnableSensorBmp280 -#define EnableSensorCcs811 -#define EnableSensorDallas -#define EnableSensorDht -#define EnableSensorPzem -#define EnableSensorUltrasonic -#define EnableSensorUptime -#define EnableTelegram -#define EnableUart -#endif - -#ifdef GATE_MODE -#define EnableSensorNode -#define EnableButtonOut -#define EnableCountDown -#define EnableInput -#define EnableLogging -#define EnableOutput -#define EnableSensorUptime -#define EnableTelegram -#define EnableUart -#endif - -//================================================================================================================================================================ - -enum TimerTask_t { WIFI_SCAN, - WIFI_MQTT_CONNECTION_CHECK, - TIME, - TIME_SYNC, - STATISTICS, - UPTIME, - UDP, - SYGNAL, - TIMES, - MYTEST }; - -enum NotAsyncActions { - do_ZERO, - do_UPGRADE, - do_GETLASTVERSION, - do_BUSSCAN, - do_MQTTPARAMSCHANGED, - do_deviceInit, - do_delChoosingItems, - do_addItem, - do_addPreset, - do_sendScenUDP, - do_sendScenMQTT, - do_webSocketSendSetup, - do_LAST, -}; - -enum LedStatus_t { - LED_OFF, - LED_ON, - LED_SLOW, - LED_FAST -}; - -enum ConfigType_t { - CT_CONFIG, - CT_SCENARIO -}; - -// history -// 07.11.2020 (SSDP OFF, UDP OFF) -// RAM: [===== ] 46.8% (used 38376 bytes from 81920 bytes) -// Flash: [===== ] 54.2% (used 566004 bytes from 1044464 bytes) - -// 13.11.2020 (SSDP OFF, UDP OFF) -// RAM: [===== ] 46.6% (used 38208 bytes from 81920 bytes) -// Flash: [===== ] 54.2% (used 566388 bytes from 1044464 bytes) - -// 15.11.2020 (SSDP OFF, UDP OFF) -// RAM: [===== ] 46.1% (used 37780 bytes from 81920 bytes) -// Flash: [===== ] 54.3% (used 566656 bytes from 1044464 bytes) - -// 17.11.2020 (SSDP OFF, UDP OFF) -// RAM: [===== ] 45.7% (used 37476 bytes from 81920 bytes) -// Flash: [===== ] 54.5% (used 569296 bytes from 1044464 bytes) - -// RAM: [===== ] 45.6% (used 37336 bytes from 81920 bytes) -// Flash: [====== ] 55.3% (used 577396 bytes from 1044464 bytes) - -// eventBuf - буфер событий которые проверяются в сценариях, -//и если событие удовлетворяет какому нибудь условию то выполняются указанные команды - -// orderBuf - буфер команд которые выполняются сейчас же diff --git a/include/ESP32.h b/include/ESP32.h deleted file mode 100644 index b144a096..00000000 --- a/include/ESP32.h +++ /dev/null @@ -1,26 +0,0 @@ -#pragma once - -#ifdef ESP32 -// don't change order -#include "WiFi.h" -// - -#include "ESPAsyncWebServer.h" -#include "SPIFFSEditor.h" -// don't change order -#include -#include -#include -#include - -// -#include - - -#ifdef MDNS_ENABLED -#include -#endif - -extern AsyncUDP udp; - -#endif \ No newline at end of file diff --git a/include/ESP8266.h b/include/ESP8266.h deleted file mode 100644 index 315a2045..00000000 --- a/include/ESP8266.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once - -#ifdef ESP8266 -//#include -#include -#include "ESPAsyncTCP.h" -#include "ESPAsyncWebServer.h" -#include -#include -#include -#include -#ifdef MDNS_ENABLED -#include -#endif - -extern WiFiUDP udp; - -#endif \ No newline at end of file diff --git a/include/FSEditor.h b/include/FSEditor.h deleted file mode 100644 index 4fcdef02..00000000 --- a/include/FSEditor.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include -#include "FileSystem.h" - -class FSEditor : public AsyncWebHandler { - private: - fs::FS _fs; - String _username; - String _password; - bool _authenticated; - uint32_t _startTime; - - private: - void getDirList(const String& path, String& output); - - public: -#ifdef ESP32 - FSEditor(const fs::FS& fs, const String& username = String(), const String& password = String()); -#else - FSEditor(const String& username = String(), const String& password = String(), const fs::FS& fs = FileFS); -#endif - virtual bool canHandle(AsyncWebServerRequest* request) override final; - virtual void handleRequest(AsyncWebServerRequest* request) override final; - virtual void handleUpload(AsyncWebServerRequest* request, const String& filename, size_t index, uint8_t* data, size_t len, bool final) override final; - virtual bool isRequestHandlerTrivial() override final { - return false; - } -}; \ No newline at end of file diff --git a/include/FileSystem.h b/include/FileSystem.h deleted file mode 100644 index ae31147e..00000000 --- a/include/FileSystem.h +++ /dev/null @@ -1,36 +0,0 @@ -#pragma once - -#include "Consts.h" - -#define FILE_READ "r" -#define FILE_WRITE "w" -#define FILE_APPEND "a" - -#include - -#ifdef ESP32 -#include -extern FS* filesystem; -#define FileFS SPIFFS -#define FS_NAME "SPIFFS" -#endif - -#ifdef ESP8266 -#if USE_LITTLEFS -#include "LittleFS.h" -extern FS LittleFS; -using littlefs_impl::LittleFSConfig; -extern FS* filesystem; -#define FileFS LittleFS -#define FS_NAME "LittleFS" -#else -extern FS* filesystem; -#define FileFS SPIFFS -#define FS_NAME "SPIFFS" -#endif -#endif - -extern void getFSInfo(); -#ifdef ESP8266 -extern bool getInfo(FSInfo& info); -#endif \ No newline at end of file diff --git a/include/Global.h b/include/Global.h deleted file mode 100644 index a9b3cfaf..00000000 --- a/include/Global.h +++ /dev/null @@ -1,160 +0,0 @@ -#pragma once -//===================Libraries=================================================================================================================================================== -#include -#include -#include -#include -#include -#include -#include -#include - -#include "CTBot.h" -#include "Clock.h" -#include "Consts.h" -#include "ESP32.h" -#include "ESP8266.h" -#include "GyverFilters.h" -#include "MqttClient.h" -#include "Upgrade.h" -#include "Utils/FileUtils.h" -#include "Utils/JsonUtils.h" -#include "Utils/SerialPrint.h" -#include "Utils/StringUtils.h" -#include "Utils/SysUtils.h" -#include "Utils/WiFiUtils.h" - -#ifdef WEBSOCKET_ENABLED -extern AsyncWebSocket ws; -extern AsyncEventSource events; -#endif - -extern TickerScheduler ts; -extern WiFiClient espClient; -extern PubSubClient mqtt; -extern StringCommand sCmd; -extern AsyncWebServer server; - -// Global vars -extern boolean just_load; -extern boolean telegramInitBeen; -extern boolean savedFromWeb; -extern boolean wsSetupFlag; - -// Json -extern String configSetupJson; //все настройки -extern String configLiveJson; //все данные с датчиков (связан с mqtt) -extern String configStoreJson; //все данные которые должны сохраняться -extern String configOptionJson; //для трансфера -extern String telegramMsgJson; -extern String getValue(String& key); - -// Mqtt -extern String mqttServer; -extern int mqttPort; -extern String mqttPrefix; -extern String mqttUser; -extern String mqttPass; - -extern String mqttRootDevice; -extern String chipId; -extern String prex; -extern String all_widgets; -extern String scenario; - -extern int mqttConnectAttempts; -extern bool changeBroker; -extern int currentBroker; - -// web sockets -extern int wsAttempts; -//extern char* wsBufChar; - -// orders and events -extern String orderBuf; -extern String wsBuf; -extern String eventBuf; -extern String mysensorBuf; -extern String itemsFile; -extern String itemsLine; - -// key lists and numbers -//========================================= -extern String impuls_KeyList; -extern int impuls_EnterCounter; -//========================================= -extern String buttonOut_KeyList; -extern int buttonOut_EnterCounter; -//========================================= -extern String input_KeyList; -extern int input_EnterCounter; -//========================================= -extern String output_KeyList; -extern int output_EnterCounter; -//========================================= -extern String pwmOut_KeyList; -extern int pwmOut_EnterCounter; -//========================================= -extern String countDown_KeyList; -extern int countDown_EnterCounter; -//========================================= -extern String logging_KeyList; -extern int logging_EnterCounter; -//========================================= - -extern String itemName; -extern String presetName; - -extern int scenario_line_status[40]; -extern int lastVersion; - -// Main -extern void setChipId(); -extern void saveConfig(); -extern void setConfigParam(const char* param, const String& value); - -extern String getURL(const String& urls); -extern void do_fscheck(); -extern void doBusScan(); -extern void servo_(); - -extern void setLedStatus(LedStatus_t); - -// Scenario -extern void eventGen2(String eventName, String eventValue); -extern String add_set(String param_name); - -// Timers -extern void Timer_countdown_init(); -extern void timerStart_(); -extern void addTimer(String number, String time); -extern void timerStop_(); -extern void delTimer(String number); -extern int readTimer(int number); - -extern void upgradeInit(); - -// widget -extern void createWidgetByType(String widget_name, String page_name, String page_number, String file, String topic); -extern void createWidgetParam(String widget_name, String page_name, String page_number, String file, String topic, String name1, String param1, String name2, String param2, String name3, String param3); -extern void createWidget(String widget_name, String page_name, String page_number, String type, String topik); -extern void createChart(String widget_name, String page_name, String page_number, String file, String topic, String maxCount); - -// PushingBox -extern void pushControl(); - -// UDP -// extern void udpInit(); -// extern void do_udp_data_parse(); -// extern void do_mqtt_send_settings_to_udp(); - -extern void do_update(); - -// Init -extern void uptime_init(); - -// Web -extern void web_init(); - -// Upgrade -extern String serverIP; diff --git a/include/Init.h b/include/Init.h deleted file mode 100644 index 40cc5e74..00000000 --- a/include/Init.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -extern void loadConfig(); -extern void espInit(); -extern void statistics_init(); -extern void loadScenario(); -extern void deviceInit(); -extern void prsets_init(); -extern void handle_uptime(); -extern void handle_statistics(); -extern void clearVectors(); \ No newline at end of file diff --git a/include/ItemsList.h b/include/ItemsList.h deleted file mode 100644 index a92da52f..00000000 --- a/include/ItemsList.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once - -#include -#include "Global.h" - -extern void itemsListInit(); -extern void addItem2(int num); -extern void addItemAuto(int num, String key, String widget, String descr); -extern bool isItemAdded(String key); -extern void addPreset(String name); -extern void addPreset2(int num); -extern void delChoosingItems(); -extern void addPreset2(int num); -extern void delChoosingItemsByNum(int num); -extern void delAllItems(); -extern uint8_t getNewElementNumber(String file); -extern uint8_t getFreePinAll(); -extern bool isPinExist(unsigned int num); -extern uint8_t getFreePinAnalog(); diff --git a/include/Macro.h b/include/Macro.h deleted file mode 100644 index bf1fe7ce..00000000 --- a/include/Macro.h +++ /dev/null @@ -1,9 +0,0 @@ -//#pragma once -//#define ST(A) #A -//#define STR(A) ST(A) -// -//#ifdef esp32_4mb -//#pragma message STR(esp32_4mb) -//#endif - -//Serial.println(STR(esp32_4mb)); \ No newline at end of file diff --git a/include/MqttClient.h b/include/MqttClient.h deleted file mode 100644 index ff4416fc..00000000 --- a/include/MqttClient.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include - -void mqttInit(); -void selectBroker(); -void getMqttData1(); -void getMqttData2(); -bool isSecondBrokerSet(); -boolean mqttConnect(); -void mqttReconnect(); -void mqttLoop(); -void mqttSubscribe(); - -boolean publish(const String& topic, const String& data); -boolean publishData(const String& topic, const String& data); -boolean publishChart(const String& topic, const String& data); -boolean publishControl(String id, String topic, String state); -boolean publishChart_test(const String& topic, const String& data); -boolean publishStatus(const String& topic, const String& data); -boolean publishEvent(const String& topic, const String& data); -boolean publishInfo(const String& topic, const String& data); -boolean publishAnyJsonKey(const String& topic, const String& key, const String& data); - -void publishWidgets(); -void publishState(); - -void mqttCallback(char* topic, uint8_t* payload, size_t length); -const String getStateStr(); diff --git a/include/MqttDiscovery.h b/include/MqttDiscovery.h deleted file mode 100644 index 282b26fc..00000000 --- a/include/MqttDiscovery.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once - -#include "Utils/SysUtils.h" - -namespace Discovery { - - -} \ No newline at end of file diff --git a/include/MySensorsDataParse.h b/include/MySensorsDataParse.h deleted file mode 100644 index 56dca7ad..00000000 --- a/include/MySensorsDataParse.h +++ /dev/null @@ -1,8 +0,0 @@ -#include "Consts.h" -#ifdef MYSENSORS -#pragma once -#include "Global.h" -extern void loopMySensorsExecute(); -extern void sensorType(int index, int &num, String &widget, String &descr); -extern void test(char* inputString); -#endif \ No newline at end of file diff --git a/include/MySensorsDataRead.h b/include/MySensorsDataRead.h deleted file mode 100644 index 97579da1..00000000 --- a/include/MySensorsDataRead.h +++ /dev/null @@ -1,14 +0,0 @@ -#include "Consts.h" -#include "Global.h" -#ifdef MYSENSORS -//#define MY_DEBUG -#define MY_RADIO_RF24 -#define MY_RF24_PA_LEVEL RF24_PA_HIGH //RF24_PA_MIN, RF24_PA_LOW, RF24_PA_HIGH, RF24_PA_MAX -//#define MY_ENCRYPTION_SIMPLE_PASSWD "XpenBam" -//#define MY_RF24_DATARATE RF24_2MBPS -#define MY_GATEWAY_SERIAL -#include "MySensors.h" -extern void receive(const MyMessage &message); -extern String parseToString(const MyMessage &message); -#endif - diff --git a/include/RemoteOrdersUdp.h b/include/RemoteOrdersUdp.h deleted file mode 100644 index 1500c55e..00000000 --- a/include/RemoteOrdersUdp.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once -#ifdef ESP8266 -#include "ESPAsyncUDP.h" -extern AsyncUDP asyncUdp; -extern void asyncUdpInit(); -extern String uint8tToString(uint8_t* data, size_t len); -extern bool udpPacketValidation(String& data); -extern void udpPacketParse(String& data); -#endif \ No newline at end of file diff --git a/include/SSDP.h b/include/SSDP.h deleted file mode 100644 index 353b193c..00000000 --- a/include/SSDP.h +++ /dev/null @@ -1,9 +0,0 @@ -#pragma once - -#include - -#include "Consts.h" - -#ifdef SSDP_ENABLED -void SsdpInit(); -#endif \ No newline at end of file diff --git a/include/Sensors.h b/include/Sensors.h deleted file mode 100644 index 45dcbb04..00000000 --- a/include/Sensors.h +++ /dev/null @@ -1,3 +0,0 @@ -#pragma once - - diff --git a/include/Servo/Servos.h b/include/Servo/Servos.h deleted file mode 100644 index db53c01e..00000000 --- a/include/Servo/Servos.h +++ /dev/null @@ -1,29 +0,0 @@ -#pragma once - -#include -#ifdef ESP8266 -#include -#else -#include -#endif - -struct Servo_t { - uint8_t num; - uint8_t pin; - Servo* obj; - Servo_t(uint8_t num, uint8_t pin) : num{num}, pin{pin}, obj{nullptr} {}; -}; - -class Servos { - public: - Servos(); - Servo* get(uint8_t num); - Servo* create(uint8_t num, uint8_t pin); - - size_t count(); - - private: - std::vector _items; -}; - -extern Servos myServo; \ No newline at end of file diff --git a/include/SetupESP.h b/include/SetupESP.h deleted file mode 100644 index 22fff364..00000000 --- a/include/SetupESP.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -#include "LittleFS.h" -#include "Utils/FileUtils.h" -#include "Utils/StringUtils.h" - -extern void setupESP(); \ No newline at end of file diff --git a/include/SoftUART.h b/include/SoftUART.h deleted file mode 100644 index fb9d64fc..00000000 --- a/include/SoftUART.h +++ /dev/null @@ -1,18 +0,0 @@ -#pragma once -#include "Consts.h" -#ifdef EnableUart -#include "SoftwareSerial.h" - -#ifdef ESP8266 -#include -extern SoftwareSerial* myUART; -#else -#include -extern HardwareSerial* myUART; -#endif - - -extern void uartInit(); -extern void uartHandle(); -extern void parse(String& incStr); -#endif \ No newline at end of file diff --git a/include/Strings_.h b/include/Strings_.h deleted file mode 100644 index 21865168..00000000 --- a/include/Strings_.h +++ /dev/null @@ -1,139 +0,0 @@ -#pragma once - -//Strings -// #include -#include - -#include -#include - -class char_array { - private: - char *p_stringarray; //initial input array - char *p_inputstring; //holds actual length data - //char **pp_database_string; //allocate data database.cpp - int stringsize; //holds array size to allocate memory - int charinput; //holds array input size - - public: - inline char_array(); //inline so other functions can call on it - inline ~char_array(); - inline void getinput(char *&); //retrieves user input - inline void grabline(char *&); //retrieve line with whitespace included NOT COMPLETE, may not need - inline int sortline(char **&, char *&); //sorts line into an array of strings and returns number of separate strings - inline int arraysize(); //returns size of string array - inline void printinput(); //print input string - inline void changedefaultsize(); //change default input size NOT COMPLETE -}; - -inline char_array::char_array() //constructor -{ - stringsize = 0; - charinput = 64; - p_stringarray = new char[charinput]; -} - -inline char_array::~char_array() //destructor -{ - delete[] p_inputstring; - delete[] p_stringarray; -} - -inline void char_array::getinput(char *&p_stringin) { - stringsize = 0; - - scanf("%63s", p_stringarray); //get input string - - while (p_stringarray[stringsize] != 0) //finding out the size of string array - { - stringsize++; - } - stringsize++; - - p_inputstring = new char[stringsize]; //reallocate memory block and set array inside - for (int i = 0; i < stringsize; i++) { - p_inputstring[i] = p_stringarray[i]; - } - - p_inputstring[stringsize - 1] = '\x00'; - - p_stringin = new char[stringsize]; //set pp_stringin - - p_stringin = p_inputstring; -} - -inline void char_array::grabline(char *&p_stringin) { - stringsize = 0; - std::cin.getline(p_stringarray, charinput); - while (p_stringarray[stringsize] != 0) { - stringsize++; - } - stringsize++; - p_inputstring = new char[stringsize]; - - for (int i = 0; i < stringsize; i++) { - p_inputstring[i] = p_stringarray[i]; - } - - p_stringin = new char[stringsize]; - p_stringin = p_inputstring; -} - -inline int char_array::sortline(char **&pp_stringin, char *&p_string) { - int position = 0; //position in string - int charcount = 1; //how many characters there are - int wordnum; //which word is being processed - int wordcount = 1; //number of words in string - int bookmark = 0; //holds last known position - - while (p_string[position] == ' ') { - position++; - } - - wordnum = position; //borrow wordnum to hold position value - while (p_string[position] != '\x00') //find total inputted string word length - { - if ((p_string[position] == ' ') && ((p_string[position + 1] != ' ') || (p_string[position + 1] != '\x00'))) { - wordcount++; - } - position++; - } - position = wordnum; //set position to original value - for (wordnum = 0; wordnum < wordcount; wordnum++) { - charcount = 1; - while (p_string[position] == ' ') { - position++; - } - while ((p_string[position] != ' ') && (p_string[position] != '\x00')) { - position++; - charcount++; - } - pp_stringin[wordnum] = new char[charcount]; - - for (int i = 0; i < charcount; i++) { - pp_stringin[wordnum][i] = p_string[i + bookmark]; - } - pp_stringin[wordnum][charcount - 1] = '\x00'; - bookmark = position + 1; - } - - return wordcount; -} - -inline int char_array::arraysize() { - if (stringsize != 0) { - return stringsize; - } else { - printf("Array size is set at 0\n"); - return 0; - } -} - -inline void char_array::printinput() { - printf("%s", p_inputstring); -} - -inline void char_array::changedefaultsize() { - printf("Input new default input string size: "); - scanf("%i", charinput); -} diff --git a/include/Telegram.h b/include/Telegram.h deleted file mode 100644 index 62700cfe..00000000 --- a/include/Telegram.h +++ /dev/null @@ -1,13 +0,0 @@ -#pragma once -#include "Consts.h" -#ifdef EnableTelegram -#include "Global.h" - -extern void sendTelegramMsg(); -extern void telegramInit(); -extern void handleTelegram(); -extern bool isEnableTelegramd(); -extern bool isTelegramInputOn(); -extern void telegramMsgParse(String msg); -extern String returnListOfParams(); -#endif \ No newline at end of file diff --git a/include/Tests.h b/include/Tests.h deleted file mode 100644 index 94006e7f..00000000 --- a/include/Tests.h +++ /dev/null @@ -1,4 +0,0 @@ -#pragma once - -extern void testsPerform(); -extern void testLoop(); \ No newline at end of file diff --git a/include/Upgrade.h b/include/Upgrade.h deleted file mode 100644 index b02adb12..00000000 --- a/include/Upgrade.h +++ /dev/null @@ -1,10 +0,0 @@ -#pragma once - -#include - -extern void upgradeInit(); -extern void getLastVersion(); -extern void upgrade_firmware(int type); -extern bool upgradeFS(); -extern bool upgradeBuild(); -extern void restartEsp(); \ No newline at end of file diff --git a/include/Utils/FileHelper.h b/include/Utils/FileHelper.h deleted file mode 100644 index b5ba764c..00000000 --- a/include/Utils/FileHelper.h +++ /dev/null @@ -1,46 +0,0 @@ -#pragma once -#include - -#include "FileSystem.h" - -class FileHelper { - public: - FileHelper(const String filename); - /* - * Проверить существование - */ - void exists(); - /* - * Удалить файл - */ - void remove(); - /* - * Открыть файл установить позицию @position - */ - File seek(size_t position = 0); - - /* - * Чтение строки с содержащей @substr - */ - String readFileString(const String substr); - - /* - * Добовление строки @str в файл - */ - String appendStr(const String str); - - /* - * Запись строки - */ - String writeStr(const String); - - /* - * Чтение в строку - */ - String readStr(size_t); - - /* - * Размер в байтах - */ - size_t getSize(); -}; \ No newline at end of file diff --git a/include/Utils/FileUtils.h b/include/Utils/FileUtils.h deleted file mode 100644 index 1a45bb73..00000000 --- a/include/Utils/FileUtils.h +++ /dev/null @@ -1,64 +0,0 @@ -#pragma once -#include - -#include "Consts.h" -#include "FileSystem.h" - -/* - * Инициализация ФС - */ -bool fileSystemInit(); - -/* - * Удалить файл - */ -void removeFile(const String& filename); - -/* - * Открыть файл на позиции - */ -File seekFile(const String& filename, size_t position = 0); - -/* - * Чтение строки из файла - * возвращает стоку из файла в которой есть искомое слово found - */ -const String readFileString(const String& filename, const String& to_find); - -/* - * Добовление строки в файл - */ -const String addFileLn(const String& filename, const String& str); - -/* - * Добовление строки в файл - */ -const String addFile(const String& filename, const String& str); - -/* - * Запись строки в файл - */ -const String writeFile(const String& filename, const String& str); - -/* - * Чтение файла в строку - */ -const String readFile(const String& filename, size_t max_size); - -/* - * Посчитать - */ -size_t countLines(const String filename); - -/* - * Размер файла - */ -size_t getFileSize(const String filename); - -bool copyFile(const String& src, const String& dst, bool overwrite = true); - -const String getFSSizeInfo(); - -const String getConfigFile(uint8_t preset, ConfigType_t type); - -bool cutFile(const String& src, const String& dst); diff --git a/include/Utils/JsonUtils.h b/include/Utils/JsonUtils.h deleted file mode 100644 index cbcf38d1..00000000 --- a/include/Utils/JsonUtils.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once - -#include - -String jsonReadStr(String& json, String name); -int jsonReadInt(String& json, String name); -boolean jsonReadBool(String& json, String name); - -String jsonWriteStr(String& json, String name, String value); -String jsonWriteInt(String& json, String name, int value); -String jsonWriteFloat(String& json, String name, float value); -String jsonWriteBool(String& json, String name, boolean value); - -bool jsonRead(String& json, String key, String& value); -bool jsonRead(String& json, String key, bool& value); -bool jsonRead(String& json, String key, int& value); - -bool jsonWriteStr_(String& json, String name, String value); -bool jsonWriteBool_(String& json, String name, bool value); -bool jsonWriteInt_(String& json, String name, int value); -bool jsonWriteFloat_(String& json, String name, float value); - -void saveConfig(); -void saveStore(); \ No newline at end of file diff --git a/include/Utils/SerialPrint.h b/include/Utils/SerialPrint.h deleted file mode 100644 index f0d2d79c..00000000 --- a/include/Utils/SerialPrint.h +++ /dev/null @@ -1,3 +0,0 @@ -#pragma once -#include -void SerialPrint(String errorLevel, String module, String msg); \ No newline at end of file diff --git a/include/Utils/StringUtils.h b/include/Utils/StringUtils.h deleted file mode 100644 index 618fbac9..00000000 --- a/include/Utils/StringUtils.h +++ /dev/null @@ -1,36 +0,0 @@ -#pragma once - -#include - -uint8_t hexStringToUint8(String hex); - -uint16_t hexStringToUint16(String hex); - -String selectToMarkerLast(String str, String found); - -String selectToMarker(String str, String found); - -String extractInner(String str); - -String deleteAfterDelimiter(String str, String found); - -String deleteBeforeDelimiter(String str, String found); - -String deleteBeforeDelimiterTo(String str, String found); - -String deleteToMarkerLast(String str, String found); - -String selectFromMarkerToMarker(String str, String found, int number); - -size_t itemsCount2(String str, const String& separator); - -char* stringToChar(String& str); - -size_t itemsCount(String& str, const char* delim); - -boolean isDigitStr(const String& str); - -boolean isDigitDotCommaStr(const String& str); - -String prettyBytes(size_t size); - diff --git a/include/Utils/SysUtils.h b/include/Utils/SysUtils.h deleted file mode 100644 index de03e287..00000000 --- a/include/Utils/SysUtils.h +++ /dev/null @@ -1,19 +0,0 @@ -#pragma once -#include -#include "Global.h" - -uint32_t ESP_getChipId(); - -const String getChipId(); - -void setLedStatus(LedStatus_t status); - -const String getUniqueId(const String& name); - -const String printMemoryStatus(); - -const String getHeapStats(); - -const String getMacAddress(); - -void setChipId(); diff --git a/include/Utils/TimeUtils.h b/include/Utils/TimeUtils.h deleted file mode 100644 index 8b4c0739..00000000 --- a/include/Utils/TimeUtils.h +++ /dev/null @@ -1,69 +0,0 @@ -#pragma once - -#include - -#include "Consts.h" - -#define ONE_MINUTE_s 60 -#define ONE_HOUR_m 60 -#define ONE_HOUR_s 60 * ONE_MINUTE_s -#define LEAP_YEAR(Y) (((1970 + Y) > 0) && !((1970 + Y) % 4) && (((1970 + Y) % 100) || !((1970 + Y) % 400))) -#define MIN_DATETIME 1575158400 -#define ONE_SECOND_ms 1000 - -/* -* Время (мс) прошедщее с @since -*/ -unsigned long millis_since(unsigned long sinse); - -/* -* Интерввал времени (мс) между @start и @finish -*/ -unsigned long millis_passed(unsigned long start, unsigned long finish); - -/* -* Форматиронное время интервала (мс) -* "чч:мм:cc", -* "дд чч:мм", если > 24 часов -*/ -const String prettyMillis(unsigned long time_ms = millis()); - -/* -* Форматиронное время интервала (c) -* "чч:мм:cc", -* "дд чч:мм", если > 24 часов -*/ -const String prettySeconds(unsigned long time_s); - -/* -* Тайм зона в секундах -*/ -int getOffsetInSeconds(int timezone); - -/* -* Тайм зона в минутах -*/ -int getOffsetInMinutes(int timezone); - -/* -* Разбивает время на составляющие -*/ - -struct Time_t { - uint8_t second; - uint8_t minute; - uint8_t hour; - uint8_t day_of_week; - uint8_t day_of_month; - uint8_t month; - uint16_t day_of_year; - uint16_t year; - unsigned long days; - unsigned long valid; -}; - -void breakEpochToTime(unsigned long epoch, Time_t& tm); - - - -void timeInit(); \ No newline at end of file diff --git a/include/Utils/Timings.h b/include/Utils/Timings.h deleted file mode 100644 index c992eeee..00000000 --- a/include/Utils/Timings.h +++ /dev/null @@ -1,71 +0,0 @@ -#include - -enum Timings_t { MT_ONE, - MT_TWO, - NUM_TIMINGS }; - -struct Timing { - unsigned long _total_mu; - unsigned long _min_mu; - unsigned long _max_mu; - - Timing() : _total_mu{0}, _min_mu{999999}, _max_mu{0} {}; - - void reset() { - _total_mu = 0; - _min_mu = 999999; - _max_mu = 0; - } - - void add(unsigned long time_mu) { - if (time_mu == 0) return; - - _total_mu += time_mu; - - if (_min_mu > time_mu) { - _min_mu = time_mu; - } - - if (_max_mu < time_mu) { - _max_mu = time_mu; - } - } -}; - -static const char* module_name[NUM_TIMINGS] = {"strings", "boolean"}; - -struct Timings { - Timing mu[NUM_TIMINGS]; - - unsigned long _counter; - unsigned long _start; - unsigned long long _total; - - Timings() : _counter{0}, _start{0} {}; - - void add(size_t module, unsigned long now = micros()) { - unsigned long time = now - _start; - _total += time; - mu[module].add(time); - _start = now; - } - - void count() { - _counter++; - _start = micros(); - } - - void print() { - if (!_counter) { - return; - }; - Serial.printf("lp/ms: %llu ", _counter / _total); - for (size_t i = 0; i < NUM_TIMINGS; i++) { - Serial.printf("%s: %.2f%% ", module_name[i], ((float)mu[i]._total_mu / _total) * 100); - mu[i].reset(); - } - Serial.println(); - _counter = 0; - _total = 0; - }; -}; \ No newline at end of file diff --git a/include/Utils/WebUtils.h b/include/Utils/WebUtils.h deleted file mode 100644 index 2d88ed83..00000000 --- a/include/Utils/WebUtils.h +++ /dev/null @@ -1,8 +0,0 @@ -#pragma once -#include - -#include "WebServer.h" - -extern String getURL(const String& urls); -extern const String getMethodName(AsyncWebServerRequest* request); -extern const String getRequestInfo(AsyncWebServerRequest* request); diff --git a/include/Utils/WiFiUtils.h b/include/Utils/WiFiUtils.h deleted file mode 100644 index 7a634009..00000000 --- a/include/Utils/WiFiUtils.h +++ /dev/null @@ -1,16 +0,0 @@ -#pragma once - -#include "Global.h" - -boolean isNetworkActive(); - -void routerConnect(); - -bool startAPMode(); - -boolean RouterFind(String ssid); - -uint8_t RSSIquality(); - -extern void wifiSignalInit(); - diff --git a/include/Utils/statUtils.h b/include/Utils/statUtils.h deleted file mode 100644 index c01e0bb8..00000000 --- a/include/Utils/statUtils.h +++ /dev/null @@ -1,22 +0,0 @@ -#pragma once -#include -#include "Global.h" - -extern void initSt(); -extern String updateDevicePsn(String lat, String lon, String accur, String geo); -extern String updateDeviceStatus(); -extern String addNewDevice(); - -extern void decide(); -extern void getPsn(); - -extern String getUptimeTotal(); -extern uint8_t getNextNumber(String file); -extern uint8_t getCurrentNumber(String file); - -//extern int plusOneHour(); -//extern void eeWriteInt(int pos, int val); -//extern int eeGetInt(int pos); -//extern void updateDeviceList(); -//extern void saveId(String file, int id); -//extern int getId(String file); \ No newline at end of file diff --git a/include/Web.h b/include/Web.h deleted file mode 100644 index a80a08d2..00000000 --- a/include/Web.h +++ /dev/null @@ -1,6 +0,0 @@ -#pragma once -#include "Arduino.h" - - -void web_init(); -void setConfigParam(const char* param, const String& value); diff --git a/include/WebServer.h b/include/WebServer.h deleted file mode 100644 index 64c0bcef..00000000 --- a/include/WebServer.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include "Global.h" - -extern void initOta(); -extern void initMDNS(); - -extern void HttpServerinitWS(); -extern void HttpServerinit(); - -//===========web sockets============================== -extern void sendEspSetupToWS(); \ No newline at end of file diff --git a/include/WebSocket.h b/include/WebSocket.h deleted file mode 100644 index 2016caaf..00000000 --- a/include/WebSocket.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once -#include "Class/TCircularBuffer.h" -#include "Global.h" -void wsInit(); -void wsPublishData(String topic, String data); - -// void wsSendSetup(); -// void wsSendSetupBuffer(); -// -// void sendDataWs(); -// void loopWsExecute(); diff --git a/include/items/ButtonInClass.h b/include/items/ButtonInClass.h deleted file mode 100644 index 8adab9cc..00000000 --- a/include/items/ButtonInClass.h +++ /dev/null @@ -1,65 +0,0 @@ - -#ifdef EnableButtonIn -#pragma once -#include -#include -#include "Class/LineParsing.h" -#include "Global.h" - -extern boolean but[NUM_BUTTONS]; -extern Bounce* buttons; - -class ButtonInClass : public LineParsing { - protected: - int numberEntering = 0; - int state = _state.toInt(); - - public: - ButtonInClass() : LineParsing(){}; - - void init() { - if (_pin != "") { - int number = numberEntering++; - buttons[number].attach(_pin.toInt()); - buttons[number].interval(_db.toInt()); - but[number] = true; - jsonWriteStr(configOptionJson, "switch_num_" + String(number), _key); - } - } - - void loop() { - static uint8_t switch_number = 1; - if (but[switch_number]) { - buttons[switch_number].update(); - if (buttons[switch_number].fell()) { - String key = jsonReadStr(configOptionJson, "switch_num_" + String(switch_number)); - state = 1; - switchChangeVirtual(key, String(state)); - } - if (buttons[switch_number].rose()) { - String key = jsonReadStr(configOptionJson, "switch_num_" + String(switch_number)); - state = 0; - switchChangeVirtual(key, String(state)); - } - } - switch_number++; - if (switch_number == NUM_BUTTONS) { - switch_number = 0; - } - } - - void switchStateSetDefault() { - if (_state != "") { - switchChangeVirtual(_key, _state); - } - } - - void switchChangeVirtual(String key, String state) { - eventGen2(key, state); - jsonWriteInt(configLiveJson, key, state.toInt()); - publishStatus(key, state); - } -}; - -extern ButtonInClass myButtonIn; -#endif \ No newline at end of file diff --git a/include/items/test.h b/include/items/test.h deleted file mode 100644 index 7ede8430..00000000 --- a/include/items/test.h +++ /dev/null @@ -1,34 +0,0 @@ -//#include "Arduino.h" -//#include "Global.h" -// -//class SensorImpulsIn; -// -//typedef std::vector MySensorImpulsInVector; -// -//struct paramsImpulsIn { -// String key; -// unsigned int pin; -// float c; -// float k; -//}; -// -//class SensorImpulsIn { -// public: -// SensorImpulsIn(const paramsImpulsIn& paramsImpuls); -// //~SensorImpulsIn(); -// -// //void begin(int interruptPin); -// void classInterruptHandler(void); -// -// void setCallback(void (*userDefinedCallback)(const int)) { -// localPointerToCallback = userDefinedCallback; -// } -// -// private: -// void (*localPointerToCallback)(const int); -// paramsImpulsIn _paramsImpuls; -//}; -// -//extern MySensorImpulsInVector* mySensorImpulsIn; -// -//extern void impulsInSensor(); \ No newline at end of file diff --git a/include/items/vButtonOut.h b/include/items/vButtonOut.h deleted file mode 100644 index ecfacfcc..00000000 --- a/include/items/vButtonOut.h +++ /dev/null @@ -1,30 +0,0 @@ -#ifdef EnableButtonOut -#pragma once -#include - -#include "Global.h" - -class ButtonOut; - -typedef std::vector MyButtonOutVector; - -class ButtonOut { - public: - ButtonOut(String pin, boolean inv, String key, String type); - - ~ButtonOut(); - - void execute(String state); - - private: - String _pin; - boolean _inv; - String _key; - String _type; -}; - -extern MyButtonOutVector* myButtonOut; - -extern void buttonOut(); -extern void buttonOutExecute(); -#endif \ No newline at end of file diff --git a/include/items/vCountDown.h b/include/items/vCountDown.h deleted file mode 100644 index 35fd6c8a..00000000 --- a/include/items/vCountDown.h +++ /dev/null @@ -1,34 +0,0 @@ -#ifdef EnableCountDown -#pragma once - -#include - -#include "Global.h" - -class CountDownClass; - -typedef std::vector MyCountDownVector; - -class CountDownClass { - public: - CountDownClass(String key); - ~CountDownClass(); - - void loop(); - void execute(unsigned int countDownPeriod); - - private: - unsigned long _countDownPeriod = 0; - bool _start = false; - String _key; - - unsigned long prevMillis; - unsigned long difference; - int sec; -}; - -extern MyCountDownVector* myCountDown; - -extern void countDown(); -extern void countDownExecute(); -#endif \ No newline at end of file diff --git a/include/items/vImpulsOut.h b/include/items/vImpulsOut.h deleted file mode 100644 index 885371ce..00000000 --- a/include/items/vImpulsOut.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifdef EnableImpulsOut -#pragma once -#include -#include "Global.h" - -class ImpulsOutClass; - -typedef std::vector MyImpulsOutVector; - -class ImpulsOutClass { - public: - ImpulsOutClass(unsigned int impulsPin); - ~ImpulsOutClass(); - - void loop(); - void execute(unsigned long impulsPeriod, unsigned int impulsCount); - - private: - unsigned long currentMillis; - unsigned long prevMillis; - unsigned long difference; - unsigned long _impulsPeriod = 0; - unsigned int _impulsCount = 0; - unsigned int _impulsCountBuf = 0; - unsigned int _impulsPin = 0; - -}; - -extern MyImpulsOutVector* myImpulsOut; - -extern void impuls(); -extern void impulsExecute(); -#endif diff --git a/include/items/vInput.h b/include/items/vInput.h deleted file mode 100644 index 69e0bbe1..00000000 --- a/include/items/vInput.h +++ /dev/null @@ -1,27 +0,0 @@ -#ifdef EnableInput -#pragma once -#include - -#include "Consts.h" -#include "Global.h" - -class Input; - -typedef std::vector MyInputVector; - -class Input { - public: - Input(String key, String widget); - ~Input(); - - void execute(String value); - - private: - String _key; -}; - -extern MyInputVector* myInput; - -extern void inputValue(); -extern void inputExecute(); -#endif diff --git a/include/items/vLogging.h b/include/items/vLogging.h deleted file mode 100644 index c1e5ad26..00000000 --- a/include/items/vLogging.h +++ /dev/null @@ -1,44 +0,0 @@ -#ifdef EnableLogging -#pragma once -#include "Consts.h" -#include - -#include "Global.h" - -class LoggingClass; - -typedef std::vector MyLoggingVector; - -class LoggingClass { - public: - - LoggingClass(String interval, unsigned int maxPoints, String loggingValueKey, String key, String startState, bool savedFromWeb); - ~LoggingClass(); - - void loop(); - void execute(String keyOrValue); - - private: - - unsigned long currentMillis; - unsigned long prevMillis; - unsigned long difference; - String _interval; - unsigned int _intervalSec; - unsigned int _type = 0; - unsigned int _maxPoints; - String _loggingValueKey; - String _key; - - -}; - -extern MyLoggingVector* myLogging; - -extern void logging(); -extern void loggingExecute(); -extern void choose_log_date_and_send(); -extern void sendLogData(String file, String topic); -extern void sendLogData2(String file, String topic); -extern void cleanLogAndData(); -#endif diff --git a/include/items/vOutput.h b/include/items/vOutput.h deleted file mode 100644 index 76ae2d62..00000000 --- a/include/items/vOutput.h +++ /dev/null @@ -1,30 +0,0 @@ -#ifdef EnableOutput -#pragma once -#include - -#include "Global.h" - -class Output; - -typedef std::vector MyOutputVector; - -class Output { - public: - - Output(String key); - ~Output(); - - void execute(String value); - - private: - - String _key; - -}; - -extern MyOutputVector* myOutput; - -extern void outputValue(); -extern void outputExecute(); -#endif - diff --git a/include/items/vPwmOut.h b/include/items/vPwmOut.h deleted file mode 100644 index de091aa3..00000000 --- a/include/items/vPwmOut.h +++ /dev/null @@ -1,28 +0,0 @@ -#ifdef EnablePwmOut -#pragma once -#include -#include "Consts.h" -#include "Global.h" - -class PwmOut; - -typedef std::vector MyPwmOutVector; - -class PwmOut { - public: - PwmOut(unsigned int pin, String key); - - ~PwmOut(); - - void execute(String state); - - private: - unsigned int _pin; - String _key; -}; - -extern MyPwmOutVector* myPwmOut; - -extern void pwmOut(); -extern void pwmOutExecute(); -#endif diff --git a/include/items/vSensorAnalog.h b/include/items/vSensorAnalog.h deleted file mode 100644 index 5a73f61c..00000000 --- a/include/items/vSensorAnalog.h +++ /dev/null @@ -1,41 +0,0 @@ -#ifdef EnableSensorAnalog -#pragma once -#include - -#include "Global.h" -#include "GyverFilters.h" - -class SensorAnalog; - -typedef std::vector MySensorAnalogVector; - -class SensorAnalog { - public: - SensorAnalog(String key, unsigned long interval, unsigned int adcPin, int map1, int map2, int map3, int map4, float c); - ~SensorAnalog(); - - void loop(); - void readAnalog(); - - private: - unsigned long currentMillis; - unsigned long prevMillis; - unsigned long difference; - - unsigned long _interval; - - String _key; - unsigned int _adcPin; - - int _map1; - int _map2; - int _map3; - int _map4; - - float _c; -}; - -extern MySensorAnalogVector* mySensorAnalog; - -extern void analogAdc(); -#endif \ No newline at end of file diff --git a/include/items/vSensorBme280.h b/include/items/vSensorBme280.h deleted file mode 100644 index 20d2d966..00000000 --- a/include/items/vSensorBme280.h +++ /dev/null @@ -1,41 +0,0 @@ -#ifdef EnableSensorBme280 -#pragma once -#include -#include - -#include "Global.h" - -extern Adafruit_BME280* bme; - -class SensorBme280; - -typedef std::vector MySensorBme280Vector; - -struct paramsBme { - String key; - String addr; - unsigned long interval; - float c; -}; - -class SensorBme280 { - public: - SensorBme280(const paramsBme& paramsTmp, const paramsBme& paramsHum, const paramsBme& paramsPrs); - ~SensorBme280(); - - void loop(); - void read(); - - private: - paramsBme _paramsTmp; - paramsBme _paramsHum; - paramsBme _paramsPrs; - - unsigned long prevMillis; - unsigned long difference; -}; - -extern MySensorBme280Vector* mySensorBme280; - -extern void bme280Sensor(); -#endif \ No newline at end of file diff --git a/include/items/vSensorBmp280.h b/include/items/vSensorBmp280.h deleted file mode 100644 index 3bf3370d..00000000 --- a/include/items/vSensorBmp280.h +++ /dev/null @@ -1,40 +0,0 @@ -#ifdef EnableSensorBmp280 -#pragma once -#include -#include - -#include "Global.h" - -extern Adafruit_BMP280* bmp; - -class SensorBmp280; - -typedef std::vector MySensorBmp280Vector; - -struct paramsBmp { - String key; - String addr; - unsigned long interval; - float c; -}; - -class SensorBmp280 { - public: - SensorBmp280(const paramsBmp& paramsTmp, const paramsBmp& paramsPrs); - ~SensorBmp280(); - - void loop(); - void read(); - - private: - paramsBmp _paramsTmp; - paramsBmp _paramsPrs; - - unsigned long prevMillis; - unsigned long difference; -}; - -extern MySensorBmp280Vector* mySensorBmp280; - -extern void bmp280Sensor(); -#endif \ No newline at end of file diff --git a/include/items/vSensorCcs811.h b/include/items/vSensorCcs811.h deleted file mode 100644 index eb7ca7ca..00000000 --- a/include/items/vSensorCcs811.h +++ /dev/null @@ -1,41 +0,0 @@ -#ifdef EnableSensorCcs811 -#pragma once -#include - -#include "Adafruit_CCS811.h" -#include "Global.h" -#include "GyverFilters.h" - -class SensorCcs811; - -typedef std::vector MySensorCcs811Vector; - -struct paramsCcs811 { - String key; - String addr; - unsigned long interval; - float c; -}; - -class SensorCcs811 { - public: - SensorCcs811(const paramsCcs811& paramsPpm, const paramsCcs811& paramsPpb); - ~SensorCcs811(); - - Adafruit_CCS811* ccs811; - - void loop(); - void read(); - - private: - paramsCcs811 _paramsPpm; - paramsCcs811 _paramsPpb; - - unsigned long prevMillis; - unsigned long difference; -}; - -extern MySensorCcs811Vector* mySensorCcs811; - -extern void ccs811Sensor(); -#endif \ No newline at end of file diff --git a/include/items/vSensorDallas.h b/include/items/vSensorDallas.h deleted file mode 100644 index a2a7278d..00000000 --- a/include/items/vSensorDallas.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifdef EnableSensorDallas -#pragma once -#include -#include -#include -#include "Global.h" - - -extern DallasTemperature sensors; -extern OneWire* oneWire; - -class SensorDallas; - -typedef std::vector MySensorDallasVector; - -class SensorDallas { - public: - SensorDallas(unsigned long interval, unsigned int pin, unsigned int index, String key); - ~SensorDallas(); - - void loop(); - void readDallas(); - - private: - unsigned long currentMillis; - unsigned long prevMillis; - unsigned long difference; - unsigned long _interval; - String _key; - unsigned int _pin; - unsigned int _index; -}; - -extern MySensorDallasVector* mySensorDallas2; - -extern void dallas(); -#endif diff --git a/include/items/vSensorDht.h b/include/items/vSensorDht.h deleted file mode 100644 index ea3fa662..00000000 --- a/include/items/vSensorDht.h +++ /dev/null @@ -1,42 +0,0 @@ -#ifdef EnableSensorDht -#pragma once -#include -#include - -#include "Global.h" -#include "GyverFilters.h" - -class SensorDht; - -typedef std::vector MySensorDhtVector; - -struct paramsDht { - String type; - String key; - unsigned long interval; - unsigned int pin; - float c; -}; - -class SensorDht { - public: - SensorDht(const paramsDht& paramsTmp, const paramsDht& paramsHum); - ~SensorDht(); - - DHTesp* dht; - - void loop(); - void readTmpHum(); - - private: - paramsDht _paramsTmp; - paramsDht _paramsHum; - - unsigned long prevMillis; - unsigned long difference; -}; - -extern MySensorDhtVector* mySensorDht; - -extern void dhtSensor(); -#endif \ No newline at end of file diff --git a/include/items/vSensorImpulsIn.h b/include/items/vSensorImpulsIn.h deleted file mode 100644 index 710db859..00000000 --- a/include/items/vSensorImpulsIn.h +++ /dev/null @@ -1,32 +0,0 @@ -//#pragma once -//#include -// -//#include "Global.h" -//#include "PZEMSensor.h" -//#include "SoftUART.h" -// -//class SensorImpulsIn; -// -//typedef std::vector MySensorImpulsInVector; -// -//struct paramsImpulsIn { -// String key; -// unsigned int pin; -// float c; -// float k; -//}; -// -//class SensorImpulsIn { -// public: -// SensorImpulsIn(const paramsImpulsIn& paramsImpuls); -// ~SensorImpulsIn(); -// -// void interruptHandler(void); -// -// private: -// paramsImpulsIn _paramsImpuls; -//}; -// -//extern MySensorImpulsInVector* mySensorImpulsIn; -// -//extern void impulsInSensor(); \ No newline at end of file diff --git a/include/items/vSensorNode.h b/include/items/vSensorNode.h deleted file mode 100644 index 291db4f7..00000000 --- a/include/items/vSensorNode.h +++ /dev/null @@ -1,41 +0,0 @@ -#ifdef EnableSensorNode -#pragma once -#include - -#include "Global.h" - -class SensorNode; - -typedef std::vector MySensorNodeVector; - -struct paramsSensorNode { - String tm1; - String tm2; - String key; - float c; - float k; -}; - -class SensorNode { - public: - SensorNode(const paramsSensorNode& params); - ~SensorNode(); - - void loop(); - void onChange(String newValue, String incommingKey); - void publish(); - - private: - paramsSensorNode _params; - long _minutesPassed; - String _updateTime; - - unsigned long prevMillis; - unsigned long difference; -}; - -extern MySensorNodeVector* mySensorNode; - -extern void nodeSensor(); -extern void publishTimes(); -#endif \ No newline at end of file diff --git a/include/items/vSensorPzem.h b/include/items/vSensorPzem.h deleted file mode 100644 index 95672730..00000000 --- a/include/items/vSensorPzem.h +++ /dev/null @@ -1,46 +0,0 @@ -#ifdef EnableSensorPzem -#pragma once -#include - -#include "Global.h" -#include "PZEMSensor.h" -#include "SoftUART.h" - -class SensorPzem; - -typedef std::vector MySensorPzemVector; - -struct paramsPzem { - String key; - String addr; - unsigned long interval; - float c; - float k; -}; - -class SensorPzem { - public: - SensorPzem(const paramsPzem& paramsV, const paramsPzem& paramsA, const paramsPzem& paramsWatt, const paramsPzem& paramsWattHrs, const paramsPzem& paramsHz); - ~SensorPzem(); - - void loop(); - - private: - void read(); - - paramsPzem _paramsV; - paramsPzem _paramsA; - paramsPzem _paramsWatt; - paramsPzem _paramsWattHrs; - paramsPzem _paramsHz; - - PZEMSensor* pzem; - - unsigned long prevMillis; - unsigned long difference; -}; - -extern MySensorPzemVector* mySensorPzem; - -extern void pzemSensor(); -#endif \ No newline at end of file diff --git a/include/items/vSensorUltrasonic.h b/include/items/vSensorUltrasonic.h deleted file mode 100644 index e2d65284..00000000 --- a/include/items/vSensorUltrasonic.h +++ /dev/null @@ -1,42 +0,0 @@ -#ifdef EnableSensorUltrasonic -#pragma once -#include - -#include "Global.h" -#include "GyverFilters.h" - -class SensorUltrasonic; - -typedef std::vector MySensorUltrasonicVector; - -class SensorUltrasonic { - public: - SensorUltrasonic(String key, unsigned long interval, unsigned int trig, unsigned int echo, int map1, int map2, int map3, int map4, float c); - ~SensorUltrasonic(); - - void loop(); - void readUltrasonic(); - - private: - unsigned long currentMillis; - unsigned long prevMillis; - unsigned long difference; - - unsigned long _interval; - - String _key; - unsigned int _echo; - unsigned int _trig; - - int _map1; - int _map2; - int _map3; - int _map4; - - float _c; -}; - -extern MySensorUltrasonicVector* mySensorUltrasonic; - -extern void ultrasonic(); -#endif \ No newline at end of file diff --git a/include/items/vSensorUptime.h b/include/items/vSensorUptime.h deleted file mode 100644 index 22571b88..00000000 --- a/include/items/vSensorUptime.h +++ /dev/null @@ -1,35 +0,0 @@ -#ifdef EnableSensorUptime -#pragma once -#include - -#include "Global.h" -#include "GyverFilters.h" - -class SensorUptime; - -typedef std::vector MySensorUptimeVector; - -struct paramsUptime { - String key; - unsigned long interval; -}; - -class SensorUptime { - public: - SensorUptime(const paramsUptime& paramsUpt); - ~SensorUptime(); - - void loop(); - void read(); - - private: - paramsUptime _paramsUpt; - - unsigned long prevMillis; - unsigned long difference; -}; - -extern MySensorUptimeVector* mySensorUptime; - -extern void uptimeSensor(); -#endif \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/.clang-format b/lib/ArduinoStreamUtils/.clang-format deleted file mode 100644 index 76317270..00000000 --- a/lib/ArduinoStreamUtils/.clang-format +++ /dev/null @@ -1,5 +0,0 @@ -BasedOnStyle: Google -AllowShortFunctionsOnASingleLine: Empty -AllowShortIfStatementsOnASingleLine: false -AllowShortLoopsOnASingleLine: false -IncludeBlocks: Preserve \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/.github/FUNDING.yml b/lib/ArduinoStreamUtils/.github/FUNDING.yml deleted file mode 100644 index 0ec57d0a..00000000 --- a/lib/ArduinoStreamUtils/.github/FUNDING.yml +++ /dev/null @@ -1,4 +0,0 @@ -github: bblanchon -custom: - - https://arduinojson.org/book/ - - https://donate.benoitblanchon.fr/ diff --git a/lib/ArduinoStreamUtils/.github/workflows/ci.yml b/lib/ArduinoStreamUtils/.github/workflows/ci.yml deleted file mode 100644 index 4458bfe0..00000000 --- a/lib/ArduinoStreamUtils/.github/workflows/ci.yml +++ /dev/null @@ -1,121 +0,0 @@ -name: Continuous Integration - -on: [push, pull_request] - -jobs: - test: - name: Unit Test - runs-on: ubuntu-latest - steps: - - name: Install - run: sudo apt-get install -y lcov - - name: Checkout - uses: actions/checkout@v2 - - name: Configure - run: cmake -DCOVERAGE=true . - - name: Build - run: cmake --build . - - name: Run tests - run: ctest --output-on-failure . - - name: Capture coverage data - run: lcov --capture --no-external --directory . --output-file coverage.info - - name: Filter coverage data - run: lcov --remove coverage.info "$(pwd)/extras/*" --output-file coverage_filtered.info - - name: Generate coverage report - run: mkdir coverage && genhtml coverage_filtered.info -o coverage -t ArduinoJson - - name: Upload coverage report - uses: actions/upload-artifact@v2 - with: - name: coverage - path: coverage - - name: Upload to Coveralls - uses: coverallsapp/github-action@master - with: - github-token: ${{ secrets.GITHUB_TOKEN }} - path-to-lcov: coverage_filtered.info - - platformio: - name: PlatformIO - needs: test - runs-on: ubuntu-latest - strategy: - fail-fast: false - matrix: - include: - - platform: atmelavr - board: leonardo - eeprom: true - softwareserial: true - - platform: espressif8266 - board: huzzah - eeprom: true - softwareserial: true - - platform: espressif32 - board: esp32dev - eeprom: true - softwareserial: false - - platform: atmelsam - board: mkr1000USB - eeprom: false - softwareserial: false - - platform: teensy - board: teensy31 - eeprom: true - softwareserial: true - - platform: ststm32 - board: nucleo_f031k6 - eeprom: true - softwareserial: true - - platform: nordicnrf52 - board: adafruit_feather_nrf52840 - eeprom: false - softwareserial: true - steps: - - name: Checkout - uses: actions/checkout@v2 - - name: Set up cache - uses: actions/cache@v2 - with: - path: | - ~/.platformio - ~/.cache/pip - key: ${{ runner.os }}-platformio - - name: Set up Python 3.x - uses: actions/setup-python@v2 - with: - python-version: '3.x' - - name: Install PlatformIO - run: pip install platformio - - name: Install platform "${{ matrix.platform }}" - run: platformio platform install ${{ matrix.platform }} - - name: Install adafruit-nrfutil - if: ${{ matrix.platform == 'nordicnrf52' }} - run: pip3 install adafruit-nrfutil - - name: Include Adafruit_TinyUSB.h # https://github.com/adafruit/Adafruit_nRF52_Arduino/issues/653 - if: ${{ matrix.platform == 'nordicnrf52' }} - run: find examples/ -name '*.ino' -exec sed -i 's/\(#include \)/\1\n#include /' {} + - - name: Build EepromRead - if: ${{ matrix.eeprom }} - run: platformio ci "examples/EepromRead/EepromRead.ino" -l '.' -b ${{ matrix.board }} - - name: Build EepromWrite - if: ${{ matrix.eeprom }} - run: platformio ci "examples/EepromWrite/EepromWrite.ino" -l '.' -b ${{ matrix.board }} - - name: Build HammingSerial1 - run: platformio ci "examples/HammingSerial1/HammingSerial1.ino" -l '.' -b ${{ matrix.board }} - - name: Build HammingSoftwareSerial - if: ${{ matrix.softwareserial }} - run: platformio ci "examples/HammingSoftwareSerial/HammingSoftwareSerial.ino" -l '.' -b ${{ matrix.board }} - - name: Build Logger - run: platformio ci "examples/Logger/Logger.ino" -l '.' -b ${{ matrix.board }} - - name: Build ReadBuffer - run: platformio ci "examples/ReadBuffer/ReadBuffer.ino" -l '.' -b ${{ matrix.board }} - - name: Build ReadLogger - run: platformio ci "examples/ReadLogger/ReadLogger.ino" -l '.' -b ${{ matrix.board }} - - name: Build StringPrint - run: platformio ci "examples/StringPrint/StringPrint.ino" -l '.' -b ${{ matrix.board }} - - name: Build StringStream - run: platformio ci "examples/StringStream/StringStream.ino" -l '.' -b ${{ matrix.board }} - - name: Build WriteBuffer - run: platformio ci "examples/WriteBuffer/WriteBuffer.ino" -l '.' -b ${{ matrix.board }} - - name: Build WriteLogger - run: platformio ci "examples/WriteLogger/WriteLogger.ino" -l '.' -b ${{ matrix.board }} diff --git a/lib/ArduinoStreamUtils/.gitignore b/lib/ArduinoStreamUtils/.gitignore deleted file mode 100644 index a7747886..00000000 --- a/lib/ArduinoStreamUtils/.gitignore +++ /dev/null @@ -1,2 +0,0 @@ -/build - diff --git a/lib/ArduinoStreamUtils/CHANGELOG.md b/lib/ArduinoStreamUtils/CHANGELOG.md deleted file mode 100644 index ae38a39c..00000000 --- a/lib/ArduinoStreamUtils/CHANGELOG.md +++ /dev/null @@ -1,79 +0,0 @@ -StreamUtils - Change log -======================== - -HEAD ----- - -* Support `Print::flush()` on AVR - -1.6.1 (2021/94/05) ------ - -* Add example `HammingSerial1.ino` -* Add support for STM32 (issue #11) - - -1.6.0 (2020/11/20) ------ - -* Add `HammingPrint<7, 4>` -* Add `HammingStream<7, 4>`, `HammingEncodingStream<7, 4>`, and `HammingDecodingStream<7, 4>` -* Add `HammingClient<7, 4>`, `HammingEncodingClient<7, 4>`, and `HammingDecodingClient<7, 4>` - -1.5.0 (2020/08/04) ------ - -* Add `WaitingPrint`, `WriteWaitingClient`, and `WriteWaitingStream`. - -1.4.1 (2020/07/01) ------ - -* Fix unwanted waits in `ReadBufferingClient` and `ReadBufferingStream`. -* Stop calling `Client::read()` in place of `Stream::readBytes()`, - because it doesn't honor the timeout. - -1.4.0 (2020/03/30) ------ - -* Add `EepromStream` -* Add support for ESP32 -* Add support for Teensy - -1.3.0 (2020/01/20) ------ - -* Move auxiliary content to `extras/` to comply with new library layout -* Add `StringPrint` and `StringStream` -* Extract `StreamUtils.hpp`, same as `StreamUtils.h` except it keeps everything in the `StreamUtils` namespace. - -1.2.2 (2019/07/18) ------ - -* Fix `BufferingPrint` taking `Stream` instead of `Print` (issue #3) -* Fix `LoggingPrint` not forwarding call to `Print::flush()` -* Fix missing `override` specifiers - -1.2.1 (2019/06/05) ------ - -* Remove workaround for ESP8266 core 2.5.0 -* Fix compatibility with ESP8266 core 2.5.1+ (issue #2) - -1.2.0 (2019/05/01) ------ - -* Add `LoggingPrint` -* Add `BufferingPrint` -* Add `WriteLoggingClient`, `ReadLoggingClient`, and `LoggingClient` -* Add `WriteBufferingClient` and `ReadBufferingClient` - -1.1.0 (2019/04/20) ------ - -* Add `LoggingStream` (=`ReadLoggingStream` + `WriteLoggingStream`) - -1.0.0 (2019/04/14) ------ - -* Add `ReadBufferingStream` and `WriteBufferingStream` -* Add `ReadLoggingStream` and `WriteLoggingStream` diff --git a/lib/ArduinoStreamUtils/CMakeLists.txt b/lib/ArduinoStreamUtils/CMakeLists.txt deleted file mode 100644 index 26061d64..00000000 --- a/lib/ArduinoStreamUtils/CMakeLists.txt +++ /dev/null @@ -1,18 +0,0 @@ -# StreamUtils - github.com/bblanchon/ArduinoStreamUtils -# Copyright Benoit Blanchon 2019-2021 -# MIT License - -cmake_minimum_required(VERSION 3.0) -project(StreamUtils) - -enable_testing() - -set(CMAKE_CXX_STANDARD 11) -set(CMAKE_CXX_STANDARD_REQUIRED ON) - -if(${COVERAGE}) - set(CMAKE_CXX_FLAGS "-fprofile-arcs -ftest-coverage -g -O0") -endif() - -include_directories(${CMAKE_CURRENT_LIST_DIR}/src) -add_subdirectory(extras/test) diff --git a/lib/ArduinoStreamUtils/LICENSE.md b/lib/ArduinoStreamUtils/LICENSE.md deleted file mode 100644 index 4774d78c..00000000 --- a/lib/ArduinoStreamUtils/LICENSE.md +++ /dev/null @@ -1,10 +0,0 @@ -The MIT License (MIT) ---------------------- - -Copyright © 2019 Benoit BLANCHON - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/lib/ArduinoStreamUtils/README.md b/lib/ArduinoStreamUtils/README.md deleted file mode 100644 index a03ffe9e..00000000 --- a/lib/ArduinoStreamUtils/README.md +++ /dev/null @@ -1,369 +0,0 @@ -StreamUtils: Power-ups for Arduino Streams -========================================== - -[![arduino-library-badge](https://www.ardu-badge.com/badge/StreamUtils.svg?version=1.6.1)](https://www.ardu-badge.com/StreamUtils/1.6.1) -[![Continuous Integration](https://github.com/bblanchon/ArduinoStreamUtils/workflows/Continuous%20Integration/badge.svg)](https://github.com/bblanchon/ArduinoStreamUtils/actions/workflows/ci.yml) -[![Coverage Status](https://coveralls.io/repos/github/bblanchon/ArduinoStreamUtils/badge.svg)](https://coveralls.io/github/bblanchon/ArduinoStreamUtils) - -The *stream* is an essential abstraction in Arduino; we find it in many places: - -* [`HardwareSerial`](https://www.arduino.cc/reference/en/language/functions/communication/serial/) -* [`SoftwareSerial`](https://www.arduino.cc/en/Reference/SoftwareSerial) -* [`File`](https://www.arduino.cc/en/Reference/SD) -* [`EthernetClient`](https://www.arduino.cc/en/Reference/EthernetClient) -* [`WiFiClient`](https://www.arduino.cc/en/Reference/WiFiClient) -* [`Wire`](https://www.arduino.cc/en/reference/wire) -* and many others... - -This library provides some helper classes and functions for dealing with streams. - -For example, with this library, you can: - -* speed of your program by buffering the data it reads from a file -* reduce the number of packets sent over WiFi by buffering the data you send -* improve the reliability of a serial connection by adding error correction codes -* debug your program more easily by logging what it sends to a Web service -* send large data with the [Wire library](https://www.arduino.cc/en/reference/wire) -* use a `String` or EEPROM with a stream interface - -Read on to see how StreamUtils can help you! - - -How to add buffering to a Stream? ---------------------------------- - -### Buffering read operations - -Sometimes, you can significantly improve performance by reading many bytes at once. -For example, [according to SPIFFS's wiki](https://github.com/pellepl/spiffs/wiki/Performance-and-Optimizing#reading-files), it's much faster to read files in chunks of 64 bytes than reading them one byte at a time. - -![ReadBufferingStream](extras/images/ReadBuffer.svg) - -To buffer the input, simply decorate the original `Stream` with `ReadBufferingStream`. For example, suppose your program reads a JSON document from SPIFFS, like that: - -```c++ -File file = SPIFFS.open("example.json", "r"); -deserializeJson(doc, file); -``` - -Then you simply need to insert one line to greatly improve the reading speed: - -```c++ -File file = SPIFFS.open("example.json", "r"); -ReadBufferingStream bufferedFile{file, 64}; // <- HERE -deserializeJson(doc, bufferedFile); -``` - -Unfortunately, this optimization is only possible if: - -1. `Stream.readBytes()` is declared `virtual` in your Arduino Code (as it's the case for ESP8266), and -2. the derived class has an optimized implementation of `readBytes()` (as it's the case for SPIFFS' `File`). - -When possible, prefer `ReadBufferingClient` to `ReadBufferingStream` because `Client` defines a `read()` method similar to `readBytes()`, except that this one is `virtual` on all platforms. - -If memory allocation fails, `ReadBufferingStream` behaves as if no buffer was used: it forwards all calls to the upstream `Stream`. - -Adding a buffer only makes sense for **unbuffered** streams. For example, there is **no benefit to adding a buffer to serial ports** because they already include an internal buffer. - -### Buffering write operations - -Similarly, you can improve performance significantly by writing many bytes at once. -For example, if you write to `WiFiClient` one bytes at a time, it will be very slow; it's much faster if you send large chunks. - -![WriteBufferingStream](extras/images/WriteBuffer.svg) - -To add a buffer, decorate the original `Stream` with `WriteBufferingStream`. For example, if your program sends a JSON document via `WiFiClient`, like that: - -```c++ -serializeJson(doc, wifiClient); -``` - -Then, you just need to add two lines: - -```c++ -WriteBufferingStream bufferedWifiClient{wifiClient, 64}; -serializeJson(doc, bufferedWifiClient); -bufferedWifiClient.flush(); -``` - -`flush()` sends the remaining data; if you forget to call it, the end of the message will be missing. The destructor of `WriteBufferingStream` calls `flush()`, so you can remove this line if you destroy the decorator immediately. - -If memory allocation fails, `WriteBufferingStream` behaves as if no buffer was used: it forwards all calls to the upstream `Stream`. - -Adding a buffer only makes sense for **unbuffered** streams. For example, there is **no benefit to adding a buffer to serial ports** because they already include an internal buffer. - -How to add logging to a stream? -------------------------------- - -### Logging write operations - -When debugging a program that makes HTTP requests, the first thing you want to check is that the request is correct. With this library, you can decorate the `EthernetClient` or the `WiFiClient` to log everything to the serial. - -![WriteLoggingStream](extras/images/WriteLogger.svg) - -For example, if you program is: - -```c++ -client.println("GET / HTTP/1.1"); -client.println("User-Agent: Arduino"); -// ... -``` - -Then, you just need to create the decorator, and update the calls to `println()`: - -```c++ -WriteLoggingStream loggingClient(client, Serial); -loggingClient.println("GET / HTTP/1.1"); -loggingClient.println("User-Agent: Arduino"); -// ... -``` - -Everything you write to `loggingClient` is written to `client` and logged to `Serial`. - - -### Logging read operations - -Similarly, you often want to see what the HTTP server sent back. With this library, you can decorate the `EthernetClient` or the `WiFiClient` to log everything to the serial. - -![ReadLoggingStream](extras/images/ReadLogger.svg) - -For example, if you program is: - -```c++ -char response[256]; -client.readBytes(response, 256); -``` - -Then, you just need to create the decorator, and update the calls to `readBytes()`: - -```c++ -ReadLoggingStream loggingClient(client, Serial); -char response[256]; -loggingClient.readBytes(response, 256); -// ... -``` - -`loggingClient` forwards all operations to `client` and logs read operation to `Serial`. - -⚠ **WARNING** ⚠ -If your program receives data from one serial port and logs to another one, **make sure the latter runs at a much higher speed**. Logging must be at least ten times faster, or it will slow down the receiving port, which may drop incoming bytes. - -### Logging read and write operations - -Of course, you could log read and write operations by combining `ReadLoggingStream` and `WriteLoggingStream`, but there is a simpler solution: `LoggingStream`. - -![LoggingStream](extras/images/Logger.svg) - -As usual, if your program is: - -```c++ -client.println("GET / HTTP/1.1"); -client.println("User-Agent: Arduino"); - -char response[256]; -client.readBytes(response, 256); -``` - -Then decorate `client` and replace the calls: - -```c++ -LoggingStream loggingClient(client, Serial); - -loggingClient.println("GET / HTTP/1.1"); -loggingClient.println("User-Agent: Arduino"); - -char response[256]; -loggingClient.readBytes(response, 256); -``` - -How to use error-correction codes (ECC)? ----------------------------------------- - -StreamUtils supports the [Hamming(7, 4)](https://en.wikipedia.org/wiki/Hamming(7,4)) error-correction code, which encodes 4 bits of data into 7 bits by adding three parity bits. -These extra bits increase the amount of traffic but allow correcting any one-bit error within the 7 bits. - -If you use this encoding on an 8-bit channel, it effectively doubles the amount of traffic. However, if you use an [`HardwareSerial`](https://www.arduino.cc/reference/en/language/functions/communication/serial/) instance (like `Serial`, `Serial1`...), you can slightly reduce the overhead by configuring the ports as a 7-bit channel, like so: - -```c++ -// Initialize serial port with 9600 bauds, 7-bits of data, no parity, and one stop bit -Serial1.begin(9600, SERIAL_7N1); -``` - -### Adding parity bits - -The class `HammingEncodingStream<7, 4>` decorates an existing `Stream` to include parity bits in every write operation. - -![HammingEncodingStream](extras/images/HammingEncodingStream.svg) - -You can use this class like so: - -```c++ -HammingEncodingStream<7, 4> eccSerial(Serial1); - -eccSerial.println("Hello world!"); -``` - -Like every `Stream` decorator in this library, `HammingEncodingStream<7, 4>` supports all `Stream` methods (like `print()`, `println()`, `read()`, `readBytes()`, and `available()`). - -### Correcting errors - -The class `HammingDecodingStream<7, 4>` decorates an existing `Stream` to decode parity bits in every read operation. - -![HammingDecodingStream](extras/images/HammingDecodingStream.svg) - -You can use this class like so: - -```c++ -HammingDecodingStream<7, 4> eccSerial(Serial1); - -char buffer[256]; -size_t n = eccSerial.readBytes(buffer, n); -``` - -Like every `Stream` decorator in this library, `HammingDecodingStream<7, 4>` supports all `Stream` methods (like `print()`, `println()`, `read()`, `readBytes()`, and `available()`). - -### Encoding and decoding in both directions - -The class `HammingStream<7, 4>` combines the features of `HammingEncodingStream<7, 4>` and `HammingDecodingStream<7, 4>`, which is very useful when you do a two-way communication. - -![HammingStream](extras/images/HammingStream.svg) - -You can use this class like so: - -```c++ -HammingStream<7, 4> eccSerial(Serial1); - -eccSerial.println("Hello world!"); - -char buffer[256]; -size_t n = eccSerial.readBytes(buffer, n); -``` - -Like every `Stream` decorator in this library, `HammingStream<7, 4>` supports all `Stream` methods (like `print()`, `println()`, `read()`, `readBytes()`, and `available()`). - - -How to retry write operations? ------------------------------- - -Sometimes, a stream is limited to the capacity of its internal buffer. In that case, you must wait before sending more data. -To solve this problem, StreamUtils provides the `WriteWaitingStream` decorator: - -![WriteWaitingStream](extras/images/WriteWaitingStream.svg) - -This function repeatedly waits and retries until it times out. -You can customize the `wait()` function; by default, it's [`yield()`](https://www.arduino.cc/en/Reference/SchedulerYield). - -For example, if you want to send more than 32 bytes with the [Wire library](https://www.arduino.cc/en/reference/wire), you can do: - -```c++ -WriteWaitingStream wireStream(Wire, [](){ - Wire.endTransmission(false); // <- don't forget this argument - Wire.beginTransmission(address); -}); - -Wire.beginTransmission(address); -wireStream.print("This is a very very long message that I'm sending!"); -Wire.endTransmission(); -``` - -As you can see, we use the `wait()` function as a hook to flush the Wire transmission buffer. Notice that we pass `false` to [`endTransmission()`](https://www.arduino.cc/en/Reference/WireEndTransmission) so that it sends the data but doesn't actually stop the transmission. - - -How to use a `String` as a stream? ---------------------- - -### Writing to a `String` - -Sometimes, you use a piece of code that expects a `Print` instance (like `ReadLoggingStream`), but you want the output in a `String` instead of a regular `Stream`. -In that case, use the `StringPrint` class. It wraps a `String` within a `Print` implementation. - -![StringPrint](extras/images/StringPrint.svg) - -Here is how you can use it: - -```c++ -StringPrint stream; - -stream.print("Temperature = "); -stream.print(22.3); -stream.print(" °C"); - -String result = stream.str(); -``` - -At the end of this snippet, the string `result` contains: - -``` -Temperature = 22.30 °C -``` - -### Reading from a `String` - -Similarly, there are cases where you have a `String`, but you need to pass a `Stream` to some other piece of code. In that case, use `StringStream`; it's similar to `StrintPrint`, except you can read as well. - -![StringStream](extras/images/StringStream.svg) - - -How to use EEPROM as a stream? ------------------------------- - -SteamUtils also allows using EEPROM as a stream. Simply create an instance of `EepromStream` and specify the start address and the size of the region you want to expose. - -![EepromStream](extras/images/EepromStream.svg) - -For example, it allows you to save a JSON document in EEPROM: - -```c++ -EepromStream eepromStream(0, 128); -serializeJson(doc, eepromStream); -eepromStream.flush(); // <- calls EEPROM.commit() on ESP (optional) -``` - -In the same way, you can read a JSON document from EEPROM: - -```c++ -EepromStream eepromStream(0, 128); -deserializeJson(doc, eepromStream); -``` - - -Summary -------- - -Some of the decorators are also available for the `Print` and `Client` classes. -See the equivalence table below. - -| Purpose | `Client` | `Stream` | `Print` | -|:-----------------------------------|:------------------------|:------------------------|:-----------------| -| Log *write* operations | `WriteLoggingClient` | `WriteLoggingStream` | `LoggingPrint` | -| Log *read* operations | `ReadLoggingClient` | `ReadLoggingStream` | | -| Log *read* and *write* op. | `LoggingClient` | `LoggingStream` | | -| Buffer *write* operations | `WriteBufferingClient` | `WriteBufferingStream` | `BufferingPrint` | -| Buffer *read* operations | `ReadBufferingClient` | `ReadBufferingStream` | | -| Repeat *write* operations | `WriteWaitingClient` | `WriteWaitingStream` | `WaitingPrint` | -| Use `String` as a stream | | `StringStream` | `StringPrint` | -| Use EEPROM as a stream | | `EepromStream` | | -| Error correction (decode only) | `HammingDecodingClient` | `HammingDecodingStream` | | -| Error correction (encode only) | `HammingEncodingClient` | `HammingEncodingStream` | `HammingPrint` | -| Error correction (encode & decode) | `HammingClient` | `HammingStream` | | - -When possible, prefer `ReadBufferingClient` to `ReadBufferingStream` because `Client::read()` often provides an optimized implementation. - - -Portability ------------ - -This library relies on the definitions of `Client`, `Print`, and `Stream`, which unfortunately differ from one core to another. - -It has been tested on the following cores: - -* [AVR](https://github.com/arduino/ArduinoCore-avr) -* [ESP32](https://github.com/espressif/arduino-esp32) -* [ESP8266](https://github.com/esp8266/Arduino) -* [nRF52](https://github.com/adafruit/Adafruit_nRF52_Arduino) -* [SAMD](https://github.com/arduino/ArduinoCore-samd) -* [STM32](https://github.com/stm32duino/Arduino_Core_STM32) -* [Teensy](https://github.com/PaulStoffregen/cores) - -If your core is not supported, please [open an issue](https://github.com/bblanchon/ArduinoStreamUtils/issues/new). -Thank you for your understanding. diff --git a/lib/ArduinoStreamUtils/examples/EepromRead/EepromRead.ino b/lib/ArduinoStreamUtils/examples/EepromRead/EepromRead.ino deleted file mode 100644 index fb5ed409..00000000 --- a/lib/ArduinoStreamUtils/examples/EepromRead/EepromRead.ino +++ /dev/null @@ -1,63 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License -// -// This example shows how to read from EEPROM - -#include - -void setup() { - // Initialize serial port - Serial.begin(9600); - while (!Serial) - continue; - -#if STREAMUTILS_ENABLE_EEPROM - -#if defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32) - Serial.println("Initializing EEPROM..."); - EEPROM.begin(512); -#endif - - Serial.println("Make sure to run the EepromWrite example first!"); - - Serial.println("Reading EEPROM... "); - EepromStream s(0, 12); - Serial.print(s.readString()); - -#else - Serial.println("EepromStream is not supported on this platform. Sorry"); -#endif -} - -void loop() { - // not used in this example -} - -/***************************************************** - * * - * Love this project? * - * Star it on GitHub! * - * * - * .,,. * - * ,,:1. * - * ,.,:;1 * - * .,,,::;: * - * ,,,,::;;. * - * .,,,:::;;; * - * .....,,,,...,.,,,,,,:::,,,,,,,,,,,,, * - * ,,,,,,,,,,,:,...,,,,,,:::,,,,:::;;;11l * - * .;::::::::,,,,,,,,,,:::::,,::;;;1lt * - * .;;;:::,,,,,,,,::::::;:::;;1t: * - * :;;:,,,,,,::::::;;;;;;l1 * - * ,,,,:::::::;;;;;;l * - * .,,,,::::;;;;;;;:::: * - * ,,,,,:::;;;;;::,:::1 * - * ,,,,,::;;;t1:,,:::::;l * - * .,,,,:;;ll ;::::::;;, * - * ,,,:;ll. .1:::;;l * - * .,:lt, .1;;l: * - * * - * https://github.com/bblanchon/ArduinoStreamUtils * - * * - *****************************************************/ \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/examples/EepromWrite/EepromWrite.ino b/lib/ArduinoStreamUtils/examples/EepromWrite/EepromWrite.ino deleted file mode 100644 index 4e988268..00000000 --- a/lib/ArduinoStreamUtils/examples/EepromWrite/EepromWrite.ino +++ /dev/null @@ -1,69 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License -// -// This example shows how to read from EEPROM - -#include - -void setup() { - // Initialize serial port - Serial.begin(9600); - while (!Serial) - continue; - -#if STREAMUTILS_ENABLE_EEPROM - -#if defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32) - Serial.println("Initializing EEPROM..."); - EEPROM.begin(512); -#endif - - Serial.println("Writing to EEPROM..."); - EepromStream s(0, 12); - s.print("Hello World!"); - -#if defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32) - Serial.println("Saving..."); - s.flush(); // only required on ESP -#endif - - Serial.println("Done!"); - Serial.println("Now, run the EepromRead example."); - -#else - Serial.println("EepromStream is not supported on this platform. Sorry"); -#endif -} - -void loop() { - // not used in this example -} - -/***************************************************** - * * - * Love this project? * - * Star it on GitHub! * - * * - * .,,. * - * ,,:1. * - * ,.,:;1 * - * .,,,::;: * - * ,,,,::;;. * - * .,,,:::;;; * - * .....,,,,...,.,,,,,,:::,,,,,,,,,,,,, * - * ,,,,,,,,,,,:,...,,,,,,:::,,,,:::;;;11l * - * .;::::::::,,,,,,,,,,:::::,,::;;;1lt * - * .;;;:::,,,,,,,,::::::;:::;;1t: * - * :;;:,,,,,,::::::;;;;;;l1 * - * ,,,,:::::::;;;;;;l * - * .,,,,::::;;;;;;;:::: * - * ,,,,,:::;;;;;::,:::1 * - * ,,,,,::;;;t1:,,:::::;l * - * .,,,,:;;ll ;::::::;;, * - * ,,,:;ll. .1:::;;l * - * .,:lt, .1;;l: * - * * - * https://github.com/bblanchon/ArduinoStreamUtils * - * * - *****************************************************/ \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/examples/HammingSerial1/HammingSerial1.ino b/lib/ArduinoStreamUtils/examples/HammingSerial1/HammingSerial1.ino deleted file mode 100644 index 16338a06..00000000 --- a/lib/ArduinoStreamUtils/examples/HammingSerial1/HammingSerial1.ino +++ /dev/null @@ -1,68 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License -// -// This example shows how to use Hamming codes for error correction -// -// To run this program, you need two boards that support Serial1 with the same -// voltage. For example: Arduino Mega, Leonardo, or Nano Every (all 5V boards) -// -// Connect the TX pin of one board to the RX pin of the other and vice-versa. - -#include - -HammingStream<7, 4> eccSerial1(Serial1); - -void setup() { - Serial.begin(115200); - while (!Serial) - continue; - - Serial1.begin(9600); - while (!Serial) - continue; - - // Discard any remaining data in the input buffer - while (Serial1.available()) - Serial1.read(); -} - -void loop() { - // Did we receive something? - if (eccSerial1.available()) - // Print it - Serial.write(eccSerial1.read()); - - // Do we have something to send? - if (Serial.available()) - // Sent it - eccSerial1.write(Serial.read()); -} - -/***************************************************** - * * - * Love this project? * - * Star it on GitHub! * - * * - * .,,. * - * ,,:1. * - * ,.,:;1 * - * .,,,::;: * - * ,,,,::;;. * - * .,,,:::;;; * - * .....,,,,...,.,,,,,,:::,,,,,,,,,,,,, * - * ,,,,,,,,,,,:,...,,,,,,:::,,,,:::;;;11l * - * .;::::::::,,,,,,,,,,:::::,,::;;;1lt * - * .;;;:::,,,,,,,,::::::;:::;;1t: * - * :;;:,,,,,,::::::;;;;;;l1 * - * ,,,,:::::::;;;;;;l * - * .,,,,::::;;;;;;;:::: * - * ,,,,,:::;;;;;::,:::1 * - * ,,,,,::;;;t1:,,:::::;l * - * .,,,,:;;ll ;::::::;;, * - * ,,,:;ll. .1:::;;l * - * .,:lt, .1;;l: * - * * - * https://github.com/bblanchon/ArduinoStreamUtils * - * * - *****************************************************/ \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/examples/HammingSoftwareSerial/HammingSoftwareSerial.ino b/lib/ArduinoStreamUtils/examples/HammingSoftwareSerial/HammingSoftwareSerial.ino deleted file mode 100644 index bf63bde0..00000000 --- a/lib/ArduinoStreamUtils/examples/HammingSoftwareSerial/HammingSoftwareSerial.ino +++ /dev/null @@ -1,67 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License -// -// This example shows how to use Hamming codes for error correction -// -// To run this program, you need two boards connected like so: -// BOARD 1 - BOARD 2 -// pin 10 - pin 11 -// pin 11 - pin 10 -// -// SoftwareSerial is here for demonstration purposes; please don't use it in -// production, as it is notoriously unreliable. - -#include -#include - -SoftwareSerial linkSerial(10, 11); // RX, TX -HammingStream<7, 4> eccLinkSerial(linkSerial); - -void setup() { - Serial.begin(115200); - while (!Serial) - continue; - - linkSerial.begin(4800); -} - -void loop() { - // Did we receive something? - if (eccLinkSerial.available()) - // Print it - Serial.write(eccLinkSerial.read()); - - // Do we have something to send? - if (Serial.available()) - // Sent it - eccLinkSerial.write(Serial.read()); -} - -/***************************************************** - * * - * Love this project? * - * Star it on GitHub! * - * * - * .,,. * - * ,,:1. * - * ,.,:;1 * - * .,,,::;: * - * ,,,,::;;. * - * .,,,:::;;; * - * .....,,,,...,.,,,,,,:::,,,,,,,,,,,,, * - * ,,,,,,,,,,,:,...,,,,,,:::,,,,:::;;;11l * - * .;::::::::,,,,,,,,,,:::::,,::;;;1lt * - * .;;;:::,,,,,,,,::::::;:::;;1t: * - * :;;:,,,,,,::::::;;;;;;l1 * - * ,,,,:::::::;;;;;;l * - * .,,,,::::;;;;;;;:::: * - * ,,,,,:::;;;;;::,:::1 * - * ,,,,,::;;;t1:,,:::::;l * - * .,,,,:;;ll ;::::::;;, * - * ,,,:;ll. .1:::;;l * - * .,:lt, .1;;l: * - * * - * https://github.com/bblanchon/ArduinoStreamUtils * - * * - *****************************************************/ \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/examples/Logger/Logger.ino b/lib/ArduinoStreamUtils/examples/Logger/Logger.ino deleted file mode 100644 index ccb483ed..00000000 --- a/lib/ArduinoStreamUtils/examples/Logger/Logger.ino +++ /dev/null @@ -1,61 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License -// -// This example shows how to log what goes through a Stream, both reads and -// writes operations. - -#include - -// Create a new stream that will forward all calls to Serial, and log to Serial. -// Everything will be written twice to the Serial! -LoggingStream loggingStream(Serial, Serial); - -void setup() { - // Initialize serial port - Serial.begin(9600); - while (!Serial) - continue; - - // Write to the serial port. - // Because loggingStream logs each write operation, the string will we written - // twice - loggingStream.println("Hello World!"); -} - -void loop() { - // Read from the serial port. - // Because loggingStream logs each read operation, everything we read is - // printed back to the serial port. - while (loggingStream.available()) { - loggingStream.read(); - } -} - -/***************************************************** - * * - * Love this project? * - * Star it on GitHub! * - * * - * .,,. * - * ,,:1. * - * ,.,:;1 * - * .,,,::;: * - * ,,,,::;;. * - * .,,,:::;;; * - * .....,,,,...,.,,,,,,:::,,,,,,,,,,,,, * - * ,,,,,,,,,,,:,...,,,,,,:::,,,,:::;;;11l * - * .;::::::::,,,,,,,,,,:::::,,::;;;1lt * - * .;;;:::,,,,,,,,::::::;:::;;1t: * - * :;;:,,,,,,::::::;;;;;;l1 * - * ,,,,:::::::;;;;;;l * - * .,,,,::::;;;;;;;:::: * - * ,,,,,:::;;;;;::,:::1 * - * ,,,,,::;;;t1:,,:::::;l * - * .,,,,:;;ll ;::::::;;, * - * ,,,:;ll. .1:::;;l * - * .,:lt, .1;;l: * - * * - * https://github.com/bblanchon/ArduinoStreamUtils * - * * - *****************************************************/ \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/examples/ReadBuffer/ReadBuffer.ino b/lib/ArduinoStreamUtils/examples/ReadBuffer/ReadBuffer.ino deleted file mode 100644 index 62e1aa4d..00000000 --- a/lib/ArduinoStreamUtils/examples/ReadBuffer/ReadBuffer.ino +++ /dev/null @@ -1,56 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License -// -// This example shows how to buffer the read operations of a stream. -// -// Like "echo," it reads from the serial port and prints back the same thing. -// What's interesting with this program is that it reads the input in chunks of -// 64 bytes, even if it seems to read them one by one. - -#include - -ReadBufferingStream bufferedSerial{Serial, 64}; - -void setup() { - // Initialize serial port - Serial.begin(9600); - while (!Serial) - continue; -} - -void loop() { - // Even if it looks like the bytes are extracted one by one, they are actually - // read by chunks of 64 bytes and placed in a buffer. - while (bufferedSerial.available()) { - Serial.write(bufferedSerial.read()); - } -} - -/***************************************************** - * * - * Love this project? * - * Star it on GitHub! * - * * - * .,,. * - * ,,:1. * - * ,.,:;1 * - * .,,,::;: * - * ,,,,::;;. * - * .,,,:::;;; * - * .....,,,,...,.,,,,,,:::,,,,,,,,,,,,, * - * ,,,,,,,,,,,:,...,,,,,,:::,,,,:::;;;11l * - * .;::::::::,,,,,,,,,,:::::,,::;;;1lt * - * .;;;:::,,,,,,,,::::::;:::;;1t: * - * :;;:,,,,,,::::::;;;;;;l1 * - * ,,,,:::::::;;;;;;l * - * .,,,,::::;;;;;;;:::: * - * ,,,,,:::;;;;;::,:::1 * - * ,,,,,::;;;t1:,,:::::;l * - * .,,,,:;;ll ;::::::;;, * - * ,,,:;ll. .1:::;;l * - * .,:lt, .1;;l: * - * * - * https://github.com/bblanchon/ArduinoStreamUtils * - * * - *****************************************************/ \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/examples/ReadLogger/ReadLogger.ino b/lib/ArduinoStreamUtils/examples/ReadLogger/ReadLogger.ino deleted file mode 100644 index 204ef9d3..00000000 --- a/lib/ArduinoStreamUtils/examples/ReadLogger/ReadLogger.ino +++ /dev/null @@ -1,55 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License -// -// This example shows how to log what read from a Stream - -#include - -// Create a new stream that will forward all calls to Serial, and log to Serial. -// It will write back everything it reads, just like "echo" -ReadLoggingStream loggingStream(Serial, Serial); - -void setup() { - // Initialize serial port - Serial.begin(9600); - while (!Serial) - continue; -} - -void loop() { - // Read the serial port. - // Because loggingStream write everything it read, the program will show what - // you sent. - while (Serial.available()) { - loggingStream.write(Serial.read()); - } -} - -/***************************************************** - * * - * Love this project? * - * Star it on GitHub! * - * * - * .,,. * - * ,,:1. * - * ,.,:;1 * - * .,,,::;: * - * ,,,,::;;. * - * .,,,:::;;; * - * .....,,,,...,.,,,,,,:::,,,,,,,,,,,,, * - * ,,,,,,,,,,,:,...,,,,,,:::,,,,:::;;;11l * - * .;::::::::,,,,,,,,,,:::::,,::;;;1lt * - * .;;;:::,,,,,,,,::::::;:::;;1t: * - * :;;:,,,,,,::::::;;;;;;l1 * - * ,,,,:::::::;;;;;;l * - * .,,,,::::;;;;;;;:::: * - * ,,,,,:::;;;;;::,:::1 * - * ,,,,,::;;;t1:,,:::::;l * - * .,,,,:;;ll ;::::::;;, * - * ,,,:;ll. .1:::;;l * - * .,:lt, .1;;l: * - * * - * https://github.com/bblanchon/ArduinoStreamUtils * - * * - *****************************************************/ \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/examples/StringPrint/StringPrint.ino b/lib/ArduinoStreamUtils/examples/StringPrint/StringPrint.ino deleted file mode 100644 index 30b5eb46..00000000 --- a/lib/ArduinoStreamUtils/examples/StringPrint/StringPrint.ino +++ /dev/null @@ -1,54 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License -// -// This example shows how to use StringPrint - -#include - -void setup() { - // Initialize serial port - Serial.begin(9600); - while (!Serial) - continue; - - StringPrint stream; - - stream.print("Temperature = "); - stream.print(22.3); - stream.print(" °C"); - - Serial.print(stream.str()); -} - -void loop() { - // no used in this example -} - -/***************************************************** - * * - * Love this project? * - * Star it on GitHub! * - * * - * .,,. * - * ,,:1. * - * ,.,:;1 * - * .,,,::;: * - * ,,,,::;;. * - * .,,,:::;;; * - * .....,,,,...,.,,,,,,:::,,,,,,,,,,,,, * - * ,,,,,,,,,,,:,...,,,,,,:::,,,,:::;;;11l * - * .;::::::::,,,,,,,,,,:::::,,::;;;1lt * - * .;;;:::,,,,,,,,::::::;:::;;1t: * - * :;;:,,,,,,::::::;;;;;;l1 * - * ,,,,:::::::;;;;;;l * - * .,,,,::::;;;;;;;:::: * - * ,,,,,:::;;;;;::,:::1 * - * ,,,,,::;;;t1:,,:::::;l * - * .,,,,:;;ll ;::::::;;, * - * ,,,:;ll. .1:::;;l * - * .,:lt, .1;;l: * - * * - * https://github.com/bblanchon/ArduinoStreamUtils * - * * - *****************************************************/ \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/examples/StringStream/StringStream.ino b/lib/ArduinoStreamUtils/examples/StringStream/StringStream.ino deleted file mode 100644 index 89d82c86..00000000 --- a/lib/ArduinoStreamUtils/examples/StringStream/StringStream.ino +++ /dev/null @@ -1,55 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License -// -// This example shows how to use StringStream - -#include - -StringStream stream; - -void setup() { - // Initialize serial port - Serial.begin(9600); - while (!Serial) - continue; - - stream.print("Temperature = "); - stream.print(22.3); - stream.print(" °C"); -} - -void loop() { - if (stream.available() > 0) { - Serial.print((char)stream.read()); - } - delay(250); -} - -/***************************************************** - * * - * Love this project? * - * Star it on GitHub! * - * * - * .,,. * - * ,,:1. * - * ,.,:;1 * - * .,,,::;: * - * ,,,,::;;. * - * .,,,:::;;; * - * .....,,,,...,.,,,,,,:::,,,,,,,,,,,,, * - * ,,,,,,,,,,,:,...,,,,,,:::,,,,:::;;;11l * - * .;::::::::,,,,,,,,,,:::::,,::;;;1lt * - * .;;;:::,,,,,,,,::::::;:::;;1t: * - * :;;:,,,,,,::::::;;;;;;l1 * - * ,,,,:::::::;;;;;;l * - * .,,,,::::;;;;;;;:::: * - * ,,,,,:::;;;;;::,:::1 * - * ,,,,,::;;;t1:,,:::::;l * - * .,,,,:;;ll ;::::::;;, * - * ,,,:;ll. .1:::;;l * - * .,:lt, .1;;l: * - * * - * https://github.com/bblanchon/ArduinoStreamUtils * - * * - *****************************************************/ \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/examples/WriteBuffer/WriteBuffer.ino b/lib/ArduinoStreamUtils/examples/WriteBuffer/WriteBuffer.ino deleted file mode 100644 index 7e68487d..00000000 --- a/lib/ArduinoStreamUtils/examples/WriteBuffer/WriteBuffer.ino +++ /dev/null @@ -1,62 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License -// -// This example shows how to buffer writes to a stream. -// -// Like "echo," it reads from the serial port and prints back the same thing. -// What's interesting with this program is that it writes in chunks of -// 8 bytes, even if it seems to write them one by one. -// -// As you'll see, you need to type at least 8 bytes to see something. That's -// because it waits for the buffered to be full before sending it to the serial. - -#include - -// Create a new Stream that buffers all writes to Serial -WriteBufferingStream bufferedSerial{Serial, 8}; - -void setup() { - // Initialize serial port - Serial.begin(9600); - while (!Serial) - continue; - - Serial.println(F("Send at least 8 bytes to see the result")); -} - -void loop() { - // Even if it looks like the bytes are sent one by one, they are actual - // written in chunks of 8 bytes. - while (Serial.available()) { - bufferedSerial.write(Serial.read()); - } -} - -/***************************************************** - * * - * Love this project? * - * Star it on GitHub! * - * * - * .,,. * - * ,,:1. * - * ,.,:;1 * - * .,,,::;: * - * ,,,,::;;. * - * .,,,:::;;; * - * .....,,,,...,.,,,,,,:::,,,,,,,,,,,,, * - * ,,,,,,,,,,,:,...,,,,,,:::,,,,:::;;;11l * - * .;::::::::,,,,,,,,,,:::::,,::;;;1lt * - * .;;;:::,,,,,,,,::::::;:::;;1t: * - * :;;:,,,,,,::::::;;;;;;l1 * - * ,,,,:::::::;;;;;;l * - * .,,,,::::;;;;;;;:::: * - * ,,,,,:::;;;;;::,:::1 * - * ,,,,,::;;;t1:,,:::::;l * - * .,,,,:;;ll ;::::::;;, * - * ,,,:;ll. .1:::;;l * - * .,:lt, .1;;l: * - * * - * https://github.com/bblanchon/ArduinoStreamUtils * - * * - *****************************************************/ \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/examples/WriteLogger/WriteLogger.ino b/lib/ArduinoStreamUtils/examples/WriteLogger/WriteLogger.ino deleted file mode 100644 index f08e4e40..00000000 --- a/lib/ArduinoStreamUtils/examples/WriteLogger/WriteLogger.ino +++ /dev/null @@ -1,55 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License -// -// This example shows how to log what written to a Stream - -#include - -// Create a new stream that will forward all calls to Serial, and log to Serial. -// Everything will be written twice to the Serial! -WriteLoggingStream loggingStream(Serial, Serial); - -void setup() { - // Initialize serial port - Serial.begin(9600); - while (!Serial) - continue; - - // Write to the serial port. - // Because loggingStream logs each write operation, the string will we written - // twice - loggingStream.println("Hello World!"); -} - -void loop() { - // not used in this example -} - -/***************************************************** - * * - * Love this project? * - * Star it on GitHub! * - * * - * .,,. * - * ,,:1. * - * ,.,:;1 * - * .,,,::;: * - * ,,,,::;;. * - * .,,,:::;;; * - * .....,,,,...,.,,,,,,:::,,,,,,,,,,,,, * - * ,,,,,,,,,,,:,...,,,,,,:::,,,,:::;;;11l * - * .;::::::::,,,,,,,,,,:::::,,::;;;1lt * - * .;;;:::,,,,,,,,::::::;:::;;1t: * - * :;;:,,,,,,::::::;;;;;;l1 * - * ,,,,:::::::;;;;;;l * - * .,,,,::::;;;;;;;:::: * - * ,,,,,:::;;;;;::,:::1 * - * ,,,,,::;;;t1:,,:::::;l * - * .,,,,:;;ll ;::::::;;, * - * ,,,:;ll. .1:::;;l * - * .,:lt, .1;;l: * - * * - * https://github.com/bblanchon/ArduinoStreamUtils * - * * - *****************************************************/ \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/images/EepromStream.svg b/lib/ArduinoStreamUtils/extras/images/EepromStream.svg deleted file mode 100644 index efe2433e..00000000 --- a/lib/ArduinoStreamUtils/extras/images/EepromStream.svg +++ /dev/null @@ -1 +0,0 @@ -EEPROM \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/images/HammingDecodingStream.svg b/lib/ArduinoStreamUtils/extras/images/HammingDecodingStream.svg deleted file mode 100644 index 1330fde7..00000000 --- a/lib/ArduinoStreamUtils/extras/images/HammingDecodingStream.svg +++ /dev/null @@ -1 +0,0 @@ -decoratedoriginalparity bits \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/images/HammingEncodingStream.svg b/lib/ArduinoStreamUtils/extras/images/HammingEncodingStream.svg deleted file mode 100644 index a2129454..00000000 --- a/lib/ArduinoStreamUtils/extras/images/HammingEncodingStream.svg +++ /dev/null @@ -1 +0,0 @@ -decoratedoriginalparity bits \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/images/HammingStream.svg b/lib/ArduinoStreamUtils/extras/images/HammingStream.svg deleted file mode 100644 index 10471609..00000000 --- a/lib/ArduinoStreamUtils/extras/images/HammingStream.svg +++ /dev/null @@ -1 +0,0 @@ -decoratedoriginalparity bitsparity bits \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/images/Logger.svg b/lib/ArduinoStreamUtils/extras/images/Logger.svg deleted file mode 100644 index 6be65429..00000000 --- a/lib/ArduinoStreamUtils/extras/images/Logger.svg +++ /dev/null @@ -1 +0,0 @@ -decoratedoriginallog \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/images/ReadBuffer.svg b/lib/ArduinoStreamUtils/extras/images/ReadBuffer.svg deleted file mode 100644 index b0913bb7..00000000 --- a/lib/ArduinoStreamUtils/extras/images/ReadBuffer.svg +++ /dev/null @@ -1 +0,0 @@ -decoratedoriginalbuffer \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/images/ReadLogger.svg b/lib/ArduinoStreamUtils/extras/images/ReadLogger.svg deleted file mode 100644 index f7ed4bc1..00000000 --- a/lib/ArduinoStreamUtils/extras/images/ReadLogger.svg +++ /dev/null @@ -1 +0,0 @@ -decoratedoriginallog \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/images/StringPrint.svg b/lib/ArduinoStreamUtils/extras/images/StringPrint.svg deleted file mode 100644 index 345696b4..00000000 --- a/lib/ArduinoStreamUtils/extras/images/StringPrint.svg +++ /dev/null @@ -1 +0,0 @@ -String \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/images/StringStream.svg b/lib/ArduinoStreamUtils/extras/images/StringStream.svg deleted file mode 100644 index ecd0863a..00000000 --- a/lib/ArduinoStreamUtils/extras/images/StringStream.svg +++ /dev/null @@ -1 +0,0 @@ -String \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/images/WriteBuffer.svg b/lib/ArduinoStreamUtils/extras/images/WriteBuffer.svg deleted file mode 100644 index 5b25c9d7..00000000 --- a/lib/ArduinoStreamUtils/extras/images/WriteBuffer.svg +++ /dev/null @@ -1 +0,0 @@ -decoratedoriginalbuffer \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/images/WriteLogger.svg b/lib/ArduinoStreamUtils/extras/images/WriteLogger.svg deleted file mode 100644 index a5b27242..00000000 --- a/lib/ArduinoStreamUtils/extras/images/WriteLogger.svg +++ /dev/null @@ -1 +0,0 @@ -decoratedoriginallog \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/images/WriteWaitingStream.svg b/lib/ArduinoStreamUtils/extras/images/WriteWaitingStream.svg deleted file mode 100644 index ca916f70..00000000 --- a/lib/ArduinoStreamUtils/extras/images/WriteWaitingStream.svg +++ /dev/null @@ -1 +0,0 @@ -decoratedoriginalwait() \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/test/BufferingPrintTest.cpp b/lib/ArduinoStreamUtils/extras/test/BufferingPrintTest.cpp deleted file mode 100644 index b6ba96a5..00000000 --- a/lib/ArduinoStreamUtils/extras/test/BufferingPrintTest.cpp +++ /dev/null @@ -1,137 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "FailingAllocator.hpp" - -#include "StreamUtils/Prints/BufferingPrint.hpp" -#include "StreamUtils/Prints/SpyingPrint.hpp" -#include "StreamUtils/Prints/StringPrint.hpp" - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("BufferingPrint") { - StringPrint target; - - StringPrint log; - SpyingPrint spy{target, log}; - - GIVEN("capacity is 4") { - BufferingPrint bufferingPrint{spy, 4}; - - SUBCASE("flush() calls write()") { - bufferingPrint.write("ABC", 3); - bufferingPrint.flush(); - -#if STREAMUTILS_PRINT_FLUSH_EXISTS - CHECK(log.str() == - "write('ABC', 3) -> 3" - "flush()"); -#else - CHECK(log.str() == "write('ABC', 3) -> 3"); -#endif - } - - GIVEN("the buffer is empty") { - SUBCASE("write(uint8_t)") { - int n = bufferingPrint.write('A'); - - CHECK(n == 1); - CHECK(log.str() == ""); - } - - SUBCASE("write(uint8_t) should flush") { - bufferingPrint.write('A'); - bufferingPrint.write('B'); - bufferingPrint.write('C'); - bufferingPrint.write('D'); - bufferingPrint.write('E'); - - CHECK(log.str() == "write('ABCD', 4) -> 4"); - } - - SUBCASE("write(char*,3) goes in buffer") { - size_t n = bufferingPrint.write("ABC", 3); - - CHECK(n == 3); - CHECK(log.str() == ""); - } - - SUBCASE("write(char*,4) bypasses buffer") { - size_t n = bufferingPrint.write("ABCD", 4); - - CHECK(n == 4); - CHECK(log.str() == "write('ABCD', 4) -> 4"); - } - SUBCASE("write(char*,2) bypasses buffer") { - size_t n = bufferingPrint.write("ABCD", 4); - - CHECK(n == 4); - CHECK(log.str() == "write('ABCD', 4) -> 4"); - } - } - - GIVEN("one byte in the buffer") { - bufferingPrint.write('A'); - - SUBCASE("write(char*,3) goes in buffer and flush") { - size_t n = bufferingPrint.write("BCD", 3); - - CHECK(n == 3); - CHECK(log.str() == "write('ABCD', 4) -> 4"); - } - - SUBCASE("write(char*,7) bypasses") { - size_t n = bufferingPrint.write("BCDEFGH", 7); - - CHECK(n == 7); - CHECK(log.str() == - "write('ABCD', 4) -> 4" - "write('EFGH', 4) -> 4"); - } - } - } - - GIVEN("capacity is 0") { - BufferingPrint bufferingPrint{spy, 0}; - - // SUBCASE("capacity()") { - // CHECK(bufferingPrint.capacity() == 0); - // } - - SUBCASE("write(uint8_t) forwards to target") { - int n = bufferingPrint.write('X'); - - CHECK(n == 1); - CHECK(log.str() == "write('X') -> 1"); - } - - SUBCASE("write(char*,1) forwards to target") { - int n = bufferingPrint.write("A", 1); - - CHECK(n == 1); - CHECK(log.str() == "write('A', 1) -> 1"); - } - - SUBCASE("flush()") { - bufferingPrint.flush(); - -#if STREAMUTILS_PRINT_FLUSH_EXISTS - CHECK(log.str() == "flush()"); -#else - CHECK(log.str() == ""); -#endif - } - } - - SUBCASE("Destructor should flush") { - { - BufferingPrint bufferingPrint{spy, 10}; - bufferingPrint.write("ABC", 3); - } - - CHECK(log.str() == "write('ABC', 3) -> 3"); - } -} diff --git a/lib/ArduinoStreamUtils/extras/test/CMakeLists.txt b/lib/ArduinoStreamUtils/extras/test/CMakeLists.txt deleted file mode 100644 index 3f49c108..00000000 --- a/lib/ArduinoStreamUtils/extras/test/CMakeLists.txt +++ /dev/null @@ -1,104 +0,0 @@ -# StreamUtils - github.com/bblanchon/ArduinoStreamUtils -# Copyright Benoit Blanchon 2019-2021 -# MIT License - -if(CMAKE_CXX_COMPILER_ID MATCHES "(GNU|Clang)") - add_compile_options(-Wall -Wextra -Werror -Wundef) -endif() - -set(SOURCES - BufferingPrintTest.cpp - EepromStreamTest.cpp - FailingAllocator.hpp - HammingClientTest.cpp - HammingDecodingClientTest.cpp - HammingDecodingStreamTest.cpp - HammingEncodingClientTest.cpp - HammingEncodingStreamTest.cpp - HammingPrintTest.cpp - HammingStreamTest.cpp - LoggingClientTest.cpp - LoggingPrintTest.cpp - LoggingStreamTest.cpp - MemoryStreamTest.cpp - ReadBufferingClientTest.cpp - ReadBufferingStreamTest.cpp - ReadLoggingClientTest.cpp - ReadLoggingStreamTest.cpp - ReadThrottlingStreamTest.cpp - StringPrintTest.cpp - StringStreamTest.cpp - WaitingPrintTest.cpp - WriteBufferingClientTest.cpp - WriteBufferingStreamTest.cpp - WriteLoggingClientTest.cpp - WriteLoggingStreamTest.cpp - WriteWaitingClientTest.cpp - WriteWaitingStreamTest.cpp - - doctest.h - main.cpp -) - -########## AVR ########## - -add_subdirectory(cores/avr) - -add_executable(StreamUtilsTestAvr ${SOURCES}) -target_link_libraries(StreamUtilsTestAvr AvrCore) - -add_test(Avr StreamUtilsTestAvr) - -########## ESP32 ########## - -add_subdirectory(cores/esp32) - -add_executable(StreamUtilsTestEsp32 ${SOURCES}) -target_link_libraries(StreamUtilsTestEsp32 Esp32Core) - -add_test(Esp32 StreamUtilsTestEsp32) - -########## ESP8266 ########## - -add_subdirectory(cores/esp8266) - -add_executable(StreamUtilsTestEsp8266 ${SOURCES}) -target_link_libraries(StreamUtilsTestEsp8266 Esp8266Core) - -add_test(Esp8266 StreamUtilsTestEsp8266) - -########## NRF52 ########## - -add_subdirectory(cores/nrf52) - -add_executable(StreamUtilsTestNrf52 ${SOURCES}) -target_link_libraries(StreamUtilsTestNrf52 Nrf52Core) - -add_test(Nrf52 StreamUtilsTestNrf52) - -########## SAMD ########## - -add_subdirectory(cores/samd) - -add_executable(StreamUtilsTestSamd ${SOURCES}) -target_link_libraries(StreamUtilsTestSamd SamdCore) - -add_test(Samd StreamUtilsTestSamd) - -########## STM32 ########## - -add_subdirectory(cores/stm32) - -add_executable(StreamUtilsTestStm32 ${SOURCES}) -target_link_libraries(StreamUtilsTestStm32 Stm32Core) - -add_test(Stm32 StreamUtilsTestStm32) - -########## Teensy ########## - -add_subdirectory(cores/teensy) - -add_executable(StreamUtilsTestTeensy ${SOURCES}) -target_link_libraries(StreamUtilsTestTeensy TeensyCore) - -add_test(Teensy StreamUtilsTestTeensy) \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/test/EepromStreamTest.cpp b/lib/ArduinoStreamUtils/extras/test/EepromStreamTest.cpp deleted file mode 100644 index 78e943f0..00000000 --- a/lib/ArduinoStreamUtils/extras/test/EepromStreamTest.cpp +++ /dev/null @@ -1,57 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "StreamUtils/Streams/EepromStream.hpp" - -#if STREAMUTILS_ENABLE_EEPROM - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("EepromStream") { - SUBCASE("available()") { - EepromStream s(42, 84); - CHECK(s.available() == 84); - } - - SUBCASE("write(uint8_t)") { - EepromStream s(0, 2); - CHECK(s.write('a') == 1); - CHECK(s.write('b') == 1); - CHECK(s.write('c') == 0); - CHECK(s.write('d') == 0); - s.flush(); - CHECK(s.readString() == "ab"); - } - - SUBCASE("write(const uint8_t *, size_t)") { - EepromStream s(0, 5); - CHECK(s.write("abc", 3) == 3); - CHECK(s.write("def", 3) == 2); - CHECK(s.write("ghi", 3) == 0); - s.flush(); - CHECK(s.readString() == "abcde"); - } - - SUBCASE("read()") { - EepromStream s(0, 2); - s.write("ab", 2); - CHECK(s.read() == 'a'); - CHECK(s.read() == 'b'); - CHECK(s.read() == -1); - } - - SUBCASE("peek()") { - EepromStream s(0, 2); - s.write("ab", 2); - CHECK(s.peek() == 'a'); - CHECK(s.peek() == 'a'); - s.read(); - CHECK(s.peek() == 'b'); - s.read(); - CHECK(s.peek() == -1); - } -} -#endif \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/test/FailingAllocator.hpp b/lib/ArduinoStreamUtils/extras/test/FailingAllocator.hpp deleted file mode 100644 index 64debc62..00000000 --- a/lib/ArduinoStreamUtils/extras/test/FailingAllocator.hpp +++ /dev/null @@ -1,14 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include // size_t - -struct FailingAllocator { - void* allocate(size_t) { - return nullptr; - } - void deallocate(void*) {} -}; diff --git a/lib/ArduinoStreamUtils/extras/test/HammingClientTest.cpp b/lib/ArduinoStreamUtils/extras/test/HammingClientTest.cpp deleted file mode 100644 index 5182956d..00000000 --- a/lib/ArduinoStreamUtils/extras/test/HammingClientTest.cpp +++ /dev/null @@ -1,30 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "SpyingAllocator.hpp" - -#include "StreamUtils/Clients/HammingClient.hpp" -#include "StreamUtils/Clients/MemoryClient.hpp" - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("HammingClient") { - MemoryClient upstream(64); - - HammingClient<7, 4> client{upstream}; - - SUBCASE("read() decodes") { - upstream.print("Tq"); - - CHECK(client.read() == 'A'); - } - - SUBCASE("write() encodes") { - client.write('A'); - - CHECK(upstream.readString() == "Tq"); - } -} diff --git a/lib/ArduinoStreamUtils/extras/test/HammingDecodingClientTest.cpp b/lib/ArduinoStreamUtils/extras/test/HammingDecodingClientTest.cpp deleted file mode 100644 index 443bf7ae..00000000 --- a/lib/ArduinoStreamUtils/extras/test/HammingDecodingClientTest.cpp +++ /dev/null @@ -1,137 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "SpyingAllocator.hpp" - -#include "StreamUtils/Clients/HammingDecodingClient.hpp" -#include "StreamUtils/Clients/MemoryClient.hpp" -#include "StreamUtils/Clients/SpyingClient.hpp" -#include "StreamUtils/Prints/StringPrint.hpp" - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("HammingDecodingClient") { - MemoryClient upstream(64); - StringPrint log; - SpyingClient spy{upstream, log}; - SpyingAllocator allocator{log}; - - BasicHammingDecodingClient<7, 4, SpyingAllocator&> client{spy, allocator}; - - SUBCASE("read() with small buffer") { - uint8_t buffer[8]; - - SUBCASE("empty input") { - size_t result = client.read(buffer, sizeof(buffer)); - - CHECK(result == 0); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == "read(16) -> 0 [timeout]"); -#endif - } - - SUBCASE("decodes input") { - upstream.print("TqTb"); - - size_t result = client.read(buffer, sizeof(buffer)); - - CHECK(result == 2); - CHECK(std::string((char*)buffer, result) == "AB"); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == "read(16) -> 4 [timeout]"); -#endif - } - - SUBCASE("includes byte loaded by peek()") { - upstream.print("TqTb"); - client.peek(); - log.clear(); - - size_t result = client.read(buffer, sizeof(buffer)); - - CHECK(result == 2); - CHECK(std::string((char*)buffer, result) == "AB"); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == "read(15) -> 3 [timeout]"); -#endif - } - - SUBCASE("stores dangling byte") { - upstream.print("TqT"); - - size_t result = client.read(buffer, sizeof(buffer)); - - CHECK(result == 1); - CHECK(std::string((char*)buffer, result) == "A"); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == "read(16) -> 3 [timeout]"); -#endif - - log.clear(); - upstream.print("b"); - CHECK(client.peek() == 'B'); - CHECK(log.str() == "peek() -> 98"); - } - - SUBCASE("clears the byte loaded by peek") { - upstream.print("TqTb"); - client.peek(); - client.read(buffer, sizeof(buffer)); - client.peek(); - CHECK(log.str() == - "read() -> 84" - "peek() -> 113" - "read(15) -> 3 [timeout]" - "read() -> -1"); - } - } - - SUBCASE("read() with large buffer") { - uint8_t buffer[32]; - - SUBCASE("empty input") { - size_t result = client.read(buffer, sizeof(buffer)); - - CHECK(result == 0); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == - "allocate(64) -> ptr" - "read(64) -> 0 [timeout]" - "deallocate(ptr)"); -#endif - } - - SUBCASE("decodes input") { - upstream.print("TqTb"); - - size_t result = client.read(buffer, sizeof(buffer)); - - CHECK(result == 2); - CHECK(std::string((char*)buffer, result) == "AB"); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == - "allocate(64) -> ptr" - "read(64) -> 4 [timeout]" - "deallocate(ptr)"); -#endif - } - - SUBCASE("uses input buffer if allocation fails") { - upstream.print("TqTb"); - allocator.forceFail = true; - - size_t result = client.read(buffer, sizeof(buffer)); - - CHECK(result == 2); - CHECK(std::string((char*)buffer, result) == "AB"); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == - "allocate(64) -> null" - "read(32) -> 4 [timeout]"); -#endif - } - } -} diff --git a/lib/ArduinoStreamUtils/extras/test/HammingDecodingStreamTest.cpp b/lib/ArduinoStreamUtils/extras/test/HammingDecodingStreamTest.cpp deleted file mode 100644 index 0c60c0d3..00000000 --- a/lib/ArduinoStreamUtils/extras/test/HammingDecodingStreamTest.cpp +++ /dev/null @@ -1,290 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "SpyingAllocator.hpp" - -#include "StreamUtils/Prints/StringPrint.hpp" -#include "StreamUtils/Streams/HammingDecodingStream.hpp" -#include "StreamUtils/Streams/SpyingStream.hpp" -#include "StreamUtils/Streams/StringStream.hpp" - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("HammingDecodingStream") { - StringStream upstream; - StringPrint log; - SpyingStream spy{upstream, log}; - SpyingAllocator allocator{log}; - - BasicHammingDecodingStream<7, 4, SpyingAllocator&> stream{spy, allocator}; - - SUBCASE("available()") { - SUBCASE("empty input") { - CHECK(stream.available() == 0); - CHECK(log.str() == "available() -> 0"); - } - - SUBCASE("even number of bytes") { - upstream.print("ABCDEFGH"); - - CHECK(stream.available() == 4); - CHECK(log.str() == "available() -> 8"); - } - - SUBCASE("odd number of bytes") { - upstream.print("ABCDEFGHI"); - - CHECK(stream.available() == 4); - CHECK(log.str() == "available() -> 9"); - } - - SUBCASE("even number of bytes after peek") { - upstream.print("ABCDEFGH"); - stream.peek(); - log.clear(); - CHECK(stream.available() == 4); - CHECK(log.str() == "available() -> 7"); - } - - SUBCASE("odd number of bytes after peek") { - upstream.print("ABCDEFGHI"); - stream.peek(); - log.clear(); - CHECK(stream.available() == 4); - CHECK(log.str() == "available() -> 8"); - } - } - - SUBCASE("peek()") { - SUBCASE("returns -1 when empty") { - int result = stream.peek(); - - CHECK(result == -1); - CHECK(log.str() == "read() -> -1"); - } - - SUBCASE("returns -1 when only one byte in input") { - upstream.print("A"); - - int result = stream.peek(); - - CHECK(result == -1); - CHECK(log.str() == - "read() -> 65" - "peek() -> -1"); - } - - SUBCASE("returns decoded value") { - upstream.print("Tq"); - - int result = stream.peek(); - - CHECK(result == 'A'); - CHECK(log.str() == - "read() -> 84" - "peek() -> 113"); - } - - SUBCASE("doesn't call read() the second time") { - upstream.print("A"); - stream.peek(); - log.clear(); - - int result = stream.peek(); - - CHECK(result == -1); - CHECK(log.str() == "peek() -> -1"); - } - } - - SUBCASE("read()") { - SUBCASE("returns -1 if empty") { - int result = stream.read(); - - CHECK(result == -1); - CHECK(log.str() == "read() -> -1"); - } - - SUBCASE("returns -1 if only one byte in input") { - upstream.print("A"); - - int result = stream.read(); - - CHECK(result == -1); - CHECK(log.str() == - "read() -> 65" - "read() -> -1"); - } - - SUBCASE("returns decoded value if two bytes in input") { - upstream.print("Tq"); - - int result = stream.read(); - - CHECK(result == 'A'); - CHECK(log.str() == - "read() -> 84" - "read() -> 113"); - } - - SUBCASE("reuses the byte read by peek()") { - upstream.print("Tq"); - stream.peek(); - log.clear(); - - int result = stream.read(); - - CHECK(result == 'A'); - CHECK(log.str() == "read() -> 113"); - } - - SUBCASE("reuses the byte read by previous call") { - upstream.print("T"); - stream.read(); - upstream.print("q"); - log.clear(); - - int result = stream.read(); - - CHECK(result == 'A'); - CHECK(log.str() == "read() -> 113"); - } - - SUBCASE("flushes the buffered byte") { - upstream.print("TqTb"); - - CHECK(stream.read() == 'A'); - CHECK(stream.read() == 'B'); - - CHECK(log.str() == - "read() -> 84" - "read() -> 113" - "read() -> 84" - "read() -> 98"); - } - } - - SUBCASE("readBytes() with small buffer") { - char buffer[8]; - - SUBCASE("empty input") { - size_t result = stream.readBytes(buffer, sizeof(buffer)); - - CHECK(result == 0); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == "readBytes(16) -> 0 [timeout]"); -#endif - } - - SUBCASE("decodes input") { - upstream.print("TqTb"); - - size_t result = stream.readBytes(buffer, sizeof(buffer)); - - CHECK(result == 2); - CHECK(std::string(buffer, result) == "AB"); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == "readBytes(16) -> 4 [timeout]"); -#endif - } - - SUBCASE("includes byte loaded by peek()") { - upstream.print("TqTb"); - stream.peek(); - log.clear(); - - size_t result = stream.readBytes(buffer, sizeof(buffer)); - - CHECK(result == 2); - CHECK(std::string(buffer, result) == "AB"); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == "readBytes(15) -> 3 [timeout]"); -#endif - } - - SUBCASE("stores dangling byte") { - upstream.print("TqT"); - - size_t result = stream.readBytes(buffer, sizeof(buffer)); - - CHECK(result == 1); - CHECK(std::string(buffer, result) == "A"); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == "readBytes(16) -> 3 [timeout]"); -#endif - - log.clear(); - upstream.print("b"); - CHECK(stream.peek() == 'B'); - CHECK(log.str() == "peek() -> 98"); - } - - SUBCASE("clears the byte loaded by peek") { - upstream.print("TqTb"); - stream.peek(); - stream.readBytes(buffer, sizeof(buffer)); - CHECK(stream.peek() == -1); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == - "read() -> 84" - "peek() -> 113" - "readBytes(15) -> 3 [timeout]" - "read() -> -1"); -#endif - } - } - - SUBCASE("readBytes() with large buffer") { - char buffer[32]; - - SUBCASE("empty input") { - size_t result = stream.readBytes(buffer, sizeof(buffer)); - - CHECK(result == 0); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == - "allocate(64) -> ptr" - "readBytes(64) -> 0 [timeout]" - "deallocate(ptr)"); -#endif - } - - SUBCASE("decodes input") { - upstream.print("TqTb"); - - size_t result = stream.readBytes(buffer, sizeof(buffer)); - - CHECK(result == 2); - CHECK(std::string(buffer, result) == "AB"); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == - "allocate(64) -> ptr" - "readBytes(64) -> 4 [timeout]" - "deallocate(ptr)"); -#endif - } - - SUBCASE("uses input buffer if allocation fails") { - upstream.print("TqTb"); - allocator.forceFail = true; - - size_t result = stream.readBytes(buffer, sizeof(buffer)); - - CHECK(result == 2); - CHECK(std::string(buffer, result) == "AB"); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == - "allocate(64) -> null" - "readBytes(32) -> 4 [timeout]"); -#endif - } - } - - SUBCASE("flush()") { - stream.flush(); - CHECK(log.str() == "flush()"); - } -} diff --git a/lib/ArduinoStreamUtils/extras/test/HammingEncodingClientTest.cpp b/lib/ArduinoStreamUtils/extras/test/HammingEncodingClientTest.cpp deleted file mode 100644 index 1356d161..00000000 --- a/lib/ArduinoStreamUtils/extras/test/HammingEncodingClientTest.cpp +++ /dev/null @@ -1,30 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "SpyingAllocator.hpp" - -#include "StreamUtils/Clients/HammingEncodingClient.hpp" -#include "StreamUtils/Clients/MemoryClient.hpp" - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("HammingEncodingClient") { - MemoryClient upstream(64); - - HammingEncodingClient<7, 4> client{upstream}; - - SUBCASE("read() forwards upstream data") { - upstream.print("A"); - - CHECK(client.read() == 'A'); - } - - SUBCASE("write() encodes") { - client.write('A'); - - CHECK(upstream.readString() == "Tq"); - } -} diff --git a/lib/ArduinoStreamUtils/extras/test/HammingEncodingStreamTest.cpp b/lib/ArduinoStreamUtils/extras/test/HammingEncodingStreamTest.cpp deleted file mode 100644 index faa51dce..00000000 --- a/lib/ArduinoStreamUtils/extras/test/HammingEncodingStreamTest.cpp +++ /dev/null @@ -1,30 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "SpyingAllocator.hpp" - -#include "StreamUtils/Streams/HammingEncodingStream.hpp" -#include "StreamUtils/Streams/MemoryStream.hpp" - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("HammingEncodingStream") { - MemoryStream upstream(64); - - HammingEncodingStream<7, 4> stream{upstream}; - - SUBCASE("read() forwards upstream data") { - upstream.print("A"); - - CHECK(stream.read() == 'A'); - } - - SUBCASE("write() encodes") { - stream.write('A'); - - CHECK(upstream.readString() == "Tq"); - } -} diff --git a/lib/ArduinoStreamUtils/extras/test/HammingPrintTest.cpp b/lib/ArduinoStreamUtils/extras/test/HammingPrintTest.cpp deleted file mode 100644 index 42d7556d..00000000 --- a/lib/ArduinoStreamUtils/extras/test/HammingPrintTest.cpp +++ /dev/null @@ -1,202 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "SpyingAllocator.hpp" - -#include "StreamUtils/Prints/HammingPrint.hpp" -#include "StreamUtils/Prints/SpyingPrint.hpp" -#include "StreamUtils/Prints/StringPrint.hpp" -#include "StreamUtils/Streams/MemoryStream.hpp" - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("HammingPrint") { - MemoryStream upstream(4); - - StringPrint log; - SpyingPrint spy{upstream, log}; - SpyingAllocator allocator{log}; - - BasicHammingPrint<7, 4, SpyingAllocator&> print{spy, allocator}; - - SUBCASE("write(char*, size_t)") { - SUBCASE("stops if even byte fails") { - CHECK(print.print("ABA") == 2); - print.write('A'); // try to flush remainder - - CHECK(log.str() == - "write('TqTbTq', 6) -> 4" - "write('T') -> 0" // no remainder - ); - } - - SUBCASE("saves remainder if odd byte fails") { - upstream.print("?"); - - CHECK(print.print("ABA") == 2); - print.write('A'); // try to flush remainder - - CHECK(log.str() == - "write('TqTbTq', 6) -> 3" - "write('b') -> 0" // remainder!! - ); - } - - SUBCASE("writes remainder first") { - upstream.print("???"); - print.write('A'); // add remainder - log.clear(); - upstream.readString(); - - CHECK(print.print("ABA") == 2); - - CHECK(log.str() == - "write('q') -> 1" - "write('TqTbTq', 6) -> 3"); - } - - SUBCASE("stops if remainder fails") { - upstream.print("???"); - print.write('A'); // add remainder - log.clear(); - - CHECK(print.print("ABA") == 0); - - CHECK(log.str() == "write('q') -> 0"); - } - - SUBCASE("allocates in stack when buffer is small") { - print.write("ABABABABABABABAB", 16); - - CHECK(log.str() == "write('TqTbTqTbTqTbTqTbTqTbTqTbTqTbTqTb', 32) -> 4"); - } - - SUBCASE("allocates in heap when buffer is large") { - print.write("ABABABABABABABABA", 17); - - CHECK(log.str() == - "allocate(34) -> ptr" - "write('TqTbTqTbTqTbTqTbTqTbTqTbTqTbTqTbTq', 34) -> 4" - "deallocate(ptr)"); - } - - SUBCASE("falls back to stack if heap fails") { - allocator.forceFail = true; - print.write("ABABABABABABABABA", 17); - - CHECK(log.str() == - "allocate(34) -> null" - "write('TqTbTqTbTqTbTqTbTqTbTqTbTqTbTqTb', 32) -> 4"); - } - } - - SUBCASE("write(char)") { - SUBCASE("writes both bytes") { - CHECK(print.write('A') == 1); - - CHECK(upstream.readString() == "Tq"); - CHECK(log.str() == - "write('T') -> 1" - "write('q') -> 1"); - } - - SUBCASE("stops if first by fails") { - upstream.print("????"); - - CHECK(print.write('A') == 0); - print.write('A'); // try to flush remainder - - CHECK(log.str() == - "write('T') -> 0" - "write('T') -> 0" // no remainder - ); - } - - SUBCASE("saves remainder if second by fails") { - upstream.print("???"); - - CHECK(print.write('A') == 1); - print.write('A'); // try to flush remainder - - CHECK(log.str() == - "write('T') -> 1" - "write('q') -> 0" - "write('q') -> 0" // remainder!! - ); - } - - SUBCASE("writes remainder first") { - upstream.print("???"); - print.write('A'); // add remainder - log.clear(); - upstream.readString(); - - CHECK(print.write('A') == 1); - - CHECK(log.str() == - "write('q') -> 1" - "write('T') -> 1" - "write('q') -> 1"); - } - - SUBCASE("stops if remainder fails") { - upstream.print("???"); - print.write('A'); // add remainder - log.clear(); - - CHECK(print.write('A') == 0); - print.write('A'); // try to flush remainder - - CHECK(log.str() == - "write('q') -> 0" - "write('q') -> 0" // remainder!! - ); - } - - SUBCASE("resets remainder") { - upstream.print("???"); - print.write('A'); // add remainder - log.clear(); - upstream.read(); - - CHECK(print.write('A') == 0); - print.write('A'); // try to flush remainder - - CHECK(log.str() == - "write('q') -> 1" - "write('T') -> 0" - "write('T') -> 0" // no remainder - ); - } - } - -#if STREAMUTILS_PRINT_FLUSH_EXISTS - SUBCASE("flush() writes remainder") { - upstream.print("???"); - print.write('A'); // add remainder - log.clear(); - upstream.read(); - - print.flush(); - - CHECK(log.str() == - "write('q') -> 1" - "flush()" // no remainder - ); - } -#endif - - SUBCASE("destructor flushes remainder") { - { - BasicHammingPrint<7, 4, SpyingAllocator&> print{spy, allocator}; - upstream.print("???"); - print.write('A'); // add remainder - log.clear(); - } - - CHECK(log.str() == "write('q') -> 0"); - } -} diff --git a/lib/ArduinoStreamUtils/extras/test/HammingStreamTest.cpp b/lib/ArduinoStreamUtils/extras/test/HammingStreamTest.cpp deleted file mode 100644 index 551f5fc8..00000000 --- a/lib/ArduinoStreamUtils/extras/test/HammingStreamTest.cpp +++ /dev/null @@ -1,30 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "SpyingAllocator.hpp" - -#include "StreamUtils/Streams/HammingStream.hpp" -#include "StreamUtils/Streams/MemoryStream.hpp" - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("HammingStream") { - MemoryStream upstream(64); - - HammingStream<7, 4> stream{upstream}; - - SUBCASE("read() decodes") { - upstream.print("Tq"); - - CHECK(stream.read() == 'A'); - } - - SUBCASE("write() encodes") { - stream.write('A'); - - CHECK(upstream.readString() == "Tq"); - } -} diff --git a/lib/ArduinoStreamUtils/extras/test/LoggingClientTest.cpp b/lib/ArduinoStreamUtils/extras/test/LoggingClientTest.cpp deleted file mode 100644 index f457abea..00000000 --- a/lib/ArduinoStreamUtils/extras/test/LoggingClientTest.cpp +++ /dev/null @@ -1,138 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "StreamUtils/Clients/LoggingClient.hpp" -#include "StreamUtils/Clients/MemoryClient.hpp" -#include "StreamUtils/Clients/SpyingClient.hpp" -#include "StreamUtils/Prints/StringPrint.hpp" - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("LoggingClient") { - MemoryClient target(4); - - StringPrint log; - SpyingClient spy{target, log}; - - StringPrint output; - LoggingClient loggingClient{spy, output}; - - SUBCASE("available()") { - target.print("ABC"); - - size_t n = loggingClient.available(); - - CHECK(n == 3); - CHECK(log.str() == "available() -> 3"); - CHECK(output.str() == ""); - } - - SUBCASE("connect(IPAddress)") { - int n = loggingClient.connect(IPAddress("1.2.3.4"), 80); - - CHECK(n == 1); - CHECK(log.str() == "connect('1.2.3.4', 80) -> 1"); - CHECK(output.str() == ""); - } - - SUBCASE("connect(const char*)") { - int n = loggingClient.connect("1.2.3.4", 80); - - CHECK(n == 1); - CHECK(log.str() == "connect('1.2.3.4', 80) -> 1"); - CHECK(output.str() == ""); - } - - SUBCASE("connected()") { - uint8_t n = loggingClient.connected(); - - CHECK(n == false); - CHECK(log.str() == "connected() -> 0"); - CHECK(output.str() == ""); - } - - SUBCASE("stop()") { - loggingClient.stop(); - - CHECK(log.str() == "stop()"); - CHECK(output.str() == ""); - } - - SUBCASE("operator bool()") { - bool n = loggingClient.operator bool(); - - CHECK(n == true); - CHECK(log.str() == "operator bool() -> true"); - CHECK(output.str() == ""); - } - - SUBCASE("peek()") { - target.print("ABC"); - - int n = loggingClient.peek(); - - CHECK(n == 'A'); - CHECK(log.str() == "peek() -> 65"); - CHECK(output.str() == ""); - } - - SUBCASE("read()") { - target.print("ABC"); - - int n = loggingClient.read(); - - CHECK(n == 'A'); - CHECK(log.str() == "read() -> 65"); - CHECK(output.str() == "A"); - } - - SUBCASE("read(uint8_t*,size_t)") { - target.print("ABC"); - - uint8_t s[4] = {0}; - size_t n = loggingClient.read(s, 4); - - CHECK(n == 3); - CHECK(log.str() == "read(4) -> 3 [timeout]"); - CHECK(output.str() == "ABC"); - } - - SUBCASE("readBytes()") { - target.print("ABC"); - - char s[4] = {0}; - size_t n = loggingClient.readBytes(s, 4); - - CHECK(n == 3); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == "readBytes(4) -> 3 [timeout]"); -#endif - CHECK(output.str() == "ABC"); - } - - SUBCASE("write(char)") { - int n = loggingClient.write('A'); - - CHECK(n == 1); - CHECK(log.str() == "write('A') -> 1"); - CHECK(output.str() == "A"); - } - - SUBCASE("write(char*,size_t)") { - int n = loggingClient.write("ABCDEF", 6); - - CHECK(n == 4); - CHECK(log.str() == "write('ABCDEF', 6) -> 4"); - CHECK(output.str() == "ABCD"); - } - - SUBCASE("flush()") { - loggingClient.flush(); - - CHECK(output.str() == ""); - CHECK(log.str() == "flush()"); - } -} diff --git a/lib/ArduinoStreamUtils/extras/test/LoggingPrintTest.cpp b/lib/ArduinoStreamUtils/extras/test/LoggingPrintTest.cpp deleted file mode 100644 index ca20c483..00000000 --- a/lib/ArduinoStreamUtils/extras/test/LoggingPrintTest.cpp +++ /dev/null @@ -1,41 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "StreamUtils/Prints/LoggingPrint.hpp" -#include "StreamUtils/Streams/MemoryStream.hpp" - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("LoggingPrint") { - MemoryStream primary(4); - MemoryStream secondary(64); - LoggingPrint loggingPrint{primary, secondary}; - - SUBCASE("write(char)") { - int n = loggingPrint.write('A'); - - CHECK(n == 1); - CHECK(primary.readString() == "A"); - CHECK(secondary.readString() == "A"); - } - - SUBCASE("write(char*,size_t)") { - int n = loggingPrint.write("ABCDEF", 6); - - CHECK(n == 4); - CHECK(primary.readString() == "ABCD"); - CHECK(secondary.readString() == "ABCD"); - } - -#if STREAMUTILS_PRINT_FLUSH_EXISTS - SUBCASE("flush()") { - loggingPrint.write("AB", 2); - REQUIRE(primary.available() == 2); - loggingPrint.flush(); - REQUIRE(primary.available() == 0); - } -#endif -} diff --git a/lib/ArduinoStreamUtils/extras/test/LoggingStreamTest.cpp b/lib/ArduinoStreamUtils/extras/test/LoggingStreamTest.cpp deleted file mode 100644 index aab8537b..00000000 --- a/lib/ArduinoStreamUtils/extras/test/LoggingStreamTest.cpp +++ /dev/null @@ -1,93 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "StreamUtils/Prints/StringPrint.hpp" -#include "StreamUtils/Streams/LoggingStream.hpp" -#include "StreamUtils/Streams/MemoryStream.hpp" -#include "StreamUtils/Streams/SpyingStream.hpp" - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("LoggingStream") { - MemoryStream upstream{4}; - StringPrint output; - - StringPrint log; - SpyingStream upstreamSpy{upstream, log}; - - LoggingStream loggingStream{upstreamSpy, output}; - - // upstream -> upstreamSpy -> loggingStream -> output - // | - // v - // log - - SUBCASE("available()") { - upstream.print("ABC"); - - size_t n = loggingStream.available(); - - CHECK(n == 3); - CHECK(log.str() == "available() -> 3"); - CHECK(output.str() == ""); - } - - SUBCASE("peek()") { - upstream.print("ABC"); - - int n = loggingStream.peek(); - - CHECK(n == 'A'); - CHECK(log.str() == "peek() -> 65"); - CHECK(output.str() == ""); - } - - SUBCASE("read()") { - upstream.print("ABC"); - - int n = loggingStream.read(); - - CHECK(n == 'A'); - CHECK(log.str() == "read() -> 65"); - CHECK(output.str() == "A"); - } - - SUBCASE("readBytes()") { - upstream.print("ABC"); - - char s[4] = {0}; - size_t n = loggingStream.readBytes(s, 4); - - CHECK(n == 3); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == "readBytes(4) -> 3 [timeout]"); -#endif - CHECK(output.str() == "ABC"); - } - - SUBCASE("write(char)") { - int n = loggingStream.write('A'); - - CHECK(n == 1); - CHECK(log.str() == "write('A') -> 1"); - CHECK(output.str() == "A"); - } - - SUBCASE("write(char*,size_t)") { - int n = loggingStream.write("ABCDEF", 6); - - CHECK(n == 4); - CHECK(log.str() == "write('ABCDEF', 6) -> 4"); - CHECK(output.str() == "ABCD"); - } - - SUBCASE("flush()") { - loggingStream.flush(); - - CHECK(log.str() == "flush()"); - CHECK(output.str() == ""); - } -} diff --git a/lib/ArduinoStreamUtils/extras/test/MemoryStreamTest.cpp b/lib/ArduinoStreamUtils/extras/test/MemoryStreamTest.cpp deleted file mode 100644 index a649d1fc..00000000 --- a/lib/ArduinoStreamUtils/extras/test/MemoryStreamTest.cpp +++ /dev/null @@ -1,116 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "StreamUtils/Streams/MemoryStream.hpp" -#include "StreamUtils/Streams/SpyingStream.hpp" - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("MemoryStream") { - MemoryStream stream(4); - - WHEN("stream is empty") { - THEN("available() return 0") { - CHECK(stream.available() == 0); - } - - THEN("write(uint8) returns 1") { - CHECK(stream.write('A') == 1); - } - - THEN("write(\"ABCD\",4) returns 4") { - CHECK(stream.write("ABCD", 4) == 4); - } - - THEN("write(uint8*,8) returns 4") { - CHECK(stream.write("ABCDEFGH", 8) == 4); - } - - THEN("read() return -1") { - CHECK(stream.read() == -1); - } - - THEN("peek() return -1") { - CHECK(stream.peek() == -1); - } - } - - WHEN("stream is full") { - stream.print("ABCD"); - - THEN("available() return 4") { - CHECK(stream.available() == 4); - } - - THEN("write(uint8) returns 0") { - CHECK(stream.write('A') == 0); - } - - THEN("write(\"ABCD\",4) returns 0") { - CHECK(stream.write("ABCD", 4) == 0); - } - - THEN("read() returns the next value") { - CHECK(stream.read() == 'A'); - CHECK(stream.read() == 'B'); - } - - THEN("read(uint8_t*,size_t) extracts the next bytes") { - char data[5] = {0}; - CHECK(stream.readBytes(data, 4) == 4); - CHECK(data == std::string("ABCD")); - } - - THEN("peek() returns the first value") { - CHECK(stream.peek() == 'A'); - CHECK(stream.peek() == 'A'); - } - - SUBCASE("read() makes room for one byte") { - stream.read(); // make room - REQUIRE(stream.available() == 3); - - stream.write('E'); // write at the beginning - REQUIRE(stream.available() == 4); - - char data[5] = {0}; - stream.readBytes(data, 4); - CHECK(data == std::string("BCDE")); - } - } - - WHEN("lower half is filled") { - stream.print("AB"); - - THEN("available() return 2") { - CHECK(stream.available() == 2); - } - - THEN("write(uint8) returns 1") { - CHECK(stream.write('C') == 1); - } - - THEN("write(\"ABCD\",4) returns 2") { - CHECK(stream.write("ABCD", 4) == 2); - } - - THEN("read() returns the next value") { - CHECK(stream.read() == 'A'); - CHECK(stream.read() == 'B'); - } - - THEN("read(uint8_t*,size_t) extracts the next bytes") { - char data[5] = {0}; - CHECK(stream.readBytes(data, 4) == 2); - CHECK(data == std::string("AB")); - } - - THEN("peek() returns the first value") { - CHECK(stream.peek() == 'A'); - CHECK(stream.peek() == 'A'); - } - } -} diff --git a/lib/ArduinoStreamUtils/extras/test/ReadBufferingClientTest.cpp b/lib/ArduinoStreamUtils/extras/test/ReadBufferingClientTest.cpp deleted file mode 100644 index 37d965ba..00000000 --- a/lib/ArduinoStreamUtils/extras/test/ReadBufferingClientTest.cpp +++ /dev/null @@ -1,337 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "FailingAllocator.hpp" - -#include "StreamUtils/Clients/MemoryClient.hpp" -#include "StreamUtils/Clients/ReadBufferingClient.hpp" -#include "StreamUtils/Clients/SpyingClient.hpp" -#include "StreamUtils/Prints/StringPrint.hpp" - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("ReadBufferingClient") { - MemoryClient target(64); - StringPrint log; - SpyingClient spy{target, log}; - - SUBCASE("capacity = 4") { - ReadBufferingClient bufferedClient{spy, 4}; - Client& client = bufferedClient; - - SUBCASE("available()") { - target.print("ABCDEFGH"); - - SUBCASE("empty input") { - target.flush(); - CHECK(client.available() == 0); - CHECK(log.str() == "available() -> 0"); - } - - SUBCASE("read empty input") { - target.flush(); - - client.read(); - - CHECK(client.available() == 0); - CHECK(log.str() == - "available() -> 0" - "read() -> -1" - "available() -> 0"); - } - - SUBCASE("same a target") { - CHECK(client.available() == 8); - CHECK(log.str() == "available() -> 8"); - } - - SUBCASE("target + in buffer") { - client.read(); - - CHECK(client.available() == 7); - CHECK(log.str() == - "available() -> 8" - "read(4) -> 4" - "available() -> 4"); - } - } - - SUBCASE("peek()") { - SUBCASE("returns -1 when empty") { - target.flush(); - - int result = client.peek(); - - CHECK(result == -1); - CHECK(log.str() == "peek() -> -1"); - } - - SUBCASE("doesn't call readBytes() when buffer is empty") { - target.print("A"); - - int result = client.peek(); - - CHECK(result == 'A'); - CHECK(log.str() == "peek() -> 65"); - } - - SUBCASE("doesn't call peek() when buffer is full") { - target.print("AB"); - - client.read(); - int result = client.peek(); - - CHECK(result == 'B'); - CHECK(log.str() == - "available() -> 2" - "read(2) -> 2"); - } - } - - SUBCASE("read()") { - SUBCASE("reads 4 bytes at a time") { - target.print("ABCDEFG"); - std::string result; - - for (int i = 0; i < 7; i++) { - result += (char)client.read(); - } - - CHECK(result == "ABCDEFG"); - CHECK(log.str() == - "available() -> 7" - "read(4) -> 4" - "available() -> 3" - "read(3) -> 3"); - } - - SUBCASE("returns -1 when empty") { - target.flush(); - - int result = client.read(); - - CHECK(result == -1); - CHECK(log.str() == - "available() -> 0" - "read() -> -1"); - } - } - - SUBCASE("read()") { - SUBCASE("empty input") { - target.flush(); - - char c; - size_t result = client.readBytes(&c, 1); - - CHECK(result == 0); - -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == - "available() -> 0" - "readBytes(1) -> 0 [timeout]"); -#else - CHECK(log.str() == - "available() -> 0" - "read() -> -1"); // [timeout] from timedRead() -#endif - } - - SUBCASE("reads 4 bytes when requested one") { - target.print("ABCDEFG"); - - char c; - size_t result = client.readBytes(&c, 1); - - CHECK(c == 'A'); - CHECK(result == 1); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == - "available() -> 7" - "readBytes(4) -> 4"); -#else - CHECK(log.str() == - "available() -> 7" - "read(4) -> 4"); -#endif - } - - SUBCASE("copy one byte from buffer") { - target.print("ABCDEFGH"); - client.read(); // load buffer - - char c; - size_t result = client.readBytes(&c, 1); - - CHECK(c == 'B'); - CHECK(result == 1); - CHECK(log.str() == - "available() -> 8" - "read(4) -> 4"); - } - - SUBCASE("copy content from buffer then bypass buffer") { - target.print("ABCDEFGH"); - client.read(); // load buffer - - char c[8] = {0}; - size_t result = client.readBytes(c, 7); - - CHECK(c == std::string("BCDEFGH")); - CHECK(result == 7); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == - "available() -> 8" - "read(4) -> 4" - "available() -> 4" - "readBytes(4) -> 4"); -#else - CHECK(log.str() == - "available() -> 8" - "read(4) -> 4" - "available() -> 4" - "read(4) -> 4"); -#endif - } - - SUBCASE("copy content from buffer twice") { - target.print("ABCDEFGH"); - client.read(); // load buffer - - char c[8] = {0}; - size_t result = client.readBytes(c, 4); - - CHECK(c == std::string("BCDE")); - CHECK(result == 4); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == - "available() -> 8" - "read(4) -> 4" - "available() -> 4" - "readBytes(4) -> 4"); -#else - CHECK(log.str() == - "available() -> 8" - "read(4) -> 4" - "available() -> 4" - "read(4) -> 4"); -#endif - } - - SUBCASE("read past the end") { - target.print("A"); - - char c; - client.readBytes(&c, 1); - size_t result = client.readBytes(&c, 1); - - CHECK(result == 0); - -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == - "available() -> 1" - "readBytes(1) -> 1" - "available() -> 0" - "readBytes(1) -> 0 [timeout]"); -#else - CHECK(log.str() == - "available() -> 1" - "read() -> 65" - "available() -> 0" - "read() -> -1"); // [timeout] from timedRead() -#endif - } - } - - SUBCASE("flush()") { - client.flush(); - CHECK(log.str() == "flush()"); - } - - SUBCASE("copy constructor") { - target.print("ABCDEFGH"); - bufferedClient.read(); - - auto dup = bufferedClient; - - int result = dup.read(); - - CHECK(result == 'B'); - CHECK(log.str() == - "available() -> 8" - "read(4) -> 4"); - } - } - - SUBCASE("No memory") { - BasicReadBufferingClient client(spy, 4); - - SUBCASE("available()") { - target.print("ABC"); - - CHECK(client.available() == 3); - } - - // SUBCASE("capacity()") { - // CHECK(client.capacity() == 0); - // } - - SUBCASE("peek()") { - target.print("ABC"); - - int c = client.peek(); - - CHECK(c == 'A'); - CHECK(log.str() == "peek() -> 65"); - } - - SUBCASE("read()") { - target.print("ABC"); - - int c = client.read(); - - CHECK(c == 'A'); - CHECK(log.str() == "read() -> 65"); - } - - SUBCASE("readBytes()") { - target.print("ABC"); - - char s[4] = {0}; - int n = client.readBytes(s, 3); - - CHECK(n == 3); - CHECK(s == std::string("ABC")); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == "readBytes(3) -> 3"); -#endif - } - } - - SUBCASE("Real example") { - ReadBufferingClient bufferedClient{spy, 64}; - Client& client = bufferedClient; - - target.print("{\"helloWorld\":\"Hello World\"}"); - - char c[] = "ABCDEFGH"; - CHECK(client.readBytes(&c[0], 1) == 1); - CHECK(client.readBytes(&c[1], 1) == 1); - CHECK(client.readBytes(&c[2], 1) == 1); - CHECK(client.readBytes(&c[3], 1) == 1); - - CHECK(c == std::string("{\"heEFGH")); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == - "available() -> 28" - "readBytes(28) -> 28"); -#else - CHECK(log.str() == - "available() -> 28" - "read(28) -> 28"); -#endif - } -} diff --git a/lib/ArduinoStreamUtils/extras/test/ReadBufferingStreamTest.cpp b/lib/ArduinoStreamUtils/extras/test/ReadBufferingStreamTest.cpp deleted file mode 100644 index bbc13b73..00000000 --- a/lib/ArduinoStreamUtils/extras/test/ReadBufferingStreamTest.cpp +++ /dev/null @@ -1,318 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "FailingAllocator.hpp" - -#include "StreamUtils/Prints/StringPrint.hpp" -#include "StreamUtils/Streams/ReadBufferingStream.hpp" -#include "StreamUtils/Streams/SpyingStream.hpp" -#include "StreamUtils/Streams/StringStream.hpp" - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("ReadBufferingStream") { - StringStream upstream; - StringPrint log; - SpyingStream spy{upstream, log}; - - SUBCASE("capacity = 4") { - ReadBufferingStream bufferedStream{spy, 4}; - Stream& stream = bufferedStream; - - SUBCASE("available()") { - SUBCASE("empty input") { - CHECK(stream.available() == 0); - CHECK(log.str() == "available() -> 0"); - } - - SUBCASE("read empty input") { - int n = stream.read(); - - CHECK(n == -1); - CHECK(stream.available() == 0); - CHECK(log.str() == - "available() -> 0" - "read() -> -1" - "available() -> 0"); - } - - SUBCASE("same a upstream") { - upstream.print("ABCDEFGH"); - - CHECK(stream.available() == 8); - CHECK(log.str() == "available() -> 8"); - } - - SUBCASE("upstream + in buffer") { - upstream.print("ABCDEFGH"); - - int n = stream.read(); - - CHECK(n == 'A'); - CHECK(stream.available() == 7); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == - "available() -> 8" - "readBytes(4) -> 4" - "available() -> 4"); -#endif - } - } - - SUBCASE("peek()") { - SUBCASE("returns -1 when empty") { - upstream.flush(); - - int result = stream.peek(); - - CHECK(result == -1); - CHECK(log.str() == "peek() -> -1"); - } - - SUBCASE("doesn't call readBytes() when buffer is empty") { - upstream.print("A"); - - int result = stream.peek(); - - CHECK(result == 'A'); - CHECK(log.str() == "peek() -> 65"); - } - - SUBCASE("doesn't call peek() when buffer is full") { - upstream.print("AB"); - - stream.read(); - int result = stream.peek(); - - CHECK(result == 'B'); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == - "available() -> 2" - "readBytes(2) -> 2"); -#endif - } - } - - SUBCASE("read()") { - SUBCASE("reads 4 bytes at a time") { - upstream.print("ABCDEFG"); - std::string result; - - for (int i = 0; i < 7; i++) { - result += (char)stream.read(); - } - - CHECK(result == "ABCDEFG"); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == - "available() -> 7" - "readBytes(4) -> 4" - "available() -> 3" - "readBytes(3) -> 3"); -#endif - } - - SUBCASE("returns -1 when empty") { - upstream.flush(); - - int result = stream.read(); - - CHECK(result == -1); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == - "available() -> 0" - "read() -> -1"); -#endif - } - } - - SUBCASE("readBytes()") { - SUBCASE("empty input") { - upstream.flush(); - - char c; - size_t result = stream.readBytes(&c, 1); - - CHECK(result == 0); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == - "available() -> 0" - "readBytes(1) -> 0 [timeout]"); -#endif - } - - SUBCASE("reads 4 bytes when requested one") { - upstream.print("ABCDEFG"); - - char c; - size_t result = stream.readBytes(&c, 1); - - CHECK(c == 'A'); - CHECK(result == 1); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == - "available() -> 7" - "readBytes(4) -> 4"); -#endif - } - - SUBCASE("copy one byte from buffer") { - upstream.print("ABCDEFGH"); - stream.read(); // load buffer - - char c; - size_t result = stream.readBytes(&c, 1); - - CHECK(c == 'B'); - CHECK(result == 1); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == - "available() -> 8" - "readBytes(4) -> 4"); -#endif - } - - SUBCASE("copy content from buffer then bypass buffer") { - upstream.print("ABCDEFGH"); - stream.read(); // load buffer - - char c[8] = {0}; - size_t result = stream.readBytes(c, 7); - - CHECK(c == std::string("BCDEFGH")); - CHECK(result == 7); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == - "available() -> 8" - "readBytes(4) -> 4" - "available() -> 4" - "readBytes(4) -> 4"); -#endif - } - - SUBCASE("copy content from buffer twice") { - upstream.print("ABCDEFGH"); - stream.read(); // load buffer - - char c[8] = {0}; - size_t result = stream.readBytes(c, 4); - - CHECK(c == std::string("BCDE")); - CHECK(result == 4); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == - "available() -> 8" - "readBytes(4) -> 4" - "available() -> 4" - "readBytes(4) -> 4"); -#endif - } - - SUBCASE("read past the end") { - upstream.print("A"); - - char c; - stream.readBytes(&c, 1); - size_t result = stream.readBytes(&c, 1); - - CHECK(result == 0); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == - "available() -> 1" - "readBytes(1) -> 1" - "available() -> 0" - "readBytes(1) -> 0 [timeout]"); -#endif - } - } - - SUBCASE("flush()") { - stream.flush(); - CHECK(log.str() == "flush()"); - } - - SUBCASE("copy constructor") { - upstream.print("ABCDEFGH"); - bufferedStream.read(); - - auto dup = bufferedStream; - - int result = dup.read(); - - CHECK(result == 'B'); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == - "available() -> 8" - "readBytes(4) -> 4"); -#endif - } - } - - SUBCASE("No memory") { - BasicReadBufferingStream stream(spy, 4); - - SUBCASE("available()") { - upstream.print("ABC"); - - CHECK(stream.available() == 3); - } - - // SUBCASE("capacity()") { - // CHECK(stream.capacity() == 0); - // } - - SUBCASE("peek()") { - upstream.print("ABC"); - - int c = stream.peek(); - - CHECK(c == 'A'); - CHECK(log.str() == "peek() -> 65"); - } - - SUBCASE("read()") { - upstream.print("ABC"); - - int c = stream.read(); - - CHECK(c == 'A'); - CHECK(log.str() == "read() -> 65"); - } - - SUBCASE("readBytes()") { - upstream.print("ABC"); - - char s[4] = {0}; - int n = stream.readBytes(s, 3); - - CHECK(n == 3); - CHECK(s == std::string("ABC")); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == "readBytes(3) -> 3"); -#endif - } - } - - SUBCASE("Real example") { - ReadBufferingStream bufferedStream{spy, 64}; - Stream& stream = bufferedStream; - - upstream.print("{\"helloWorld\":\"Hello World\"}"); - - char c[] = "ABCDEFGH"; - CHECK(stream.readBytes(&c[0], 1) == 1); - CHECK(stream.readBytes(&c[1], 1) == 1); - CHECK(stream.readBytes(&c[2], 1) == 1); - CHECK(stream.readBytes(&c[3], 1) == 1); - - CHECK(c == std::string("{\"heEFGH")); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == - "available() -> 28" - "readBytes(28) -> 28"); -#endif - } -} diff --git a/lib/ArduinoStreamUtils/extras/test/ReadLoggingClientTest.cpp b/lib/ArduinoStreamUtils/extras/test/ReadLoggingClientTest.cpp deleted file mode 100644 index bbd0128a..00000000 --- a/lib/ArduinoStreamUtils/extras/test/ReadLoggingClientTest.cpp +++ /dev/null @@ -1,139 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "FailingAllocator.hpp" - -#include "StreamUtils/Clients/MemoryClient.hpp" -#include "StreamUtils/Clients/ReadLoggingClient.hpp" -#include "StreamUtils/Clients/SpyingClient.hpp" -#include "StreamUtils/Prints/StringPrint.hpp" - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("ReadLoggingClient") { - MemoryClient target(4); - - StringPrint log; - SpyingClient upstreamSpy{target, log}; - - StringPrint output; - ReadLoggingClient loggingClient{upstreamSpy, output}; - - SUBCASE("available()") { - target.print("ABC"); - - size_t n = loggingClient.available(); - - CHECK(n == 3); - CHECK(log.str() == "available() -> 3"); - CHECK(output.str() == ""); - } - - SUBCASE("connect(IPAddress)") { - int n = loggingClient.connect(IPAddress("1.2.3.4"), 80); - - CHECK(n == 1); - CHECK(log.str() == "connect('1.2.3.4', 80) -> 1"); - CHECK(output.str() == ""); - } - - SUBCASE("connect(const char*)") { - int n = loggingClient.connect("1.2.3.4", 80); - - CHECK(n == 1); - CHECK(log.str() == "connect('1.2.3.4', 80) -> 1"); - CHECK(output.str() == ""); - } - - SUBCASE("connected()") { - uint8_t n = loggingClient.connected(); - - CHECK(n == false); - CHECK(log.str() == "connected() -> 0"); - CHECK(output.str() == ""); - } - - SUBCASE("stop()") { - loggingClient.stop(); - - CHECK(log.str() == "stop()"); - CHECK(output.str() == ""); - } - - SUBCASE("operator bool()") { - bool n = loggingClient.operator bool(); - - CHECK(n == true); - CHECK(log.str() == "operator bool() -> true"); - CHECK(output.str() == ""); - } - - SUBCASE("peek()") { - target.print("ABC"); - - int n = loggingClient.peek(); - - CHECK(n == 'A'); - CHECK(log.str() == "peek() -> 65"); - CHECK(output.str() == ""); - } - - SUBCASE("read()") { - target.print("ABC"); - - int n = loggingClient.read(); - - CHECK(n == 'A'); - CHECK(log.str() == "read() -> 65"); - CHECK(output.str() == "A"); - } - - SUBCASE("read(uint8_t*,size_t)") { - target.print("ABC"); - - uint8_t s[4] = {0}; - size_t n = loggingClient.read(s, 4); - - CHECK(n == 3); - CHECK(log.str() == "read(4) -> 3 [timeout]"); - CHECK(output.str() == "ABC"); - } - - SUBCASE("readBytes()") { - target.print("ABC"); - - char s[4] = {0}; - size_t n = loggingClient.readBytes(s, 4); - - CHECK(n == 3); - CHECK(output.str() == "ABC"); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == "readBytes(4) -> 3 [timeout]"); -#endif - } - - SUBCASE("write(char)") { - int n = loggingClient.write('A'); - - CHECK(n == 1); - CHECK(log.str() == "write('A') -> 1"); - CHECK(output.str() == ""); - } - - SUBCASE("write(char*,size_t)") { - int n = loggingClient.write("ABCDEF", 6); - - CHECK(n == 4); - CHECK(log.str() == "write('ABCDEF', 6) -> 4"); - CHECK(output.str() == ""); - } - - SUBCASE("flush()") { - loggingClient.flush(); - - CHECK(log.str() == "flush()"); - } -} diff --git a/lib/ArduinoStreamUtils/extras/test/ReadLoggingStreamTest.cpp b/lib/ArduinoStreamUtils/extras/test/ReadLoggingStreamTest.cpp deleted file mode 100644 index aa2c5744..00000000 --- a/lib/ArduinoStreamUtils/extras/test/ReadLoggingStreamTest.cpp +++ /dev/null @@ -1,89 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "FailingAllocator.hpp" - -#include "StreamUtils/Prints/StringPrint.hpp" -#include "StreamUtils/Streams/MemoryStream.hpp" -#include "StreamUtils/Streams/ReadLoggingStream.hpp" -#include "StreamUtils/Streams/SpyingStream.hpp" - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("ReadLoggingStream") { - MemoryStream upstream(4); - - StringPrint log; - SpyingStream upstreamSpy{upstream, log}; - - StringPrint output; - ReadLoggingStream loggingStream{upstreamSpy, output}; - - SUBCASE("available()") { - upstream.print("ABC"); - - size_t n = loggingStream.available(); - - CHECK(n == 3); - CHECK(log.str() == "available() -> 3"); - CHECK(output.str() == ""); - } - - SUBCASE("peek()") { - upstream.print("ABC"); - - int n = loggingStream.peek(); - - CHECK(n == 'A'); - CHECK(log.str() == "peek() -> 65"); - CHECK(output.str() == ""); - } - - SUBCASE("read()") { - upstream.print("ABC"); - - int n = loggingStream.read(); - - CHECK(n == 'A'); - CHECK(log.str() == "read() -> 65"); - CHECK(output.str() == "A"); - } - - SUBCASE("readBytes()") { - upstream.print("ABC"); - - char s[4] = {0}; - size_t n = loggingStream.readBytes(s, 4); - - CHECK(n == 3); - CHECK(output.str() == "ABC"); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == "readBytes(4) -> 3 [timeout]"); -#endif - } - - SUBCASE("write(char)") { - int n = loggingStream.write('A'); - - CHECK(n == 1); - CHECK(log.str() == "write('A') -> 1"); - CHECK(output.str() == ""); - } - - SUBCASE("write(char*,size_t)") { - int n = loggingStream.write("ABCDEF", 6); - - CHECK(n == 4); - CHECK(log.str() == "write('ABCDEF', 6) -> 4"); - CHECK(output.str() == ""); - } - - SUBCASE("flush()") { - loggingStream.flush(); - - CHECK(log.str() == "flush()"); - } -} diff --git a/lib/ArduinoStreamUtils/extras/test/ReadThrottlingStreamTest.cpp b/lib/ArduinoStreamUtils/extras/test/ReadThrottlingStreamTest.cpp deleted file mode 100644 index bb87dc59..00000000 --- a/lib/ArduinoStreamUtils/extras/test/ReadThrottlingStreamTest.cpp +++ /dev/null @@ -1,89 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "FailingAllocator.hpp" - -#include "StreamUtils/Streams/ReadThrottlingStream.hpp" -#include "StreamUtils/Streams/StringStream.hpp" - -#include "doctest.h" - -#include - -using namespace StreamUtils; - -class SpyingThrottler { - public: - SpyingThrottler(uint32_t rate) { - _log << "C(" << rate << ")"; - } - - SpyingThrottler(const SpyingThrottler& src) { - _log << src._log.str(); - } - - void throttle() { - _log << "T"; - } - - std::string log() const { - return _log.str(); - } - - private: - std::stringstream _log; -}; - -using ReadThrottlingStream = BasicReadThrottlingStream; - -TEST_CASE("ReadThrottlingStream") { - StringStream upstream; - - ReadThrottlingStream throttledStream{upstream, 4}; - Stream& stream = throttledStream; - const SpyingThrottler& throttler = throttledStream.throttler(); - - SUBCASE("available()") { - upstream.print("ABCD"); - CHECK(stream.available() == 4); - CHECK(throttler.log() == "C(4)"); - } - - SUBCASE("read()") { - upstream.print("ABCD"); - int n = stream.read(); - - CHECK(n == 'A'); - CHECK(throttler.log() == "C(4)T"); - } - - SUBCASE("readBytes()") { - upstream.print("ABCD"); - char output[8] = {0}; - - SUBCASE("read more than available") { - size_t n = stream.readBytes(output, sizeof(output)); - - CHECK(n == 4); - CHECK(strcmp("ABCD", output) == 0); - CHECK(throttler.log() == "C(4)TTTTT"); - } - - SUBCASE("read less than available") { - size_t n = stream.readBytes(output, 2); - - CHECK(n == 2); - CHECK(strcmp("AB", output) == 0); - CHECK(throttler.log() == "C(4)TT"); - } - - SUBCASE("read as many as available") { - size_t n = stream.readBytes(output, 4); - - CHECK(n == 4); - CHECK(strcmp("ABCD", output) == 0); - CHECK(throttler.log() == "C(4)TTTT"); - } - } -} diff --git a/lib/ArduinoStreamUtils/extras/test/SpyingAllocator.hpp b/lib/ArduinoStreamUtils/extras/test/SpyingAllocator.hpp deleted file mode 100644 index 89f5c087..00000000 --- a/lib/ArduinoStreamUtils/extras/test/SpyingAllocator.hpp +++ /dev/null @@ -1,36 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include - -#include "StreamUtils/Ports/DefaultAllocator.hpp" - -class SpyingAllocator { - public: - SpyingAllocator(Print& log) : _log(&log) {} - - bool forceFail = false; - - void* allocate(size_t n) { - void* ptr = forceFail ? 0 : _allocator.allocate(n); - _log->print("allocate("); - _log->print(n); - _log->print(") -> "); - _log->print(ptr ? "ptr" : "null"); - return ptr; - } - - void deallocate(void* ptr) { - _log->print("deallocate("); - _log->print(ptr ? "ptr" : "null"); - _log->print(")"); - _allocator.deallocate(ptr); - } - - private: - Print* _log; - StreamUtils::DefaultAllocator _allocator; -}; diff --git a/lib/ArduinoStreamUtils/extras/test/StringPrintTest.cpp b/lib/ArduinoStreamUtils/extras/test/StringPrintTest.cpp deleted file mode 100644 index 24163bf7..00000000 --- a/lib/ArduinoStreamUtils/extras/test/StringPrintTest.cpp +++ /dev/null @@ -1,77 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "StreamUtils/Prints/StringPrint.hpp" - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("StringPrint") { - WHEN("Constructed with no argument") { - StringPrint s; - - THEN("str() return an empty String") { - CHECK(s.str() == ""); - } - - THEN("write(uint8_t) appends the string") { - s.write('A'); - s.write('B'); - CHECK(s.str() == "AB"); - } - - THEN("write(uint8_t) return 1") { - CHECK(s.write('A') == 1); - CHECK(s.write('B') == 1); - } - - THEN("write(0) return 0") { - CHECK(s.write(0) == 0); - } - - THEN("write(uint8_t*, size_t) appends the string") { - s.write(reinterpret_cast("ABXXX"), 2); - s.write(reinterpret_cast("CDEXX"), 3); - CHECK(s.str() == "ABCDE"); - } - - THEN("write(uint8_t*, size_t) return number of chars written") { - uint8_t dummy[32] = {1, 2, 3, 0, 5, 6}; - CHECK(s.write(dummy, 2) == 2); - CHECK(s.write(dummy, 3) == 3); - CHECK(s.write(dummy, 4) == 3); - } - - THEN("str(String) sets the string") { - s.str("world!"); - CHECK(s.str() == "world!"); - } - } - - WHEN("Constructed with string") { - StringPrint s("hello"); - - THEN("str() return the stirng passed to contructor") { - CHECK(s.str() == "hello"); - } - - THEN("write(uint8_t) appends the string") { - s.write('A'); - s.write('B'); - CHECK(s.str() == "helloAB"); - } - - THEN("write(uint8_t*, size_t) appends the string") { - s.write(reinterpret_cast("ABXXX"), 2); - s.write(reinterpret_cast("CDEXX"), 3); - CHECK(s.str() == "helloABCDE"); - } - - THEN("str(String) replaces the string") { - s.str("world!"); - CHECK(s.str() == "world!"); - } - } -} diff --git a/lib/ArduinoStreamUtils/extras/test/StringStreamTest.cpp b/lib/ArduinoStreamUtils/extras/test/StringStreamTest.cpp deleted file mode 100644 index cf0821c8..00000000 --- a/lib/ArduinoStreamUtils/extras/test/StringStreamTest.cpp +++ /dev/null @@ -1,116 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "StreamUtils/Streams/StringStream.hpp" - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("StringStream") { - WHEN("Constructed with no argument") { - StringStream s; - - THEN("str() return an empty String") { - CHECK(s.str() == ""); - } - - THEN("write(uint8_t) appends the string") { - s.write('A'); - s.write('B'); - CHECK(s.str() == "AB"); - } - - THEN("write(uint8_t) return 1") { - CHECK(s.write('A') == 1); - CHECK(s.write('B') == 1); - } - - THEN("write(0) return 0") { - CHECK(s.write(0) == 0); - } - - THEN("write(uint8_t*, size_t) appends the string") { - s.write(reinterpret_cast("ABXXX"), 2); - s.write(reinterpret_cast("CDEXX"), 3); - CHECK(s.str() == "ABCDE"); - } - - THEN("write(uint8_t*, size_t) return number of chars written") { - uint8_t dummy[32] = {1, 2, 3, 0, 5, 6}; - CHECK(s.write(dummy, 2) == 2); - CHECK(s.write(dummy, 3) == 3); - CHECK(s.write(dummy, 4) == 3); - } - - THEN("str(String) sets the string") { - s.str("world!"); - CHECK(s.str() == "world!"); - } - - THEN("available() returns 0") { - CHECK(s.available() == 0); - } - - THEN("peek() return -1") { - CHECK(s.peek() == -1); - } - - THEN("peek() return -1") { - CHECK(s.read() == -1); - } - } - - WHEN("Constructed with string") { - StringStream s("hello"); - - THEN("str() returns the string passed to contructor") { - CHECK(s.str() == "hello"); - } - - THEN("available() returns the length passed to the constructor") { - CHECK(s.available() == 5); - } - - THEN("write(uint8_t) appends the string") { - s.write('A'); - s.write('B'); - CHECK(s.str() == "helloAB"); - } - - THEN("write(uint8_t*, size_t) appends the string") { - s.write(reinterpret_cast("ABXXX"), 2); - s.write(reinterpret_cast("CDEXX"), 3); - CHECK(s.str() == "helloABCDE"); - } - - THEN("str(String) replaces the string") { - s.str("world!"); - CHECK(s.str() == "world!"); - } - - THEN("peek() return the first char") { - CHECK(s.peek() == 'h'); - } - - THEN("peek() return the next char") { - CHECK(s.read() == 'h'); - CHECK(s.read() == 'e'); - } - - THEN("readBytes() can return the begining of the string") { - char buffer[32] = {0}; - CHECK(s.readBytes(buffer, 3) == 3); - CHECK(buffer == std::string("hel")); - CHECK(s.available() == 2); - } - - THEN("readBytes() can return the whole string") { - char buffer[32] = {0}; - CHECK(s.readBytes(buffer, 32) == 5); - CHECK(buffer == std::string("hello")); - CHECK(s.available() == 0); - } - } -} diff --git a/lib/ArduinoStreamUtils/extras/test/WaitingPrintTest.cpp b/lib/ArduinoStreamUtils/extras/test/WaitingPrintTest.cpp deleted file mode 100644 index 8a691204..00000000 --- a/lib/ArduinoStreamUtils/extras/test/WaitingPrintTest.cpp +++ /dev/null @@ -1,104 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "FailingAllocator.hpp" - -#include "StreamUtils/Prints/StringPrint.hpp" -#include "StreamUtils/Prints/WaitingPrint.hpp" -#include "StreamUtils/Streams/MemoryStream.hpp" -#include "StreamUtils/Streams/SpyingStream.hpp" - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("WaitingPrint") { - MemoryStream upstream(4); - - StringPrint log; - SpyingStream spy{upstream, log}; - WaitingPrint stream{static_cast(spy), [&spy]() { spy.flush(); }}; - - SUBCASE("write(char*, size_t)") { - SUBCASE("no need to wait") { - CHECK(stream.print("ABC") == 3); - - CHECK(log.str() == "write('ABC', 3) -> 3"); - } - - SUBCASE("need to wait") { - CHECK(stream.print("ABCDEFG") == 7); - - CHECK(log.str() == - "write('ABCDEFG', 7) -> 4" - "flush()" - "write('EFG', 3) -> 3"); - } - - SUBCASE("need to wait twice") { - CHECK(stream.print("ABCDEFGIJKL") == 11); - - CHECK(log.str() == - "write('ABCDEFGIJKL', 11) -> 4" - "flush()" - "write('EFGIJKL', 7) -> 4" - "flush()" - "write('JKL', 3) -> 3"); - } - - SUBCASE("doesn't wait when timeout is 0") { - stream.setTimeout(0); - - CHECK(stream.print("ABCDEFG") == 4); - - CHECK(log.str() == "write('ABCDEFG', 7) -> 4"); - } - } - - SUBCASE("write(char)") { - SUBCASE("no need to wait") { - CHECK(stream.write('A') == 1); - CHECK(stream.write('B') == 1); - CHECK(stream.write('C') == 1); - - CHECK(log.str() == - "write('A') -> 1" - "write('B') -> 1" - "write('C') -> 1"); - } - - SUBCASE("need to wait") { - for (int i = 0; i < 7; i++) - CHECK(stream.write("ABCDEFG"[i]) == 1); - - CHECK(log.str() == - "write('A') -> 1" - "write('B') -> 1" - "write('C') -> 1" - "write('D') -> 1" - "write('E') -> 0" - "flush()" - "write('E') -> 1" - "write('F') -> 1" - "write('G') -> 1"); - } - - SUBCASE("doesn't wait when timeout is 0") { - stream.setTimeout(0); - - CHECK(stream.write('A') == 1); - CHECK(stream.write('B') == 1); - CHECK(stream.write('C') == 1); - CHECK(stream.write('D') == 1); - CHECK(stream.write('E') == 0); - - CHECK(log.str() == - "write('A') -> 1" - "write('B') -> 1" - "write('C') -> 1" - "write('D') -> 1" - "write('E') -> 0"); - } - } -} diff --git a/lib/ArduinoStreamUtils/extras/test/WriteBufferingClientTest.cpp b/lib/ArduinoStreamUtils/extras/test/WriteBufferingClientTest.cpp deleted file mode 100644 index e300a06f..00000000 --- a/lib/ArduinoStreamUtils/extras/test/WriteBufferingClientTest.cpp +++ /dev/null @@ -1,203 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "FailingAllocator.hpp" - -#include "StreamUtils/Clients/MemoryClient.hpp" -#include "StreamUtils/Clients/SpyingClient.hpp" -#include "StreamUtils/Clients/WriteBufferingClient.hpp" -#include "StreamUtils/Prints/StringPrint.hpp" - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("WriteBufferingClient") { - MemoryClient target(64); - - StringPrint log; - SpyingClient spy{target, log}; - - GIVEN("capacity is 4") { - WriteBufferingClient bufferingClient{spy, 4}; - - SUBCASE("available()") { - target.print("ABC"); - - CHECK(bufferingClient.available() == 3); - CHECK(log.str() == "available() -> 3"); - } - - SUBCASE("connect(IPAddress)") { - int n = bufferingClient.connect(IPAddress("1.2.3.4"), 80); - - CHECK(n == 1); - CHECK(log.str() == "connect('1.2.3.4', 80) -> 1"); - } - - SUBCASE("connect(const char*)") { - int n = bufferingClient.connect("1.2.3.4", 80); - - CHECK(n == 1); - CHECK(log.str() == "connect('1.2.3.4', 80) -> 1"); - } - - SUBCASE("connected()") { - uint8_t n = bufferingClient.connected(); - - CHECK(n == false); - CHECK(log.str() == "connected() -> 0"); - } - - SUBCASE("stop()") { - bufferingClient.write("ABC", 3); - bufferingClient.stop(); - - CHECK(log.str() == - "write('ABC', 3) -> 3" - "stop()"); - } - - SUBCASE("operator bool()") { - bool n = bufferingClient.operator bool(); - - CHECK(n == true); - CHECK(log.str() == "operator bool() -> true"); - } - - SUBCASE("flush() forwards to target)") { - bufferingClient.flush(); - - CHECK(log.str() == "flush()"); - } - - SUBCASE("flush() calls write() and flush()") { - bufferingClient.write("ABC", 3); - bufferingClient.flush(); - - CHECK(log.str() == - "write('ABC', 3) -> 3" - "flush()"); - } - - SUBCASE("peek()") { - target.print("ABC"); - - CHECK(bufferingClient.peek() == 'A'); - CHECK(log.str() == "peek() -> 65"); - } - - SUBCASE("read()") { - target.print("ABC"); - - CHECK(bufferingClient.read() == 'A'); - CHECK(log.str() == "read() -> 65"); - } - - SUBCASE("readBytes()") { - target.print("ABC"); - - char s[4] = {0}; - int n = bufferingClient.readBytes(s, 3); - - CHECK(n == 3); - CHECK(s == std::string("ABC")); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == "readBytes(3) -> 3"); -#endif - } - - GIVEN("the buffer is empty") { - SUBCASE("write(uint8_t)") { - int n = bufferingClient.write('A'); - - CHECK(n == 1); - CHECK(log.str() == ""); - } - - SUBCASE("write(uint8_t) should flush") { - bufferingClient.write('A'); - bufferingClient.write('B'); - bufferingClient.write('C'); - bufferingClient.write('D'); - bufferingClient.write('E'); - - CHECK(log.str() == "write('ABCD', 4) -> 4"); - } - - SUBCASE("write(char*,3) goes in buffer") { - size_t n = bufferingClient.write("ABC", 3); - - CHECK(n == 3); - CHECK(log.str() == ""); - } - - SUBCASE("write(char*,4) bypasses buffer") { - size_t n = bufferingClient.write("ABCD", 4); - - CHECK(n == 4); - CHECK(log.str() == "write('ABCD', 4) -> 4"); - } - SUBCASE("write(char*,2) bypasses buffer") { - size_t n = bufferingClient.write("ABCD", 4); - - CHECK(n == 4); - CHECK(log.str() == "write('ABCD', 4) -> 4"); - } - } - - GIVEN("one byte in the buffer") { - bufferingClient.write('A'); - - SUBCASE("write(char*,3) goes in buffer and flush") { - size_t n = bufferingClient.write("BCD", 3); - - CHECK(n == 3); - CHECK(log.str() == "write('ABCD', 4) -> 4"); - } - - SUBCASE("write(char*,7) bypasses") { - size_t n = bufferingClient.write("BCDEFGH", 7); - - CHECK(n == 7); - CHECK(log.str() == - "write('ABCD', 4) -> 4" - "write('EFGH', 4) -> 4"); - } - } - } - - GIVEN("capacity is 0") { - WriteBufferingClient bufferingClient{spy, 0}; - - SUBCASE("write(uint8_t) forwards to target") { - int n = bufferingClient.write('X'); - - CHECK(n == 1); - CHECK(log.str() == "write('X') -> 1"); - } - - SUBCASE("write(char*,1) forwards to target") { - int n = bufferingClient.write("A", 1); - - CHECK(n == 1); - CHECK(log.str() == "write('A', 1) -> 1"); - } - - SUBCASE("flush() forwards to target") { - bufferingClient.flush(); - - CHECK(log.str() == "flush()"); - } - } - - SUBCASE("Destructor should flush") { - { - WriteBufferingClient bufferingClient{spy, 10}; - bufferingClient.write("ABC", 3); - } - - CHECK(log.str() == "write('ABC', 3) -> 3"); - } -} diff --git a/lib/ArduinoStreamUtils/extras/test/WriteBufferingStreamTest.cpp b/lib/ArduinoStreamUtils/extras/test/WriteBufferingStreamTest.cpp deleted file mode 100644 index 0dae701e..00000000 --- a/lib/ArduinoStreamUtils/extras/test/WriteBufferingStreamTest.cpp +++ /dev/null @@ -1,166 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "FailingAllocator.hpp" - -#include "StreamUtils/Prints/StringPrint.hpp" -#include "StreamUtils/Streams/MemoryStream.hpp" -#include "StreamUtils/Streams/SpyingStream.hpp" -#include "StreamUtils/Streams/WriteBufferingStream.hpp" - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("WriteBufferingStream") { - MemoryStream upstream(64); - - StringPrint log; - SpyingStream spy{upstream, log}; - - GIVEN("capacity is 4") { - WriteBufferingStream stream{spy, 4}; - - SUBCASE("available()") { - upstream.print("ABC"); - - CHECK(stream.available() == 3); - CHECK(log.str() == "available() -> 3"); - } - - SUBCASE("flush() forwards to upstream)") { - stream.flush(); - - CHECK(log.str() == "flush()"); - } - - SUBCASE("flush() calls write() and flush()") { - stream.write("ABC", 3); - stream.flush(); - - CHECK(log.str() == - "write('ABC', 3) -> 3" - "flush()"); - } - - SUBCASE("peek()") { - upstream.print("ABC"); - - CHECK(stream.peek() == 'A'); - CHECK(log.str() == "peek() -> 65"); - } - - SUBCASE("read()") { - upstream.print("ABC"); - - CHECK(stream.read() == 'A'); - CHECK(log.str() == "read() -> 65"); - } - - SUBCASE("readBytes()") { - upstream.print("ABC"); - - char s[4] = {0}; - int n = stream.readBytes(s, 3); - - CHECK(n == 3); - CHECK(s == std::string("ABC")); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == "readBytes(3) -> 3"); -#endif - } - - GIVEN("the buffer is empty") { - SUBCASE("write(uint8_t)") { - int n = stream.write('A'); - - CHECK(n == 1); - CHECK(log.str() == ""); - } - - SUBCASE("write(uint8_t) should flush") { - stream.write('A'); - stream.write('B'); - stream.write('C'); - stream.write('D'); - stream.write('E'); - - CHECK(log.str() == "write('ABCD', 4) -> 4"); - } - - SUBCASE("write(char*,3) goes in buffer") { - size_t n = stream.write("ABC", 3); - - CHECK(n == 3); - CHECK(log.str() == ""); - } - - SUBCASE("write(char*,4) bypasses buffer") { - size_t n = stream.write("ABCD", 4); - - CHECK(n == 4); - CHECK(log.str() == "write('ABCD', 4) -> 4"); - } - SUBCASE("write(char*,2) bypasses buffer") { - size_t n = stream.write("ABCD", 4); - - CHECK(n == 4); - CHECK(log.str() == "write('ABCD', 4) -> 4"); - } - } - - GIVEN("one byte in the buffer") { - stream.write('A'); - - SUBCASE("write(char*,3) goes in buffer and flush") { - size_t n = stream.write("BCD", 3); - - CHECK(n == 3); - CHECK(log.str() == "write('ABCD', 4) -> 4"); - } - - SUBCASE("write(char*,7) bypasses") { - size_t n = stream.write("BCDEFGH", 7); - - CHECK(n == 7); - CHECK(log.str() == - "write('ABCD', 4) -> 4" - "write('EFGH', 4) -> 4"); - } - } - } - - GIVEN("capacity is 0") { - WriteBufferingStream stream{spy, 0}; - - SUBCASE("write(uint8_t) forwards to upstream") { - int n = stream.write('X'); - - CHECK(n == 1); - CHECK(log.str() == "write('X') -> 1"); - } - - SUBCASE("write(char*,1) forwards to upstream") { - int n = stream.write("A", 1); - - CHECK(n == 1); - CHECK(log.str() == "write('A', 1) -> 1"); - } - - SUBCASE("flush() forwards to upstream") { - stream.flush(); - - CHECK(log.str() == "flush()"); - } - } - - SUBCASE("Destructor should flush") { - { - WriteBufferingStream stream{spy, 10}; - stream.write("ABC", 3); - } - - CHECK(log.str() == "write('ABC', 3) -> 3"); - } -} diff --git a/lib/ArduinoStreamUtils/extras/test/WriteLoggingClientTest.cpp b/lib/ArduinoStreamUtils/extras/test/WriteLoggingClientTest.cpp deleted file mode 100644 index 3d5c6115..00000000 --- a/lib/ArduinoStreamUtils/extras/test/WriteLoggingClientTest.cpp +++ /dev/null @@ -1,140 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "FailingAllocator.hpp" - -#include "StreamUtils/Clients/MemoryClient.hpp" -#include "StreamUtils/Clients/SpyingClient.hpp" -#include "StreamUtils/Clients/WriteLoggingClient.hpp" -#include "StreamUtils/Prints/StringPrint.hpp" - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("WriteLoggingClient") { - MemoryClient target(4); - - StringPrint log; - SpyingClient spy{target, log}; - - StringPrint output; - WriteLoggingClient loggingClient{spy, output}; - - SUBCASE("available()") { - target.print("ABC"); - - size_t n = loggingClient.available(); - - CHECK(n == 3); - CHECK(log.str() == "available() -> 3"); - CHECK(output.str() == ""); - } - - SUBCASE("connect(IPAddress)") { - int n = loggingClient.connect(IPAddress("1.2.3.4"), 80); - - CHECK(n == 1); - CHECK(log.str() == "connect('1.2.3.4', 80) -> 1"); - CHECK(output.str() == ""); - } - - SUBCASE("connect(const char*)") { - int n = loggingClient.connect("1.2.3.4", 80); - - CHECK(n == 1); - CHECK(log.str() == "connect('1.2.3.4', 80) -> 1"); - CHECK(output.str() == ""); - } - - SUBCASE("connected()") { - uint8_t n = loggingClient.connected(); - - CHECK(n == false); - CHECK(log.str() == "connected() -> 0"); - CHECK(output.str() == ""); - } - - SUBCASE("stop()") { - loggingClient.stop(); - - CHECK(log.str() == "stop()"); - CHECK(output.str() == ""); - } - - SUBCASE("operator bool()") { - bool n = loggingClient.operator bool(); - - CHECK(n == true); - CHECK(log.str() == "operator bool() -> true"); - CHECK(output.str() == ""); - } - - SUBCASE("peek()") { - target.print("ABC"); - - int n = loggingClient.peek(); - - CHECK(n == 'A'); - CHECK(log.str() == "peek() -> 65"); - CHECK(output.str() == ""); - } - - SUBCASE("read()") { - target.print("ABC"); - - int n = loggingClient.read(); - - CHECK(n == 'A'); - CHECK(log.str() == "read() -> 65"); - CHECK(output.str() == ""); - } - - SUBCASE("read(uint8_t*,size_t)") { - target.print("ABC"); - - uint8_t s[4] = {0}; - size_t n = loggingClient.read(s, 4); - - CHECK(n == 3); - CHECK(log.str() == "read(4) -> 3 [timeout]"); - CHECK(output.str() == ""); - } - - SUBCASE("readBytes()") { - target.print("ABC"); - - char s[4] = {0}; - size_t n = loggingClient.readBytes(s, 4); - - CHECK(n == 3); - CHECK(output.str() == ""); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == "readBytes(4) -> 3 [timeout]"); -#endif - } - - SUBCASE("write(char)") { - int n = loggingClient.write('A'); - - CHECK(n == 1); - CHECK(log.str() == "write('A') -> 1"); - CHECK(output.str() == "A"); - } - - SUBCASE("write(char*,size_t)") { - int n = loggingClient.write("ABCDEF", 6); - - CHECK(n == 4); - CHECK(log.str() == "write('ABCDEF', 6) -> 4"); - CHECK(output.str() == "ABCD"); - } - - SUBCASE("flush()") { - loggingClient.flush(); - - CHECK(output.str() == ""); - CHECK(log.str() == "flush()"); - } -} diff --git a/lib/ArduinoStreamUtils/extras/test/WriteLoggingStreamTest.cpp b/lib/ArduinoStreamUtils/extras/test/WriteLoggingStreamTest.cpp deleted file mode 100644 index e38ae525..00000000 --- a/lib/ArduinoStreamUtils/extras/test/WriteLoggingStreamTest.cpp +++ /dev/null @@ -1,90 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "FailingAllocator.hpp" - -#include "StreamUtils/Prints/StringPrint.hpp" -#include "StreamUtils/Streams/MemoryStream.hpp" -#include "StreamUtils/Streams/SpyingStream.hpp" -#include "StreamUtils/Streams/WriteLoggingStream.hpp" - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("WriteLoggingStream") { - MemoryStream upstream(4); - - StringPrint log; - SpyingStream upstreamSpy{upstream, log}; - - StringPrint output; - WriteLoggingStream loggingStream{upstreamSpy, output}; - - SUBCASE("available()") { - upstream.print("ABC"); - - size_t n = loggingStream.available(); - - CHECK(n == 3); - CHECK(log.str() == "available() -> 3"); - CHECK(output.str() == ""); - } - - SUBCASE("peek()") { - upstream.print("ABC"); - - int n = loggingStream.peek(); - - CHECK(n == 'A'); - CHECK(log.str() == "peek() -> 65"); - CHECK(output.str() == ""); - } - - SUBCASE("read()") { - upstream.print("ABC"); - - int n = loggingStream.read(); - - CHECK(n == 'A'); - CHECK(log.str() == "read() -> 65"); - CHECK(output.str() == ""); - } - - SUBCASE("readBytes()") { - upstream.print("ABC"); - - char s[4] = {0}; - size_t n = loggingStream.readBytes(s, 4); - - CHECK(n == 3); - CHECK(output.str() == ""); -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - CHECK(log.str() == "readBytes(4) -> 3 [timeout]"); -#endif - } - - SUBCASE("write(char)") { - int n = loggingStream.write('A'); - - CHECK(n == 1); - CHECK(log.str() == "write('A') -> 1"); - CHECK(output.str() == "A"); - } - - SUBCASE("write(char*,size_t)") { - int n = loggingStream.write("ABCDEF", 6); - - CHECK(n == 4); - CHECK(log.str() == "write('ABCDEF', 6) -> 4"); - CHECK(output.str() == "ABCD"); - } - - SUBCASE("flush()") { - loggingStream.flush(); - - CHECK(log.str() == "flush()"); - CHECK(output.str() == ""); - } -} diff --git a/lib/ArduinoStreamUtils/extras/test/WriteWaitingClientTest.cpp b/lib/ArduinoStreamUtils/extras/test/WriteWaitingClientTest.cpp deleted file mode 100644 index 20b2d901..00000000 --- a/lib/ArduinoStreamUtils/extras/test/WriteWaitingClientTest.cpp +++ /dev/null @@ -1,104 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "FailingAllocator.hpp" - -#include "StreamUtils/Clients/MemoryClient.hpp" -#include "StreamUtils/Clients/SpyingClient.hpp" -#include "StreamUtils/Clients/WriteWaitingClient.hpp" -#include "StreamUtils/Prints/StringPrint.hpp" - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("WriteWaitingClient") { - MemoryClient upstream(4); - - StringPrint log; - SpyingClient spy{upstream, log}; - WriteWaitingClient client{spy, [&spy]() { spy.flush(); }}; - - SUBCASE("write(char*, size_t)") { - SUBCASE("no need to wait") { - CHECK(client.print("ABC") == 3); - - CHECK(log.str() == "write('ABC', 3) -> 3"); - } - - SUBCASE("need to wait") { - CHECK(client.print("ABCDEFG") == 7); - - CHECK(log.str() == - "write('ABCDEFG', 7) -> 4" - "flush()" - "write('EFG', 3) -> 3"); - } - - SUBCASE("need to wait twice") { - CHECK(client.print("ABCDEFGIJKL") == 11); - - CHECK(log.str() == - "write('ABCDEFGIJKL', 11) -> 4" - "flush()" - "write('EFGIJKL', 7) -> 4" - "flush()" - "write('JKL', 3) -> 3"); - } - - SUBCASE("doesn't wait when timeout is 0") { - client.setTimeout(0); - - CHECK(client.print("ABCDEFG") == 4); - - CHECK(log.str() == "write('ABCDEFG', 7) -> 4"); - } - } - - SUBCASE("write(char)") { - SUBCASE("no need to wait") { - CHECK(client.write('A') == 1); - CHECK(client.write('B') == 1); - CHECK(client.write('C') == 1); - - CHECK(log.str() == - "write('A') -> 1" - "write('B') -> 1" - "write('C') -> 1"); - } - - SUBCASE("need to wait") { - for (int i = 0; i < 7; i++) - CHECK(client.write("ABCDEFG"[i]) == 1); - - CHECK(log.str() == - "write('A') -> 1" - "write('B') -> 1" - "write('C') -> 1" - "write('D') -> 1" - "write('E') -> 0" - "flush()" - "write('E') -> 1" - "write('F') -> 1" - "write('G') -> 1"); - } - - SUBCASE("doesn't wait when timeout is 0") { - client.setTimeout(0); - - CHECK(client.write('A') == 1); - CHECK(client.write('B') == 1); - CHECK(client.write('C') == 1); - CHECK(client.write('D') == 1); - CHECK(client.write('E') == 0); - - CHECK(log.str() == - "write('A') -> 1" - "write('B') -> 1" - "write('C') -> 1" - "write('D') -> 1" - "write('E') -> 0"); - } - } -} diff --git a/lib/ArduinoStreamUtils/extras/test/WriteWaitingStreamTest.cpp b/lib/ArduinoStreamUtils/extras/test/WriteWaitingStreamTest.cpp deleted file mode 100644 index f071ea02..00000000 --- a/lib/ArduinoStreamUtils/extras/test/WriteWaitingStreamTest.cpp +++ /dev/null @@ -1,104 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "FailingAllocator.hpp" - -#include "StreamUtils/Prints/StringPrint.hpp" -#include "StreamUtils/Streams/MemoryStream.hpp" -#include "StreamUtils/Streams/SpyingStream.hpp" -#include "StreamUtils/Streams/WriteWaitingStream.hpp" - -#include "doctest.h" - -using namespace StreamUtils; - -TEST_CASE("WriteWaitingStream") { - MemoryStream upstream(4); - - StringPrint log; - SpyingStream spy{upstream, log}; - WriteWaitingStream stream{spy, [&spy]() { spy.flush(); }}; - - SUBCASE("write(char*, size_t)") { - SUBCASE("no need to wait") { - CHECK(stream.print("ABC") == 3); - - CHECK(log.str() == "write('ABC', 3) -> 3"); - } - - SUBCASE("need to wait") { - CHECK(stream.print("ABCDEFG") == 7); - - CHECK(log.str() == - "write('ABCDEFG', 7) -> 4" - "flush()" - "write('EFG', 3) -> 3"); - } - - SUBCASE("need to wait twice") { - CHECK(stream.print("ABCDEFGIJKL") == 11); - - CHECK(log.str() == - "write('ABCDEFGIJKL', 11) -> 4" - "flush()" - "write('EFGIJKL', 7) -> 4" - "flush()" - "write('JKL', 3) -> 3"); - } - - SUBCASE("doesn't wait when timeout is 0") { - stream.setTimeout(0); - - CHECK(stream.print("ABCDEFG") == 4); - - CHECK(log.str() == "write('ABCDEFG', 7) -> 4"); - } - } - - SUBCASE("write(char)") { - SUBCASE("no need to wait") { - CHECK(stream.write('A') == 1); - CHECK(stream.write('B') == 1); - CHECK(stream.write('C') == 1); - - CHECK(log.str() == - "write('A') -> 1" - "write('B') -> 1" - "write('C') -> 1"); - } - - SUBCASE("need to wait") { - for (int i = 0; i < 7; i++) - CHECK(stream.write("ABCDEFG"[i]) == 1); - - CHECK(log.str() == - "write('A') -> 1" - "write('B') -> 1" - "write('C') -> 1" - "write('D') -> 1" - "write('E') -> 0" - "flush()" - "write('E') -> 1" - "write('F') -> 1" - "write('G') -> 1"); - } - - SUBCASE("doesn't wait when timeout is 0") { - stream.setTimeout(0); - - CHECK(stream.write('A') == 1); - CHECK(stream.write('B') == 1); - CHECK(stream.write('C') == 1); - CHECK(stream.write('D') == 1); - CHECK(stream.write('E') == 0); - - CHECK(log.str() == - "write('A') -> 1" - "write('B') -> 1" - "write('C') -> 1" - "write('D') -> 1" - "write('E') -> 0"); - } - } -} diff --git a/lib/ArduinoStreamUtils/extras/test/cores/avr/Arduino.h b/lib/ArduinoStreamUtils/extras/test/cores/avr/Arduino.h deleted file mode 100644 index e94f54ff..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/avr/Arduino.h +++ /dev/null @@ -1,18 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include -#include -#include -#include - -#include - -inline unsigned long millis() { - return static_cast(time(NULL)); -} - -inline void yield() {} \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/test/cores/avr/CMakeLists.txt b/lib/ArduinoStreamUtils/extras/test/cores/avr/CMakeLists.txt deleted file mode 100644 index 4cc892e0..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/avr/CMakeLists.txt +++ /dev/null @@ -1,22 +0,0 @@ -# StreamUtils - github.com/bblanchon/ArduinoStreamUtils -# Copyright Benoit Blanchon 2019-2021 -# MIT License - -add_library(AvrCore - Client.h - EEPROM.cpp - EEPROM.h - Print.h - Stream.h - WString.h -) - -target_include_directories(AvrCore - PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR} -) - -target_compile_definitions(AvrCore - PUBLIC - ARDUINO_ARCH_AVR -) diff --git a/lib/ArduinoStreamUtils/extras/test/cores/avr/Client.h b/lib/ArduinoStreamUtils/extras/test/cores/avr/Client.h deleted file mode 100644 index 79d7a5d1..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/avr/Client.h +++ /dev/null @@ -1,27 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "Stream.h" -#include "WString.h" - -using IPAddress = String; - -struct Client : Stream { - virtual int connect(IPAddress ip, uint16_t port) = 0; - virtual int connect(const char *host, uint16_t port) = 0; - virtual uint8_t connected() = 0; - virtual void stop() = 0; - virtual operator bool() = 0; - - // Already in Stream - virtual size_t write(uint8_t) = 0; - virtual size_t write(const uint8_t *buf, size_t size) = 0; - virtual int available() = 0; - virtual int read() = 0; - - // Curiously not in Stream - virtual int read(uint8_t *buf, size_t size) = 0; -}; diff --git a/lib/ArduinoStreamUtils/extras/test/cores/avr/EEPROM.cpp b/lib/ArduinoStreamUtils/extras/test/cores/avr/EEPROM.cpp deleted file mode 100644 index 2b2eb1a8..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/avr/EEPROM.cpp +++ /dev/null @@ -1,12 +0,0 @@ -#include "EEPROM.h" - -EEPROMClass EEPROM; -static uint8_t data[512]; - -uint8_t EEPROMClass::read(int address) { - return data[address]; -} - -void EEPROMClass::update(int address, uint8_t value) { - data[address] = value; -} diff --git a/lib/ArduinoStreamUtils/extras/test/cores/avr/EEPROM.h b/lib/ArduinoStreamUtils/extras/test/cores/avr/EEPROM.h deleted file mode 100644 index b5e3360c..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/avr/EEPROM.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include - -class EEPROMClass { - public: - uint8_t read(int); - void update(int, uint8_t); - // void write(int, uint8_t); <- it exists but we want to use update() instead -}; - -extern EEPROMClass EEPROM; diff --git a/lib/ArduinoStreamUtils/extras/test/cores/avr/Print.h b/lib/ArduinoStreamUtils/extras/test/cores/avr/Print.h deleted file mode 100644 index 34b48916..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/avr/Print.h +++ /dev/null @@ -1,42 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include -#include - -#include - -struct Print { - virtual size_t write(const uint8_t *buffer, size_t size) = 0; - virtual size_t write(uint8_t data) = 0; - virtual void flush() {} - - size_t write(const char *buffer, size_t size) { - return write((const uint8_t *)buffer, size); - } - - size_t print(const String &s) { - return write(s.c_str(), s.length()); - } - - size_t print(const char *s) { - return write(s, std::strlen(s)); - } - - size_t println() { - return 0; - } - - template - size_t print(const T &value) { - return print(String(value)); - } - - template - size_t println(const T &value) { - return print(value); - } -}; diff --git a/lib/ArduinoStreamUtils/extras/test/cores/avr/Stream.h b/lib/ArduinoStreamUtils/extras/test/cores/avr/Stream.h deleted file mode 100644 index 869b9d4c..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/avr/Stream.h +++ /dev/null @@ -1,41 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "Print.h" - -struct Stream : Print { - virtual int available() = 0; - virtual int read() = 0; - virtual int peek() = 0; - - size_t readBytes(char *buffer, size_t length) { - size_t count = 0; - while (count < length) { - int c = timedRead(); - if (c < 0) - break; - *buffer++ = (char)c; - count++; - } - return count; - } - - String readString() { - String result; - int c; - while ((c = timedRead()) >= 0) { - result += static_cast(c); - } - return result; - } - - void setTimeout(unsigned long) {} - - protected: - int timedRead() { - return read(); - } -}; diff --git a/lib/ArduinoStreamUtils/extras/test/cores/avr/WString.h b/lib/ArduinoStreamUtils/extras/test/cores/avr/WString.h deleted file mode 100644 index a4c911bd..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/avr/WString.h +++ /dev/null @@ -1,43 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include - -class String : private std::string { - public: - String() {} - String(const String& s) : std::string(s) {} - String(String&& s) : std::string(std::move(s)) {} - String(const char* s) : std::string(s) {} - String(int n) : std::string(std::to_string(n)) {} - - String& operator=(const String& rhs) { - std::string::operator=(rhs); - return *this; - } - - using std::string::c_str; - using std::string::length; - using std::string::operator+=; - using std::string::operator[]; - - void remove(unsigned int index, unsigned int count) { - erase(begin() + index, begin() + index + count); - } - - void toCharArray(char* buf, unsigned int bufsize, - unsigned int index = 0) const { - copy(buf, bufsize, index); - } - - friend bool operator==(const String& lhs, const char* rhs) { - return static_cast(lhs) == rhs; - } - - friend std::ostream& operator<<(std::ostream& lhs, const String& rhs) { - return lhs << static_cast(rhs); - } -}; diff --git a/lib/ArduinoStreamUtils/extras/test/cores/esp32/Arduino.h b/lib/ArduinoStreamUtils/extras/test/cores/esp32/Arduino.h deleted file mode 100644 index e94f54ff..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/esp32/Arduino.h +++ /dev/null @@ -1,18 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include -#include -#include -#include - -#include - -inline unsigned long millis() { - return static_cast(time(NULL)); -} - -inline void yield() {} \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/test/cores/esp32/CMakeLists.txt b/lib/ArduinoStreamUtils/extras/test/cores/esp32/CMakeLists.txt deleted file mode 100644 index cc3cd733..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/esp32/CMakeLists.txt +++ /dev/null @@ -1,22 +0,0 @@ -# StreamUtils - github.com/bblanchon/ArduinoStreamUtils -# Copyright Benoit Blanchon 2019-2021 -# MIT License - -add_library(Esp32Core - Client.h - EEPROM.cpp - EEPROM.h - Print.h - Stream.h - WString.h -) - -target_include_directories(Esp32Core - PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR} -) - -target_compile_definitions(Esp32Core - PUBLIC - ARDUINO_ARCH_ESP32 -) diff --git a/lib/ArduinoStreamUtils/extras/test/cores/esp32/Client.h b/lib/ArduinoStreamUtils/extras/test/cores/esp32/Client.h deleted file mode 100644 index 1fc8d8f0..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/esp32/Client.h +++ /dev/null @@ -1,26 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "Stream.h" -#include "WString.h" - -using IPAddress = String; - -class Client : public Stream { - public: - virtual int connect(IPAddress ip, uint16_t port) = 0; - virtual int connect(const char *host, uint16_t port) = 0; - virtual size_t write(uint8_t) = 0; - virtual size_t write(const uint8_t *buf, size_t size) = 0; - virtual int available() = 0; - virtual int read() = 0; - virtual int read(uint8_t *buf, size_t size) = 0; - virtual int peek() = 0; - virtual void flush() = 0; - virtual void stop() = 0; - virtual uint8_t connected() = 0; - virtual operator bool() = 0; -}; diff --git a/lib/ArduinoStreamUtils/extras/test/cores/esp32/EEPROM.cpp b/lib/ArduinoStreamUtils/extras/test/cores/esp32/EEPROM.cpp deleted file mode 100644 index a47dd834..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/esp32/EEPROM.cpp +++ /dev/null @@ -1,20 +0,0 @@ -#include "EEPROM.h" - -#include // memcpy - -EEPROMClass EEPROM; -static uint8_t commitedData[512]; -static uint8_t pendingData[512]; - -uint8_t EEPROMClass::read(int address) { - return commitedData[address]; -} - -void EEPROMClass::write(int address, uint8_t value) { - pendingData[address] = value; -} - -bool EEPROMClass::commit() { - memcpy(commitedData, pendingData, 512); - return true; -} \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/test/cores/esp32/EEPROM.h b/lib/ArduinoStreamUtils/extras/test/cores/esp32/EEPROM.h deleted file mode 100644 index cd9eb00c..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/esp32/EEPROM.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include - -class EEPROMClass { - public: - uint8_t read(int); - void write(int, uint8_t); - bool commit(); -}; - -extern EEPROMClass EEPROM; diff --git a/lib/ArduinoStreamUtils/extras/test/cores/esp32/Print.h b/lib/ArduinoStreamUtils/extras/test/cores/esp32/Print.h deleted file mode 100644 index 40ff3646..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/esp32/Print.h +++ /dev/null @@ -1,42 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include - -#include -#include - -struct Print { - virtual ~Print() {} - virtual size_t write(const uint8_t *buffer, size_t size) = 0; - virtual size_t write(uint8_t data) = 0; - - size_t write(const char *buffer, size_t size) { - return write((const uint8_t *)buffer, size); - } - - size_t print(const String &s) { - return write(s.c_str(), s.length()); - } - - size_t print(const char *s) { - return write(s, std::strlen(s)); - } - - size_t println() { - return 0; - } - - template - size_t print(const T &value) { - return print(String(value)); - } - - template - size_t println(const T &value) { - return print(value); - } -}; \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/test/cores/esp32/Stream.h b/lib/ArduinoStreamUtils/extras/test/cores/esp32/Stream.h deleted file mode 100644 index dae174d3..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/esp32/Stream.h +++ /dev/null @@ -1,48 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "Print.h" - -struct Stream : Print { - virtual ~Stream() {} - - virtual int available() = 0; - virtual int read() = 0; - virtual int peek() = 0; - virtual void flush() = 0; - - virtual size_t readBytes(char *buffer, size_t length) { - size_t count = 0; - while (count < length) { - int c = timedRead(); - if (c < 0) - break; - *buffer++ = (char)c; - count++; - } - return count; - } - - virtual size_t readBytes(uint8_t *buffer, size_t length) { - return readBytes((char *)buffer, length); - } - - virtual String readString() { - String result; - int c; - while ((c = timedRead()) >= 0) { - result += c; - } - return result; - } - - void setTimeout(unsigned long) {} - - protected: - int timedRead() { - return read(); - } -}; diff --git a/lib/ArduinoStreamUtils/extras/test/cores/esp32/WString.h b/lib/ArduinoStreamUtils/extras/test/cores/esp32/WString.h deleted file mode 100644 index 9023e414..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/esp32/WString.h +++ /dev/null @@ -1,5 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "../avr/WString.h" \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/test/cores/esp8266/Arduino.h b/lib/ArduinoStreamUtils/extras/test/cores/esp8266/Arduino.h deleted file mode 100644 index e94f54ff..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/esp8266/Arduino.h +++ /dev/null @@ -1,18 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include -#include -#include -#include - -#include - -inline unsigned long millis() { - return static_cast(time(NULL)); -} - -inline void yield() {} \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/test/cores/esp8266/CMakeLists.txt b/lib/ArduinoStreamUtils/extras/test/cores/esp8266/CMakeLists.txt deleted file mode 100644 index 94d385d5..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/esp8266/CMakeLists.txt +++ /dev/null @@ -1,22 +0,0 @@ -# StreamUtils - github.com/bblanchon/ArduinoStreamUtils -# Copyright Benoit Blanchon 2019-2021 -# MIT License - -add_library(Esp8266Core - Client.h - EEPROM.cpp - EEPROM.h - Print.h - Stream.h - WString.h -) - -target_include_directories(Esp8266Core - PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR} -) - -target_compile_definitions(Esp8266Core - PUBLIC - ARDUINO_ARCH_ESP8266 -) diff --git a/lib/ArduinoStreamUtils/extras/test/cores/esp8266/Client.h b/lib/ArduinoStreamUtils/extras/test/cores/esp8266/Client.h deleted file mode 100644 index 1fc8d8f0..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/esp8266/Client.h +++ /dev/null @@ -1,26 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "Stream.h" -#include "WString.h" - -using IPAddress = String; - -class Client : public Stream { - public: - virtual int connect(IPAddress ip, uint16_t port) = 0; - virtual int connect(const char *host, uint16_t port) = 0; - virtual size_t write(uint8_t) = 0; - virtual size_t write(const uint8_t *buf, size_t size) = 0; - virtual int available() = 0; - virtual int read() = 0; - virtual int read(uint8_t *buf, size_t size) = 0; - virtual int peek() = 0; - virtual void flush() = 0; - virtual void stop() = 0; - virtual uint8_t connected() = 0; - virtual operator bool() = 0; -}; diff --git a/lib/ArduinoStreamUtils/extras/test/cores/esp8266/EEPROM.cpp b/lib/ArduinoStreamUtils/extras/test/cores/esp8266/EEPROM.cpp deleted file mode 100644 index fd0ef682..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/esp8266/EEPROM.cpp +++ /dev/null @@ -1,19 +0,0 @@ -#include "EEPROM.h" - -#include // memcpy - -EEPROMClass EEPROM; -static uint8_t commitedData[512]; -static uint8_t pendingData[512]; - -uint8_t EEPROMClass::read(int address) { - return commitedData[address]; -} - -void EEPROMClass::write(int address, uint8_t value) { - pendingData[address] = value; -} - -void EEPROMClass::commit() { - memcpy(commitedData, pendingData, 512); -} \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/test/cores/esp8266/EEPROM.h b/lib/ArduinoStreamUtils/extras/test/cores/esp8266/EEPROM.h deleted file mode 100644 index 63da03ba..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/esp8266/EEPROM.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include - -class EEPROMClass { - public: - uint8_t read(int); - void write(int, uint8_t); - void commit(); -}; - -extern EEPROMClass EEPROM; diff --git a/lib/ArduinoStreamUtils/extras/test/cores/esp8266/Print.h b/lib/ArduinoStreamUtils/extras/test/cores/esp8266/Print.h deleted file mode 100644 index 2abf7369..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/esp8266/Print.h +++ /dev/null @@ -1,43 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include - -#include -#include - -struct Print { - virtual size_t write(const uint8_t *buffer, size_t size) = 0; - virtual size_t write(uint8_t data) = 0; - - size_t write(const char *buffer, size_t size) { - return write((const uint8_t *)buffer, size); - } - - size_t print(const String &s) { - return write(s.c_str(), s.length()); - } - - size_t print(const char *s) { - return write(s, std::strlen(s)); - } - - size_t println() { - return 0; - } - - template - size_t print(const T &value) { - return print(String(value)); - } - - template - size_t println(const T &value) { - return print(value); - } - - virtual void flush() {} -}; \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/test/cores/esp8266/Stream.h b/lib/ArduinoStreamUtils/extras/test/cores/esp8266/Stream.h deleted file mode 100644 index 5dea8c51..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/esp8266/Stream.h +++ /dev/null @@ -1,45 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "Print.h" - -struct Stream : Print { - virtual int available() = 0; - virtual int read() = 0; - virtual int peek() = 0; - - virtual size_t readBytes(char *buffer, size_t length) { - size_t count = 0; - while (count < length) { - int c = timedRead(); - if (c < 0) - break; - *buffer++ = (char)c; - count++; - } - return count; - } - - virtual size_t readBytes(uint8_t *buffer, size_t length) { - return readBytes((char *)buffer, length); - } - - virtual String readString() { - String result; - int c; - while ((c = timedRead()) >= 0) { - result += c; - } - return result; - } - - void setTimeout(unsigned long) {} - - protected: - int timedRead() { - return read(); - } -}; diff --git a/lib/ArduinoStreamUtils/extras/test/cores/esp8266/WString.h b/lib/ArduinoStreamUtils/extras/test/cores/esp8266/WString.h deleted file mode 100644 index 9023e414..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/esp8266/WString.h +++ /dev/null @@ -1,5 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "../avr/WString.h" \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/test/cores/nrf52/Arduino.h b/lib/ArduinoStreamUtils/extras/test/cores/nrf52/Arduino.h deleted file mode 100644 index e94f54ff..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/nrf52/Arduino.h +++ /dev/null @@ -1,18 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include -#include -#include -#include - -#include - -inline unsigned long millis() { - return static_cast(time(NULL)); -} - -inline void yield() {} \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/test/cores/nrf52/CMakeLists.txt b/lib/ArduinoStreamUtils/extras/test/cores/nrf52/CMakeLists.txt deleted file mode 100644 index 85f8ae8c..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/nrf52/CMakeLists.txt +++ /dev/null @@ -1,15 +0,0 @@ -# StreamUtils - github.com/bblanchon/ArduinoStreamUtils -# Copyright Benoit Blanchon 2019-2021 -# MIT License - -add_library(Nrf52Core INTERFACE) - -target_include_directories(Nrf52Core - INTERFACE - ${CMAKE_CURRENT_SOURCE_DIR} -) - -target_compile_definitions(Nrf52Core - INTERFACE - ARDUINO_ARCH_NRF52 -) diff --git a/lib/ArduinoStreamUtils/extras/test/cores/nrf52/Client.h b/lib/ArduinoStreamUtils/extras/test/cores/nrf52/Client.h deleted file mode 100644 index 1fc8d8f0..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/nrf52/Client.h +++ /dev/null @@ -1,26 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "Stream.h" -#include "WString.h" - -using IPAddress = String; - -class Client : public Stream { - public: - virtual int connect(IPAddress ip, uint16_t port) = 0; - virtual int connect(const char *host, uint16_t port) = 0; - virtual size_t write(uint8_t) = 0; - virtual size_t write(const uint8_t *buf, size_t size) = 0; - virtual int available() = 0; - virtual int read() = 0; - virtual int read(uint8_t *buf, size_t size) = 0; - virtual int peek() = 0; - virtual void flush() = 0; - virtual void stop() = 0; - virtual uint8_t connected() = 0; - virtual operator bool() = 0; -}; diff --git a/lib/ArduinoStreamUtils/extras/test/cores/nrf52/Print.h b/lib/ArduinoStreamUtils/extras/test/cores/nrf52/Print.h deleted file mode 100644 index 2d02babf..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/nrf52/Print.h +++ /dev/null @@ -1,45 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include - -#include -#include - -struct Print { - virtual size_t write(const uint8_t *buffer, size_t size) = 0; - virtual size_t write(uint8_t data) = 0; - - virtual int availableForWrite() { - return 0; - } - - size_t write(const char *buffer, size_t size) { - return write((const uint8_t *)buffer, size); - } - - size_t print(const String &s) { - return write(s.c_str(), s.length()); - } - - size_t print(const char *s) { - return write(s, std::strlen(s)); - } - - size_t println() { - return 0; - } - - template - size_t print(const T &value) { - return print(String(value)); - } - - template - size_t println(const T &value) { - return print(value); - } -}; \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/test/cores/nrf52/Stream.h b/lib/ArduinoStreamUtils/extras/test/cores/nrf52/Stream.h deleted file mode 100644 index 884dbabd..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/nrf52/Stream.h +++ /dev/null @@ -1,45 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "Print.h" - -struct Stream : Print { - virtual int available() = 0; - virtual int read() = 0; - virtual int peek() = 0; - virtual void flush() {} - - size_t readBytes(char *buffer, size_t length) { - size_t count = 0; - while (count < length) { - int c = timedRead(); - if (c < 0) - break; - *buffer++ = (char)c; - count++; - } - return count; - } - - size_t readBytes(uint8_t *buffer, size_t length) { - return readBytes((char *)buffer, length); - } - - String readString() { - String result; - int c; - while ((c = timedRead()) >= 0) - result += c; - return result; - } - - void setTimeout(unsigned long) {} - - protected: - int timedRead() { - return read(); - } -}; diff --git a/lib/ArduinoStreamUtils/extras/test/cores/nrf52/WString.h b/lib/ArduinoStreamUtils/extras/test/cores/nrf52/WString.h deleted file mode 100644 index 9023e414..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/nrf52/WString.h +++ /dev/null @@ -1,5 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "../avr/WString.h" \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/test/cores/samd/Arduino.h b/lib/ArduinoStreamUtils/extras/test/cores/samd/Arduino.h deleted file mode 100644 index e94f54ff..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/samd/Arduino.h +++ /dev/null @@ -1,18 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include -#include -#include -#include - -#include - -inline unsigned long millis() { - return static_cast(time(NULL)); -} - -inline void yield() {} \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/test/cores/samd/CMakeLists.txt b/lib/ArduinoStreamUtils/extras/test/cores/samd/CMakeLists.txt deleted file mode 100644 index ffc774b1..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/samd/CMakeLists.txt +++ /dev/null @@ -1,15 +0,0 @@ -# StreamUtils - github.com/bblanchon/ArduinoStreamUtils -# Copyright Benoit Blanchon 2019-2021 -# MIT License - -add_library(SamdCore INTERFACE) - -target_include_directories(SamdCore - INTERFACE - ${CMAKE_CURRENT_SOURCE_DIR} -) - -target_compile_definitions(SamdCore - INTERFACE - ARDUINO_ARCH_SAMD -) diff --git a/lib/ArduinoStreamUtils/extras/test/cores/samd/Client.h b/lib/ArduinoStreamUtils/extras/test/cores/samd/Client.h deleted file mode 100644 index 1fc8d8f0..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/samd/Client.h +++ /dev/null @@ -1,26 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "Stream.h" -#include "WString.h" - -using IPAddress = String; - -class Client : public Stream { - public: - virtual int connect(IPAddress ip, uint16_t port) = 0; - virtual int connect(const char *host, uint16_t port) = 0; - virtual size_t write(uint8_t) = 0; - virtual size_t write(const uint8_t *buf, size_t size) = 0; - virtual int available() = 0; - virtual int read() = 0; - virtual int read(uint8_t *buf, size_t size) = 0; - virtual int peek() = 0; - virtual void flush() = 0; - virtual void stop() = 0; - virtual uint8_t connected() = 0; - virtual operator bool() = 0; -}; diff --git a/lib/ArduinoStreamUtils/extras/test/cores/samd/Print.h b/lib/ArduinoStreamUtils/extras/test/cores/samd/Print.h deleted file mode 100644 index 7d2c8a0b..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/samd/Print.h +++ /dev/null @@ -1,46 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include - -#include -#include - -struct Print { - virtual size_t write(const uint8_t *buffer, size_t size) = 0; - virtual size_t write(uint8_t data) = 0; - virtual void flush() {} - - virtual int availableForWrite() { - return 0; - } - - size_t write(const char *buffer, size_t size) { - return write((const uint8_t *)buffer, size); - } - - size_t print(const String &s) { - return write(s.c_str(), s.length()); - } - - size_t print(const char *s) { - return write(s, std::strlen(s)); - } - - size_t println() { - return 0; - } - - template - size_t print(const T &value) { - return print(String(value)); - } - - template - size_t println(const T &value) { - return print(value); - } -}; \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/test/cores/samd/Stream.h b/lib/ArduinoStreamUtils/extras/test/cores/samd/Stream.h deleted file mode 100644 index 458f9c3a..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/samd/Stream.h +++ /dev/null @@ -1,44 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "Print.h" - -struct Stream : Print { - virtual int available() = 0; - virtual int read() = 0; - virtual int peek() = 0; - - size_t readBytes(char *buffer, size_t length) { - size_t count = 0; - while (count < length) { - int c = timedRead(); - if (c < 0) - break; - *buffer++ = (char)c; - count++; - } - return count; - } - - size_t readBytes(uint8_t *buffer, size_t length) { - return readBytes((char *)buffer, length); - } - - String readString() { - String result; - int c; - while ((c = timedRead()) >= 0) - result += c; - return result; - } - - void setTimeout(unsigned long) {} - - protected: - int timedRead() { - return read(); - } -}; diff --git a/lib/ArduinoStreamUtils/extras/test/cores/samd/WString.h b/lib/ArduinoStreamUtils/extras/test/cores/samd/WString.h deleted file mode 100644 index 9023e414..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/samd/WString.h +++ /dev/null @@ -1,5 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "../avr/WString.h" \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/test/cores/stm32/Arduino.h b/lib/ArduinoStreamUtils/extras/test/cores/stm32/Arduino.h deleted file mode 100644 index e94f54ff..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/stm32/Arduino.h +++ /dev/null @@ -1,18 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include -#include -#include -#include - -#include - -inline unsigned long millis() { - return static_cast(time(NULL)); -} - -inline void yield() {} \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/test/cores/stm32/CMakeLists.txt b/lib/ArduinoStreamUtils/extras/test/cores/stm32/CMakeLists.txt deleted file mode 100644 index 092f6753..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/stm32/CMakeLists.txt +++ /dev/null @@ -1,22 +0,0 @@ -# StreamUtils - github.com/bblanchon/ArduinoStreamUtils -# Copyright Benoit Blanchon 2019-2021 -# MIT License - -add_library(Stm32Core - Client.h - EEPROM.cpp - EEPROM.h - Print.h - Stream.h - WString.h -) - -target_include_directories(Stm32Core - PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR} -) - -target_compile_definitions(Stm32Core - PUBLIC - ARDUINO_ARCH_STM32 -) diff --git a/lib/ArduinoStreamUtils/extras/test/cores/stm32/Client.h b/lib/ArduinoStreamUtils/extras/test/cores/stm32/Client.h deleted file mode 100644 index 907948de..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/stm32/Client.h +++ /dev/null @@ -1,28 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "Stream.h" -#include "WString.h" - -using IPAddress = String; - -struct Client : Stream { - // Print - virtual size_t write(uint8_t) = 0; - virtual size_t write(const uint8_t *buf, size_t size) = 0; - - // Stream - virtual int available() = 0; - virtual int read() = 0; - virtual void flush() = 0; - - virtual int connect(IPAddress ip, uint16_t port) = 0; - virtual int connect(const char *host, uint16_t port) = 0; - virtual uint8_t connected() = 0; - virtual void stop() = 0; - virtual operator bool() = 0; - virtual int read(uint8_t *buf, size_t size) = 0; -}; diff --git a/lib/ArduinoStreamUtils/extras/test/cores/stm32/EEPROM.cpp b/lib/ArduinoStreamUtils/extras/test/cores/stm32/EEPROM.cpp deleted file mode 100644 index 83af6c18..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/stm32/EEPROM.cpp +++ /dev/null @@ -1,12 +0,0 @@ -#include "EEPROM.h" - -EEPROMClass EEPROM; -static uint8_t data[512]; - -uint8_t EEPROMClass::read(int address) { - return data[address]; -} - -void EEPROMClass::write(int address, uint8_t value) { - data[address] = value; -} diff --git a/lib/ArduinoStreamUtils/extras/test/cores/stm32/EEPROM.h b/lib/ArduinoStreamUtils/extras/test/cores/stm32/EEPROM.h deleted file mode 100644 index 6da7e0c2..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/stm32/EEPROM.h +++ /dev/null @@ -1,11 +0,0 @@ -#pragma once - -#include - -class EEPROMClass { - public: - uint8_t read(int); - void write(int, uint8_t); -}; - -extern EEPROMClass EEPROM; diff --git a/lib/ArduinoStreamUtils/extras/test/cores/stm32/Print.h b/lib/ArduinoStreamUtils/extras/test/cores/stm32/Print.h deleted file mode 100644 index e255ec63..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/stm32/Print.h +++ /dev/null @@ -1,41 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include -#include - -#include - -struct Print { - virtual size_t write(const uint8_t *buffer, size_t size) = 0; - virtual size_t write(uint8_t data) = 0; - - size_t write(const char *buffer, size_t size) { - return write((const uint8_t *)buffer, size); - } - - size_t print(const String &s) { - return write(s.c_str(), s.length()); - } - - size_t print(const char *s) { - return write(s, std::strlen(s)); - } - - size_t println() { - return 0; - } - - template - size_t print(const T &value) { - return print(String(value)); - } - - template - size_t println(const T &value) { - return print(value); - } -}; diff --git a/lib/ArduinoStreamUtils/extras/test/cores/stm32/Stream.h b/lib/ArduinoStreamUtils/extras/test/cores/stm32/Stream.h deleted file mode 100644 index 441eb574..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/stm32/Stream.h +++ /dev/null @@ -1,42 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "Print.h" - -struct Stream : Print { - virtual int available() = 0; - virtual int read() = 0; - virtual int peek() = 0; - virtual void flush() = 0; - - virtual size_t readBytes(char *buffer, size_t length) { - size_t count = 0; - while (count < length) { - int c = timedRead(); - if (c < 0) - break; - *buffer++ = (char)c; - count++; - } - return count; - } - - String readString() { - String result; - int c; - while ((c = timedRead()) >= 0) { - result += static_cast(c); - } - return result; - } - - void setTimeout(unsigned long) {} - - protected: - int timedRead() { - return read(); - } -}; diff --git a/lib/ArduinoStreamUtils/extras/test/cores/stm32/WString.h b/lib/ArduinoStreamUtils/extras/test/cores/stm32/WString.h deleted file mode 100644 index a4c911bd..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/stm32/WString.h +++ /dev/null @@ -1,43 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include - -class String : private std::string { - public: - String() {} - String(const String& s) : std::string(s) {} - String(String&& s) : std::string(std::move(s)) {} - String(const char* s) : std::string(s) {} - String(int n) : std::string(std::to_string(n)) {} - - String& operator=(const String& rhs) { - std::string::operator=(rhs); - return *this; - } - - using std::string::c_str; - using std::string::length; - using std::string::operator+=; - using std::string::operator[]; - - void remove(unsigned int index, unsigned int count) { - erase(begin() + index, begin() + index + count); - } - - void toCharArray(char* buf, unsigned int bufsize, - unsigned int index = 0) const { - copy(buf, bufsize, index); - } - - friend bool operator==(const String& lhs, const char* rhs) { - return static_cast(lhs) == rhs; - } - - friend std::ostream& operator<<(std::ostream& lhs, const String& rhs) { - return lhs << static_cast(rhs); - } -}; diff --git a/lib/ArduinoStreamUtils/extras/test/cores/teensy/Arduino.h b/lib/ArduinoStreamUtils/extras/test/cores/teensy/Arduino.h deleted file mode 100644 index e94f54ff..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/teensy/Arduino.h +++ /dev/null @@ -1,18 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include -#include -#include -#include - -#include - -inline unsigned long millis() { - return static_cast(time(NULL)); -} - -inline void yield() {} \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/test/cores/teensy/CMakeLists.txt b/lib/ArduinoStreamUtils/extras/test/cores/teensy/CMakeLists.txt deleted file mode 100644 index 2b8cb8be..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/teensy/CMakeLists.txt +++ /dev/null @@ -1,22 +0,0 @@ -# StreamUtils - github.com/bblanchon/ArduinoStreamUtils -# Copyright Benoit Blanchon 2019-2021 -# MIT License - -add_library(TeensyCore - Client.h - EEPROM.cpp - EEPROM.h - Print.h - Stream.h - WString.h -) - -target_include_directories(TeensyCore - PUBLIC - ${CMAKE_CURRENT_SOURCE_DIR} -) - -target_compile_definitions(TeensyCore - PUBLIC - CORE_TEENSY -) diff --git a/lib/ArduinoStreamUtils/extras/test/cores/teensy/Client.h b/lib/ArduinoStreamUtils/extras/test/cores/teensy/Client.h deleted file mode 100644 index 20dc08b6..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/teensy/Client.h +++ /dev/null @@ -1,31 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "Stream.h" -#include "WString.h" - -using IPAddress = String; - -struct Client : Stream { - virtual int connect(IPAddress ip, uint16_t port) = 0; - virtual int connect(const char *host, uint16_t port) = 0; - virtual uint8_t connected() = 0; - virtual void stop() = 0; - virtual operator bool() = 0; - - // Already in Print - virtual size_t write(uint8_t) = 0; - virtual size_t write(const uint8_t *buf, size_t size) = 0; - virtual void flush() = 0; - - // Already in Stream - virtual int available() = 0; - virtual int read() = 0; - virtual int peek() = 0; - - // Curiously not in Stream - virtual int read(uint8_t *buf, size_t size) = 0; -}; diff --git a/lib/ArduinoStreamUtils/extras/test/cores/teensy/EEPROM.cpp b/lib/ArduinoStreamUtils/extras/test/cores/teensy/EEPROM.cpp deleted file mode 100644 index 2b2eb1a8..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/teensy/EEPROM.cpp +++ /dev/null @@ -1,12 +0,0 @@ -#include "EEPROM.h" - -EEPROMClass EEPROM; -static uint8_t data[512]; - -uint8_t EEPROMClass::read(int address) { - return data[address]; -} - -void EEPROMClass::update(int address, uint8_t value) { - data[address] = value; -} diff --git a/lib/ArduinoStreamUtils/extras/test/cores/teensy/EEPROM.h b/lib/ArduinoStreamUtils/extras/test/cores/teensy/EEPROM.h deleted file mode 100644 index b5e3360c..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/teensy/EEPROM.h +++ /dev/null @@ -1,12 +0,0 @@ -#pragma once - -#include - -class EEPROMClass { - public: - uint8_t read(int); - void update(int, uint8_t); - // void write(int, uint8_t); <- it exists but we want to use update() instead -}; - -extern EEPROMClass EEPROM; diff --git a/lib/ArduinoStreamUtils/extras/test/cores/teensy/Print.h b/lib/ArduinoStreamUtils/extras/test/cores/teensy/Print.h deleted file mode 100644 index 7d2c8a0b..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/teensy/Print.h +++ /dev/null @@ -1,46 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include - -#include -#include - -struct Print { - virtual size_t write(const uint8_t *buffer, size_t size) = 0; - virtual size_t write(uint8_t data) = 0; - virtual void flush() {} - - virtual int availableForWrite() { - return 0; - } - - size_t write(const char *buffer, size_t size) { - return write((const uint8_t *)buffer, size); - } - - size_t print(const String &s) { - return write(s.c_str(), s.length()); - } - - size_t print(const char *s) { - return write(s, std::strlen(s)); - } - - size_t println() { - return 0; - } - - template - size_t print(const T &value) { - return print(String(value)); - } - - template - size_t println(const T &value) { - return print(value); - } -}; \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/test/cores/teensy/Stream.h b/lib/ArduinoStreamUtils/extras/test/cores/teensy/Stream.h deleted file mode 100644 index 6515a1e3..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/teensy/Stream.h +++ /dev/null @@ -1,42 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "Print.h" - -struct Stream : Print { - virtual int available() = 0; - virtual int read() = 0; - virtual int peek() = 0; - virtual void flush() = 0; - - size_t readBytes(char *buffer, size_t length) { - size_t count = 0; - while (count < length) { - int c = timedRead(); - if (c < 0) - break; - *buffer++ = (char)c; - count++; - } - return count; - } - - String readString() { - String result; - int c; - while ((c = timedRead()) >= 0) { - result += static_cast(c); - } - return result; - } - - void setTimeout(unsigned long) {} - - private: - int timedRead() { - return read(); - } -}; diff --git a/lib/ArduinoStreamUtils/extras/test/cores/teensy/WString.h b/lib/ArduinoStreamUtils/extras/test/cores/teensy/WString.h deleted file mode 100644 index f0b99e22..00000000 --- a/lib/ArduinoStreamUtils/extras/test/cores/teensy/WString.h +++ /dev/null @@ -1,7 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../avr/WString.h" \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/extras/test/doctest.h b/lib/ArduinoStreamUtils/extras/test/doctest.h deleted file mode 100644 index 9f004da5..00000000 --- a/lib/ArduinoStreamUtils/extras/test/doctest.h +++ /dev/null @@ -1,6000 +0,0 @@ -// ====================================================================== lgtm [cpp/missing-header-guard] -// == DO NOT MODIFY THIS FILE BY HAND - IT IS AUTO GENERATED BY CMAKE! == -// ====================================================================== -// -// doctest.h - the lightest feature-rich C++ single-header testing framework for unit tests and TDD -// -// Copyright (c) 2016-2019 Viktor Kirilov -// -// Distributed under the MIT Software License -// See accompanying file LICENSE.txt or copy at -// https://opensource.org/licenses/MIT -// -// The documentation can be found at the library's page: -// https://github.com/onqtam/doctest/blob/master/doc/markdown/readme.md -// -// ================================================================================================= -// ================================================================================================= -// ================================================================================================= -// -// The library is heavily influenced by Catch - https://github.com/catchorg/Catch2 -// which uses the Boost Software License - Version 1.0 -// see here - https://github.com/catchorg/Catch2/blob/master/LICENSE.txt -// -// The concept of subcases (sections in Catch) and expression decomposition are from there. -// Some parts of the code are taken directly: -// - stringification - the detection of "ostream& operator<<(ostream&, const T&)" and StringMaker<> -// - the Approx() helper class for floating point comparison -// - colors in the console -// - breaking into a debugger -// - signal / SEH handling -// - timer -// - XmlWriter class - thanks to Phil Nash for allowing the direct reuse (AKA copy/paste) -// -// The expression decomposing templates are taken from lest - https://github.com/martinmoene/lest -// which uses the Boost Software License - Version 1.0 -// see here - https://github.com/martinmoene/lest/blob/master/LICENSE.txt -// -// ================================================================================================= -// ================================================================================================= -// ================================================================================================= - -#ifndef DOCTEST_LIBRARY_INCLUDED -#define DOCTEST_LIBRARY_INCLUDED - -// ================================================================================================= -// == VERSION ====================================================================================== -// ================================================================================================= - -#define DOCTEST_VERSION_MAJOR 2 -#define DOCTEST_VERSION_MINOR 3 -#define DOCTEST_VERSION_PATCH 1 -#define DOCTEST_VERSION_STR "2.3.1" - -#define DOCTEST_VERSION \ - (DOCTEST_VERSION_MAJOR * 10000 + DOCTEST_VERSION_MINOR * 100 + DOCTEST_VERSION_PATCH) - -// ================================================================================================= -// == COMPILER VERSION ============================================================================= -// ================================================================================================= - -// ideas for the version stuff are taken from here: https://github.com/cxxstuff/cxx_detect - -#define DOCTEST_COMPILER(MAJOR, MINOR, PATCH) ((MAJOR)*10000000 + (MINOR)*100000 + (PATCH)) - -// GCC/Clang and GCC/MSVC are mutually exclusive, but Clang/MSVC are not because of clang-cl... -#if defined(_MSC_VER) && defined(_MSC_FULL_VER) -#if _MSC_VER == _MSC_FULL_VER / 10000 -#define DOCTEST_MSVC DOCTEST_COMPILER(_MSC_VER / 100, _MSC_VER % 100, _MSC_FULL_VER % 10000) -#else // MSVC -#define DOCTEST_MSVC \ - DOCTEST_COMPILER(_MSC_VER / 100, (_MSC_FULL_VER / 100000) % 100, _MSC_FULL_VER % 100000) -#endif // MSVC -#endif // MSVC -#if defined(__clang__) && defined(__clang_minor__) -#define DOCTEST_CLANG DOCTEST_COMPILER(__clang_major__, __clang_minor__, __clang_patchlevel__) -#elif defined(__GNUC__) && defined(__GNUC_MINOR__) && defined(__GNUC_PATCHLEVEL__) && \ - !defined(__INTEL_COMPILER) -#define DOCTEST_GCC DOCTEST_COMPILER(__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__) -#endif // GCC - -#ifndef DOCTEST_MSVC -#define DOCTEST_MSVC 0 -#endif // DOCTEST_MSVC -#ifndef DOCTEST_CLANG -#define DOCTEST_CLANG 0 -#endif // DOCTEST_CLANG -#ifndef DOCTEST_GCC -#define DOCTEST_GCC 0 -#endif // DOCTEST_GCC - -// ================================================================================================= -// == COMPILER WARNINGS HELPERS ==================================================================== -// ================================================================================================= - -#if DOCTEST_CLANG -#define DOCTEST_PRAGMA_TO_STR(x) _Pragma(#x) -#define DOCTEST_CLANG_SUPPRESS_WARNING_PUSH _Pragma("clang diagnostic push") -#define DOCTEST_CLANG_SUPPRESS_WARNING(w) DOCTEST_PRAGMA_TO_STR(clang diagnostic ignored w) -#define DOCTEST_CLANG_SUPPRESS_WARNING_POP _Pragma("clang diagnostic pop") -#define DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH(w) \ - DOCTEST_CLANG_SUPPRESS_WARNING_PUSH DOCTEST_CLANG_SUPPRESS_WARNING(w) -#else // DOCTEST_CLANG -#define DOCTEST_CLANG_SUPPRESS_WARNING_PUSH -#define DOCTEST_CLANG_SUPPRESS_WARNING(w) -#define DOCTEST_CLANG_SUPPRESS_WARNING_POP -#define DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH(w) -#endif // DOCTEST_CLANG - -#if DOCTEST_GCC -#define DOCTEST_PRAGMA_TO_STR(x) _Pragma(#x) -#define DOCTEST_GCC_SUPPRESS_WARNING_PUSH _Pragma("GCC diagnostic push") -#define DOCTEST_GCC_SUPPRESS_WARNING(w) DOCTEST_PRAGMA_TO_STR(GCC diagnostic ignored w) -#define DOCTEST_GCC_SUPPRESS_WARNING_POP _Pragma("GCC diagnostic pop") -#define DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH(w) \ - DOCTEST_GCC_SUPPRESS_WARNING_PUSH DOCTEST_GCC_SUPPRESS_WARNING(w) -#else // DOCTEST_GCC -#define DOCTEST_GCC_SUPPRESS_WARNING_PUSH -#define DOCTEST_GCC_SUPPRESS_WARNING(w) -#define DOCTEST_GCC_SUPPRESS_WARNING_POP -#define DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH(w) -#endif // DOCTEST_GCC - -#if DOCTEST_MSVC -#define DOCTEST_MSVC_SUPPRESS_WARNING_PUSH __pragma(warning(push)) -#define DOCTEST_MSVC_SUPPRESS_WARNING(w) __pragma(warning(disable : w)) -#define DOCTEST_MSVC_SUPPRESS_WARNING_POP __pragma(warning(pop)) -#define DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(w) \ - DOCTEST_MSVC_SUPPRESS_WARNING_PUSH DOCTEST_MSVC_SUPPRESS_WARNING(w) -#else // DOCTEST_MSVC -#define DOCTEST_MSVC_SUPPRESS_WARNING_PUSH -#define DOCTEST_MSVC_SUPPRESS_WARNING(w) -#define DOCTEST_MSVC_SUPPRESS_WARNING_POP -#define DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(w) -#endif // DOCTEST_MSVC - -// ================================================================================================= -// == COMPILER WARNINGS ============================================================================ -// ================================================================================================= - -DOCTEST_CLANG_SUPPRESS_WARNING_PUSH -DOCTEST_CLANG_SUPPRESS_WARNING("-Wunknown-pragmas") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wnon-virtual-dtor") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wweak-vtables") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wpadded") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wdeprecated") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-prototypes") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wunused-local-typedef") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wc++98-compat") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wc++98-compat-pedantic") - -DOCTEST_GCC_SUPPRESS_WARNING_PUSH -DOCTEST_GCC_SUPPRESS_WARNING("-Wunknown-pragmas") -DOCTEST_GCC_SUPPRESS_WARNING("-Wpragmas") -DOCTEST_GCC_SUPPRESS_WARNING("-Weffc++") -DOCTEST_GCC_SUPPRESS_WARNING("-Wstrict-overflow") -DOCTEST_GCC_SUPPRESS_WARNING("-Wstrict-aliasing") -DOCTEST_GCC_SUPPRESS_WARNING("-Wctor-dtor-privacy") -DOCTEST_GCC_SUPPRESS_WARNING("-Wmissing-declarations") -DOCTEST_GCC_SUPPRESS_WARNING("-Wnon-virtual-dtor") -DOCTEST_GCC_SUPPRESS_WARNING("-Winline") -DOCTEST_GCC_SUPPRESS_WARNING("-Wunused-local-typedefs") -DOCTEST_GCC_SUPPRESS_WARNING("-Wuseless-cast") - -DOCTEST_MSVC_SUPPRESS_WARNING_PUSH -DOCTEST_MSVC_SUPPRESS_WARNING(4616) // invalid compiler warning -DOCTEST_MSVC_SUPPRESS_WARNING(4619) // invalid compiler warning -DOCTEST_MSVC_SUPPRESS_WARNING(4996) // The compiler encountered a deprecated declaration -DOCTEST_MSVC_SUPPRESS_WARNING(4706) // assignment within conditional expression -DOCTEST_MSVC_SUPPRESS_WARNING(4512) // 'class' : assignment operator could not be generated -DOCTEST_MSVC_SUPPRESS_WARNING(4127) // conditional expression is constant -DOCTEST_MSVC_SUPPRESS_WARNING(4820) // padding -DOCTEST_MSVC_SUPPRESS_WARNING(4625) // copy constructor was implicitly defined as deleted -DOCTEST_MSVC_SUPPRESS_WARNING(4626) // assignment operator was implicitly defined as deleted -DOCTEST_MSVC_SUPPRESS_WARNING(5027) // move assignment operator was implicitly defined as deleted -DOCTEST_MSVC_SUPPRESS_WARNING(5026) // move constructor was implicitly defined as deleted -DOCTEST_MSVC_SUPPRESS_WARNING(4623) // default constructor was implicitly defined as deleted -DOCTEST_MSVC_SUPPRESS_WARNING(4640) // construction of local static object is not thread-safe -// static analysis -DOCTEST_MSVC_SUPPRESS_WARNING(26439) // This kind of function may not throw. Declare it 'noexcept' -DOCTEST_MSVC_SUPPRESS_WARNING(26495) // Always initialize a member variable -DOCTEST_MSVC_SUPPRESS_WARNING(26451) // Arithmetic overflow ... -DOCTEST_MSVC_SUPPRESS_WARNING(26444) // Avoid unnamed objects with custom construction and dtr... - -// 4548 - expression before comma has no effect; expected expression with side - effect -// 4265 - class has virtual functions, but destructor is not virtual -// 4986 - exception specification does not match previous declaration -// 4350 - behavior change: 'member1' called instead of 'member2' -// 4668 - 'x' is not defined as a preprocessor macro, replacing with '0' for '#if/#elif' -// 4365 - conversion from 'int' to 'unsigned long', signed/unsigned mismatch -// 4774 - format string expected in argument 'x' is not a string literal -// 4820 - padding in structs - -// only 4 should be disabled globally: -// - 4514 # unreferenced inline function has been removed -// - 4571 # SEH related -// - 4710 # function not inlined -// - 4711 # function 'x' selected for automatic inline expansion - -#define DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_BEGIN \ - DOCTEST_MSVC_SUPPRESS_WARNING_PUSH \ - DOCTEST_MSVC_SUPPRESS_WARNING(4548) \ - DOCTEST_MSVC_SUPPRESS_WARNING(4265) \ - DOCTEST_MSVC_SUPPRESS_WARNING(4986) \ - DOCTEST_MSVC_SUPPRESS_WARNING(4350) \ - DOCTEST_MSVC_SUPPRESS_WARNING(4668) \ - DOCTEST_MSVC_SUPPRESS_WARNING(4365) \ - DOCTEST_MSVC_SUPPRESS_WARNING(4774) \ - DOCTEST_MSVC_SUPPRESS_WARNING(4820) \ - DOCTEST_MSVC_SUPPRESS_WARNING(4625) \ - DOCTEST_MSVC_SUPPRESS_WARNING(4626) \ - DOCTEST_MSVC_SUPPRESS_WARNING(5027) \ - DOCTEST_MSVC_SUPPRESS_WARNING(5026) \ - DOCTEST_MSVC_SUPPRESS_WARNING(4623) \ - DOCTEST_MSVC_SUPPRESS_WARNING(5039) \ - DOCTEST_MSVC_SUPPRESS_WARNING(5045) - -#define DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_END DOCTEST_MSVC_SUPPRESS_WARNING_POP - -// ================================================================================================= -// == FEATURE DETECTION ============================================================================ -// ================================================================================================= - -// general compiler feature support table: https://en.cppreference.com/w/cpp/compiler_support -// MSVC C++11 feature support table: https://msdn.microsoft.com/en-us/library/hh567368.aspx -// GCC C++11 feature support table: https://gcc.gnu.org/projects/cxx-status.html -// MSVC version table: -// https://en.wikipedia.org/wiki/Microsoft_Visual_C%2B%2B#Internal_version_numbering -// MSVC++ 14.2 (16) _MSC_VER == 1920 (Visual Studio 2019) << NOT YET RELEASED - April 2 2019 -// MSVC++ 14.1 (15) _MSC_VER == 1910 (Visual Studio 2017) -// MSVC++ 14.0 _MSC_VER == 1900 (Visual Studio 2015) -// MSVC++ 12.0 _MSC_VER == 1800 (Visual Studio 2013) -// MSVC++ 11.0 _MSC_VER == 1700 (Visual Studio 2012) -// MSVC++ 10.0 _MSC_VER == 1600 (Visual Studio 2010) -// MSVC++ 9.0 _MSC_VER == 1500 (Visual Studio 2008) -// MSVC++ 8.0 _MSC_VER == 1400 (Visual Studio 2005) - -#if DOCTEST_MSVC && !defined(DOCTEST_CONFIG_WINDOWS_SEH) -#define DOCTEST_CONFIG_WINDOWS_SEH -#endif // MSVC -#if defined(DOCTEST_CONFIG_NO_WINDOWS_SEH) && defined(DOCTEST_CONFIG_WINDOWS_SEH) -#undef DOCTEST_CONFIG_WINDOWS_SEH -#endif // DOCTEST_CONFIG_NO_WINDOWS_SEH - -#if !defined(_WIN32) && !defined(__QNX__) && !defined(DOCTEST_CONFIG_POSIX_SIGNALS) && \ - !defined(__EMSCRIPTEN__) -#define DOCTEST_CONFIG_POSIX_SIGNALS -#endif // _WIN32 -#if defined(DOCTEST_CONFIG_NO_POSIX_SIGNALS) && defined(DOCTEST_CONFIG_POSIX_SIGNALS) -#undef DOCTEST_CONFIG_POSIX_SIGNALS -#endif // DOCTEST_CONFIG_NO_POSIX_SIGNALS - -#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS -#if !defined(__cpp_exceptions) && !defined(__EXCEPTIONS) && !defined(_CPPUNWIND) -#define DOCTEST_CONFIG_NO_EXCEPTIONS -#endif // no exceptions -#endif // DOCTEST_CONFIG_NO_EXCEPTIONS - -#ifdef DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS -#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS -#define DOCTEST_CONFIG_NO_EXCEPTIONS -#endif // DOCTEST_CONFIG_NO_EXCEPTIONS -#endif // DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS - -#if defined(DOCTEST_CONFIG_NO_EXCEPTIONS) && !defined(DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS) -#define DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS -#endif // DOCTEST_CONFIG_NO_EXCEPTIONS && !DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS - -#if defined(DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN) && !defined(DOCTEST_CONFIG_IMPLEMENT) -#define DOCTEST_CONFIG_IMPLEMENT -#endif // DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN - -#if defined(_WIN32) || defined(__CYGWIN__) -#if DOCTEST_MSVC -#define DOCTEST_SYMBOL_EXPORT __declspec(dllexport) -#define DOCTEST_SYMBOL_IMPORT __declspec(dllimport) -#else // MSVC -#define DOCTEST_SYMBOL_EXPORT __attribute__((dllexport)) -#define DOCTEST_SYMBOL_IMPORT __attribute__((dllimport)) -#endif // MSVC -#else // _WIN32 -#define DOCTEST_SYMBOL_EXPORT __attribute__((visibility("default"))) -#define DOCTEST_SYMBOL_IMPORT -#endif // _WIN32 - -#ifdef DOCTEST_CONFIG_IMPLEMENTATION_IN_DLL -#ifdef DOCTEST_CONFIG_IMPLEMENT -#define DOCTEST_INTERFACE DOCTEST_SYMBOL_EXPORT -#else // DOCTEST_CONFIG_IMPLEMENT -#define DOCTEST_INTERFACE DOCTEST_SYMBOL_IMPORT -#endif // DOCTEST_CONFIG_IMPLEMENT -#else // DOCTEST_CONFIG_IMPLEMENTATION_IN_DLL -#define DOCTEST_INTERFACE -#endif // DOCTEST_CONFIG_IMPLEMENTATION_IN_DLL - -#define DOCTEST_EMPTY - -#if DOCTEST_MSVC -#define DOCTEST_NOINLINE __declspec(noinline) -#define DOCTEST_UNUSED -#define DOCTEST_ALIGNMENT(x) -#else // MSVC -#define DOCTEST_NOINLINE __attribute__((noinline)) -#define DOCTEST_UNUSED __attribute__((unused)) -#define DOCTEST_ALIGNMENT(x) __attribute__((aligned(x))) -#endif // MSVC - -#ifndef DOCTEST_CONFIG_NUM_CAPTURES_ON_STACK -#define DOCTEST_CONFIG_NUM_CAPTURES_ON_STACK 5 -#endif // DOCTEST_CONFIG_NUM_CAPTURES_ON_STACK - -// ================================================================================================= -// == FEATURE DETECTION END ======================================================================== -// ================================================================================================= - -// internal macros for string concatenation and anonymous variable name generation -#define DOCTEST_CAT_IMPL(s1, s2) s1##s2 -#define DOCTEST_CAT(s1, s2) DOCTEST_CAT_IMPL(s1, s2) -#ifdef __COUNTER__ // not standard and may be missing for some compilers -#define DOCTEST_ANONYMOUS(x) DOCTEST_CAT(x, __COUNTER__) -#else // __COUNTER__ -#define DOCTEST_ANONYMOUS(x) DOCTEST_CAT(x, __LINE__) -#endif // __COUNTER__ - -#define DOCTEST_TOSTR(x) #x - -#ifndef DOCTEST_CONFIG_ASSERTION_PARAMETERS_BY_VALUE -#define DOCTEST_REF_WRAP(x) x& -#else // DOCTEST_CONFIG_ASSERTION_PARAMETERS_BY_VALUE -#define DOCTEST_REF_WRAP(x) x -#endif // DOCTEST_CONFIG_ASSERTION_PARAMETERS_BY_VALUE - -// not using __APPLE__ because... this is how Catch does it -#ifdef __MAC_OS_X_VERSION_MIN_REQUIRED -#define DOCTEST_PLATFORM_MAC -#elif defined(__IPHONE_OS_VERSION_MIN_REQUIRED) -#define DOCTEST_PLATFORM_IPHONE -#elif defined(_WIN32) -#define DOCTEST_PLATFORM_WINDOWS -#else // DOCTEST_PLATFORM -#define DOCTEST_PLATFORM_LINUX -#endif // DOCTEST_PLATFORM - -// clang-format off -#define DOCTEST_DELETE_COPIES(type) type(const type&) = delete; type& operator=(const type&) = delete -#define DOCTEST_DECLARE_COPIES(type) type(const type&); type& operator=(const type&) -#define DOCTEST_DEFINE_COPIES(type) type::type(const type&) = default; type& type::operator=(const type&) = default -#define DOCTEST_DECLARE_DEFAULTS(type) type(); ~type() -#define DOCTEST_DEFINE_DEFAULTS(type) type::type() = default; type::~type() = default -// clang-format on - -#define DOCTEST_GLOBAL_NO_WARNINGS(var) \ - DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wglobal-constructors") \ - static int var DOCTEST_UNUSED // NOLINT(fuchsia-statically-constructed-objects,cert-err58-cpp) -#define DOCTEST_GLOBAL_NO_WARNINGS_END() DOCTEST_CLANG_SUPPRESS_WARNING_POP - -// should probably take a look at https://github.com/scottt/debugbreak -#ifdef DOCTEST_PLATFORM_MAC -#define DOCTEST_BREAK_INTO_DEBUGGER() __asm__("int $3\n" : :) -#elif DOCTEST_MSVC -#define DOCTEST_BREAK_INTO_DEBUGGER() __debugbreak() -#elif defined(__MINGW32__) -extern "C" __declspec(dllimport) void __stdcall DebugBreak(); -#define DOCTEST_BREAK_INTO_DEBUGGER() ::DebugBreak() -#else // linux -#define DOCTEST_BREAK_INTO_DEBUGGER() ((void)0) -#endif // linux - -// this is kept here for backwards compatibility since the config option was changed -#ifdef DOCTEST_CONFIG_USE_IOSFWD -#define DOCTEST_CONFIG_USE_STD_HEADERS -#endif // DOCTEST_CONFIG_USE_IOSFWD - -#ifdef DOCTEST_CONFIG_USE_STD_HEADERS -#include -#include -#else // DOCTEST_CONFIG_USE_STD_HEADERS - -#if DOCTEST_CLANG -// to detect if libc++ is being used with clang (the _LIBCPP_VERSION identifier) -#include -#endif // clang - -#ifdef _LIBCPP_VERSION -#define DOCTEST_STD_NAMESPACE_BEGIN _LIBCPP_BEGIN_NAMESPACE_STD -#define DOCTEST_STD_NAMESPACE_END _LIBCPP_END_NAMESPACE_STD -#else // _LIBCPP_VERSION -#define DOCTEST_STD_NAMESPACE_BEGIN namespace std { -#define DOCTEST_STD_NAMESPACE_END } -#endif // _LIBCPP_VERSION - -// Forward declaring 'X' in namespace std is not permitted by the C++ Standard. -DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4643) - -DOCTEST_STD_NAMESPACE_BEGIN -typedef decltype(nullptr) nullptr_t; -template -struct char_traits; -template <> -struct char_traits; -template -class basic_ostream; -typedef basic_ostream> ostream; -template -class tuple; -DOCTEST_STD_NAMESPACE_END - -DOCTEST_MSVC_SUPPRESS_WARNING_POP - -#endif // DOCTEST_CONFIG_USE_STD_HEADERS - -#ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS -#include -#endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS - -namespace doctest { - -DOCTEST_INTERFACE extern bool is_running_in_test; - -// A 24 byte string class (can be as small as 17 for x64 and 13 for x86) that can hold strings with length -// of up to 23 chars on the stack before going on the heap - the last byte of the buffer is used for: -// - "is small" bit - the highest bit - if "0" then it is small - otherwise its "1" (128) -// - if small - capacity left before going on the heap - using the lowest 5 bits -// - if small - 2 bits are left unused - the second and third highest ones -// - if small - acts as a null terminator if strlen() is 23 (24 including the null terminator) -// and the "is small" bit remains "0" ("as well as the capacity left") so its OK -// Idea taken from this lecture about the string implementation of facebook/folly - fbstring -// https://www.youtube.com/watch?v=kPR8h4-qZdk -// TODO: -// - optimizations - like not deleting memory unnecessarily in operator= and etc. -// - resize/reserve/clear -// - substr -// - replace -// - back/front -// - iterator stuff -// - find & friends -// - push_back/pop_back -// - assign/insert/erase -// - relational operators as free functions - taking const char* as one of the params -class DOCTEST_INTERFACE String -{ - static const unsigned len = 24; //!OCLINT avoid private static members - static const unsigned last = len - 1; //!OCLINT avoid private static members - - struct view // len should be more than sizeof(view) - because of the final byte for flags - { - char* ptr; - unsigned size; - unsigned capacity; - }; - - union - { - char buf[len]; - view data; - }; - - bool isOnStack() const { return (buf[last] & 128) == 0; } - void setOnHeap(); - void setLast(unsigned in = last); - - void copy(const String& other); - -public: - String(); - ~String(); - - // cppcheck-suppress noExplicitConstructor - String(const char* in); - String(const char* in, unsigned in_size); - - String(const String& other); - String& operator=(const String& other); - - String& operator+=(const String& other); - String operator+(const String& other) const; - - String(String&& other); - String& operator=(String&& other); - - char operator[](unsigned i) const; - char& operator[](unsigned i); - - // the only functions I'm willing to leave in the interface - available for inlining - const char* c_str() const { return const_cast(this)->c_str(); } // NOLINT - char* c_str() { - if(isOnStack()) - return reinterpret_cast(buf); - return data.ptr; - } - - unsigned size() const; - unsigned capacity() const; - - int compare(const char* other, bool no_case = false) const; - int compare(const String& other, bool no_case = false) const; -}; - -DOCTEST_INTERFACE bool operator==(const String& lhs, const String& rhs); -DOCTEST_INTERFACE bool operator!=(const String& lhs, const String& rhs); -DOCTEST_INTERFACE bool operator<(const String& lhs, const String& rhs); -DOCTEST_INTERFACE bool operator>(const String& lhs, const String& rhs); -DOCTEST_INTERFACE bool operator<=(const String& lhs, const String& rhs); -DOCTEST_INTERFACE bool operator>=(const String& lhs, const String& rhs); - -DOCTEST_INTERFACE std::ostream& operator<<(std::ostream& s, const String& in); - -namespace Color { - enum Enum - { - None = 0, - White, - Red, - Green, - Blue, - Cyan, - Yellow, - Grey, - - Bright = 0x10, - - BrightRed = Bright | Red, - BrightGreen = Bright | Green, - LightGrey = Bright | Grey, - BrightWhite = Bright | White - }; - - DOCTEST_INTERFACE std::ostream& operator<<(std::ostream& s, Color::Enum code); -} // namespace Color - -namespace assertType { - enum Enum - { - // macro traits - - is_warn = 1, - is_check = 2 * is_warn, - is_require = 2 * is_check, - - is_normal = 2 * is_require, - is_throws = 2 * is_normal, - is_throws_as = 2 * is_throws, - is_throws_with = 2 * is_throws_as, - is_nothrow = 2 * is_throws_with, - - is_false = 2 * is_nothrow, - is_unary = 2 * is_false, // not checked anywhere - used just to distinguish the types - - is_eq = 2 * is_unary, - is_ne = 2 * is_eq, - - is_lt = 2 * is_ne, - is_gt = 2 * is_lt, - - is_ge = 2 * is_gt, - is_le = 2 * is_ge, - - // macro types - - DT_WARN = is_normal | is_warn, - DT_CHECK = is_normal | is_check, - DT_REQUIRE = is_normal | is_require, - - DT_WARN_FALSE = is_normal | is_false | is_warn, - DT_CHECK_FALSE = is_normal | is_false | is_check, - DT_REQUIRE_FALSE = is_normal | is_false | is_require, - - DT_WARN_THROWS = is_throws | is_warn, - DT_CHECK_THROWS = is_throws | is_check, - DT_REQUIRE_THROWS = is_throws | is_require, - - DT_WARN_THROWS_AS = is_throws_as | is_warn, - DT_CHECK_THROWS_AS = is_throws_as | is_check, - DT_REQUIRE_THROWS_AS = is_throws_as | is_require, - - DT_WARN_THROWS_WITH = is_throws_with | is_warn, - DT_CHECK_THROWS_WITH = is_throws_with | is_check, - DT_REQUIRE_THROWS_WITH = is_throws_with | is_require, - - DT_WARN_NOTHROW = is_nothrow | is_warn, - DT_CHECK_NOTHROW = is_nothrow | is_check, - DT_REQUIRE_NOTHROW = is_nothrow | is_require, - - DT_WARN_EQ = is_normal | is_eq | is_warn, - DT_CHECK_EQ = is_normal | is_eq | is_check, - DT_REQUIRE_EQ = is_normal | is_eq | is_require, - - DT_WARN_NE = is_normal | is_ne | is_warn, - DT_CHECK_NE = is_normal | is_ne | is_check, - DT_REQUIRE_NE = is_normal | is_ne | is_require, - - DT_WARN_GT = is_normal | is_gt | is_warn, - DT_CHECK_GT = is_normal | is_gt | is_check, - DT_REQUIRE_GT = is_normal | is_gt | is_require, - - DT_WARN_LT = is_normal | is_lt | is_warn, - DT_CHECK_LT = is_normal | is_lt | is_check, - DT_REQUIRE_LT = is_normal | is_lt | is_require, - - DT_WARN_GE = is_normal | is_ge | is_warn, - DT_CHECK_GE = is_normal | is_ge | is_check, - DT_REQUIRE_GE = is_normal | is_ge | is_require, - - DT_WARN_LE = is_normal | is_le | is_warn, - DT_CHECK_LE = is_normal | is_le | is_check, - DT_REQUIRE_LE = is_normal | is_le | is_require, - - DT_WARN_UNARY = is_normal | is_unary | is_warn, - DT_CHECK_UNARY = is_normal | is_unary | is_check, - DT_REQUIRE_UNARY = is_normal | is_unary | is_require, - - DT_WARN_UNARY_FALSE = is_normal | is_false | is_unary | is_warn, - DT_CHECK_UNARY_FALSE = is_normal | is_false | is_unary | is_check, - DT_REQUIRE_UNARY_FALSE = is_normal | is_false | is_unary | is_require, - }; -} // namespace assertType - -DOCTEST_INTERFACE const char* assertString(assertType::Enum at); -DOCTEST_INTERFACE const char* failureString(assertType::Enum at); -DOCTEST_INTERFACE const char* skipPathFromFilename(const char* file); - -struct DOCTEST_INTERFACE TestCaseData -{ - const char* m_file; // the file in which the test was registered - unsigned m_line; // the line where the test was registered - const char* m_name; // name of the test case - const char* m_test_suite; // the test suite in which the test was added - const char* m_description; - bool m_skip; - bool m_may_fail; - bool m_should_fail; - int m_expected_failures; - double m_timeout; - - DOCTEST_DECLARE_DEFAULTS(TestCaseData); - DOCTEST_DECLARE_COPIES(TestCaseData); -}; - -struct DOCTEST_INTERFACE AssertData -{ - // common - for all asserts - const TestCaseData* m_test_case; - assertType::Enum m_at; - const char* m_file; - int m_line; - const char* m_expr; - bool m_failed; - - // exception-related - for all asserts - bool m_threw; - String m_exception; - - // for normal asserts - String m_decomp; - - // for specific exception-related asserts - bool m_threw_as; - const char* m_exception_type; - - DOCTEST_DECLARE_DEFAULTS(AssertData); - DOCTEST_DELETE_COPIES(AssertData); -}; - -struct DOCTEST_INTERFACE MessageData -{ - String m_string; - const char* m_file; - int m_line; - assertType::Enum m_severity; - - DOCTEST_DECLARE_DEFAULTS(MessageData); - DOCTEST_DELETE_COPIES(MessageData); -}; - -struct DOCTEST_INTERFACE SubcaseSignature -{ - const char* m_name; - const char* m_file; - int m_line; - - SubcaseSignature(const char* name, const char* file, int line); - - bool operator<(const SubcaseSignature& other) const; - - DOCTEST_DECLARE_DEFAULTS(SubcaseSignature); - DOCTEST_DECLARE_COPIES(SubcaseSignature); -}; - -struct DOCTEST_INTERFACE IContextScope -{ - DOCTEST_DELETE_COPIES(IContextScope); - - IContextScope(); - virtual ~IContextScope(); - virtual void stringify(std::ostream*) const = 0; -}; - -struct ContextOptions //!OCLINT too many fields -{ - std::ostream* cout; // stdout stream - std::cout by default - std::ostream* cerr; // stderr stream - std::cerr by default - String binary_name; // the test binary name - - // == parameters from the command line - String out; // output filename - String order_by; // how tests should be ordered - unsigned rand_seed; // the seed for rand ordering - - unsigned first; // the first (matching) test to be executed - unsigned last; // the last (matching) test to be executed - - int abort_after; // stop tests after this many failed assertions - int subcase_filter_levels; // apply the subcase filters for the first N levels - - bool success; // include successful assertions in output - bool case_sensitive; // if filtering should be case sensitive - bool exit; // if the program should be exited after the tests are ran/whatever - bool duration; // print the time duration of each test case - bool no_throw; // to skip exceptions-related assertion macros - bool no_exitcode; // if the framework should return 0 as the exitcode - bool no_run; // to not run the tests at all (can be done with an "*" exclude) - bool no_version; // to not print the version of the framework - bool no_colors; // if output to the console should be colorized - bool force_colors; // forces the use of colors even when a tty cannot be detected - bool no_breaks; // to not break into the debugger - bool no_skip; // don't skip test cases which are marked to be skipped - bool gnu_file_line; // if line numbers should be surrounded with :x: and not (x): - bool no_path_in_filenames; // if the path to files should be removed from the output - bool no_line_numbers; // if source code line numbers should be omitted from the output - bool no_skipped_summary; // don't print "skipped" in the summary !!! UNDOCUMENTED !!! - - bool help; // to print the help - bool version; // to print the version - bool count; // if only the count of matching tests is to be retreived - bool list_test_cases; // to list all tests matching the filters - bool list_test_suites; // to list all suites matching the filters - bool list_reporters; // lists all registered reporters - - DOCTEST_DECLARE_DEFAULTS(ContextOptions); - DOCTEST_DELETE_COPIES(ContextOptions); -}; - -namespace detail { -#if defined(DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING) || defined(DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS) - template - struct enable_if - {}; - - template - struct enable_if - { typedef TYPE type; }; -#endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING) || DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS - - // clang-format off - template struct remove_reference { typedef T type; }; - template struct remove_reference { typedef T type; }; - template struct remove_reference { typedef T type; }; - - template struct remove_const { typedef T type; }; - template struct remove_const { typedef T type; }; - // clang-format on - - template - struct deferred_false - // cppcheck-suppress unusedStructMember - { static const bool value = false; }; - - namespace has_insertion_operator_impl { - typedef char no; - typedef char yes[2]; - - struct any_t - { - template - // cppcheck-suppress noExplicitConstructor - any_t(const DOCTEST_REF_WRAP(T)); - }; - - yes& testStreamable(std::ostream&); - no testStreamable(no); - - no operator<<(const std::ostream&, const any_t&); - - template - struct has_insertion_operator - { - static std::ostream& s; - static const DOCTEST_REF_WRAP(T) t; - static const bool value = sizeof(decltype(testStreamable(s << t))) == sizeof(yes); - }; - } // namespace has_insertion_operator_impl - - template - struct has_insertion_operator : has_insertion_operator_impl::has_insertion_operator - {}; - - DOCTEST_INTERFACE void my_memcpy(void* dest, const void* src, unsigned num); - - DOCTEST_INTERFACE std::ostream* getTlsOss(); // returns a thread-local ostringstream - DOCTEST_INTERFACE String getTlsOssResult(); - - template - struct StringMakerBase - { - template - static String convert(const DOCTEST_REF_WRAP(T)) { - return "{?}"; - } - }; - - template <> - struct StringMakerBase - { - template - static String convert(const DOCTEST_REF_WRAP(T) in) { - *getTlsOss() << in; - return getTlsOssResult(); - } - }; - - DOCTEST_INTERFACE String rawMemoryToString(const void* object, unsigned size); - - template - String rawMemoryToString(const DOCTEST_REF_WRAP(T) object) { - return rawMemoryToString(&object, sizeof(object)); - } - - template - const char* type_to_string() { - return "<>"; - } -} // namespace detail - -template -struct StringMaker : public detail::StringMakerBase::value> -{}; - -template -struct StringMaker -{ - template - static String convert(U* p) { - if(p) - return detail::rawMemoryToString(p); - return "NULL"; - } -}; - -template -struct StringMaker -{ - static String convert(R C::*p) { - if(p) - return detail::rawMemoryToString(p); - return "NULL"; - } -}; - -template -String toString(const DOCTEST_REF_WRAP(T) value) { - return StringMaker::convert(value); -} - -#ifdef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING -DOCTEST_INTERFACE String toString(char* in); -DOCTEST_INTERFACE String toString(const char* in); -#endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING -DOCTEST_INTERFACE String toString(bool in); -DOCTEST_INTERFACE String toString(float in); -DOCTEST_INTERFACE String toString(double in); -DOCTEST_INTERFACE String toString(double long in); - -DOCTEST_INTERFACE String toString(char in); -DOCTEST_INTERFACE String toString(char signed in); -DOCTEST_INTERFACE String toString(char unsigned in); -DOCTEST_INTERFACE String toString(int short in); -DOCTEST_INTERFACE String toString(int short unsigned in); -DOCTEST_INTERFACE String toString(int in); -DOCTEST_INTERFACE String toString(int unsigned in); -DOCTEST_INTERFACE String toString(int long in); -DOCTEST_INTERFACE String toString(int long unsigned in); -DOCTEST_INTERFACE String toString(int long long in); -DOCTEST_INTERFACE String toString(int long long unsigned in); -DOCTEST_INTERFACE String toString(std::nullptr_t in); - -class DOCTEST_INTERFACE Approx -{ -public: - explicit Approx(double value); - - DOCTEST_DECLARE_COPIES(Approx); - - Approx operator()(double value) const; - -#ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS - template - explicit Approx(const T& value, - typename detail::enable_if::value>::type* = - static_cast(nullptr)) { - *this = Approx(static_cast(value)); - } -#endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS - - Approx& epsilon(double newEpsilon); - -#ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS - template - typename detail::enable_if::value, Approx&>::type epsilon( - const T& newEpsilon) { - m_epsilon = static_cast(newEpsilon); - return *this; - } -#endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS - - Approx& scale(double newScale); - -#ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS - template - typename detail::enable_if::value, Approx&>::type scale( - const T& newScale) { - m_scale = static_cast(newScale); - return *this; - } -#endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS - - // clang-format off - DOCTEST_INTERFACE friend bool operator==(double lhs, const Approx & rhs); - DOCTEST_INTERFACE friend bool operator==(const Approx & lhs, double rhs); - DOCTEST_INTERFACE friend bool operator!=(double lhs, const Approx & rhs); - DOCTEST_INTERFACE friend bool operator!=(const Approx & lhs, double rhs); - DOCTEST_INTERFACE friend bool operator<=(double lhs, const Approx & rhs); - DOCTEST_INTERFACE friend bool operator<=(const Approx & lhs, double rhs); - DOCTEST_INTERFACE friend bool operator>=(double lhs, const Approx & rhs); - DOCTEST_INTERFACE friend bool operator>=(const Approx & lhs, double rhs); - DOCTEST_INTERFACE friend bool operator< (double lhs, const Approx & rhs); - DOCTEST_INTERFACE friend bool operator< (const Approx & lhs, double rhs); - DOCTEST_INTERFACE friend bool operator> (double lhs, const Approx & rhs); - DOCTEST_INTERFACE friend bool operator> (const Approx & lhs, double rhs); - - DOCTEST_INTERFACE friend String toString(const Approx& in); - -#ifdef DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS -#define DOCTEST_APPROX_PREFIX \ - template friend typename detail::enable_if::value, bool>::type - - DOCTEST_APPROX_PREFIX operator==(const T& lhs, const Approx& rhs) { return operator==(double(lhs), rhs); } - DOCTEST_APPROX_PREFIX operator==(const Approx& lhs, const T& rhs) { return operator==(rhs, lhs); } - DOCTEST_APPROX_PREFIX operator!=(const T& lhs, const Approx& rhs) { return !operator==(lhs, rhs); } - DOCTEST_APPROX_PREFIX operator!=(const Approx& lhs, const T& rhs) { return !operator==(rhs, lhs); } - DOCTEST_APPROX_PREFIX operator<=(const T& lhs, const Approx& rhs) { return double(lhs) < rhs.m_value || lhs == rhs; } - DOCTEST_APPROX_PREFIX operator<=(const Approx& lhs, const T& rhs) { return lhs.m_value < double(rhs) || lhs == rhs; } - DOCTEST_APPROX_PREFIX operator>=(const T& lhs, const Approx& rhs) { return double(lhs) > rhs.m_value || lhs == rhs; } - DOCTEST_APPROX_PREFIX operator>=(const Approx& lhs, const T& rhs) { return lhs.m_value > double(rhs) || lhs == rhs; } - DOCTEST_APPROX_PREFIX operator< (const T& lhs, const Approx& rhs) { return double(lhs) < rhs.m_value && lhs != rhs; } - DOCTEST_APPROX_PREFIX operator< (const Approx& lhs, const T& rhs) { return lhs.m_value < double(rhs) && lhs != rhs; } - DOCTEST_APPROX_PREFIX operator> (const T& lhs, const Approx& rhs) { return double(lhs) > rhs.m_value && lhs != rhs; } - DOCTEST_APPROX_PREFIX operator> (const Approx& lhs, const T& rhs) { return lhs.m_value > double(rhs) && lhs != rhs; } -#undef DOCTEST_APPROX_PREFIX -#endif // DOCTEST_CONFIG_INCLUDE_TYPE_TRAITS - - // clang-format on - -private: - double m_epsilon; - double m_scale; - double m_value; -}; - -DOCTEST_INTERFACE String toString(const Approx& in); - -DOCTEST_INTERFACE const ContextOptions* getContextOptions(); - -#if !defined(DOCTEST_CONFIG_DISABLE) - -namespace detail { - // clang-format off -#ifdef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING - template struct decay_array { typedef T type; }; - template struct decay_array { typedef T* type; }; - template struct decay_array { typedef T* type; }; - - template struct not_char_pointer { enum { value = 1 }; }; - template<> struct not_char_pointer { enum { value = 0 }; }; - template<> struct not_char_pointer { enum { value = 0 }; }; - - template struct can_use_op : public not_char_pointer::type> {}; -#endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING - // clang-format on - - struct DOCTEST_INTERFACE TestFailureException - { - DOCTEST_DECLARE_DEFAULTS(TestFailureException); - DOCTEST_DECLARE_COPIES(TestFailureException); - }; - - DOCTEST_INTERFACE bool checkIfShouldThrow(assertType::Enum at); - DOCTEST_INTERFACE void throwException(); - - struct DOCTEST_INTERFACE Subcase - { - SubcaseSignature m_signature; - bool m_entered = false; - - Subcase(const char* name, const char* file, int line); - ~Subcase(); - - DOCTEST_DELETE_COPIES(Subcase); - - operator bool() const; - }; - - template - String stringifyBinaryExpr(const DOCTEST_REF_WRAP(L) lhs, const char* op, - const DOCTEST_REF_WRAP(R) rhs) { - return toString(lhs) + op + toString(rhs); - } - -#define DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(op, op_str, op_macro) \ - template \ - DOCTEST_NOINLINE Result operator op(const DOCTEST_REF_WRAP(R) rhs) { \ - bool res = op_macro(lhs, rhs); \ - if(m_at & assertType::is_false) \ - res = !res; \ - if(!res || doctest::getContextOptions()->success) \ - return Result(res, stringifyBinaryExpr(lhs, op_str, rhs)); \ - return Result(res); \ - } - - // more checks could be added - like in Catch: - // https://github.com/catchorg/Catch2/pull/1480/files - // https://github.com/catchorg/Catch2/pull/1481/files -#define DOCTEST_FORBIT_EXPRESSION(rt, op) \ - template \ - rt& operator op(const R&) { \ - static_assert(deferred_false::value, \ - "Expression Too Complex Please Rewrite As Binary Comparison!"); \ - return *this; \ - } - - struct DOCTEST_INTERFACE Result - { - bool m_passed; - String m_decomp; - - Result(bool passed, const String& decomposition = String()); - - DOCTEST_DECLARE_DEFAULTS(Result); - DOCTEST_DECLARE_COPIES(Result); - - // forbidding some expressions based on this table: http://en.cppreference.com/w/cpp/language/operator_precedence - DOCTEST_FORBIT_EXPRESSION(Result, &) - DOCTEST_FORBIT_EXPRESSION(Result, ^) - DOCTEST_FORBIT_EXPRESSION(Result, |) - DOCTEST_FORBIT_EXPRESSION(Result, &&) - DOCTEST_FORBIT_EXPRESSION(Result, ||) - DOCTEST_FORBIT_EXPRESSION(Result, ==) - DOCTEST_FORBIT_EXPRESSION(Result, !=) - DOCTEST_FORBIT_EXPRESSION(Result, <) - DOCTEST_FORBIT_EXPRESSION(Result, >) - DOCTEST_FORBIT_EXPRESSION(Result, <=) - DOCTEST_FORBIT_EXPRESSION(Result, >=) - DOCTEST_FORBIT_EXPRESSION(Result, =) - DOCTEST_FORBIT_EXPRESSION(Result, +=) - DOCTEST_FORBIT_EXPRESSION(Result, -=) - DOCTEST_FORBIT_EXPRESSION(Result, *=) - DOCTEST_FORBIT_EXPRESSION(Result, /=) - DOCTEST_FORBIT_EXPRESSION(Result, %=) - DOCTEST_FORBIT_EXPRESSION(Result, <<=) - DOCTEST_FORBIT_EXPRESSION(Result, >>=) - DOCTEST_FORBIT_EXPRESSION(Result, &=) - DOCTEST_FORBIT_EXPRESSION(Result, ^=) - DOCTEST_FORBIT_EXPRESSION(Result, |=) - }; - -#ifndef DOCTEST_CONFIG_NO_COMPARISON_WARNING_SUPPRESSION - - DOCTEST_CLANG_SUPPRESS_WARNING_PUSH - DOCTEST_CLANG_SUPPRESS_WARNING("-Wsign-conversion") - DOCTEST_CLANG_SUPPRESS_WARNING("-Wsign-compare") - //DOCTEST_CLANG_SUPPRESS_WARNING("-Wdouble-promotion") - //DOCTEST_CLANG_SUPPRESS_WARNING("-Wconversion") - //DOCTEST_CLANG_SUPPRESS_WARNING("-Wfloat-equal") - - DOCTEST_GCC_SUPPRESS_WARNING_PUSH - DOCTEST_GCC_SUPPRESS_WARNING("-Wsign-conversion") - DOCTEST_GCC_SUPPRESS_WARNING("-Wsign-compare") - //DOCTEST_GCC_SUPPRESS_WARNING("-Wdouble-promotion") - //DOCTEST_GCC_SUPPRESS_WARNING("-Wconversion") - //DOCTEST_GCC_SUPPRESS_WARNING("-Wfloat-equal") - - DOCTEST_MSVC_SUPPRESS_WARNING_PUSH - // http://stackoverflow.com/questions/39479163 what's the difference between 4018 and 4389 - DOCTEST_MSVC_SUPPRESS_WARNING(4388) // signed/unsigned mismatch - DOCTEST_MSVC_SUPPRESS_WARNING(4389) // 'operator' : signed/unsigned mismatch - DOCTEST_MSVC_SUPPRESS_WARNING(4018) // 'expression' : signed/unsigned mismatch - //DOCTEST_MSVC_SUPPRESS_WARNING(4805) // 'operation' : unsafe mix of type 'type' and type 'type' in operation - -#endif // DOCTEST_CONFIG_NO_COMPARISON_WARNING_SUPPRESSION - - // clang-format off -#ifndef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING -#define DOCTEST_COMPARISON_RETURN_TYPE bool -#else // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING -#define DOCTEST_COMPARISON_RETURN_TYPE typename enable_if::value || can_use_op::value, bool>::type - inline bool eq(const char* lhs, const char* rhs) { return String(lhs) == String(rhs); } - inline bool ne(const char* lhs, const char* rhs) { return String(lhs) != String(rhs); } - inline bool lt(const char* lhs, const char* rhs) { return String(lhs) < String(rhs); } - inline bool gt(const char* lhs, const char* rhs) { return String(lhs) > String(rhs); } - inline bool le(const char* lhs, const char* rhs) { return String(lhs) <= String(rhs); } - inline bool ge(const char* lhs, const char* rhs) { return String(lhs) >= String(rhs); } -#endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING - // clang-format on - -#define DOCTEST_RELATIONAL_OP(name, op) \ - template \ - DOCTEST_COMPARISON_RETURN_TYPE name(const DOCTEST_REF_WRAP(L) lhs, \ - const DOCTEST_REF_WRAP(R) rhs) { \ - return lhs op rhs; \ - } - - DOCTEST_RELATIONAL_OP(eq, ==) - DOCTEST_RELATIONAL_OP(ne, !=) - DOCTEST_RELATIONAL_OP(lt, <) - DOCTEST_RELATIONAL_OP(gt, >) - DOCTEST_RELATIONAL_OP(le, <=) - DOCTEST_RELATIONAL_OP(ge, >=) - -#ifndef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING -#define DOCTEST_CMP_EQ(l, r) l == r -#define DOCTEST_CMP_NE(l, r) l != r -#define DOCTEST_CMP_GT(l, r) l > r -#define DOCTEST_CMP_LT(l, r) l < r -#define DOCTEST_CMP_GE(l, r) l >= r -#define DOCTEST_CMP_LE(l, r) l <= r -#else // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING -#define DOCTEST_CMP_EQ(l, r) eq(l, r) -#define DOCTEST_CMP_NE(l, r) ne(l, r) -#define DOCTEST_CMP_GT(l, r) gt(l, r) -#define DOCTEST_CMP_LT(l, r) lt(l, r) -#define DOCTEST_CMP_GE(l, r) ge(l, r) -#define DOCTEST_CMP_LE(l, r) le(l, r) -#endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING - - template - // cppcheck-suppress copyCtorAndEqOperator - struct Expression_lhs - { - L lhs; - assertType::Enum m_at; - - explicit Expression_lhs(L in, assertType::Enum at) - : lhs(in) - , m_at(at) {} - - DOCTEST_NOINLINE operator Result() { - bool res = !!lhs; - if(m_at & assertType::is_false) //!OCLINT bitwise operator in conditional - res = !res; - - if(!res || getContextOptions()->success) - return Result(res, toString(lhs)); - return Result(res); - } - - // clang-format off - DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(==, " == ", DOCTEST_CMP_EQ) //!OCLINT bitwise operator in conditional - DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(!=, " != ", DOCTEST_CMP_NE) //!OCLINT bitwise operator in conditional - DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(>, " > ", DOCTEST_CMP_GT) //!OCLINT bitwise operator in conditional - DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(<, " < ", DOCTEST_CMP_LT) //!OCLINT bitwise operator in conditional - DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(>=, " >= ", DOCTEST_CMP_GE) //!OCLINT bitwise operator in conditional - DOCTEST_DO_BINARY_EXPRESSION_COMPARISON(<=, " <= ", DOCTEST_CMP_LE) //!OCLINT bitwise operator in conditional - // clang-format on - - // forbidding some expressions based on this table: http://en.cppreference.com/w/cpp/language/operator_precedence - DOCTEST_FORBIT_EXPRESSION(Expression_lhs, &) - DOCTEST_FORBIT_EXPRESSION(Expression_lhs, ^) - DOCTEST_FORBIT_EXPRESSION(Expression_lhs, |) - DOCTEST_FORBIT_EXPRESSION(Expression_lhs, &&) - DOCTEST_FORBIT_EXPRESSION(Expression_lhs, ||) - DOCTEST_FORBIT_EXPRESSION(Expression_lhs, =) - DOCTEST_FORBIT_EXPRESSION(Expression_lhs, +=) - DOCTEST_FORBIT_EXPRESSION(Expression_lhs, -=) - DOCTEST_FORBIT_EXPRESSION(Expression_lhs, *=) - DOCTEST_FORBIT_EXPRESSION(Expression_lhs, /=) - DOCTEST_FORBIT_EXPRESSION(Expression_lhs, %=) - DOCTEST_FORBIT_EXPRESSION(Expression_lhs, <<=) - DOCTEST_FORBIT_EXPRESSION(Expression_lhs, >>=) - DOCTEST_FORBIT_EXPRESSION(Expression_lhs, &=) - DOCTEST_FORBIT_EXPRESSION(Expression_lhs, ^=) - DOCTEST_FORBIT_EXPRESSION(Expression_lhs, |=) - // these 2 are unfortunate because they should be allowed - they have higher precedence over the comparisons, but the - // ExpressionDecomposer class uses the left shift operator to capture the left operand of the binary expression... - DOCTEST_FORBIT_EXPRESSION(Expression_lhs, <<) - DOCTEST_FORBIT_EXPRESSION(Expression_lhs, >>) - }; - -#ifndef DOCTEST_CONFIG_NO_COMPARISON_WARNING_SUPPRESSION - - DOCTEST_CLANG_SUPPRESS_WARNING_POP - DOCTEST_MSVC_SUPPRESS_WARNING_POP - DOCTEST_GCC_SUPPRESS_WARNING_POP - -#endif // DOCTEST_CONFIG_NO_COMPARISON_WARNING_SUPPRESSION - - struct DOCTEST_INTERFACE ExpressionDecomposer - { - assertType::Enum m_at; - - ExpressionDecomposer(assertType::Enum at); - - DOCTEST_DECLARE_DEFAULTS(ExpressionDecomposer); - DOCTEST_DELETE_COPIES(ExpressionDecomposer); - - // The right operator for capturing expressions is "<=" instead of "<<" (based on the operator precedence table) - // but then there will be warnings from GCC about "-Wparentheses" and since "_Pragma()" is problematic this will stay for now... - // https://github.com/catchorg/Catch2/issues/870 - // https://github.com/catchorg/Catch2/issues/565 - template - Expression_lhs operator<<(const DOCTEST_REF_WRAP(L) operand) { - return Expression_lhs(operand, m_at); - } - }; - - struct DOCTEST_INTERFACE TestSuite - { - const char* m_test_suite; - const char* m_description; - bool m_skip; - bool m_may_fail; - bool m_should_fail; - int m_expected_failures; - double m_timeout; - - DOCTEST_DECLARE_DEFAULTS(TestSuite); - DOCTEST_DECLARE_COPIES(TestSuite); - - TestSuite& operator*(const char* in); - - template - TestSuite& operator*(const T& in) { - in.fill(*this); - return *this; - } - }; - - typedef void (*funcType)(); - - struct DOCTEST_INTERFACE TestCase : public TestCaseData - { - funcType m_test; // a function pointer to the test case - - const char* m_type; // for templated test cases - gets appended to the real name - int m_template_id; // an ID used to distinguish between the different versions of a templated test case - String m_full_name; // contains the name (only for templated test cases!) + the template type - - TestCase(funcType test, const char* file, unsigned line, const TestSuite& test_suite, - const char* type = "", int template_id = -1); - - DOCTEST_DECLARE_DEFAULTS(TestCase); - - TestCase(const TestCase& other); - - DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(26434) // hides a non-virtual function - TestCase& operator=(const TestCase& other); - DOCTEST_MSVC_SUPPRESS_WARNING_POP - - TestCase& operator*(const char* in); - - template - TestCase& operator*(const T& in) { - in.fill(*this); - return *this; - } - - bool operator<(const TestCase& other) const; - }; - - // forward declarations of functions used by the macros - DOCTEST_INTERFACE int regTest(const TestCase& tc); - DOCTEST_INTERFACE int setTestSuite(const TestSuite& ts); - DOCTEST_INTERFACE bool isDebuggerActive(); - - namespace binaryAssertComparison { - enum Enum - { - eq = 0, - ne, - gt, - lt, - ge, - le - }; - } // namespace binaryAssertComparison - - // clang-format off - template struct RelationalComparator { bool operator()(const DOCTEST_REF_WRAP(L), const DOCTEST_REF_WRAP(R) ) const { return false; } }; - -#define DOCTEST_BINARY_RELATIONAL_OP(n, op) \ - template struct RelationalComparator { bool operator()(const DOCTEST_REF_WRAP(L) lhs, const DOCTEST_REF_WRAP(R) rhs) const { return op(lhs, rhs); } }; - // clang-format on - - DOCTEST_BINARY_RELATIONAL_OP(0, eq) - DOCTEST_BINARY_RELATIONAL_OP(1, ne) - DOCTEST_BINARY_RELATIONAL_OP(2, gt) - DOCTEST_BINARY_RELATIONAL_OP(3, lt) - DOCTEST_BINARY_RELATIONAL_OP(4, ge) - DOCTEST_BINARY_RELATIONAL_OP(5, le) - - struct DOCTEST_INTERFACE ResultBuilder : public AssertData - { - ResultBuilder(assertType::Enum at, const char* file, int line, const char* expr, - const char* exception_type = ""); - - DOCTEST_DECLARE_DEFAULTS(ResultBuilder); - DOCTEST_DELETE_COPIES(ResultBuilder); - - void setResult(const Result& res); - - template - DOCTEST_NOINLINE void binary_assert(const DOCTEST_REF_WRAP(L) lhs, - const DOCTEST_REF_WRAP(R) rhs) { - m_failed = !RelationalComparator()(lhs, rhs); - if(m_failed || getContextOptions()->success) - m_decomp = stringifyBinaryExpr(lhs, ", ", rhs); - } - - template - DOCTEST_NOINLINE void unary_assert(const DOCTEST_REF_WRAP(L) val) { - m_failed = !val; - - if(m_at & assertType::is_false) //!OCLINT bitwise operator in conditional - m_failed = !m_failed; - - if(m_failed || getContextOptions()->success) - m_decomp = toString(val); - } - - void translateException(); - - bool log(); - void react() const; - }; - - namespace assertAction { - enum Enum - { - nothing = 0, - dbgbreak = 1, - shouldthrow = 2 - }; - } // namespace assertAction - - DOCTEST_INTERFACE void failed_out_of_a_testing_context(const AssertData& ad); - - DOCTEST_INTERFACE void decomp_assert(assertType::Enum at, const char* file, int line, - const char* expr, Result result); - -#define DOCTEST_ASSERT_OUT_OF_TESTS(decomp) \ - do { \ - if(!is_running_in_test) { \ - if(failed) { \ - ResultBuilder rb(at, file, line, expr); \ - rb.m_failed = failed; \ - rb.m_decomp = decomp; \ - failed_out_of_a_testing_context(rb); \ - if(isDebuggerActive() && !getContextOptions()->no_breaks) \ - DOCTEST_BREAK_INTO_DEBUGGER(); \ - if(checkIfShouldThrow(at)) \ - throwException(); \ - } \ - return; \ - } \ - } while(false) - -#define DOCTEST_ASSERT_IN_TESTS(decomp) \ - ResultBuilder rb(at, file, line, expr); \ - rb.m_failed = failed; \ - if(rb.m_failed || getContextOptions()->success) \ - rb.m_decomp = decomp; \ - if(rb.log()) \ - DOCTEST_BREAK_INTO_DEBUGGER(); \ - if(rb.m_failed && checkIfShouldThrow(at)) \ - throwException() - - template - DOCTEST_NOINLINE void binary_assert(assertType::Enum at, const char* file, int line, - const char* expr, const DOCTEST_REF_WRAP(L) lhs, - const DOCTEST_REF_WRAP(R) rhs) { - bool failed = !RelationalComparator()(lhs, rhs); - - // ################################################################################### - // IF THE DEBUGGER BREAKS HERE - GO 1 LEVEL UP IN THE CALLSTACK FOR THE FAILING ASSERT - // THIS IS THE EFFECT OF HAVING 'DOCTEST_CONFIG_SUPER_FAST_ASSERTS' DEFINED - // ################################################################################### - DOCTEST_ASSERT_OUT_OF_TESTS(stringifyBinaryExpr(lhs, ", ", rhs)); - DOCTEST_ASSERT_IN_TESTS(stringifyBinaryExpr(lhs, ", ", rhs)); - } - - template - DOCTEST_NOINLINE void unary_assert(assertType::Enum at, const char* file, int line, - const char* expr, const DOCTEST_REF_WRAP(L) val) { - bool failed = !val; - - if(at & assertType::is_false) //!OCLINT bitwise operator in conditional - failed = !failed; - - // ################################################################################### - // IF THE DEBUGGER BREAKS HERE - GO 1 LEVEL UP IN THE CALLSTACK FOR THE FAILING ASSERT - // THIS IS THE EFFECT OF HAVING 'DOCTEST_CONFIG_SUPER_FAST_ASSERTS' DEFINED - // ################################################################################### - DOCTEST_ASSERT_OUT_OF_TESTS(toString(val)); - DOCTEST_ASSERT_IN_TESTS(toString(val)); - } - - struct DOCTEST_INTERFACE IExceptionTranslator - { - DOCTEST_DELETE_COPIES(IExceptionTranslator); - - IExceptionTranslator(); - virtual ~IExceptionTranslator(); - virtual bool translate(String&) const = 0; - }; - - template - class ExceptionTranslator : public IExceptionTranslator //!OCLINT destructor of virtual class - { - public: - explicit ExceptionTranslator(String (*translateFunction)(T)) - : m_translateFunction(translateFunction) {} - - bool translate(String& res) const override { -#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS - try { - throw; // lgtm [cpp/rethrow-no-exception] - // cppcheck-suppress catchExceptionByValue - } catch(T ex) { // NOLINT - res = m_translateFunction(ex); //!OCLINT parameter reassignment - return true; - } catch(...) {} //!OCLINT - empty catch statement -#endif // DOCTEST_CONFIG_NO_EXCEPTIONS - ((void)res); // to silence -Wunused-parameter - return false; - } - - private: - String (*m_translateFunction)(T); - }; - - DOCTEST_INTERFACE void registerExceptionTranslatorImpl(const IExceptionTranslator* et); - - template - struct StringStreamBase - { - template - static void convert(std::ostream* s, const T& in) { - *s << toString(in); - } - - // always treat char* as a string in this context - no matter - // if DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING is defined - static void convert(std::ostream* s, const char* in) { *s << String(in); } - }; - - template <> - struct StringStreamBase - { - template - static void convert(std::ostream* s, const T& in) { - *s << in; - } - }; - - template - struct StringStream : public StringStreamBase::value> - {}; - - template - void toStream(std::ostream* s, const T& value) { - StringStream::convert(s, value); - } - -#ifdef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING - DOCTEST_INTERFACE void toStream(std::ostream* s, char* in); - DOCTEST_INTERFACE void toStream(std::ostream* s, const char* in); -#endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING - DOCTEST_INTERFACE void toStream(std::ostream* s, bool in); - DOCTEST_INTERFACE void toStream(std::ostream* s, float in); - DOCTEST_INTERFACE void toStream(std::ostream* s, double in); - DOCTEST_INTERFACE void toStream(std::ostream* s, double long in); - - DOCTEST_INTERFACE void toStream(std::ostream* s, char in); - DOCTEST_INTERFACE void toStream(std::ostream* s, char signed in); - DOCTEST_INTERFACE void toStream(std::ostream* s, char unsigned in); - DOCTEST_INTERFACE void toStream(std::ostream* s, int short in); - DOCTEST_INTERFACE void toStream(std::ostream* s, int short unsigned in); - DOCTEST_INTERFACE void toStream(std::ostream* s, int in); - DOCTEST_INTERFACE void toStream(std::ostream* s, int unsigned in); - DOCTEST_INTERFACE void toStream(std::ostream* s, int long in); - DOCTEST_INTERFACE void toStream(std::ostream* s, int long unsigned in); - DOCTEST_INTERFACE void toStream(std::ostream* s, int long long in); - DOCTEST_INTERFACE void toStream(std::ostream* s, int long long unsigned in); - - class DOCTEST_INTERFACE ContextBuilder - { - friend class ContextScope; - - struct DOCTEST_INTERFACE ICapture - { - DOCTEST_DELETE_COPIES(ICapture); - ICapture(); - virtual ~ICapture(); - virtual void toStream(std::ostream*) const = 0; - }; - - template - struct Capture : public ICapture //!OCLINT destructor of virtual class - { - const T* capture; - - explicit Capture(const T* in) - : capture(in) {} - void toStream(std::ostream* s) const override { detail::toStream(s, *capture); } - }; - - struct DOCTEST_INTERFACE Chunk - { - char buf[sizeof(Capture)] DOCTEST_ALIGNMENT( - 2 * sizeof(void*)); // place to construct a Capture - - DOCTEST_DECLARE_DEFAULTS(Chunk); - DOCTEST_DELETE_COPIES(Chunk); - }; - - struct DOCTEST_INTERFACE Node - { - Chunk chunk; - Node* next; - - DOCTEST_DECLARE_DEFAULTS(Node); - DOCTEST_DELETE_COPIES(Node); - }; - - Chunk stackChunks[DOCTEST_CONFIG_NUM_CAPTURES_ON_STACK]; - int numCaptures = 0; - Node* head = nullptr; - Node* tail = nullptr; - - ContextBuilder(ContextBuilder& other); - - ContextBuilder& operator=(const ContextBuilder&) = delete; - - void stringify(std::ostream* s) const; - - public: - ContextBuilder(); - ~ContextBuilder(); - - template - DOCTEST_NOINLINE ContextBuilder& operator<<(T& in) { - Capture temp(&in); - - // construct either on stack or on heap - // copy the bytes for the whole object - including the vtable because we cant construct - // the object directly in the buffer using placement new - need the header... - if(numCaptures < DOCTEST_CONFIG_NUM_CAPTURES_ON_STACK) { - my_memcpy(stackChunks[numCaptures].buf, &temp, sizeof(Chunk)); - } else { - auto curr = new Node; - curr->next = nullptr; - if(tail) { - tail->next = curr; - tail = curr; - } else { - head = tail = curr; - } - - my_memcpy(tail->chunk.buf, &temp, sizeof(Chunk)); - } - ++numCaptures; - return *this; - } - - template - ContextBuilder& operator<<(const T&&) { - static_assert(deferred_false::value, - "Cannot pass temporaries or rvalues to the streaming operator because it " - "caches pointers to the passed objects for lazy evaluation!"); - return *this; - } - }; - - class DOCTEST_INTERFACE ContextScope : public IContextScope - { - ContextBuilder contextBuilder; - - public: - explicit ContextScope(ContextBuilder& temp); - - DOCTEST_DELETE_COPIES(ContextScope); - - ~ContextScope(); - - void stringify(std::ostream* s) const; - }; - - struct DOCTEST_INTERFACE MessageBuilder : public MessageData - { - std::ostream* m_stream; - - MessageBuilder(const char* file, int line, assertType::Enum severity); - MessageBuilder() = delete; - ~MessageBuilder(); - - DOCTEST_DELETE_COPIES(MessageBuilder); - - template - MessageBuilder& operator<<(const T& in) { - toStream(m_stream, in); - return *this; - } - - bool log(); - void react(); - }; -} // namespace detail - -#define DOCTEST_DEFINE_DECORATOR(name, type, def) \ - struct name \ - { \ - type data; \ - name(type in = def) \ - : data(in) {} \ - void fill(detail::TestCase& state) const { state.DOCTEST_CAT(m_, name) = data; } \ - void fill(detail::TestSuite& state) const { state.DOCTEST_CAT(m_, name) = data; } \ - } - -DOCTEST_DEFINE_DECORATOR(test_suite, const char*, ""); -DOCTEST_DEFINE_DECORATOR(description, const char*, ""); -DOCTEST_DEFINE_DECORATOR(skip, bool, true); -DOCTEST_DEFINE_DECORATOR(timeout, double, 0); -DOCTEST_DEFINE_DECORATOR(may_fail, bool, true); -DOCTEST_DEFINE_DECORATOR(should_fail, bool, true); -DOCTEST_DEFINE_DECORATOR(expected_failures, int, 0); - -template -int registerExceptionTranslator(String (*translateFunction)(T)) { - DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wexit-time-destructors") - static detail::ExceptionTranslator exceptionTranslator(translateFunction); - DOCTEST_CLANG_SUPPRESS_WARNING_POP - detail::registerExceptionTranslatorImpl(&exceptionTranslator); - return 0; -} - -} // namespace doctest - -// in a separate namespace outside of doctest because the DOCTEST_TEST_SUITE macro -// introduces an anonymous namespace in which getCurrentTestSuite gets overridden -namespace doctest_detail_test_suite_ns { -DOCTEST_INTERFACE doctest::detail::TestSuite& getCurrentTestSuite(); -} // namespace doctest_detail_test_suite_ns - -namespace doctest { -#else // DOCTEST_CONFIG_DISABLE -template -int registerExceptionTranslator(String (*)(T)) { - return 0; -} -#endif // DOCTEST_CONFIG_DISABLE - -namespace detail { - typedef void (*assert_handler)(const AssertData&); - struct ContextState; -} // namespace detail - -class DOCTEST_INTERFACE Context -{ - detail::ContextState* p; - - void parseArgs(int argc, const char* const* argv, bool withDefaults = false); - -public: - explicit Context(int argc = 0, const char* const* argv = nullptr); - - DOCTEST_DELETE_COPIES(Context); - - ~Context(); - - void applyCommandLine(int argc, const char* const* argv); - - void addFilter(const char* filter, const char* value); - void clearFilters(); - void setOption(const char* option, int value); - void setOption(const char* option, const char* value); - - bool shouldExit(); - - void setAsDefaultForAssertsOutOfTestCases(); - - void setAssertHandler(detail::assert_handler ah); - - int run(); -}; - -namespace TestCaseFailureReason { - enum Enum - { - None = 0, - AssertFailure = 1, // an assertion has failed in the test case - Exception = 2, // test case threw an exception - Crash = 4, // a crash... - TooManyFailedAsserts = 8, // the abort-after option - Timeout = 16, // see the timeout decorator - ShouldHaveFailedButDidnt = 32, // see the should_fail decorator - ShouldHaveFailedAndDid = 64, // see the should_fail decorator - DidntFailExactlyNumTimes = 128, // see the expected_failures decorator - FailedExactlyNumTimes = 256, // see the expected_failures decorator - CouldHaveFailedAndDid = 512 // see the may_fail decorator - }; -} // namespace TestCaseFailureReason - -struct DOCTEST_INTERFACE CurrentTestCaseStats -{ - int numAssertsCurrentTest; - int numAssertsFailedCurrentTest; - double seconds; - int failure_flags; // use TestCaseFailureReason::Enum - - DOCTEST_DECLARE_DEFAULTS(CurrentTestCaseStats); - DOCTEST_DELETE_COPIES(CurrentTestCaseStats); -}; - -struct DOCTEST_INTERFACE TestCaseException -{ - String error_string; - bool is_crash; -}; - -struct DOCTEST_INTERFACE TestRunStats -{ - unsigned numTestCases; - unsigned numTestCasesPassingFilters; - unsigned numTestSuitesPassingFilters; - unsigned numTestCasesFailed; - int numAsserts; - int numAssertsFailed; - - DOCTEST_DECLARE_DEFAULTS(TestRunStats); - DOCTEST_DELETE_COPIES(TestRunStats); -}; - -struct QueryData -{ - const TestRunStats* run_stats = nullptr; - String* data = nullptr; - unsigned num_data = 0; -}; - -struct DOCTEST_INTERFACE IReporter -{ - // The constructor has to accept "const ContextOptions&" as a single argument - // which has most of the options for the run + a pointer to the stdout stream - // Reporter(const ContextOptions& in) - - // called when a query should be reported (listing test cases, printing the version, etc.) - virtual void report_query(const QueryData&) = 0; - - // called when the whole test run starts - virtual void test_run_start() = 0; - // called when the whole test run ends (caching a pointer to the input doesn't make sense here) - virtual void test_run_end(const TestRunStats&) = 0; - - // called when a test case is started (safe to cache a pointer to the input) - virtual void test_case_start(const TestCaseData&) = 0; - // called when a test case has ended - virtual void test_case_end(const CurrentTestCaseStats&) = 0; - - // called when an exception is thrown from the test case (or it crashes) - virtual void test_case_exception(const TestCaseException&) = 0; - - // called whenever a subcase is entered (don't cache pointers to the input) - virtual void subcase_start(const SubcaseSignature&) = 0; - // called whenever a subcase is exited (don't cache pointers to the input) - virtual void subcase_end() = 0; - - // called for each assert (don't cache pointers to the input) - virtual void log_assert(const AssertData&) = 0; - // called for each message (don't cache pointers to the input) - virtual void log_message(const MessageData&) = 0; - - // called when a test case is skipped either because it doesn't pass the filters, has a skip decorator - // or isn't in the execution range (between first and last) (safe to cache a pointer to the input) - virtual void test_case_skipped(const TestCaseData&) = 0; - - // doctest will not be managing the lifetimes of reporters given to it but this would still be nice to have - virtual ~IReporter(); - - // can obtain all currently active contexts and stringify them if one wishes to do so - static int get_num_active_contexts(); - static const IContextScope* const* get_active_contexts(); - - // can iterate through contexts which have been stringified automatically in their destructors when an exception has been thrown - static int get_num_stringified_contexts(); - static const String* get_stringified_contexts(); -}; - -namespace detail { - typedef IReporter* (*reporterCreatorFunc)(const ContextOptions&); - - DOCTEST_INTERFACE void registerReporterImpl(const char* name, int prio, reporterCreatorFunc c); - - template - IReporter* reporterCreator(const ContextOptions& o) { - return new Reporter(o); - } -} // namespace detail - -template -int registerReporter(const char* name, int priority) { - detail::registerReporterImpl(name, priority, detail::reporterCreator); - return 0; -} -} // namespace doctest - -// if registering is not disabled -#if !defined(DOCTEST_CONFIG_DISABLE) - -// common code in asserts - for convenience -#define DOCTEST_ASSERT_LOG_AND_REACT(b) \ - if(b.log()) \ - DOCTEST_BREAK_INTO_DEBUGGER(); \ - b.react() - -#ifdef DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS -#define DOCTEST_WRAP_IN_TRY(x) x; -#else // DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS -#define DOCTEST_WRAP_IN_TRY(x) \ - try { \ - x; \ - } catch(...) { _DOCTEST_RB.translateException(); } -#endif // DOCTEST_CONFIG_NO_TRY_CATCH_IN_ASSERTS - -// registers the test by initializing a dummy var with a function -#define DOCTEST_REGISTER_FUNCTION(global_prefix, f, decorators) \ - global_prefix DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(_DOCTEST_ANON_VAR_)) = \ - doctest::detail::regTest( \ - doctest::detail::TestCase( \ - f, __FILE__, __LINE__, \ - doctest_detail_test_suite_ns::getCurrentTestSuite()) * \ - decorators); \ - DOCTEST_GLOBAL_NO_WARNINGS_END() - -#define DOCTEST_IMPLEMENT_FIXTURE(der, base, func, decorators) \ - namespace { \ - struct der : public base \ - { \ - void f(); \ - }; \ - static void func() { \ - der v; \ - v.f(); \ - } \ - DOCTEST_REGISTER_FUNCTION(DOCTEST_EMPTY, func, decorators) \ - } \ - inline DOCTEST_NOINLINE void der::f() - -#define DOCTEST_CREATE_AND_REGISTER_FUNCTION(f, decorators) \ - static void f(); \ - DOCTEST_REGISTER_FUNCTION(DOCTEST_EMPTY, f, decorators) \ - static void f() - -#define DOCTEST_CREATE_AND_REGISTER_FUNCTION_IN_CLASS(f, proxy, decorators) \ - static doctest::detail::funcType proxy() { return f; } \ - DOCTEST_REGISTER_FUNCTION(inline const, proxy(), decorators) \ - static void f() - -// for registering tests -#define DOCTEST_TEST_CASE(decorators) \ - DOCTEST_CREATE_AND_REGISTER_FUNCTION(DOCTEST_ANONYMOUS(_DOCTEST_ANON_FUNC_), decorators) - -// for registering tests in classes - requires C++17 for inline variables! -#if __cplusplus >= 201703L || (DOCTEST_MSVC >= DOCTEST_COMPILER(19, 12, 0) && _MSVC_LANG >= 201703L) -#define DOCTEST_TEST_CASE_CLASS(decorators) \ - DOCTEST_CREATE_AND_REGISTER_FUNCTION_IN_CLASS(DOCTEST_ANONYMOUS(_DOCTEST_ANON_FUNC_), \ - DOCTEST_ANONYMOUS(_DOCTEST_ANON_PROXY_), \ - decorators) -#else // DOCTEST_TEST_CASE_CLASS -#define DOCTEST_TEST_CASE_CLASS(...) \ - TEST_CASES_CAN_BE_REGISTERED_IN_CLASSES_ONLY_IN_CPP17_MODE_OR_WITH_VS_2017_OR_NEWER -#endif // DOCTEST_TEST_CASE_CLASS - -// for registering tests with a fixture -#define DOCTEST_TEST_CASE_FIXTURE(c, decorators) \ - DOCTEST_IMPLEMENT_FIXTURE(DOCTEST_ANONYMOUS(_DOCTEST_ANON_CLASS_), c, \ - DOCTEST_ANONYMOUS(_DOCTEST_ANON_FUNC_), decorators) - -// for converting types to strings without the header and demangling -#define DOCTEST_TYPE_TO_STRING_IMPL(...) \ - template <> \ - inline const char* type_to_string<__VA_ARGS__>() { \ - return "<" #__VA_ARGS__ ">"; \ - } -#define DOCTEST_TYPE_TO_STRING(...) \ - namespace doctest { namespace detail { \ - DOCTEST_TYPE_TO_STRING_IMPL(__VA_ARGS__) \ - } \ - } \ - typedef int DOCTEST_ANONYMOUS(_DOCTEST_ANON_FOR_SEMICOLON_) - -// for typed tests -#define DOCTEST_REGISTER_TYPED_TEST_CASE_IMPL(func, type, decorators, idx) \ - doctest::detail::regTest( \ - doctest::detail::TestCase(func, __FILE__, __LINE__, \ - doctest_detail_test_suite_ns::getCurrentTestSuite(), \ - doctest::detail::type_to_string(), idx) * \ - decorators) - -#define DOCTEST_TEST_CASE_TEMPLATE_DEFINE_IMPL(dec, T, iter, func) \ - template \ - inline void func(); \ - template \ - struct iter; \ - template \ - struct iter> \ - { \ - iter(int line, int index) { \ - DOCTEST_REGISTER_TYPED_TEST_CASE_IMPL(func, Type, dec, line * 1000 + index); \ - iter>(line, index + 1); \ - } \ - }; \ - template <> \ - struct iter> \ - { \ - iter(int, int) {} \ - }; \ - template \ - inline void func() - -#define DOCTEST_TEST_CASE_TEMPLATE_DEFINE(dec, T, id) \ - DOCTEST_TEST_CASE_TEMPLATE_DEFINE_IMPL(dec, T, DOCTEST_CAT(id, ITERATOR), \ - DOCTEST_ANONYMOUS(_DOCTEST_ANON_TMP_)) - -#define DOCTEST_TEST_CASE_TEMPLATE_INVOKE_IMPL(id, anon, ...) \ - DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_CAT(anon, DUMMY)) = [] { \ - DOCTEST_CAT(id, ITERATOR)> DOCTEST_UNUSED DOCTEST_CAT( \ - anon, inner_dummy)(__LINE__, 0); \ - return 0; \ - }(); \ - DOCTEST_GLOBAL_NO_WARNINGS_END() - -#define DOCTEST_TEST_CASE_TEMPLATE_INVOKE(id, ...) \ - DOCTEST_TEST_CASE_TEMPLATE_INVOKE_IMPL(id, DOCTEST_ANONYMOUS(_DOCTEST_ANON_TMP_), __VA_ARGS__) \ - typedef int DOCTEST_ANONYMOUS(_DOCTEST_ANON_FOR_SEMICOLON_) - -#define DOCTEST_TEST_CASE_TEMPLATE_APPLY_IMPL(id, anon, ...) \ - DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_CAT(anon, DUMMY)) = [] { \ - DOCTEST_CAT(id, ITERATOR)<__VA_ARGS__> DOCTEST_UNUSED DOCTEST_CAT(anon, inner_dummy)( \ - __LINE__, 0); \ - return 0; \ - }(); \ - DOCTEST_GLOBAL_NO_WARNINGS_END() - -#define DOCTEST_TEST_CASE_TEMPLATE_APPLY(id, ...) \ - DOCTEST_TEST_CASE_TEMPLATE_APPLY_IMPL(id, DOCTEST_ANONYMOUS(_DOCTEST_ANON_TMP_), __VA_ARGS__) \ - typedef int DOCTEST_ANONYMOUS(_DOCTEST_ANON_FOR_SEMICOLON_) - -#define DOCTEST_TEST_CASE_TEMPLATE_IMPL(dec, T, anon, ...) \ - DOCTEST_TEST_CASE_TEMPLATE_DEFINE_IMPL(dec, T, DOCTEST_CAT(anon, ITERATOR), anon); \ - DOCTEST_TEST_CASE_TEMPLATE_INVOKE_IMPL(anon, anon, __VA_ARGS__) \ - template \ - inline void anon() - -#define DOCTEST_TEST_CASE_TEMPLATE(dec, T, ...) \ - DOCTEST_TEST_CASE_TEMPLATE_IMPL(dec, T, DOCTEST_ANONYMOUS(_DOCTEST_ANON_TMP_), __VA_ARGS__) - -// for subcases -#define DOCTEST_SUBCASE(name) \ - if(const doctest::detail::Subcase & DOCTEST_ANONYMOUS(_DOCTEST_ANON_SUBCASE_) DOCTEST_UNUSED = \ - doctest::detail::Subcase(name, __FILE__, __LINE__)) - -// for grouping tests in test suites by using code blocks -#define DOCTEST_TEST_SUITE_IMPL(decorators, ns_name) \ - namespace ns_name { namespace doctest_detail_test_suite_ns { \ - static DOCTEST_NOINLINE doctest::detail::TestSuite& getCurrentTestSuite() { \ - DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4640) \ - DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wexit-time-destructors") \ - static doctest::detail::TestSuite data; \ - static bool inited = false; \ - DOCTEST_MSVC_SUPPRESS_WARNING_POP \ - DOCTEST_CLANG_SUPPRESS_WARNING_POP \ - if(!inited) { \ - data* decorators; \ - inited = true; \ - } \ - return data; \ - } \ - } \ - } \ - namespace ns_name - -#define DOCTEST_TEST_SUITE(decorators) \ - DOCTEST_TEST_SUITE_IMPL(decorators, DOCTEST_ANONYMOUS(_DOCTEST_ANON_SUITE_)) - -// for starting a testsuite block -#define DOCTEST_TEST_SUITE_BEGIN(decorators) \ - DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(_DOCTEST_ANON_VAR_)) = \ - doctest::detail::setTestSuite(doctest::detail::TestSuite() * decorators); \ - DOCTEST_GLOBAL_NO_WARNINGS_END() \ - typedef int DOCTEST_ANONYMOUS(_DOCTEST_ANON_FOR_SEMICOLON_) - -// for ending a testsuite block -#define DOCTEST_TEST_SUITE_END \ - DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(_DOCTEST_ANON_VAR_)) = \ - doctest::detail::setTestSuite(doctest::detail::TestSuite() * ""); \ - DOCTEST_GLOBAL_NO_WARNINGS_END() \ - typedef int DOCTEST_ANONYMOUS(_DOCTEST_ANON_FOR_SEMICOLON_) - -// for registering exception translators -#define DOCTEST_REGISTER_EXCEPTION_TRANSLATOR_IMPL(translatorName, signature) \ - inline doctest::String translatorName(signature); \ - DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(_DOCTEST_ANON_TRANSLATOR_)) = \ - doctest::registerExceptionTranslator(translatorName); \ - DOCTEST_GLOBAL_NO_WARNINGS_END() \ - doctest::String translatorName(signature) - -#define DOCTEST_REGISTER_EXCEPTION_TRANSLATOR(signature) \ - DOCTEST_REGISTER_EXCEPTION_TRANSLATOR_IMPL(DOCTEST_ANONYMOUS(_DOCTEST_ANON_TRANSLATOR_), \ - signature) - -// for registering -#define DOCTEST_REGISTER_REPORTER(name, priority, reporter) \ - DOCTEST_GLOBAL_NO_WARNINGS(DOCTEST_ANONYMOUS(_DOCTEST_ANON_REPORTER_)) = \ - doctest::registerReporter(name, priority); \ - DOCTEST_GLOBAL_NO_WARNINGS_END() typedef int DOCTEST_ANONYMOUS(_DOCTEST_ANON_FOR_SEMICOLON_) - -// for logging -#define DOCTEST_INFO(x) \ - doctest::detail::ContextScope DOCTEST_ANONYMOUS(_DOCTEST_CAPTURE_)( \ - doctest::detail::ContextBuilder() << x) -#define DOCTEST_CAPTURE(x) DOCTEST_INFO(#x " := " << x) - -#define DOCTEST_ADD_AT_IMPL(type, file, line, mb, x) \ - do { \ - doctest::detail::MessageBuilder mb(file, line, doctest::assertType::type); \ - mb << x; \ - DOCTEST_ASSERT_LOG_AND_REACT(mb); \ - } while((void)0, 0) - -// clang-format off -#define DOCTEST_ADD_MESSAGE_AT(file, line, x) DOCTEST_ADD_AT_IMPL(is_warn, file, line, DOCTEST_ANONYMOUS(_DOCTEST_MESSAGE_), x) -#define DOCTEST_ADD_FAIL_CHECK_AT(file, line, x) DOCTEST_ADD_AT_IMPL(is_check, file, line, DOCTEST_ANONYMOUS(_DOCTEST_MESSAGE_), x) -#define DOCTEST_ADD_FAIL_AT(file, line, x) DOCTEST_ADD_AT_IMPL(is_require, file, line, DOCTEST_ANONYMOUS(_DOCTEST_MESSAGE_), x) -// clang-format on - -#define DOCTEST_MESSAGE(x) DOCTEST_ADD_MESSAGE_AT(__FILE__, __LINE__, x) -#define DOCTEST_FAIL_CHECK(x) DOCTEST_ADD_FAIL_CHECK_AT(__FILE__, __LINE__, x) -#define DOCTEST_FAIL(x) DOCTEST_ADD_FAIL_AT(__FILE__, __LINE__, x) - -// hack for macros like INFO() that require lvalues -#if __cplusplus >= 201402L || (DOCTEST_MSVC >= DOCTEST_COMPILER(19, 10, 0)) -template -constexpr T to_lvalue = x; -#define DOCTEST_TO_LVALUE(...) to_lvalue -#else // TO_LVALUE -#define DOCTEST_TO_LVALUE(...) TO_LVALUE_CAN_BE_USED_ONLY_IN_CPP14_MODE_OR_WITH_VS_2017_OR_NEWER -#endif // TO_LVALUE - -#ifndef DOCTEST_CONFIG_SUPER_FAST_ASSERTS - -#define DOCTEST_ASSERT_IMPLEMENT_2(assert_type, ...) \ - DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Woverloaded-shift-op-parentheses") \ - doctest::detail::ResultBuilder _DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ - __LINE__, #__VA_ARGS__); \ - DOCTEST_WRAP_IN_TRY(_DOCTEST_RB.setResult( \ - doctest::detail::ExpressionDecomposer(doctest::assertType::assert_type) \ - << __VA_ARGS__)) \ - DOCTEST_ASSERT_LOG_AND_REACT(_DOCTEST_RB) \ - DOCTEST_CLANG_SUPPRESS_WARNING_POP - -#define DOCTEST_ASSERT_IMPLEMENT_1(assert_type, ...) \ - do { \ - DOCTEST_ASSERT_IMPLEMENT_2(assert_type, __VA_ARGS__); \ - } while((void)0, 0) - -#else // DOCTEST_CONFIG_SUPER_FAST_ASSERTS - -#define DOCTEST_ASSERT_IMPLEMENT_1(assert_type, ...) \ - DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Woverloaded-shift-op-parentheses") \ - doctest::detail::decomp_assert( \ - doctest::assertType::assert_type, __FILE__, __LINE__, #__VA_ARGS__, \ - doctest::detail::ExpressionDecomposer(doctest::assertType::assert_type) \ - << __VA_ARGS__) DOCTEST_CLANG_SUPPRESS_WARNING_POP - -#endif // DOCTEST_CONFIG_SUPER_FAST_ASSERTS - -#define DOCTEST_WARN(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_WARN, __VA_ARGS__) -#define DOCTEST_CHECK(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_CHECK, __VA_ARGS__) -#define DOCTEST_REQUIRE(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_REQUIRE, __VA_ARGS__) -#define DOCTEST_WARN_FALSE(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_WARN_FALSE, __VA_ARGS__) -#define DOCTEST_CHECK_FALSE(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_CHECK_FALSE, __VA_ARGS__) -#define DOCTEST_REQUIRE_FALSE(...) DOCTEST_ASSERT_IMPLEMENT_1(DT_REQUIRE_FALSE, __VA_ARGS__) - -// clang-format off -#define DOCTEST_WARN_MESSAGE(cond, msg) do { DOCTEST_INFO(msg); DOCTEST_ASSERT_IMPLEMENT_2(DT_WARN, cond); } while((void)0, 0) -#define DOCTEST_CHECK_MESSAGE(cond, msg) do { DOCTEST_INFO(msg); DOCTEST_ASSERT_IMPLEMENT_2(DT_CHECK, cond); } while((void)0, 0) -#define DOCTEST_REQUIRE_MESSAGE(cond, msg) do { DOCTEST_INFO(msg); DOCTEST_ASSERT_IMPLEMENT_2(DT_REQUIRE, cond); } while((void)0, 0) -#define DOCTEST_WARN_FALSE_MESSAGE(cond, msg) do { DOCTEST_INFO(msg); DOCTEST_ASSERT_IMPLEMENT_2(DT_WARN_FALSE, cond); } while((void)0, 0) -#define DOCTEST_CHECK_FALSE_MESSAGE(cond, msg) do { DOCTEST_INFO(msg); DOCTEST_ASSERT_IMPLEMENT_2(DT_CHECK_FALSE, cond); } while((void)0, 0) -#define DOCTEST_REQUIRE_FALSE_MESSAGE(cond, msg) do { DOCTEST_INFO(msg); DOCTEST_ASSERT_IMPLEMENT_2(DT_REQUIRE_FALSE, cond); } while((void)0, 0) -// clang-format on - -#define DOCTEST_ASSERT_THROWS(expr, assert_type) DOCTEST_ASSERT_THROWS_WITH(expr, assert_type, "") - -#define DOCTEST_ASSERT_THROWS_AS(expr, assert_type, ...) \ - do { \ - if(!doctest::getContextOptions()->no_throw) { \ - doctest::detail::ResultBuilder _DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ - __LINE__, #expr, #__VA_ARGS__); \ - try { \ - expr; \ - } catch(const doctest::detail::remove_const< \ - doctest::detail::remove_reference<__VA_ARGS__>::type>::type&) { \ - _DOCTEST_RB.translateException(); \ - _DOCTEST_RB.m_threw_as = true; \ - } catch(...) { _DOCTEST_RB.translateException(); } \ - DOCTEST_ASSERT_LOG_AND_REACT(_DOCTEST_RB); \ - } \ - } while((void)0, 0) - -#define DOCTEST_ASSERT_THROWS_WITH(expr, assert_type, ...) \ - do { \ - if(!doctest::getContextOptions()->no_throw) { \ - doctest::detail::ResultBuilder _DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ - __LINE__, #expr, __VA_ARGS__); \ - try { \ - expr; \ - } catch(...) { _DOCTEST_RB.translateException(); } \ - DOCTEST_ASSERT_LOG_AND_REACT(_DOCTEST_RB); \ - } \ - } while((void)0, 0) - -#define DOCTEST_ASSERT_NOTHROW(expr, assert_type) \ - do { \ - doctest::detail::ResultBuilder _DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ - __LINE__, #expr); \ - try { \ - expr; \ - } catch(...) { _DOCTEST_RB.translateException(); } \ - DOCTEST_ASSERT_LOG_AND_REACT(_DOCTEST_RB); \ - } while((void)0, 0) - -// clang-format off -#define DOCTEST_WARN_THROWS(expr) DOCTEST_ASSERT_THROWS(expr, DT_WARN_THROWS) -#define DOCTEST_CHECK_THROWS(expr) DOCTEST_ASSERT_THROWS(expr, DT_CHECK_THROWS) -#define DOCTEST_REQUIRE_THROWS(expr) DOCTEST_ASSERT_THROWS(expr, DT_REQUIRE_THROWS) - -#define DOCTEST_WARN_THROWS_AS(expr, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_WARN_THROWS_AS, __VA_ARGS__) -#define DOCTEST_CHECK_THROWS_AS(expr, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_CHECK_THROWS_AS, __VA_ARGS__) -#define DOCTEST_REQUIRE_THROWS_AS(expr, ...) DOCTEST_ASSERT_THROWS_AS(expr, DT_REQUIRE_THROWS_AS, __VA_ARGS__) - -#define DOCTEST_WARN_THROWS_WITH(expr, ...) DOCTEST_ASSERT_THROWS_WITH(expr, DT_WARN_THROWS_WITH, __VA_ARGS__) -#define DOCTEST_CHECK_THROWS_WITH(expr, ...) DOCTEST_ASSERT_THROWS_WITH(expr, DT_CHECK_THROWS_WITH, __VA_ARGS__) -#define DOCTEST_REQUIRE_THROWS_WITH(expr, ...) DOCTEST_ASSERT_THROWS_WITH(expr, DT_REQUIRE_THROWS_WITH, __VA_ARGS__) - -#define DOCTEST_WARN_NOTHROW(expr) DOCTEST_ASSERT_NOTHROW(expr, DT_WARN_NOTHROW) -#define DOCTEST_CHECK_NOTHROW(expr) DOCTEST_ASSERT_NOTHROW(expr, DT_CHECK_NOTHROW) -#define DOCTEST_REQUIRE_NOTHROW(expr) DOCTEST_ASSERT_NOTHROW(expr, DT_REQUIRE_NOTHROW) - -#define DOCTEST_WARN_THROWS_MESSAGE(expr, msg) do { DOCTEST_INFO(msg); DOCTEST_WARN_THROWS(expr); } while((void)0, 0) -#define DOCTEST_CHECK_THROWS_MESSAGE(expr, msg) do { DOCTEST_INFO(msg); DOCTEST_CHECK_THROWS(expr); } while((void)0, 0) -#define DOCTEST_REQUIRE_THROWS_MESSAGE(expr, msg) do { DOCTEST_INFO(msg); DOCTEST_REQUIRE_THROWS(expr); } while((void)0, 0) -#define DOCTEST_WARN_THROWS_AS_MESSAGE(expr, ex, msg) do { DOCTEST_INFO(msg); DOCTEST_WARN_THROWS_AS(expr, ex); } while((void)0, 0) -#define DOCTEST_CHECK_THROWS_AS_MESSAGE(expr, ex, msg) do { DOCTEST_INFO(msg); DOCTEST_CHECK_THROWS_AS(expr, ex); } while((void)0, 0) -#define DOCTEST_REQUIRE_THROWS_AS_MESSAGE(expr, ex, msg) do { DOCTEST_INFO(msg); DOCTEST_REQUIRE_THROWS_AS(expr, ex); } while((void)0, 0) -#define DOCTEST_WARN_THROWS_WITH_MESSAGE(expr, ex, msg) do { DOCTEST_INFO(msg); DOCTEST_WARN_THROWS_WITH(expr, ex); } while((void)0, 0) -#define DOCTEST_CHECK_THROWS_WITH_MESSAGE(expr, ex, msg) do { DOCTEST_INFO(msg); DOCTEST_CHECK_THROWS_WITH(expr, ex); } while((void)0, 0) -#define DOCTEST_REQUIRE_THROWS_WITH_MESSAGE(expr, ex, msg) do { DOCTEST_INFO(msg); DOCTEST_REQUIRE_THROWS_WITH(expr, ex); } while((void)0, 0) -#define DOCTEST_WARN_NOTHROW_MESSAGE(expr, msg) do { DOCTEST_INFO(msg); DOCTEST_WARN_NOTHROW(expr); } while((void)0, 0) -#define DOCTEST_CHECK_NOTHROW_MESSAGE(expr, msg) do { DOCTEST_INFO(msg); DOCTEST_CHECK_NOTHROW(expr); } while((void)0, 0) -#define DOCTEST_REQUIRE_NOTHROW_MESSAGE(expr, msg) do { DOCTEST_INFO(msg); DOCTEST_REQUIRE_NOTHROW(expr); } while((void)0, 0) -// clang-format on - -#ifndef DOCTEST_CONFIG_SUPER_FAST_ASSERTS - -#define DOCTEST_BINARY_ASSERT(assert_type, comp, ...) \ - do { \ - doctest::detail::ResultBuilder _DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ - __LINE__, #__VA_ARGS__); \ - DOCTEST_WRAP_IN_TRY( \ - _DOCTEST_RB.binary_assert( \ - __VA_ARGS__)) \ - DOCTEST_ASSERT_LOG_AND_REACT(_DOCTEST_RB); \ - } while((void)0, 0) - -#define DOCTEST_UNARY_ASSERT(assert_type, ...) \ - do { \ - doctest::detail::ResultBuilder _DOCTEST_RB(doctest::assertType::assert_type, __FILE__, \ - __LINE__, #__VA_ARGS__); \ - DOCTEST_WRAP_IN_TRY(_DOCTEST_RB.unary_assert(__VA_ARGS__)) \ - DOCTEST_ASSERT_LOG_AND_REACT(_DOCTEST_RB); \ - } while((void)0, 0) - -#else // DOCTEST_CONFIG_SUPER_FAST_ASSERTS - -#define DOCTEST_BINARY_ASSERT(assert_type, comparison, ...) \ - doctest::detail::binary_assert( \ - doctest::assertType::assert_type, __FILE__, __LINE__, #__VA_ARGS__, __VA_ARGS__) - -#define DOCTEST_UNARY_ASSERT(assert_type, ...) \ - doctest::detail::unary_assert(doctest::assertType::assert_type, __FILE__, __LINE__, \ - #__VA_ARGS__, __VA_ARGS__) - -#endif // DOCTEST_CONFIG_SUPER_FAST_ASSERTS - -#define DOCTEST_WARN_EQ(...) DOCTEST_BINARY_ASSERT(DT_WARN_EQ, eq, __VA_ARGS__) -#define DOCTEST_CHECK_EQ(...) DOCTEST_BINARY_ASSERT(DT_CHECK_EQ, eq, __VA_ARGS__) -#define DOCTEST_REQUIRE_EQ(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_EQ, eq, __VA_ARGS__) -#define DOCTEST_WARN_NE(...) DOCTEST_BINARY_ASSERT(DT_WARN_NE, ne, __VA_ARGS__) -#define DOCTEST_CHECK_NE(...) DOCTEST_BINARY_ASSERT(DT_CHECK_NE, ne, __VA_ARGS__) -#define DOCTEST_REQUIRE_NE(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_NE, ne, __VA_ARGS__) -#define DOCTEST_WARN_GT(...) DOCTEST_BINARY_ASSERT(DT_WARN_GT, gt, __VA_ARGS__) -#define DOCTEST_CHECK_GT(...) DOCTEST_BINARY_ASSERT(DT_CHECK_GT, gt, __VA_ARGS__) -#define DOCTEST_REQUIRE_GT(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_GT, gt, __VA_ARGS__) -#define DOCTEST_WARN_LT(...) DOCTEST_BINARY_ASSERT(DT_WARN_LT, lt, __VA_ARGS__) -#define DOCTEST_CHECK_LT(...) DOCTEST_BINARY_ASSERT(DT_CHECK_LT, lt, __VA_ARGS__) -#define DOCTEST_REQUIRE_LT(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_LT, lt, __VA_ARGS__) -#define DOCTEST_WARN_GE(...) DOCTEST_BINARY_ASSERT(DT_WARN_GE, ge, __VA_ARGS__) -#define DOCTEST_CHECK_GE(...) DOCTEST_BINARY_ASSERT(DT_CHECK_GE, ge, __VA_ARGS__) -#define DOCTEST_REQUIRE_GE(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_GE, ge, __VA_ARGS__) -#define DOCTEST_WARN_LE(...) DOCTEST_BINARY_ASSERT(DT_WARN_LE, le, __VA_ARGS__) -#define DOCTEST_CHECK_LE(...) DOCTEST_BINARY_ASSERT(DT_CHECK_LE, le, __VA_ARGS__) -#define DOCTEST_REQUIRE_LE(...) DOCTEST_BINARY_ASSERT(DT_REQUIRE_LE, le, __VA_ARGS__) - -#define DOCTEST_WARN_UNARY(...) DOCTEST_UNARY_ASSERT(DT_WARN_UNARY, __VA_ARGS__) -#define DOCTEST_CHECK_UNARY(...) DOCTEST_UNARY_ASSERT(DT_CHECK_UNARY, __VA_ARGS__) -#define DOCTEST_REQUIRE_UNARY(...) DOCTEST_UNARY_ASSERT(DT_REQUIRE_UNARY, __VA_ARGS__) -#define DOCTEST_WARN_UNARY_FALSE(...) DOCTEST_UNARY_ASSERT(DT_WARN_UNARY_FALSE, __VA_ARGS__) -#define DOCTEST_CHECK_UNARY_FALSE(...) DOCTEST_UNARY_ASSERT(DT_CHECK_UNARY_FALSE, __VA_ARGS__) -#define DOCTEST_REQUIRE_UNARY_FALSE(...) DOCTEST_UNARY_ASSERT(DT_REQUIRE_UNARY_FALSE, __VA_ARGS__) - -#ifdef DOCTEST_CONFIG_NO_EXCEPTIONS - -#undef DOCTEST_WARN_THROWS -#undef DOCTEST_CHECK_THROWS -#undef DOCTEST_REQUIRE_THROWS -#undef DOCTEST_WARN_THROWS_AS -#undef DOCTEST_CHECK_THROWS_AS -#undef DOCTEST_REQUIRE_THROWS_AS -#undef DOCTEST_WARN_THROWS_WITH -#undef DOCTEST_CHECK_THROWS_WITH -#undef DOCTEST_REQUIRE_THROWS_WITH -#undef DOCTEST_WARN_NOTHROW -#undef DOCTEST_CHECK_NOTHROW -#undef DOCTEST_REQUIRE_NOTHROW - -#undef DOCTEST_WARN_THROWS_MESSAGE -#undef DOCTEST_CHECK_THROWS_MESSAGE -#undef DOCTEST_REQUIRE_THROWS_MESSAGE -#undef DOCTEST_WARN_THROWS_AS_MESSAGE -#undef DOCTEST_CHECK_THROWS_AS_MESSAGE -#undef DOCTEST_REQUIRE_THROWS_AS_MESSAGE -#undef DOCTEST_WARN_THROWS_WITH_MESSAGE -#undef DOCTEST_CHECK_THROWS_WITH_MESSAGE -#undef DOCTEST_REQUIRE_THROWS_WITH_MESSAGE -#undef DOCTEST_WARN_NOTHROW_MESSAGE -#undef DOCTEST_CHECK_NOTHROW_MESSAGE -#undef DOCTEST_REQUIRE_NOTHROW_MESSAGE - -#ifdef DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS - -#define DOCTEST_WARN_THROWS(expr) ((void)0) -#define DOCTEST_CHECK_THROWS(expr) ((void)0) -#define DOCTEST_REQUIRE_THROWS(expr) ((void)0) -#define DOCTEST_WARN_THROWS_AS(expr, ...) ((void)0) -#define DOCTEST_CHECK_THROWS_AS(expr, ...) ((void)0) -#define DOCTEST_REQUIRE_THROWS_AS(expr, ...) ((void)0) -#define DOCTEST_WARN_THROWS_WITH(expr, ...) ((void)0) -#define DOCTEST_CHECK_THROWS_WITH(expr, ...) ((void)0) -#define DOCTEST_REQUIRE_THROWS_WITH(expr, ...) ((void)0) -#define DOCTEST_WARN_NOTHROW(expr) ((void)0) -#define DOCTEST_CHECK_NOTHROW(expr) ((void)0) -#define DOCTEST_REQUIRE_NOTHROW(expr) ((void)0) - -#define DOCTEST_WARN_THROWS_MESSAGE(expr, msg) ((void)0) -#define DOCTEST_CHECK_THROWS_MESSAGE(expr, msg) ((void)0) -#define DOCTEST_REQUIRE_THROWS_MESSAGE(expr, msg) ((void)0) -#define DOCTEST_WARN_THROWS_AS_MESSAGE(expr, ex, msg) ((void)0) -#define DOCTEST_CHECK_THROWS_AS_MESSAGE(expr, ex, msg) ((void)0) -#define DOCTEST_REQUIRE_THROWS_AS_MESSAGE(expr, ex, msg) ((void)0) -#define DOCTEST_WARN_THROWS_WITH_MESSAGE(expr, ex, msg) ((void)0) -#define DOCTEST_CHECK_THROWS_WITH_MESSAGE(expr, ex, msg) ((void)0) -#define DOCTEST_REQUIRE_THROWS_WITH_MESSAGE(expr, ex, msg) ((void)0) -#define DOCTEST_WARN_NOTHROW_MESSAGE(expr, msg) ((void)0) -#define DOCTEST_CHECK_NOTHROW_MESSAGE(expr, msg) ((void)0) -#define DOCTEST_REQUIRE_NOTHROW_MESSAGE(expr, msg) ((void)0) - -#else // DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS - -#undef DOCTEST_REQUIRE -#undef DOCTEST_REQUIRE_FALSE -#undef DOCTEST_REQUIRE_MESSAGE -#undef DOCTEST_REQUIRE_FALSE_MESSAGE -#undef DOCTEST_REQUIRE_EQ -#undef DOCTEST_REQUIRE_NE -#undef DOCTEST_REQUIRE_GT -#undef DOCTEST_REQUIRE_LT -#undef DOCTEST_REQUIRE_GE -#undef DOCTEST_REQUIRE_LE -#undef DOCTEST_REQUIRE_UNARY -#undef DOCTEST_REQUIRE_UNARY_FALSE - -#endif // DOCTEST_CONFIG_NO_EXCEPTIONS_BUT_WITH_ALL_ASSERTS - -#endif // DOCTEST_CONFIG_NO_EXCEPTIONS - -// ================================================================================================= -// == WHAT FOLLOWS IS VERSIONS OF THE MACROS THAT DO NOT DO ANY REGISTERING! == -// == THIS CAN BE ENABLED BY DEFINING DOCTEST_CONFIG_DISABLE GLOBALLY! == -// ================================================================================================= -#else // DOCTEST_CONFIG_DISABLE - -#define DOCTEST_IMPLEMENT_FIXTURE(der, base, func, name) \ - namespace { \ - template \ - struct der : public base \ - { void f(); }; \ - } \ - template \ - inline void der::f() - -#define DOCTEST_CREATE_AND_REGISTER_FUNCTION(f, name) \ - template \ - static inline void f() - -// for registering tests -#define DOCTEST_TEST_CASE(name) \ - DOCTEST_CREATE_AND_REGISTER_FUNCTION(DOCTEST_ANONYMOUS(_DOCTEST_ANON_FUNC_), name) - -// for registering tests in classes -#define DOCTEST_TEST_CASE_CLASS(name) \ - DOCTEST_CREATE_AND_REGISTER_FUNCTION(DOCTEST_ANONYMOUS(_DOCTEST_ANON_FUNC_), name) - -// for registering tests with a fixture -#define DOCTEST_TEST_CASE_FIXTURE(x, name) \ - DOCTEST_IMPLEMENT_FIXTURE(DOCTEST_ANONYMOUS(_DOCTEST_ANON_CLASS_), x, \ - DOCTEST_ANONYMOUS(_DOCTEST_ANON_FUNC_), name) - -// for converting types to strings without the header and demangling -#define DOCTEST_TYPE_TO_STRING(...) typedef int DOCTEST_ANONYMOUS(_DOCTEST_ANON_FOR_SEMICOLON_) -#define DOCTEST_TYPE_TO_STRING_IMPL(...) - -// for typed tests -#define DOCTEST_TEST_CASE_TEMPLATE(name, type, ...) \ - template \ - inline void DOCTEST_ANONYMOUS(_DOCTEST_ANON_TMP_)() - -#define DOCTEST_TEST_CASE_TEMPLATE_DEFINE(name, type, id) \ - template \ - inline void DOCTEST_ANONYMOUS(_DOCTEST_ANON_TMP_)() - -#define DOCTEST_TEST_CASE_TEMPLATE_INVOKE(id, ...) \ - typedef int DOCTEST_ANONYMOUS(_DOCTEST_ANON_FOR_SEMICOLON_) - -#define DOCTEST_TEST_CASE_TEMPLATE_APPLY(id, ...) \ - typedef int DOCTEST_ANONYMOUS(_DOCTEST_ANON_FOR_SEMICOLON_) - -// for subcases -#define DOCTEST_SUBCASE(name) - -// for a testsuite block -#define DOCTEST_TEST_SUITE(name) namespace - -// for starting a testsuite block -#define DOCTEST_TEST_SUITE_BEGIN(name) typedef int DOCTEST_ANONYMOUS(_DOCTEST_ANON_FOR_SEMICOLON_) - -// for ending a testsuite block -#define DOCTEST_TEST_SUITE_END typedef int DOCTEST_ANONYMOUS(_DOCTEST_ANON_FOR_SEMICOLON_) - -#define DOCTEST_REGISTER_EXCEPTION_TRANSLATOR(signature) \ - template \ - static inline doctest::String DOCTEST_ANONYMOUS(_DOCTEST_ANON_TRANSLATOR_)(signature) - -#define DOCTEST_REGISTER_REPORTER(name, priority, reporter) - -#define DOCTEST_INFO(x) ((void)0) -#define DOCTEST_CAPTURE(x) ((void)0) -#define DOCTEST_ADD_MESSAGE_AT(file, line, x) ((void)0) -#define DOCTEST_ADD_FAIL_CHECK_AT(file, line, x) ((void)0) -#define DOCTEST_ADD_FAIL_AT(file, line, x) ((void)0) -#define DOCTEST_MESSAGE(x) ((void)0) -#define DOCTEST_FAIL_CHECK(x) ((void)0) -#define DOCTEST_FAIL(x) ((void)0) - -#define DOCTEST_WARN(...) ((void)0) -#define DOCTEST_CHECK(...) ((void)0) -#define DOCTEST_REQUIRE(...) ((void)0) -#define DOCTEST_WARN_FALSE(...) ((void)0) -#define DOCTEST_CHECK_FALSE(...) ((void)0) -#define DOCTEST_REQUIRE_FALSE(...) ((void)0) - -#define DOCTEST_WARN_MESSAGE(cond, msg) ((void)0) -#define DOCTEST_CHECK_MESSAGE(cond, msg) ((void)0) -#define DOCTEST_REQUIRE_MESSAGE(cond, msg) ((void)0) -#define DOCTEST_WARN_FALSE_MESSAGE(cond, msg) ((void)0) -#define DOCTEST_CHECK_FALSE_MESSAGE(cond, msg) ((void)0) -#define DOCTEST_REQUIRE_FALSE_MESSAGE(cond, msg) ((void)0) - -#define DOCTEST_WARN_THROWS(expr) ((void)0) -#define DOCTEST_CHECK_THROWS(expr) ((void)0) -#define DOCTEST_REQUIRE_THROWS(expr) ((void)0) -#define DOCTEST_WARN_THROWS_AS(expr, ...) ((void)0) -#define DOCTEST_CHECK_THROWS_AS(expr, ...) ((void)0) -#define DOCTEST_REQUIRE_THROWS_AS(expr, ...) ((void)0) -#define DOCTEST_WARN_THROWS_WITH(expr, ...) ((void)0) -#define DOCTEST_CHECK_THROWS_WITH(expr, ...) ((void)0) -#define DOCTEST_REQUIRE_THROWS_WITH(expr, ...) ((void)0) -#define DOCTEST_WARN_NOTHROW(expr) ((void)0) -#define DOCTEST_CHECK_NOTHROW(expr) ((void)0) -#define DOCTEST_REQUIRE_NOTHROW(expr) ((void)0) - -#define DOCTEST_WARN_THROWS_MESSAGE(expr, msg) ((void)0) -#define DOCTEST_CHECK_THROWS_MESSAGE(expr, msg) ((void)0) -#define DOCTEST_REQUIRE_THROWS_MESSAGE(expr, msg) ((void)0) -#define DOCTEST_WARN_THROWS_AS_MESSAGE(expr, ex, msg) ((void)0) -#define DOCTEST_CHECK_THROWS_AS_MESSAGE(expr, ex, msg) ((void)0) -#define DOCTEST_REQUIRE_THROWS_AS_MESSAGE(expr, ex, msg) ((void)0) -#define DOCTEST_WARN_THROWS_WITH_MESSAGE(expr, ex, msg) ((void)0) -#define DOCTEST_CHECK_THROWS_WITH_MESSAGE(expr, ex, msg) ((void)0) -#define DOCTEST_REQUIRE_THROWS_WITH_MESSAGE(expr, ex, msg) ((void)0) -#define DOCTEST_WARN_NOTHROW_MESSAGE(expr, msg) ((void)0) -#define DOCTEST_CHECK_NOTHROW_MESSAGE(expr, msg) ((void)0) -#define DOCTEST_REQUIRE_NOTHROW_MESSAGE(expr, msg) ((void)0) - -#define DOCTEST_WARN_EQ(...) ((void)0) -#define DOCTEST_CHECK_EQ(...) ((void)0) -#define DOCTEST_REQUIRE_EQ(...) ((void)0) -#define DOCTEST_WARN_NE(...) ((void)0) -#define DOCTEST_CHECK_NE(...) ((void)0) -#define DOCTEST_REQUIRE_NE(...) ((void)0) -#define DOCTEST_WARN_GT(...) ((void)0) -#define DOCTEST_CHECK_GT(...) ((void)0) -#define DOCTEST_REQUIRE_GT(...) ((void)0) -#define DOCTEST_WARN_LT(...) ((void)0) -#define DOCTEST_CHECK_LT(...) ((void)0) -#define DOCTEST_REQUIRE_LT(...) ((void)0) -#define DOCTEST_WARN_GE(...) ((void)0) -#define DOCTEST_CHECK_GE(...) ((void)0) -#define DOCTEST_REQUIRE_GE(...) ((void)0) -#define DOCTEST_WARN_LE(...) ((void)0) -#define DOCTEST_CHECK_LE(...) ((void)0) -#define DOCTEST_REQUIRE_LE(...) ((void)0) - -#define DOCTEST_WARN_UNARY(...) ((void)0) -#define DOCTEST_CHECK_UNARY(...) ((void)0) -#define DOCTEST_REQUIRE_UNARY(...) ((void)0) -#define DOCTEST_WARN_UNARY_FALSE(...) ((void)0) -#define DOCTEST_CHECK_UNARY_FALSE(...) ((void)0) -#define DOCTEST_REQUIRE_UNARY_FALSE(...) ((void)0) - -#endif // DOCTEST_CONFIG_DISABLE - -// clang-format off -// KEPT FOR BACKWARDS COMPATIBILITY - FORWARDING TO THE RIGHT MACROS -#define DOCTEST_FAST_WARN_EQ DOCTEST_WARN_EQ -#define DOCTEST_FAST_CHECK_EQ DOCTEST_CHECK_EQ -#define DOCTEST_FAST_REQUIRE_EQ DOCTEST_REQUIRE_EQ -#define DOCTEST_FAST_WARN_NE DOCTEST_WARN_NE -#define DOCTEST_FAST_CHECK_NE DOCTEST_CHECK_NE -#define DOCTEST_FAST_REQUIRE_NE DOCTEST_REQUIRE_NE -#define DOCTEST_FAST_WARN_GT DOCTEST_WARN_GT -#define DOCTEST_FAST_CHECK_GT DOCTEST_CHECK_GT -#define DOCTEST_FAST_REQUIRE_GT DOCTEST_REQUIRE_GT -#define DOCTEST_FAST_WARN_LT DOCTEST_WARN_LT -#define DOCTEST_FAST_CHECK_LT DOCTEST_CHECK_LT -#define DOCTEST_FAST_REQUIRE_LT DOCTEST_REQUIRE_LT -#define DOCTEST_FAST_WARN_GE DOCTEST_WARN_GE -#define DOCTEST_FAST_CHECK_GE DOCTEST_CHECK_GE -#define DOCTEST_FAST_REQUIRE_GE DOCTEST_REQUIRE_GE -#define DOCTEST_FAST_WARN_LE DOCTEST_WARN_LE -#define DOCTEST_FAST_CHECK_LE DOCTEST_CHECK_LE -#define DOCTEST_FAST_REQUIRE_LE DOCTEST_REQUIRE_LE - -#define DOCTEST_FAST_WARN_UNARY DOCTEST_WARN_UNARY -#define DOCTEST_FAST_CHECK_UNARY DOCTEST_CHECK_UNARY -#define DOCTEST_FAST_REQUIRE_UNARY DOCTEST_REQUIRE_UNARY -#define DOCTEST_FAST_WARN_UNARY_FALSE DOCTEST_WARN_UNARY_FALSE -#define DOCTEST_FAST_CHECK_UNARY_FALSE DOCTEST_CHECK_UNARY_FALSE -#define DOCTEST_FAST_REQUIRE_UNARY_FALSE DOCTEST_REQUIRE_UNARY_FALSE - -#define DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE DOCTEST_TEST_CASE_TEMPLATE_INVOKE -// clang-format on - -// BDD style macros -// clang-format off -#define DOCTEST_SCENARIO(name) DOCTEST_TEST_CASE(" Scenario: " name) -#define DOCTEST_SCENARIO_CLASS(name) DOCTEST_TEST_CASE_CLASS(" Scenario: " name) -#define DOCTEST_SCENARIO_TEMPLATE(name, T, ...) DOCTEST_TEST_CASE_TEMPLATE(" Scenario: " name, T, __VA_ARGS__) -#define DOCTEST_SCENARIO_TEMPLATE_DEFINE(name, T, id) DOCTEST_TEST_CASE_TEMPLATE_DEFINE(" Scenario: " name, T, id) - -#define DOCTEST_GIVEN(name) SUBCASE(" Given: " name) -#define DOCTEST_WHEN(name) SUBCASE(" When: " name) -#define DOCTEST_AND_WHEN(name) SUBCASE("And when: " name) -#define DOCTEST_THEN(name) SUBCASE(" Then: " name) -#define DOCTEST_AND_THEN(name) SUBCASE(" And: " name) -// clang-format on - -// == SHORT VERSIONS OF THE MACROS -#if !defined(DOCTEST_CONFIG_NO_SHORT_MACRO_NAMES) - -#define TEST_CASE DOCTEST_TEST_CASE -#define TEST_CASE_CLASS DOCTEST_TEST_CASE_CLASS -#define TEST_CASE_FIXTURE DOCTEST_TEST_CASE_FIXTURE -#define TYPE_TO_STRING DOCTEST_TYPE_TO_STRING -#define TEST_CASE_TEMPLATE DOCTEST_TEST_CASE_TEMPLATE -#define TEST_CASE_TEMPLATE_DEFINE DOCTEST_TEST_CASE_TEMPLATE_DEFINE -#define TEST_CASE_TEMPLATE_INVOKE DOCTEST_TEST_CASE_TEMPLATE_INVOKE -#define TEST_CASE_TEMPLATE_APPLY DOCTEST_TEST_CASE_TEMPLATE_APPLY -#define SUBCASE DOCTEST_SUBCASE -#define TEST_SUITE DOCTEST_TEST_SUITE -#define TEST_SUITE_BEGIN DOCTEST_TEST_SUITE_BEGIN -#define TEST_SUITE_END DOCTEST_TEST_SUITE_END -#define REGISTER_EXCEPTION_TRANSLATOR DOCTEST_REGISTER_EXCEPTION_TRANSLATOR -#define REGISTER_REPORTER DOCTEST_REGISTER_REPORTER -#define INFO DOCTEST_INFO -#define CAPTURE DOCTEST_CAPTURE -#define ADD_MESSAGE_AT DOCTEST_ADD_MESSAGE_AT -#define ADD_FAIL_CHECK_AT DOCTEST_ADD_FAIL_CHECK_AT -#define ADD_FAIL_AT DOCTEST_ADD_FAIL_AT -#define MESSAGE DOCTEST_MESSAGE -#define FAIL_CHECK DOCTEST_FAIL_CHECK -#define FAIL DOCTEST_FAIL -#define TO_LVALUE DOCTEST_TO_LVALUE - -#define WARN DOCTEST_WARN -#define WARN_FALSE DOCTEST_WARN_FALSE -#define WARN_THROWS DOCTEST_WARN_THROWS -#define WARN_THROWS_AS DOCTEST_WARN_THROWS_AS -#define WARN_THROWS_WITH DOCTEST_WARN_THROWS_WITH -#define WARN_NOTHROW DOCTEST_WARN_NOTHROW -#define CHECK DOCTEST_CHECK -#define CHECK_FALSE DOCTEST_CHECK_FALSE -#define CHECK_THROWS DOCTEST_CHECK_THROWS -#define CHECK_THROWS_AS DOCTEST_CHECK_THROWS_AS -#define CHECK_THROWS_WITH DOCTEST_CHECK_THROWS_WITH -#define CHECK_NOTHROW DOCTEST_CHECK_NOTHROW -#define REQUIRE DOCTEST_REQUIRE -#define REQUIRE_FALSE DOCTEST_REQUIRE_FALSE -#define REQUIRE_THROWS DOCTEST_REQUIRE_THROWS -#define REQUIRE_THROWS_AS DOCTEST_REQUIRE_THROWS_AS -#define REQUIRE_THROWS_WITH DOCTEST_REQUIRE_THROWS_WITH -#define REQUIRE_NOTHROW DOCTEST_REQUIRE_NOTHROW - -#define WARN_MESSAGE DOCTEST_WARN_MESSAGE -#define WARN_FALSE_MESSAGE DOCTEST_WARN_FALSE_MESSAGE -#define WARN_THROWS_MESSAGE DOCTEST_WARN_THROWS_MESSAGE -#define WARN_THROWS_AS_MESSAGE DOCTEST_WARN_THROWS_AS_MESSAGE -#define WARN_THROWS_WITH_MESSAGE DOCTEST_WARN_THROWS_WITH_MESSAGE -#define WARN_NOTHROW_MESSAGE DOCTEST_WARN_NOTHROW_MESSAGE -#define CHECK_MESSAGE DOCTEST_CHECK_MESSAGE -#define CHECK_FALSE_MESSAGE DOCTEST_CHECK_FALSE_MESSAGE -#define CHECK_THROWS_MESSAGE DOCTEST_CHECK_THROWS_MESSAGE -#define CHECK_THROWS_AS_MESSAGE DOCTEST_CHECK_THROWS_AS_MESSAGE -#define CHECK_THROWS_WITH_MESSAGE DOCTEST_CHECK_THROWS_WITH_MESSAGE -#define CHECK_NOTHROW_MESSAGE DOCTEST_CHECK_NOTHROW_MESSAGE -#define REQUIRE_MESSAGE DOCTEST_REQUIRE_MESSAGE -#define REQUIRE_FALSE_MESSAGE DOCTEST_REQUIRE_FALSE_MESSAGE -#define REQUIRE_THROWS_MESSAGE DOCTEST_REQUIRE_THROWS_MESSAGE -#define REQUIRE_THROWS_AS_MESSAGE DOCTEST_REQUIRE_THROWS_AS_MESSAGE -#define REQUIRE_THROWS_WITH_MESSAGE DOCTEST_REQUIRE_THROWS_WITH_MESSAGE -#define REQUIRE_NOTHROW_MESSAGE DOCTEST_REQUIRE_NOTHROW_MESSAGE - -#define SCENARIO DOCTEST_SCENARIO -#define SCENARIO_CLASS DOCTEST_SCENARIO_CLASS -#define SCENARIO_TEMPLATE DOCTEST_SCENARIO_TEMPLATE -#define SCENARIO_TEMPLATE_DEFINE DOCTEST_SCENARIO_TEMPLATE_DEFINE -#define GIVEN DOCTEST_GIVEN -#define WHEN DOCTEST_WHEN -#define AND_WHEN DOCTEST_AND_WHEN -#define THEN DOCTEST_THEN -#define AND_THEN DOCTEST_AND_THEN - -#define WARN_EQ DOCTEST_WARN_EQ -#define CHECK_EQ DOCTEST_CHECK_EQ -#define REQUIRE_EQ DOCTEST_REQUIRE_EQ -#define WARN_NE DOCTEST_WARN_NE -#define CHECK_NE DOCTEST_CHECK_NE -#define REQUIRE_NE DOCTEST_REQUIRE_NE -#define WARN_GT DOCTEST_WARN_GT -#define CHECK_GT DOCTEST_CHECK_GT -#define REQUIRE_GT DOCTEST_REQUIRE_GT -#define WARN_LT DOCTEST_WARN_LT -#define CHECK_LT DOCTEST_CHECK_LT -#define REQUIRE_LT DOCTEST_REQUIRE_LT -#define WARN_GE DOCTEST_WARN_GE -#define CHECK_GE DOCTEST_CHECK_GE -#define REQUIRE_GE DOCTEST_REQUIRE_GE -#define WARN_LE DOCTEST_WARN_LE -#define CHECK_LE DOCTEST_CHECK_LE -#define REQUIRE_LE DOCTEST_REQUIRE_LE -#define WARN_UNARY DOCTEST_WARN_UNARY -#define CHECK_UNARY DOCTEST_CHECK_UNARY -#define REQUIRE_UNARY DOCTEST_REQUIRE_UNARY -#define WARN_UNARY_FALSE DOCTEST_WARN_UNARY_FALSE -#define CHECK_UNARY_FALSE DOCTEST_CHECK_UNARY_FALSE -#define REQUIRE_UNARY_FALSE DOCTEST_REQUIRE_UNARY_FALSE - -// KEPT FOR BACKWARDS COMPATIBILITY -#define FAST_WARN_EQ DOCTEST_FAST_WARN_EQ -#define FAST_CHECK_EQ DOCTEST_FAST_CHECK_EQ -#define FAST_REQUIRE_EQ DOCTEST_FAST_REQUIRE_EQ -#define FAST_WARN_NE DOCTEST_FAST_WARN_NE -#define FAST_CHECK_NE DOCTEST_FAST_CHECK_NE -#define FAST_REQUIRE_NE DOCTEST_FAST_REQUIRE_NE -#define FAST_WARN_GT DOCTEST_FAST_WARN_GT -#define FAST_CHECK_GT DOCTEST_FAST_CHECK_GT -#define FAST_REQUIRE_GT DOCTEST_FAST_REQUIRE_GT -#define FAST_WARN_LT DOCTEST_FAST_WARN_LT -#define FAST_CHECK_LT DOCTEST_FAST_CHECK_LT -#define FAST_REQUIRE_LT DOCTEST_FAST_REQUIRE_LT -#define FAST_WARN_GE DOCTEST_FAST_WARN_GE -#define FAST_CHECK_GE DOCTEST_FAST_CHECK_GE -#define FAST_REQUIRE_GE DOCTEST_FAST_REQUIRE_GE -#define FAST_WARN_LE DOCTEST_FAST_WARN_LE -#define FAST_CHECK_LE DOCTEST_FAST_CHECK_LE -#define FAST_REQUIRE_LE DOCTEST_FAST_REQUIRE_LE - -#define FAST_WARN_UNARY DOCTEST_FAST_WARN_UNARY -#define FAST_CHECK_UNARY DOCTEST_FAST_CHECK_UNARY -#define FAST_REQUIRE_UNARY DOCTEST_FAST_REQUIRE_UNARY -#define FAST_WARN_UNARY_FALSE DOCTEST_FAST_WARN_UNARY_FALSE -#define FAST_CHECK_UNARY_FALSE DOCTEST_FAST_CHECK_UNARY_FALSE -#define FAST_REQUIRE_UNARY_FALSE DOCTEST_FAST_REQUIRE_UNARY_FALSE - -#define TEST_CASE_TEMPLATE_INSTANTIATE DOCTEST_TEST_CASE_TEMPLATE_INSTANTIATE - -#endif // DOCTEST_CONFIG_NO_SHORT_MACRO_NAMES - -#if !defined(DOCTEST_CONFIG_DISABLE) - -// this is here to clear the 'current test suite' for the current translation unit - at the top -DOCTEST_TEST_SUITE_END(); - -// add stringification for primitive/fundamental types -namespace doctest { namespace detail { - DOCTEST_TYPE_TO_STRING_IMPL(bool) - DOCTEST_TYPE_TO_STRING_IMPL(float) - DOCTEST_TYPE_TO_STRING_IMPL(double) - DOCTEST_TYPE_TO_STRING_IMPL(long double) - DOCTEST_TYPE_TO_STRING_IMPL(char) - DOCTEST_TYPE_TO_STRING_IMPL(signed char) - DOCTEST_TYPE_TO_STRING_IMPL(unsigned char) -#if !DOCTEST_MSVC || defined(_NATIVE_WCHAR_T_DEFINED) - DOCTEST_TYPE_TO_STRING_IMPL(wchar_t) -#endif // not MSVC or wchar_t support enabled - DOCTEST_TYPE_TO_STRING_IMPL(short int) - DOCTEST_TYPE_TO_STRING_IMPL(unsigned short int) - DOCTEST_TYPE_TO_STRING_IMPL(int) - DOCTEST_TYPE_TO_STRING_IMPL(unsigned int) - DOCTEST_TYPE_TO_STRING_IMPL(long int) - DOCTEST_TYPE_TO_STRING_IMPL(unsigned long int) - DOCTEST_TYPE_TO_STRING_IMPL(long long int) - DOCTEST_TYPE_TO_STRING_IMPL(unsigned long long int) -}} // namespace doctest::detail - -#endif // DOCTEST_CONFIG_DISABLE - -DOCTEST_CLANG_SUPPRESS_WARNING_POP -DOCTEST_MSVC_SUPPRESS_WARNING_POP -DOCTEST_GCC_SUPPRESS_WARNING_POP - -#endif // DOCTEST_LIBRARY_INCLUDED - -#ifndef DOCTEST_SINGLE_HEADER -#define DOCTEST_SINGLE_HEADER -#endif // DOCTEST_SINGLE_HEADER - -#if defined(DOCTEST_CONFIG_IMPLEMENT) || !defined(DOCTEST_SINGLE_HEADER) -#ifndef DOCTEST_LIBRARY_IMPLEMENTATION -#define DOCTEST_LIBRARY_IMPLEMENTATION - -#ifndef DOCTEST_SINGLE_HEADER -#include "doctest_fwd.h" -#endif // DOCTEST_SINGLE_HEADER - -DOCTEST_CLANG_SUPPRESS_WARNING_PUSH -DOCTEST_CLANG_SUPPRESS_WARNING("-Wunknown-pragmas") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wpadded") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wweak-vtables") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wglobal-constructors") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wexit-time-destructors") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-prototypes") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wsign-conversion") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wshorten-64-to-32") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-variable-declarations") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wswitch") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wswitch-enum") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wcovered-switch-default") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-noreturn") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wunused-local-typedef") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wdisabled-macro-expansion") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-braces") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wmissing-field-initializers") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wc++98-compat") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wc++98-compat-pedantic") -DOCTEST_CLANG_SUPPRESS_WARNING("-Wunused-member-function") - -DOCTEST_GCC_SUPPRESS_WARNING_PUSH -DOCTEST_GCC_SUPPRESS_WARNING("-Wunknown-pragmas") -DOCTEST_GCC_SUPPRESS_WARNING("-Wpragmas") -DOCTEST_GCC_SUPPRESS_WARNING("-Wconversion") -DOCTEST_GCC_SUPPRESS_WARNING("-Weffc++") -DOCTEST_GCC_SUPPRESS_WARNING("-Wsign-conversion") -DOCTEST_GCC_SUPPRESS_WARNING("-Wstrict-overflow") -DOCTEST_GCC_SUPPRESS_WARNING("-Wstrict-aliasing") -DOCTEST_GCC_SUPPRESS_WARNING("-Wmissing-field-initializers") -DOCTEST_GCC_SUPPRESS_WARNING("-Wmissing-braces") -DOCTEST_GCC_SUPPRESS_WARNING("-Wmissing-declarations") -DOCTEST_GCC_SUPPRESS_WARNING("-Winline") -DOCTEST_GCC_SUPPRESS_WARNING("-Wswitch") -DOCTEST_GCC_SUPPRESS_WARNING("-Wswitch-enum") -DOCTEST_GCC_SUPPRESS_WARNING("-Wswitch-default") -DOCTEST_GCC_SUPPRESS_WARNING("-Wunsafe-loop-optimizations") -DOCTEST_GCC_SUPPRESS_WARNING("-Wold-style-cast") -DOCTEST_GCC_SUPPRESS_WARNING("-Wunused-local-typedefs") -DOCTEST_GCC_SUPPRESS_WARNING("-Wuseless-cast") -DOCTEST_GCC_SUPPRESS_WARNING("-Wunused-function") - -DOCTEST_MSVC_SUPPRESS_WARNING_PUSH -DOCTEST_MSVC_SUPPRESS_WARNING(4616) // invalid compiler warning -DOCTEST_MSVC_SUPPRESS_WARNING(4619) // invalid compiler warning -DOCTEST_MSVC_SUPPRESS_WARNING(4996) // The compiler encountered a deprecated declaration -DOCTEST_MSVC_SUPPRESS_WARNING(4267) // 'var' : conversion from 'x' to 'y', possible loss of data -DOCTEST_MSVC_SUPPRESS_WARNING(4706) // assignment within conditional expression -DOCTEST_MSVC_SUPPRESS_WARNING(4512) // 'class' : assignment operator could not be generated -DOCTEST_MSVC_SUPPRESS_WARNING(4127) // conditional expression is constant -DOCTEST_MSVC_SUPPRESS_WARNING(4530) // C++ exception handler used, but unwind semantics not enabled -DOCTEST_MSVC_SUPPRESS_WARNING(4577) // 'noexcept' used with no exception handling mode specified -DOCTEST_MSVC_SUPPRESS_WARNING(4774) // format string expected in argument is not a string literal -DOCTEST_MSVC_SUPPRESS_WARNING(4365) // conversion from 'int' to 'unsigned', signed/unsigned mismatch -DOCTEST_MSVC_SUPPRESS_WARNING(4820) // padding in structs -DOCTEST_MSVC_SUPPRESS_WARNING(4640) // construction of local static object is not thread-safe -DOCTEST_MSVC_SUPPRESS_WARNING(5039) // pointer to potentially throwing function passed to extern C -DOCTEST_MSVC_SUPPRESS_WARNING(5045) // Spectre mitigation stuff -DOCTEST_MSVC_SUPPRESS_WARNING(4626) // assignment operator was implicitly defined as deleted -DOCTEST_MSVC_SUPPRESS_WARNING(5027) // move assignment operator was implicitly defined as deleted -DOCTEST_MSVC_SUPPRESS_WARNING(5026) // move constructor was implicitly defined as deleted -DOCTEST_MSVC_SUPPRESS_WARNING(4625) // copy constructor was implicitly defined as deleted -DOCTEST_MSVC_SUPPRESS_WARNING(4800) // forcing value to bool 'true' or 'false' (performance warning) -// static analysis -DOCTEST_MSVC_SUPPRESS_WARNING(26439) // This kind of function may not throw. Declare it 'noexcept' -DOCTEST_MSVC_SUPPRESS_WARNING(26495) // Always initialize a member variable -DOCTEST_MSVC_SUPPRESS_WARNING(26451) // Arithmetic overflow ... -DOCTEST_MSVC_SUPPRESS_WARNING(26444) // Avoid unnamed objects with custom construction and dtor... - -DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_BEGIN - -// required includes - will go only in one translation unit! -#include -#include -#include -// borland (Embarcadero) compiler requires math.h and not cmath - https://github.com/onqtam/doctest/pull/37 -#ifdef __BORLANDC__ -#include -#endif // __BORLANDC__ -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#ifdef DOCTEST_CONFIG_POSIX_SIGNALS -#include -#endif // DOCTEST_CONFIG_POSIX_SIGNALS -#include -#include -#include - -#ifdef DOCTEST_PLATFORM_MAC -#include -#include -#include -#endif // DOCTEST_PLATFORM_MAC - -#ifdef DOCTEST_PLATFORM_WINDOWS - -// defines for a leaner windows.h -#ifndef WIN32_LEAN_AND_MEAN -#define WIN32_LEAN_AND_MEAN -#endif // WIN32_LEAN_AND_MEAN -#ifndef VC_EXTRA_LEAN -#define VC_EXTRA_LEAN -#endif // VC_EXTRA_LEAN -#ifndef NOMINMAX -#define NOMINMAX -#endif // NOMINMAX - -// not sure what AfxWin.h is for - here I do what Catch does -#ifdef __AFXDLL -#include -#else -#include -#endif -#include - -#else // DOCTEST_PLATFORM_WINDOWS - -#include -#include - -#endif // DOCTEST_PLATFORM_WINDOWS - -DOCTEST_MAKE_STD_HEADERS_CLEAN_FROM_WARNINGS_ON_WALL_END - -// counts the number of elements in a C array -#define DOCTEST_COUNTOF(x) (sizeof(x) / sizeof(x[0])) - -#ifdef DOCTEST_CONFIG_DISABLE -#define DOCTEST_BRANCH_ON_DISABLED(if_disabled, if_not_disabled) if_disabled -#else // DOCTEST_CONFIG_DISABLE -#define DOCTEST_BRANCH_ON_DISABLED(if_disabled, if_not_disabled) if_not_disabled -#endif // DOCTEST_CONFIG_DISABLE - -#ifndef DOCTEST_CONFIG_OPTIONS_PREFIX -#define DOCTEST_CONFIG_OPTIONS_PREFIX "dt-" -#endif - -#ifndef DOCTEST_THREAD_LOCAL -#define DOCTEST_THREAD_LOCAL thread_local -#endif - -#ifdef DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS -#define DOCTEST_OPTIONS_PREFIX_DISPLAY DOCTEST_CONFIG_OPTIONS_PREFIX -#else -#define DOCTEST_OPTIONS_PREFIX_DISPLAY "" -#endif - -namespace doctest { - -bool is_running_in_test = false; - -namespace { - using namespace detail; - // case insensitive strcmp - int stricmp(const char* a, const char* b) { - for(;; a++, b++) { - const int d = tolower(*a) - tolower(*b); - if(d != 0 || !*a) - return d; - } - } - - template - String fpToString(T value, int precision) { - std::ostringstream oss; - oss << std::setprecision(precision) << std::fixed << value; - std::string d = oss.str(); - size_t i = d.find_last_not_of('0'); - if(i != std::string::npos && i != d.size() - 1) { - if(d[i] == '.') - i++; - d = d.substr(0, i + 1); - } - return d.c_str(); - } - - struct Endianness - { - enum Arch - { - Big, - Little - }; - - static Arch which() { - int x = 1; - // casting any data pointer to char* is allowed - auto ptr = reinterpret_cast(&x); - if(*ptr) - return Little; - return Big; - } - }; -} // namespace - -namespace detail { - void my_memcpy(void* dest, const void* src, unsigned num) { memcpy(dest, src, num); } - - String rawMemoryToString(const void* object, unsigned size) { - // Reverse order for little endian architectures - int i = 0, end = static_cast(size), inc = 1; - if(Endianness::which() == Endianness::Little) { - i = end - 1; - end = inc = -1; - } - - unsigned const char* bytes = static_cast(object); - std::ostringstream oss; - oss << "0x" << std::setfill('0') << std::hex; - for(; i != end; i += inc) - oss << std::setw(2) << static_cast(bytes[i]); - return oss.str().c_str(); - } - - DOCTEST_THREAD_LOCAL std::ostringstream g_oss; - - std::ostream* getTlsOss() { - g_oss.clear(); // there shouldn't be anything worth clearing in the flags - g_oss.str(""); // the slow way of resetting a string stream - //g_oss.seekp(0); // optimal reset - as seen here: https://stackoverflow.com/a/624291/3162383 - return &g_oss; - } - - String getTlsOssResult() { - //g_oss << std::ends; // needed - as shown here: https://stackoverflow.com/a/624291/3162383 - return g_oss.str().c_str(); - } - -#ifndef DOCTEST_CONFIG_DISABLE - - typedef uint64_t UInt64; - -#ifdef DOCTEST_CONFIG_GETCURRENTTICKS - UInt64 getCurrentTicks() { return DOCTEST_CONFIG_GETCURRENTTICKS(); } -#elif defined(DOCTEST_PLATFORM_WINDOWS) - UInt64 getCurrentTicks() { - static UInt64 hz = 0, hzo = 0; - if(!hz) { - QueryPerformanceFrequency(reinterpret_cast(&hz)); - QueryPerformanceCounter(reinterpret_cast(&hzo)); - } - UInt64 t; - QueryPerformanceCounter(reinterpret_cast(&t)); - return ((t - hzo) * 1000000) / hz; - } -#else // DOCTEST_PLATFORM_WINDOWS - UInt64 getCurrentTicks() { - timeval t; - gettimeofday(&t, nullptr); - return static_cast(t.tv_sec) * 1000000 + static_cast(t.tv_usec); - } -#endif // DOCTEST_PLATFORM_WINDOWS - - struct Timer - { - void start() { m_ticks = getCurrentTicks(); } - unsigned int getElapsedMicroseconds() const { - return static_cast(getCurrentTicks() - m_ticks); - } - //unsigned int getElapsedMilliseconds() const { - // return static_cast(getElapsedMicroseconds() / 1000); - //} - double getElapsedSeconds() const { return getElapsedMicroseconds() / 1000000.0; } - - private: - UInt64 m_ticks = 0; - }; - - // this holds both parameters from the command line and runtime data for tests - struct ContextState : ContextOptions, TestRunStats, CurrentTestCaseStats - { - std::atomic numAssertsCurrentTest_atomic; - std::atomic numAssertsFailedCurrentTest_atomic; - - std::vector> filters = decltype(filters)(9); // 9 different filters - - std::vector reporters_currently_used; - - const TestCase* currentTest = nullptr; - - assert_handler ah = nullptr; - - Timer timer; - - std::vector stringifiedContexts; // logging from INFO() due to an exception - - // stuff for subcases - std::set subcasesPassed; - std::set subcasesEnteredLevels; - int subcasesCurrentLevel; - bool should_reenter; - - void resetRunData() { - numTestCases = 0; - numTestCasesPassingFilters = 0; - numTestSuitesPassingFilters = 0; - numTestCasesFailed = 0; - numAsserts = 0; - numAssertsFailed = 0; - numAssertsCurrentTest = 0; - numAssertsFailedCurrentTest = 0; - } - - void finalizeTestCaseData() { - seconds = timer.getElapsedSeconds(); - - // update the non-atomic counters - numAsserts += numAssertsCurrentTest_atomic; - numAssertsFailed += numAssertsFailedCurrentTest_atomic; - numAssertsCurrentTest = numAssertsCurrentTest_atomic; - numAssertsFailedCurrentTest = numAssertsFailedCurrentTest_atomic; - - if(numAssertsFailedCurrentTest) - failure_flags |= TestCaseFailureReason::AssertFailure; - - if(Approx(currentTest->m_timeout).epsilon(DBL_EPSILON) != 0 && - Approx(seconds).epsilon(DBL_EPSILON) > currentTest->m_timeout) - failure_flags |= TestCaseFailureReason::Timeout; - - if(currentTest->m_should_fail) { - if(failure_flags) { - failure_flags |= TestCaseFailureReason::ShouldHaveFailedAndDid; - } else { - failure_flags |= TestCaseFailureReason::ShouldHaveFailedButDidnt; - } - } else if(failure_flags && currentTest->m_may_fail) { - failure_flags |= TestCaseFailureReason::CouldHaveFailedAndDid; - } else if(currentTest->m_expected_failures > 0) { - if(numAssertsFailedCurrentTest == currentTest->m_expected_failures) { - failure_flags |= TestCaseFailureReason::FailedExactlyNumTimes; - } else { - failure_flags |= TestCaseFailureReason::DidntFailExactlyNumTimes; - } - } - - bool ok_to_fail = (TestCaseFailureReason::ShouldHaveFailedAndDid & failure_flags) || - (TestCaseFailureReason::CouldHaveFailedAndDid & failure_flags) || - (TestCaseFailureReason::FailedExactlyNumTimes & failure_flags); - - // if any subcase has failed - the whole test case has failed - if(failure_flags && !ok_to_fail) - numTestCasesFailed++; - } - }; - - ContextState* g_cs = nullptr; - - // used to avoid locks for the debug output - // TODO: figure out if this is indeed necessary/correct - seems like either there still - // could be a race or that there wouldn't be a race even if using the context directly - DOCTEST_THREAD_LOCAL bool g_no_colors; - -#endif // DOCTEST_CONFIG_DISABLE -} // namespace detail - -void String::setOnHeap() { *reinterpret_cast(&buf[last]) = 128; } -void String::setLast(unsigned in) { buf[last] = char(in); } - -void String::copy(const String& other) { - if(other.isOnStack()) { - memcpy(buf, other.buf, len); - } else { - setOnHeap(); - data.size = other.data.size; - data.capacity = data.size + 1; - data.ptr = new char[data.capacity]; - memcpy(data.ptr, other.data.ptr, data.size + 1); - } -} - -String::String() { - buf[0] = '\0'; - setLast(); -} - -String::~String() { - if(!isOnStack()) - delete[] data.ptr; -} - -String::String(const char* in) - : String(in, strlen(in)) {} - -String::String(const char* in, unsigned in_size) { - if(in_size <= last) { - memcpy(buf, in, in_size + 1); - setLast(last - in_size); - } else { - setOnHeap(); - data.size = in_size; - data.capacity = data.size + 1; - data.ptr = new char[data.capacity]; - memcpy(data.ptr, in, in_size + 1); - } -} - -String::String(const String& other) { copy(other); } - -String& String::operator=(const String& other) { - if(this != &other) { - if(!isOnStack()) - delete[] data.ptr; - - copy(other); - } - - return *this; -} - -String& String::operator+=(const String& other) { - const unsigned my_old_size = size(); - const unsigned other_size = other.size(); - const unsigned total_size = my_old_size + other_size; - if(isOnStack()) { - if(total_size < len) { - // append to the current stack space - memcpy(buf + my_old_size, other.c_str(), other_size + 1); - setLast(last - total_size); - } else { - // alloc new chunk - char* temp = new char[total_size + 1]; - // copy current data to new location before writing in the union - memcpy(temp, buf, my_old_size); // skip the +1 ('\0') for speed - // update data in union - setOnHeap(); - data.size = total_size; - data.capacity = data.size + 1; - data.ptr = temp; - // transfer the rest of the data - memcpy(data.ptr + my_old_size, other.c_str(), other_size + 1); - } - } else { - if(data.capacity > total_size) { - // append to the current heap block - data.size = total_size; - memcpy(data.ptr + my_old_size, other.c_str(), other_size + 1); - } else { - // resize - data.capacity *= 2; - if(data.capacity <= total_size) - data.capacity = total_size + 1; - // alloc new chunk - char* temp = new char[data.capacity]; - // copy current data to new location before releasing it - memcpy(temp, data.ptr, my_old_size); // skip the +1 ('\0') for speed - // release old chunk - delete[] data.ptr; - // update the rest of the union members - data.size = total_size; - data.ptr = temp; - // transfer the rest of the data - memcpy(data.ptr + my_old_size, other.c_str(), other_size + 1); - } - } - - return *this; -} - -String String::operator+(const String& other) const { return String(*this) += other; } - -String::String(String&& other) { - memcpy(buf, other.buf, len); - other.buf[0] = '\0'; - other.setLast(); -} - -String& String::operator=(String&& other) { - if(this != &other) { - if(!isOnStack()) - delete[] data.ptr; - memcpy(buf, other.buf, len); - other.buf[0] = '\0'; - other.setLast(); - } - return *this; -} - -char String::operator[](unsigned i) const { - return const_cast(this)->operator[](i); // NOLINT -} - -char& String::operator[](unsigned i) { - if(isOnStack()) - return reinterpret_cast(buf)[i]; - return data.ptr[i]; -} - -DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wmaybe-uninitialized") -unsigned String::size() const { - if(isOnStack()) - return last - (unsigned(buf[last]) & 31); // using "last" would work only if "len" is 32 - return data.size; -} -DOCTEST_GCC_SUPPRESS_WARNING_POP - -unsigned String::capacity() const { - if(isOnStack()) - return len; - return data.capacity; -} - -int String::compare(const char* other, bool no_case) const { - if(no_case) - return stricmp(c_str(), other); - return std::strcmp(c_str(), other); -} - -int String::compare(const String& other, bool no_case) const { - return compare(other.c_str(), no_case); -} - -// clang-format off -bool operator==(const String& lhs, const String& rhs) { return lhs.compare(rhs) == 0; } -bool operator!=(const String& lhs, const String& rhs) { return lhs.compare(rhs) != 0; } -bool operator< (const String& lhs, const String& rhs) { return lhs.compare(rhs) < 0; } -bool operator> (const String& lhs, const String& rhs) { return lhs.compare(rhs) > 0; } -bool operator<=(const String& lhs, const String& rhs) { return (lhs != rhs) ? lhs.compare(rhs) < 0 : true; } -bool operator>=(const String& lhs, const String& rhs) { return (lhs != rhs) ? lhs.compare(rhs) > 0 : true; } -// clang-format on - -std::ostream& operator<<(std::ostream& s, const String& in) { return s << in.c_str(); } - -namespace { - void color_to_stream(std::ostream&, Color::Enum) DOCTEST_BRANCH_ON_DISABLED({}, ;) -} // namespace - -namespace Color { - std::ostream& operator<<(std::ostream& s, Color::Enum code) { - color_to_stream(s, code); - return s; - } -} // namespace Color - -// clang-format off -const char* assertString(assertType::Enum at) { - DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4062) // enum 'x' in switch of enum 'y' is not handled - switch(at) { //!OCLINT missing default in switch statements - case assertType::DT_WARN : return "WARN"; - case assertType::DT_CHECK : return "CHECK"; - case assertType::DT_REQUIRE : return "REQUIRE"; - - case assertType::DT_WARN_FALSE : return "WARN_FALSE"; - case assertType::DT_CHECK_FALSE : return "CHECK_FALSE"; - case assertType::DT_REQUIRE_FALSE : return "REQUIRE_FALSE"; - - case assertType::DT_WARN_THROWS : return "WARN_THROWS"; - case assertType::DT_CHECK_THROWS : return "CHECK_THROWS"; - case assertType::DT_REQUIRE_THROWS : return "REQUIRE_THROWS"; - - case assertType::DT_WARN_THROWS_AS : return "WARN_THROWS_AS"; - case assertType::DT_CHECK_THROWS_AS : return "CHECK_THROWS_AS"; - case assertType::DT_REQUIRE_THROWS_AS : return "REQUIRE_THROWS_AS"; - - case assertType::DT_WARN_THROWS_WITH : return "WARN_THROWS_WITH"; - case assertType::DT_CHECK_THROWS_WITH : return "CHECK_THROWS_WITH"; - case assertType::DT_REQUIRE_THROWS_WITH : return "REQUIRE_THROWS_WITH"; - - case assertType::DT_WARN_NOTHROW : return "WARN_NOTHROW"; - case assertType::DT_CHECK_NOTHROW : return "CHECK_NOTHROW"; - case assertType::DT_REQUIRE_NOTHROW : return "REQUIRE_NOTHROW"; - - case assertType::DT_WARN_EQ : return "WARN_EQ"; - case assertType::DT_CHECK_EQ : return "CHECK_EQ"; - case assertType::DT_REQUIRE_EQ : return "REQUIRE_EQ"; - case assertType::DT_WARN_NE : return "WARN_NE"; - case assertType::DT_CHECK_NE : return "CHECK_NE"; - case assertType::DT_REQUIRE_NE : return "REQUIRE_NE"; - case assertType::DT_WARN_GT : return "WARN_GT"; - case assertType::DT_CHECK_GT : return "CHECK_GT"; - case assertType::DT_REQUIRE_GT : return "REQUIRE_GT"; - case assertType::DT_WARN_LT : return "WARN_LT"; - case assertType::DT_CHECK_LT : return "CHECK_LT"; - case assertType::DT_REQUIRE_LT : return "REQUIRE_LT"; - case assertType::DT_WARN_GE : return "WARN_GE"; - case assertType::DT_CHECK_GE : return "CHECK_GE"; - case assertType::DT_REQUIRE_GE : return "REQUIRE_GE"; - case assertType::DT_WARN_LE : return "WARN_LE"; - case assertType::DT_CHECK_LE : return "CHECK_LE"; - case assertType::DT_REQUIRE_LE : return "REQUIRE_LE"; - - case assertType::DT_WARN_UNARY : return "WARN_UNARY"; - case assertType::DT_CHECK_UNARY : return "CHECK_UNARY"; - case assertType::DT_REQUIRE_UNARY : return "REQUIRE_UNARY"; - case assertType::DT_WARN_UNARY_FALSE : return "WARN_UNARY_FALSE"; - case assertType::DT_CHECK_UNARY_FALSE : return "CHECK_UNARY_FALSE"; - case assertType::DT_REQUIRE_UNARY_FALSE : return "REQUIRE_UNARY_FALSE"; - } - DOCTEST_MSVC_SUPPRESS_WARNING_POP - return ""; -} -// clang-format on - -const char* failureString(assertType::Enum at) { - if(at & assertType::is_warn) //!OCLINT bitwise operator in conditional - return "WARNING"; - if(at & assertType::is_check) //!OCLINT bitwise operator in conditional - return "ERROR"; - if(at & assertType::is_require) //!OCLINT bitwise operator in conditional - return "FATAL ERROR"; - return ""; -} - -DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wnull-dereference") -DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wnull-dereference") -// depending on the current options this will remove the path of filenames -const char* skipPathFromFilename(const char* file) { - if(getContextOptions()->no_path_in_filenames) { - auto back = std::strrchr(file, '\\'); - auto forward = std::strrchr(file, '/'); - if(back || forward) { - if(back > forward) - forward = back; - return forward + 1; - } - } - return file; -} -DOCTEST_CLANG_SUPPRESS_WARNING_POP -DOCTEST_GCC_SUPPRESS_WARNING_POP - -DOCTEST_DEFINE_DEFAULTS(TestCaseData); -DOCTEST_DEFINE_COPIES(TestCaseData); - -DOCTEST_DEFINE_DEFAULTS(AssertData); - -DOCTEST_DEFINE_DEFAULTS(MessageData); - -SubcaseSignature::SubcaseSignature(const char* name, const char* file, int line) - : m_name(name) - , m_file(file) - , m_line(line) {} - -DOCTEST_DEFINE_DEFAULTS(SubcaseSignature); -DOCTEST_DEFINE_COPIES(SubcaseSignature); - -bool SubcaseSignature::operator<(const SubcaseSignature& other) const { - if(m_line != other.m_line) - return m_line < other.m_line; - if(std::strcmp(m_file, other.m_file) != 0) - return std::strcmp(m_file, other.m_file) < 0; - return std::strcmp(m_name, other.m_name) < 0; -} - -IContextScope::IContextScope() = default; -IContextScope::~IContextScope() = default; - -DOCTEST_DEFINE_DEFAULTS(ContextOptions); - -#ifdef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING -String toString(char* in) { return toString(static_cast(in)); } -String toString(const char* in) { return String("\"") + (in ? in : "{null string}") + "\""; } -#endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING -String toString(bool in) { return in ? "true" : "false"; } -String toString(float in) { return fpToString(in, 5) + "f"; } -String toString(double in) { return fpToString(in, 10); } -String toString(double long in) { return fpToString(in, 15); } - -#define DOCTEST_TO_STRING_OVERLOAD(type, fmt) \ - String toString(type in) { \ - char buf[64]; \ - std::sprintf(buf, fmt, in); \ - return buf; \ - } - -DOCTEST_TO_STRING_OVERLOAD(char, "%d") -DOCTEST_TO_STRING_OVERLOAD(char signed, "%d") -DOCTEST_TO_STRING_OVERLOAD(char unsigned, "%u") -DOCTEST_TO_STRING_OVERLOAD(int short, "%d") -DOCTEST_TO_STRING_OVERLOAD(int short unsigned, "%u") -DOCTEST_TO_STRING_OVERLOAD(int, "%d") -DOCTEST_TO_STRING_OVERLOAD(unsigned, "%u") -DOCTEST_TO_STRING_OVERLOAD(int long, "%ld") -DOCTEST_TO_STRING_OVERLOAD(int long unsigned, "%lu") -DOCTEST_TO_STRING_OVERLOAD(int long long, "%lld") -DOCTEST_TO_STRING_OVERLOAD(int long long unsigned, "%llu") - -String toString(std::nullptr_t) { return "NULL"; } - -Approx::Approx(double value) - : m_epsilon(static_cast(std::numeric_limits::epsilon()) * 100) - , m_scale(1.0) - , m_value(value) {} - -DOCTEST_DEFINE_COPIES(Approx); - -Approx Approx::operator()(double value) const { - Approx approx(value); - approx.epsilon(m_epsilon); - approx.scale(m_scale); - return approx; -} - -Approx& Approx::epsilon(double newEpsilon) { - m_epsilon = newEpsilon; - return *this; -} -Approx& Approx::scale(double newScale) { - m_scale = newScale; - return *this; -} - -bool operator==(double lhs, const Approx& rhs) { - // Thanks to Richard Harris for his help refining this formula - return std::fabs(lhs - rhs.m_value) < - rhs.m_epsilon * (rhs.m_scale + std::max(std::fabs(lhs), std::fabs(rhs.m_value))); -} -bool operator==(const Approx& lhs, double rhs) { return operator==(rhs, lhs); } -bool operator!=(double lhs, const Approx& rhs) { return !operator==(lhs, rhs); } -bool operator!=(const Approx& lhs, double rhs) { return !operator==(rhs, lhs); } -bool operator<=(double lhs, const Approx& rhs) { return lhs < rhs.m_value || lhs == rhs; } -bool operator<=(const Approx& lhs, double rhs) { return lhs.m_value < rhs || lhs == rhs; } -bool operator>=(double lhs, const Approx& rhs) { return lhs > rhs.m_value || lhs == rhs; } -bool operator>=(const Approx& lhs, double rhs) { return lhs.m_value > rhs || lhs == rhs; } -bool operator<(double lhs, const Approx& rhs) { return lhs < rhs.m_value && lhs != rhs; } -bool operator<(const Approx& lhs, double rhs) { return lhs.m_value < rhs && lhs != rhs; } -bool operator>(double lhs, const Approx& rhs) { return lhs > rhs.m_value && lhs != rhs; } -bool operator>(const Approx& lhs, double rhs) { return lhs.m_value > rhs && lhs != rhs; } - -String toString(const Approx& in) { - return String("Approx( ") + doctest::toString(in.m_value) + " )"; -} -const ContextOptions* getContextOptions() { return DOCTEST_BRANCH_ON_DISABLED(nullptr, g_cs); } - -} // namespace doctest - -#ifdef DOCTEST_CONFIG_DISABLE -namespace doctest { -Context::Context(int, const char* const*) {} -Context::~Context() = default; -void Context::applyCommandLine(int, const char* const*) {} -void Context::addFilter(const char*, const char*) {} -void Context::clearFilters() {} -void Context::setOption(const char*, int) {} -void Context::setOption(const char*, const char*) {} -bool Context::shouldExit() { return false; } -void Context::setAsDefaultForAssertsOutOfTestCases() {} -void Context::setAssertHandler(detail::assert_handler) {} -int Context::run() { return 0; } - -DOCTEST_DEFINE_DEFAULTS(CurrentTestCaseStats); - -DOCTEST_DEFINE_DEFAULTS(TestRunStats); - -IReporter::~IReporter() = default; - -int IReporter::get_num_active_contexts() { return 0; } -const IContextScope* const* IReporter::get_active_contexts() { return nullptr; } -int IReporter::get_num_stringified_contexts() { return 0; } -const String* IReporter::get_stringified_contexts() { return nullptr; } - -int registerReporter(const char*, int, IReporter*) { return 0; } - -} // namespace doctest -#else // DOCTEST_CONFIG_DISABLE - -#if !defined(DOCTEST_CONFIG_COLORS_NONE) -#if !defined(DOCTEST_CONFIG_COLORS_WINDOWS) && !defined(DOCTEST_CONFIG_COLORS_ANSI) -#ifdef DOCTEST_PLATFORM_WINDOWS -#define DOCTEST_CONFIG_COLORS_WINDOWS -#else // linux -#define DOCTEST_CONFIG_COLORS_ANSI -#endif // platform -#endif // DOCTEST_CONFIG_COLORS_WINDOWS && DOCTEST_CONFIG_COLORS_ANSI -#endif // DOCTEST_CONFIG_COLORS_NONE - -namespace doctest_detail_test_suite_ns { -// holds the current test suite -doctest::detail::TestSuite& getCurrentTestSuite() { - static doctest::detail::TestSuite data; - return data; -} -} // namespace doctest_detail_test_suite_ns - -namespace doctest { -namespace { - // the int (priority) is part of the key for automatic sorting - sadly one can register a - // reporter with a duplicate name and a different priority but hopefully that won't happen often :| - typedef std::map, reporterCreatorFunc> reporterMap; - reporterMap& getReporters() { - static reporterMap data; - return data; - } -} // namespace -namespace detail { -#define DOCTEST_ITERATE_THROUGH_REPORTERS(function, ...) \ - for(auto& curr_rep : g_cs->reporters_currently_used) \ - curr_rep->function(__VA_ARGS__) - - DOCTEST_DEFINE_DEFAULTS(TestFailureException); - DOCTEST_DEFINE_COPIES(TestFailureException); - bool checkIfShouldThrow(assertType::Enum at) { - if(at & assertType::is_require) //!OCLINT bitwise operator in conditional - return true; - - if((at & assertType::is_check) //!OCLINT bitwise operator in conditional - && getContextOptions()->abort_after > 0 && - (g_cs->numAssertsFailed + g_cs->numAssertsFailedCurrentTest_atomic) >= - getContextOptions()->abort_after) - return true; - - return false; - } - - void throwException() { -#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS - throw TestFailureException(); -#endif // DOCTEST_CONFIG_NO_EXCEPTIONS - } -} // namespace detail - -namespace { - using namespace detail; - // matching of a string against a wildcard mask (case sensitivity configurable) taken from - // https://www.codeproject.com/Articles/1088/Wildcard-string-compare-globbing - int wildcmp(const char* str, const char* wild, bool caseSensitive) { - const char* cp = nullptr; - const char* mp = nullptr; - - while((*str) && (*wild != '*')) { - if((caseSensitive ? (*wild != *str) : (tolower(*wild) != tolower(*str))) && - (*wild != '?')) { - return 0; - } - wild++; - str++; - } - - while(*str) { - if(*wild == '*') { - if(!*++wild) { - return 1; - } - mp = wild; - cp = str + 1; - } else if((caseSensitive ? (*wild == *str) : (tolower(*wild) == tolower(*str))) || - (*wild == '?')) { - wild++; - str++; - } else { - wild = mp; //!OCLINT parameter reassignment - str = cp++; //!OCLINT parameter reassignment - } - } - - while(*wild == '*') { - wild++; - } - return !*wild; - } - - //// C string hash function (djb2) - taken from http://www.cse.yorku.ca/~oz/hash.html - //unsigned hashStr(unsigned const char* str) { - // unsigned long hash = 5381; - // char c; - // while((c = *str++)) - // hash = ((hash << 5) + hash) + c; // hash * 33 + c - // return hash; - //} - - // checks if the name matches any of the filters (and can be configured what to do when empty) - bool matchesAny(const char* name, const std::vector& filters, bool matchEmpty, - bool caseSensitive) { - if(filters.empty() && matchEmpty) - return true; - for(auto& curr : filters) - if(wildcmp(name, curr.c_str(), caseSensitive)) - return true; - return false; - } -} // namespace -namespace detail { - - Subcase::Subcase(const char* name, const char* file, int line) - : m_signature(name, file, line) { - ContextState* s = g_cs; - - // if we have already completed it - if(s->subcasesPassed.count(m_signature) != 0) - return; - - // check subcase filters - if(s->subcasesCurrentLevel < s->subcase_filter_levels) { - if(!matchesAny(m_signature.m_name, s->filters[6], true, s->case_sensitive)) - return; - if(matchesAny(m_signature.m_name, s->filters[7], false, s->case_sensitive)) - return; - } - - // if a Subcase on the same level has already been entered - if(s->subcasesEnteredLevels.count(s->subcasesCurrentLevel) != 0) { - s->should_reenter = true; - return; - } - - s->subcasesEnteredLevels.insert(s->subcasesCurrentLevel++); - m_entered = true; - - DOCTEST_ITERATE_THROUGH_REPORTERS(subcase_start, m_signature); - } - - Subcase::~Subcase() { - if(m_entered) { - ContextState* s = g_cs; - - s->subcasesCurrentLevel--; - // only mark the subcase as passed if no subcases have been skipped - if(s->should_reenter == false) - s->subcasesPassed.insert(m_signature); - - DOCTEST_ITERATE_THROUGH_REPORTERS(subcase_end, DOCTEST_EMPTY); - } - } - - Subcase::operator bool() const { return m_entered; } - - Result::Result(bool passed, const String& decomposition) - : m_passed(passed) - , m_decomp(decomposition) {} - - DOCTEST_DEFINE_DEFAULTS(Result); - DOCTEST_DEFINE_COPIES(Result); - - ExpressionDecomposer::ExpressionDecomposer(assertType::Enum at) - : m_at(at) {} - - DOCTEST_DEFINE_DEFAULTS(ExpressionDecomposer); - - DOCTEST_DEFINE_DEFAULTS(TestSuite); - DOCTEST_DEFINE_COPIES(TestSuite); - - TestSuite& TestSuite::operator*(const char* in) { - m_test_suite = in; - // clear state - m_description = nullptr; - m_skip = false; - m_may_fail = false; - m_should_fail = false; - m_expected_failures = 0; - m_timeout = 0; - return *this; - } - - TestCase::TestCase(funcType test, const char* file, unsigned line, const TestSuite& test_suite, - const char* type, int template_id) { - m_file = file; - m_line = line; - m_name = nullptr; - m_test_suite = test_suite.m_test_suite; - m_description = test_suite.m_description; - m_skip = test_suite.m_skip; - m_may_fail = test_suite.m_may_fail; - m_should_fail = test_suite.m_should_fail; - m_expected_failures = test_suite.m_expected_failures; - m_timeout = test_suite.m_timeout; - - m_test = test; - m_type = type; - m_template_id = template_id; - } - - DOCTEST_DEFINE_DEFAULTS(TestCase); - - TestCase::TestCase(const TestCase& other) - : TestCaseData() { - *this = other; - } - - DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(26434) // hides a non-virtual function - DOCTEST_MSVC_SUPPRESS_WARNING(26437) // Do not slice - TestCase& TestCase::operator=(const TestCase& other) { - static_cast(*this) = static_cast(other); - - m_test = other.m_test; - m_type = other.m_type; - m_template_id = other.m_template_id; - m_full_name = other.m_full_name; - - if(m_template_id != -1) - m_name = m_full_name.c_str(); - return *this; - } - DOCTEST_MSVC_SUPPRESS_WARNING_POP - - TestCase& TestCase::operator*(const char* in) { - m_name = in; - // make a new name with an appended type for templated test case - if(m_template_id != -1) { - m_full_name = String(m_name) + m_type; - // redirect the name to point to the newly constructed full name - m_name = m_full_name.c_str(); - } - return *this; - } - - bool TestCase::operator<(const TestCase& other) const { - if(m_line != other.m_line) - return m_line < other.m_line; - const int file_cmp = std::strcmp(m_file, other.m_file); - if(file_cmp != 0) - return file_cmp < 0; - return m_template_id < other.m_template_id; - } -} // namespace detail -namespace { - using namespace detail; - // for sorting tests by file/line - bool fileOrderComparator(const TestCase* lhs, const TestCase* rhs) { -#if DOCTEST_MSVC - // this is needed because MSVC gives different case for drive letters - // for __FILE__ when evaluated in a header and a source file - const int res = stricmp(lhs->m_file, rhs->m_file); -#else // MSVC - const int res = std::strcmp(lhs->m_file, rhs->m_file); -#endif // MSVC - if(res != 0) - return res < 0; - if(lhs->m_line != rhs->m_line) - return lhs->m_line < rhs->m_line; - return lhs->m_template_id < rhs->m_template_id; - } - - // for sorting tests by suite/file/line - bool suiteOrderComparator(const TestCase* lhs, const TestCase* rhs) { - const int res = std::strcmp(lhs->m_test_suite, rhs->m_test_suite); - if(res != 0) - return res < 0; - return fileOrderComparator(lhs, rhs); - } - - // for sorting tests by name/suite/file/line - bool nameOrderComparator(const TestCase* lhs, const TestCase* rhs) { - const int res = std::strcmp(lhs->m_name, rhs->m_name); - if(res != 0) - return res < 0; - return suiteOrderComparator(lhs, rhs); - } - - // all the registered tests - std::set& getRegisteredTests() { - static std::set data; - return data; - } - -#ifdef DOCTEST_CONFIG_COLORS_WINDOWS - HANDLE g_stdoutHandle; - WORD g_origFgAttrs; - WORD g_origBgAttrs; - bool g_attrsInitted = false; - - int colors_init() { - if(!g_attrsInitted) { - g_stdoutHandle = GetStdHandle(STD_OUTPUT_HANDLE); - g_attrsInitted = true; - CONSOLE_SCREEN_BUFFER_INFO csbiInfo; - GetConsoleScreenBufferInfo(g_stdoutHandle, &csbiInfo); - g_origFgAttrs = csbiInfo.wAttributes & ~(BACKGROUND_GREEN | BACKGROUND_RED | - BACKGROUND_BLUE | BACKGROUND_INTENSITY); - g_origBgAttrs = csbiInfo.wAttributes & ~(FOREGROUND_GREEN | FOREGROUND_RED | - FOREGROUND_BLUE | FOREGROUND_INTENSITY); - } - return 0; - } - - int dumy_init_console_colors = colors_init(); -#endif // DOCTEST_CONFIG_COLORS_WINDOWS - - DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations") - void color_to_stream(std::ostream& s, Color::Enum code) { - ((void)s); // for DOCTEST_CONFIG_COLORS_NONE or DOCTEST_CONFIG_COLORS_WINDOWS - ((void)code); // for DOCTEST_CONFIG_COLORS_NONE -#ifdef DOCTEST_CONFIG_COLORS_ANSI - if(g_no_colors || - (isatty(STDOUT_FILENO) == false && getContextOptions()->force_colors == false)) - return; - - auto col = ""; - // clang-format off - switch(code) { //!OCLINT missing break in switch statement / unnecessary default statement in covered switch statement - case Color::Red: col = "[0;31m"; break; - case Color::Green: col = "[0;32m"; break; - case Color::Blue: col = "[0;34m"; break; - case Color::Cyan: col = "[0;36m"; break; - case Color::Yellow: col = "[0;33m"; break; - case Color::Grey: col = "[1;30m"; break; - case Color::LightGrey: col = "[0;37m"; break; - case Color::BrightRed: col = "[1;31m"; break; - case Color::BrightGreen: col = "[1;32m"; break; - case Color::BrightWhite: col = "[1;37m"; break; - case Color::Bright: // invalid - case Color::None: - case Color::White: - default: col = "[0m"; - } - // clang-format on - s << "\033" << col; -#endif // DOCTEST_CONFIG_COLORS_ANSI - -#ifdef DOCTEST_CONFIG_COLORS_WINDOWS - if(g_no_colors || - (isatty(fileno(stdout)) == false && getContextOptions()->force_colors == false)) - return; - -#define DOCTEST_SET_ATTR(x) SetConsoleTextAttribute(g_stdoutHandle, x | g_origBgAttrs) - - // clang-format off - switch (code) { - case Color::White: DOCTEST_SET_ATTR(FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE); break; - case Color::Red: DOCTEST_SET_ATTR(FOREGROUND_RED); break; - case Color::Green: DOCTEST_SET_ATTR(FOREGROUND_GREEN); break; - case Color::Blue: DOCTEST_SET_ATTR(FOREGROUND_BLUE); break; - case Color::Cyan: DOCTEST_SET_ATTR(FOREGROUND_BLUE | FOREGROUND_GREEN); break; - case Color::Yellow: DOCTEST_SET_ATTR(FOREGROUND_RED | FOREGROUND_GREEN); break; - case Color::Grey: DOCTEST_SET_ATTR(0); break; - case Color::LightGrey: DOCTEST_SET_ATTR(FOREGROUND_INTENSITY); break; - case Color::BrightRed: DOCTEST_SET_ATTR(FOREGROUND_INTENSITY | FOREGROUND_RED); break; - case Color::BrightGreen: DOCTEST_SET_ATTR(FOREGROUND_INTENSITY | FOREGROUND_GREEN); break; - case Color::BrightWhite: DOCTEST_SET_ATTR(FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE); break; - case Color::None: - case Color::Bright: // invalid - default: DOCTEST_SET_ATTR(g_origFgAttrs); - } - // clang-format on -#endif // DOCTEST_CONFIG_COLORS_WINDOWS - } - DOCTEST_CLANG_SUPPRESS_WARNING_POP - - std::vector& getExceptionTranslators() { - static std::vector data; - return data; - } - - String translateActiveException() { -#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS - String res; - auto& translators = getExceptionTranslators(); - for(auto& curr : translators) - if(curr->translate(res)) - return res; - // clang-format off - try { - throw; - } catch(std::exception& ex) { - return ex.what(); - } catch(std::string& msg) { - return msg.c_str(); - } catch(const char* msg) { - return msg; - } catch(...) { - return "unknown exception"; - } -// clang-format on -#else // DOCTEST_CONFIG_NO_EXCEPTIONS - return ""; -#endif // DOCTEST_CONFIG_NO_EXCEPTIONS - } -} // namespace - -namespace detail { - // used by the macros for registering tests - int regTest(const TestCase& tc) { - getRegisteredTests().insert(tc); - return 0; - } - - // sets the current test suite - int setTestSuite(const TestSuite& ts) { - doctest_detail_test_suite_ns::getCurrentTestSuite() = ts; - return 0; - } - -#ifdef DOCTEST_PLATFORM_MAC - // The following function is taken directly from the following technical note: - // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html - // Returns true if the current process is being debugged (either - // running under the debugger or has a debugger attached post facto). - bool isDebuggerActive() { - int mib[4]; - kinfo_proc info; - size_t size; - // Initialize the flags so that, if sysctl fails for some bizarre - // reason, we get a predictable result. - info.kp_proc.p_flag = 0; - // Initialize mib, which tells sysctl the info we want, in this case - // we're looking for information about a specific process ID. - mib[0] = CTL_KERN; - mib[1] = KERN_PROC; - mib[2] = KERN_PROC_PID; - mib[3] = getpid(); - // Call sysctl. - size = sizeof(info); - if(sysctl(mib, DOCTEST_COUNTOF(mib), &info, &size, 0, 0) != 0) { - std::cerr << "\nCall to sysctl failed - unable to determine if debugger is active **\n"; - return false; - } - // We're being debugged if the P_TRACED flag is set. - return ((info.kp_proc.p_flag & P_TRACED) != 0); - } -#elif DOCTEST_MSVC || defined(__MINGW32__) - bool isDebuggerActive() { return ::IsDebuggerPresent() != 0; } -#else - bool isDebuggerActive() { return false; } -#endif // Platform - - void registerExceptionTranslatorImpl(const IExceptionTranslator* et) { - if(std::find(getExceptionTranslators().begin(), getExceptionTranslators().end(), et) == - getExceptionTranslators().end()) - getExceptionTranslators().push_back(et); - } - -#ifdef DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING - void toStream(std::ostream* s, char* in) { *s << in; } - void toStream(std::ostream* s, const char* in) { *s << in; } -#endif // DOCTEST_CONFIG_TREAT_CHAR_STAR_AS_STRING - void toStream(std::ostream* s, bool in) { *s << std::boolalpha << in << std::noboolalpha; } - void toStream(std::ostream* s, float in) { *s << in; } - void toStream(std::ostream* s, double in) { *s << in; } - void toStream(std::ostream* s, double long in) { *s << in; } - - void toStream(std::ostream* s, char in) { *s << in; } - void toStream(std::ostream* s, char signed in) { *s << in; } - void toStream(std::ostream* s, char unsigned in) { *s << in; } - void toStream(std::ostream* s, int short in) { *s << in; } - void toStream(std::ostream* s, int short unsigned in) { *s << in; } - void toStream(std::ostream* s, int in) { *s << in; } - void toStream(std::ostream* s, int unsigned in) { *s << in; } - void toStream(std::ostream* s, int long in) { *s << in; } - void toStream(std::ostream* s, int long unsigned in) { *s << in; } - void toStream(std::ostream* s, int long long in) { *s << in; } - void toStream(std::ostream* s, int long long unsigned in) { *s << in; } - - DOCTEST_THREAD_LOCAL std::vector g_infoContexts; // for logging with INFO() - - ContextBuilder::ICapture::ICapture() = default; - ContextBuilder::ICapture::~ICapture() = default; - - ContextBuilder::Chunk::Chunk() = default; - ContextBuilder::Chunk::~Chunk() = default; - - ContextBuilder::Node::Node() = default; - ContextBuilder::Node::~Node() = default; - - // steal the contents of the other - acting as a move constructor... - ContextBuilder::ContextBuilder(ContextBuilder& other) - : numCaptures(other.numCaptures) - , head(other.head) - , tail(other.tail) { - other.numCaptures = 0; - other.head = nullptr; - other.tail = nullptr; - memcpy(stackChunks, other.stackChunks, - unsigned(int(sizeof(Chunk)) * DOCTEST_CONFIG_NUM_CAPTURES_ON_STACK)); - } - - DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wcast-align") - void ContextBuilder::stringify(std::ostream* s) const { - int curr = 0; - // iterate over small buffer - while(curr < numCaptures && curr < DOCTEST_CONFIG_NUM_CAPTURES_ON_STACK) - reinterpret_cast(stackChunks[curr++].buf)->toStream(s); - // iterate over list - auto curr_elem = head; - while(curr < numCaptures) { - reinterpret_cast(curr_elem->chunk.buf)->toStream(s); - curr_elem = curr_elem->next; - ++curr; - } - } - DOCTEST_GCC_SUPPRESS_WARNING_POP - - ContextBuilder::ContextBuilder() = default; - - ContextBuilder::~ContextBuilder() { - // free the linked list - the ones on the stack are left as-is - // no destructors are called at all - there is no need - while(head) { - auto next = head->next; - delete head; - head = next; - } - } - - ContextScope::ContextScope(ContextBuilder& temp) - : contextBuilder(temp) { - g_infoContexts.push_back(this); - } - - DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4996) // std::uncaught_exception is deprecated in C++17 - DOCTEST_GCC_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations") - DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations") - ContextScope::~ContextScope() { - if(std::uncaught_exception()) { - std::ostringstream s; - this->stringify(&s); - g_cs->stringifiedContexts.push_back(s.str().c_str()); - } - g_infoContexts.pop_back(); - } - DOCTEST_CLANG_SUPPRESS_WARNING_POP - DOCTEST_GCC_SUPPRESS_WARNING_POP - DOCTEST_MSVC_SUPPRESS_WARNING_POP - - void ContextScope::stringify(std::ostream* s) const { contextBuilder.stringify(s); } -} // namespace detail -namespace { - using namespace detail; - - std::ostream& file_line_to_stream(std::ostream& s, const char* file, int line, - const char* tail = "") { - const auto opt = getContextOptions(); - s << Color::LightGrey << skipPathFromFilename(file) << (opt->gnu_file_line ? ":" : "(") - << (opt->no_line_numbers ? 0 : line) // 0 or the real num depending on the option - << (opt->gnu_file_line ? ":" : "):") << tail; - return s; - } - -#if !defined(DOCTEST_CONFIG_POSIX_SIGNALS) && !defined(DOCTEST_CONFIG_WINDOWS_SEH) - struct FatalConditionHandler - { - void reset() {} - }; -#else // DOCTEST_CONFIG_POSIX_SIGNALS || DOCTEST_CONFIG_WINDOWS_SEH - - void reportFatal(const std::string&); - -#ifdef DOCTEST_PLATFORM_WINDOWS - - struct SignalDefs - { - DWORD id; - const char* name; - }; - // There is no 1-1 mapping between signals and windows exceptions. - // Windows can easily distinguish between SO and SigSegV, - // but SigInt, SigTerm, etc are handled differently. - SignalDefs signalDefs[] = { - {EXCEPTION_ILLEGAL_INSTRUCTION, "SIGILL - Illegal instruction signal"}, - {EXCEPTION_STACK_OVERFLOW, "SIGSEGV - Stack overflow"}, - {EXCEPTION_ACCESS_VIOLATION, "SIGSEGV - Segmentation violation signal"}, - {EXCEPTION_INT_DIVIDE_BY_ZERO, "Divide by zero error"}, - }; - - struct FatalConditionHandler - { - static LONG CALLBACK handleVectoredException(PEXCEPTION_POINTERS ExceptionInfo) { - for(size_t i = 0; i < DOCTEST_COUNTOF(signalDefs); ++i) { - if(ExceptionInfo->ExceptionRecord->ExceptionCode == signalDefs[i].id) { - reportFatal(signalDefs[i].name); - } - } - // If its not an exception we care about, pass it along. - // This stops us from eating debugger breaks etc. - return EXCEPTION_CONTINUE_SEARCH; - } - - FatalConditionHandler() { - isSet = true; - // 32k seems enough for doctest to handle stack overflow, - // but the value was found experimentally, so there is no strong guarantee - guaranteeSize = 32 * 1024; - exceptionHandlerHandle = nullptr; - // Register as first handler in current chain - exceptionHandlerHandle = AddVectoredExceptionHandler(1, handleVectoredException); - // Pass in guarantee size to be filled - SetThreadStackGuarantee(&guaranteeSize); - } - - static void reset() { - if(isSet) { - // Unregister handler and restore the old guarantee - RemoveVectoredExceptionHandler(exceptionHandlerHandle); - SetThreadStackGuarantee(&guaranteeSize); - exceptionHandlerHandle = nullptr; - isSet = false; - } - } - - ~FatalConditionHandler() { reset(); } - - private: - static bool isSet; - static ULONG guaranteeSize; - static PVOID exceptionHandlerHandle; - }; - - bool FatalConditionHandler::isSet = false; - ULONG FatalConditionHandler::guaranteeSize = 0; - PVOID FatalConditionHandler::exceptionHandlerHandle = nullptr; - -#else // DOCTEST_PLATFORM_WINDOWS - - struct SignalDefs - { - int id; - const char* name; - }; - SignalDefs signalDefs[] = {{SIGINT, "SIGINT - Terminal interrupt signal"}, - {SIGILL, "SIGILL - Illegal instruction signal"}, - {SIGFPE, "SIGFPE - Floating point error signal"}, - {SIGSEGV, "SIGSEGV - Segmentation violation signal"}, - {SIGTERM, "SIGTERM - Termination request signal"}, - {SIGABRT, "SIGABRT - Abort (abnormal termination) signal"}}; - - struct FatalConditionHandler - { - static bool isSet; - static struct sigaction oldSigActions[DOCTEST_COUNTOF(signalDefs)]; - static stack_t oldSigStack; - static char altStackMem[4 * SIGSTKSZ]; - - static void handleSignal(int sig) { - const char* name = ""; - for(std::size_t i = 0; i < DOCTEST_COUNTOF(signalDefs); ++i) { - SignalDefs& def = signalDefs[i]; - if(sig == def.id) { - name = def.name; - break; - } - } - reset(); - reportFatal(name); - raise(sig); - } - - FatalConditionHandler() { - isSet = true; - stack_t sigStack; - sigStack.ss_sp = altStackMem; - sigStack.ss_size = sizeof(altStackMem); - sigStack.ss_flags = 0; - sigaltstack(&sigStack, &oldSigStack); - struct sigaction sa = {}; - sa.sa_handler = handleSignal; // NOLINT - sa.sa_flags = SA_ONSTACK; - for(std::size_t i = 0; i < DOCTEST_COUNTOF(signalDefs); ++i) { - sigaction(signalDefs[i].id, &sa, &oldSigActions[i]); - } - } - - ~FatalConditionHandler() { reset(); } - static void reset() { - if(isSet) { - // Set signals back to previous values -- hopefully nobody overwrote them in the meantime - for(std::size_t i = 0; i < DOCTEST_COUNTOF(signalDefs); ++i) { - sigaction(signalDefs[i].id, &oldSigActions[i], nullptr); - } - // Return the old stack - sigaltstack(&oldSigStack, nullptr); - isSet = false; - } - } - }; - - bool FatalConditionHandler::isSet = false; - struct sigaction FatalConditionHandler::oldSigActions[DOCTEST_COUNTOF(signalDefs)] = {}; - stack_t FatalConditionHandler::oldSigStack = {}; - char FatalConditionHandler::altStackMem[] = {}; - -#endif // DOCTEST_PLATFORM_WINDOWS -#endif // DOCTEST_CONFIG_POSIX_SIGNALS || DOCTEST_CONFIG_WINDOWS_SEH - -} // namespace - -namespace { - using namespace detail; - -#ifdef DOCTEST_PLATFORM_WINDOWS -#define DOCTEST_OUTPUT_DEBUG_STRING(text) ::OutputDebugStringA(text) -#else - // TODO: integration with XCode and other IDEs -#define DOCTEST_OUTPUT_DEBUG_STRING(text) -#endif // Platform - - void addAssert(assertType::Enum at) { - if((at & assertType::is_warn) == 0) //!OCLINT bitwise operator in conditional - g_cs->numAssertsCurrentTest_atomic++; - } - - void addFailedAssert(assertType::Enum at) { - if((at & assertType::is_warn) == 0) //!OCLINT bitwise operator in conditional - g_cs->numAssertsFailedCurrentTest_atomic++; - } - -#if defined(DOCTEST_CONFIG_POSIX_SIGNALS) || defined(DOCTEST_CONFIG_WINDOWS_SEH) - void reportFatal(const std::string& message) { - g_cs->failure_flags |= TestCaseFailureReason::Crash; - - DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_exception, {message.c_str(), true}); - - while(g_cs->subcasesCurrentLevel--) - DOCTEST_ITERATE_THROUGH_REPORTERS(subcase_end, DOCTEST_EMPTY); - - g_cs->finalizeTestCaseData(); - - DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_end, *g_cs); - - DOCTEST_ITERATE_THROUGH_REPORTERS(test_run_end, *g_cs); - } -#endif // DOCTEST_CONFIG_POSIX_SIGNALS || DOCTEST_CONFIG_WINDOWS_SEH -} // namespace -namespace detail { - - ResultBuilder::ResultBuilder(assertType::Enum at, const char* file, int line, const char* expr, - const char* exception_type) { - m_test_case = g_cs->currentTest; - m_at = at; - m_file = file; - m_line = line; - m_expr = expr; - m_failed = true; - m_threw = false; - m_threw_as = false; - m_exception_type = exception_type; -#if DOCTEST_MSVC - if(m_expr[0] == ' ') // this happens when variadic macros are disabled under MSVC - ++m_expr; -#endif // MSVC - } - - DOCTEST_DEFINE_DEFAULTS(ResultBuilder); - - void ResultBuilder::setResult(const Result& res) { - m_decomp = res.m_decomp; - m_failed = !res.m_passed; - } - - void ResultBuilder::translateException() { - m_threw = true; - m_exception = translateActiveException(); - } - - bool ResultBuilder::log() { - if(m_at & assertType::is_throws) { //!OCLINT bitwise operator in conditional - m_failed = !m_threw; - } else if(m_at & assertType::is_throws_as) { //!OCLINT bitwise operator in conditional - m_failed = !m_threw_as; - } else if(m_at & assertType::is_throws_with) { //!OCLINT bitwise operator in conditional - m_failed = m_exception != m_exception_type; - } else if(m_at & assertType::is_nothrow) { //!OCLINT bitwise operator in conditional - m_failed = m_threw; - } - - if(m_exception.size()) - m_exception = String("\"") + m_exception + "\""; - - if(is_running_in_test) { - addAssert(m_at); - DOCTEST_ITERATE_THROUGH_REPORTERS(log_assert, *this); - - if(m_failed) - addFailedAssert(m_at); - } else if(m_failed) { - failed_out_of_a_testing_context(*this); - } - - return m_failed && isDebuggerActive() && - !getContextOptions()->no_breaks; // break into debugger - } - - void ResultBuilder::react() const { - if(m_failed && checkIfShouldThrow(m_at)) - throwException(); - } - - void failed_out_of_a_testing_context(const AssertData& ad) { - if(g_cs->ah) - g_cs->ah(ad); - else - std::abort(); - } - - void decomp_assert(assertType::Enum at, const char* file, int line, const char* expr, - Result result) { - bool failed = !result.m_passed; - - // ################################################################################### - // IF THE DEBUGGER BREAKS HERE - GO 1 LEVEL UP IN THE CALLSTACK FOR THE FAILING ASSERT - // THIS IS THE EFFECT OF HAVING 'DOCTEST_CONFIG_SUPER_FAST_ASSERTS' DEFINED - // ################################################################################### - DOCTEST_ASSERT_OUT_OF_TESTS(result.m_decomp); - DOCTEST_ASSERT_IN_TESTS(result.m_decomp); - } - - MessageBuilder::MessageBuilder(const char* file, int line, assertType::Enum severity) { - m_stream = getTlsOss(); - m_file = file; - m_line = line; - m_severity = severity; - } - - IExceptionTranslator::IExceptionTranslator() = default; - IExceptionTranslator::~IExceptionTranslator() = default; - - bool MessageBuilder::log() { - m_string = getTlsOssResult(); - DOCTEST_ITERATE_THROUGH_REPORTERS(log_message, *this); - - const bool isWarn = m_severity & assertType::is_warn; - - // warn is just a message in this context so we dont treat it as an assert - if(!isWarn) { - addAssert(m_severity); - addFailedAssert(m_severity); - } - - return isDebuggerActive() && !getContextOptions()->no_breaks && !isWarn; // break - } - - void MessageBuilder::react() { - if(m_severity & assertType::is_require) //!OCLINT bitwise operator in conditional - throwException(); - } - - MessageBuilder::~MessageBuilder() = default; -} // namespace detail -namespace { - using namespace detail; - - template - [[noreturn]] void throw_exception(Ex const& e) { -#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS - throw e; -#else // DOCTEST_CONFIG_NO_EXCEPTIONS - std::cerr << "doctest will terminate because it needed to throw an exception.\n" - << "The message was: " << e.what() << '\n'; - std::terminate(); -#endif // DOCTEST_CONFIG_NO_EXCEPTIONS - } - -#define DOCTEST_INTERNAL_ERROR(msg) \ - throw_exception(std::logic_error( \ - __FILE__ ":" DOCTEST_TOSTR(__LINE__) ": Internal doctest error: " msg)) - - // clang-format off - -// ================================================================================================= -// The following code has been taken verbatim from Catch2/include/internal/catch_xmlwriter.h/cpp -// This is done so cherry-picking bug fixes is trivial - even the style/formatting is untouched. -// ================================================================================================= - - class XmlEncode { - public: - enum ForWhat { ForTextNodes, ForAttributes }; - - XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes ); - - void encodeTo( std::ostream& os ) const; - - friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ); - - private: - std::string m_str; - ForWhat m_forWhat; - }; - - class XmlWriter { - public: - - class ScopedElement { - public: - ScopedElement( XmlWriter* writer ); - - ScopedElement( ScopedElement&& other ) noexcept; - ScopedElement& operator=( ScopedElement&& other ) noexcept; - - ~ScopedElement(); - - ScopedElement& writeText( std::string const& text, bool indent = true ); - - template - ScopedElement& writeAttribute( std::string const& name, T const& attribute ) { - m_writer->writeAttribute( name, attribute ); - return *this; - } - - private: - mutable XmlWriter* m_writer = nullptr; - }; - - XmlWriter( std::ostream& os = std::cout ); - ~XmlWriter(); - - XmlWriter( XmlWriter const& ) = delete; - XmlWriter& operator=( XmlWriter const& ) = delete; - - XmlWriter& startElement( std::string const& name ); - - ScopedElement scopedElement( std::string const& name ); - - XmlWriter& endElement(); - - XmlWriter& writeAttribute( std::string const& name, std::string const& attribute ); - - XmlWriter& writeAttribute( std::string const& name, const char* attribute ); - - XmlWriter& writeAttribute( std::string const& name, bool attribute ); - - template - XmlWriter& writeAttribute( std::string const& name, T const& attribute ) { - std::stringstream rss; - rss << attribute; - return writeAttribute( name, rss.str() ); - } - - XmlWriter& writeText( std::string const& text, bool indent = true ); - - //XmlWriter& writeComment( std::string const& text ); - - //void writeStylesheetRef( std::string const& url ); - - //XmlWriter& writeBlankLine(); - - void ensureTagClosed(); - - private: - - void writeDeclaration(); - - void newlineIfNecessary(); - - bool m_tagIsOpen = false; - bool m_needsNewline = false; - std::vector m_tags; - std::string m_indent; - std::ostream& m_os; - }; - -// ================================================================================================= -// The following code has been taken verbatim from Catch2/include/internal/catch_xmlwriter.h/cpp -// This is done so cherry-picking bug fixes is trivial - even the style/formatting is untouched. -// ================================================================================================= - -using uchar = unsigned char; - -namespace { - - size_t trailingBytes(unsigned char c) { - if ((c & 0xE0) == 0xC0) { - return 2; - } - if ((c & 0xF0) == 0xE0) { - return 3; - } - if ((c & 0xF8) == 0xF0) { - return 4; - } - DOCTEST_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered"); - } - - uint32_t headerValue(unsigned char c) { - if ((c & 0xE0) == 0xC0) { - return c & 0x1F; - } - if ((c & 0xF0) == 0xE0) { - return c & 0x0F; - } - if ((c & 0xF8) == 0xF0) { - return c & 0x07; - } - DOCTEST_INTERNAL_ERROR("Invalid multibyte utf-8 start byte encountered"); - } - - void hexEscapeChar(std::ostream& os, unsigned char c) { - std::ios_base::fmtflags f(os.flags()); - os << "\\x" - << std::uppercase << std::hex << std::setfill('0') << std::setw(2) - << static_cast(c); - os.flags(f); - } - -} // anonymous namespace - - XmlEncode::XmlEncode( std::string const& str, ForWhat forWhat ) - : m_str( str ), - m_forWhat( forWhat ) - {} - - void XmlEncode::encodeTo( std::ostream& os ) const { - // Apostrophe escaping not necessary if we always use " to write attributes - // (see: http://www.w3.org/TR/xml/#syntax) - - for( std::size_t idx = 0; idx < m_str.size(); ++ idx ) { - uchar c = m_str[idx]; - switch (c) { - case '<': os << "<"; break; - case '&': os << "&"; break; - - case '>': - // See: http://www.w3.org/TR/xml/#syntax - if (idx > 2 && m_str[idx - 1] == ']' && m_str[idx - 2] == ']') - os << ">"; - else - os << c; - break; - - case '\"': - if (m_forWhat == ForAttributes) - os << """; - else - os << c; - break; - - default: - // Check for control characters and invalid utf-8 - - // Escape control characters in standard ascii - // see http://stackoverflow.com/questions/404107/why-are-control-characters-illegal-in-xml-1-0 - if (c < 0x09 || (c > 0x0D && c < 0x20) || c == 0x7F) { - hexEscapeChar(os, c); - break; - } - - // Plain ASCII: Write it to stream - if (c < 0x7F) { - os << c; - break; - } - - // UTF-8 territory - // Check if the encoding is valid and if it is not, hex escape bytes. - // Important: We do not check the exact decoded values for validity, only the encoding format - // First check that this bytes is a valid lead byte: - // This means that it is not encoded as 1111 1XXX - // Or as 10XX XXXX - if (c < 0xC0 || - c >= 0xF8) { - hexEscapeChar(os, c); - break; - } - - auto encBytes = trailingBytes(c); - // Are there enough bytes left to avoid accessing out-of-bounds memory? - if (idx + encBytes - 1 >= m_str.size()) { - hexEscapeChar(os, c); - break; - } - // The header is valid, check data - // The next encBytes bytes must together be a valid utf-8 - // This means: bitpattern 10XX XXXX and the extracted value is sane (ish) - bool valid = true; - uint32_t value = headerValue(c); - for (std::size_t n = 1; n < encBytes; ++n) { - uchar nc = m_str[idx + n]; - valid &= ((nc & 0xC0) == 0x80); - value = (value << 6) | (nc & 0x3F); - } - - if ( - // Wrong bit pattern of following bytes - (!valid) || - // Overlong encodings - (value < 0x80) || - ( value < 0x800 && encBytes > 2) || // removed "0x80 <= value &&" because redundant - (0x800 < value && value < 0x10000 && encBytes > 3) || - // Encoded value out of range - (value >= 0x110000) - ) { - hexEscapeChar(os, c); - break; - } - - // If we got here, this is in fact a valid(ish) utf-8 sequence - for (std::size_t n = 0; n < encBytes; ++n) { - os << m_str[idx + n]; - } - idx += encBytes - 1; - break; - } - } - } - - std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) { - xmlEncode.encodeTo( os ); - return os; - } - - XmlWriter::ScopedElement::ScopedElement( XmlWriter* writer ) - : m_writer( writer ) - {} - - XmlWriter::ScopedElement::ScopedElement( ScopedElement&& other ) noexcept - : m_writer( other.m_writer ){ - other.m_writer = nullptr; - } - XmlWriter::ScopedElement& XmlWriter::ScopedElement::operator=( ScopedElement&& other ) noexcept { - if ( m_writer ) { - m_writer->endElement(); - } - m_writer = other.m_writer; - other.m_writer = nullptr; - return *this; - } - - - XmlWriter::ScopedElement::~ScopedElement() { - if( m_writer ) - m_writer->endElement(); - } - - XmlWriter::ScopedElement& XmlWriter::ScopedElement::writeText( std::string const& text, bool indent ) { - m_writer->writeText( text, indent ); - return *this; - } - - XmlWriter::XmlWriter( std::ostream& os ) : m_os( os ) - { - writeDeclaration(); - } - - XmlWriter::~XmlWriter() { - while( !m_tags.empty() ) - endElement(); - } - - XmlWriter& XmlWriter::startElement( std::string const& name ) { - ensureTagClosed(); - newlineIfNecessary(); - m_os << m_indent << '<' << name; - m_tags.push_back( name ); - m_indent += " "; - m_tagIsOpen = true; - return *this; - } - - XmlWriter::ScopedElement XmlWriter::scopedElement( std::string const& name ) { - ScopedElement scoped( this ); - startElement( name ); - return scoped; - } - - XmlWriter& XmlWriter::endElement() { - newlineIfNecessary(); - m_indent = m_indent.substr( 0, m_indent.size()-2 ); - if( m_tagIsOpen ) { - m_os << "/>"; - m_tagIsOpen = false; - } - else { - m_os << m_indent << ""; - } - m_os << std::endl; - m_tags.pop_back(); - return *this; - } - - XmlWriter& XmlWriter::writeAttribute( std::string const& name, std::string const& attribute ) { - if( !name.empty() && !attribute.empty() ) - m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"'; - return *this; - } - - XmlWriter& XmlWriter::writeAttribute( std::string const& name, const char* attribute ) { - if( !name.empty() && attribute && attribute[0] != '\0' ) - m_os << ' ' << name << "=\"" << XmlEncode( attribute, XmlEncode::ForAttributes ) << '"'; - return *this; - } - - XmlWriter& XmlWriter::writeAttribute( std::string const& name, bool attribute ) { - m_os << ' ' << name << "=\"" << ( attribute ? "true" : "false" ) << '"'; - return *this; - } - - XmlWriter& XmlWriter::writeText( std::string const& text, bool indent ) { - if( !text.empty() ){ - bool tagWasOpen = m_tagIsOpen; - ensureTagClosed(); - if( tagWasOpen && indent ) - m_os << m_indent; - m_os << XmlEncode( text ); - m_needsNewline = true; - } - return *this; - } - - //XmlWriter& XmlWriter::writeComment( std::string const& text ) { - // ensureTagClosed(); - // m_os << m_indent << ""; - // m_needsNewline = true; - // return *this; - //} - - //void XmlWriter::writeStylesheetRef( std::string const& url ) { - // m_os << "\n"; - //} - - //XmlWriter& XmlWriter::writeBlankLine() { - // ensureTagClosed(); - // m_os << '\n'; - // return *this; - //} - - void XmlWriter::ensureTagClosed() { - if( m_tagIsOpen ) { - m_os << ">" << std::endl; - m_tagIsOpen = false; - } - } - - void XmlWriter::writeDeclaration() { - m_os << "\n"; - } - - void XmlWriter::newlineIfNecessary() { - if( m_needsNewline ) { - m_os << std::endl; - m_needsNewline = false; - } - } - -// ================================================================================================= -// End of copy-pasted code from Catch -// ================================================================================================= - - // clang-format on - - struct XmlReporter : public IReporter - { - XmlWriter xml; - std::mutex mutex; - - // caching pointers/references to objects of these types - safe to do - const ContextOptions& opt; - const TestCaseData* tc = nullptr; - - XmlReporter(const ContextOptions& co) - : xml(*co.cout) - , opt(co) {} - - void log_contexts() { - int num_contexts = get_num_active_contexts(); - if(num_contexts) { - auto contexts = get_active_contexts(); - std::stringstream ss; - for(int i = 0; i < num_contexts; ++i) { - contexts[i]->stringify(&ss); - xml.scopedElement("Info").writeText(ss.str()); - ss.str(""); - } - } - } - - unsigned line(unsigned l) const { return opt.no_line_numbers ? 0 : l; } - - void test_case_start_impl(const TestCaseData& in) { - bool open_ts_tag = false; - if(tc != nullptr) { // we have already opened a test suite - if(strcmp(tc->m_test_suite, in.m_test_suite) != 0) { - xml.endElement(); - open_ts_tag = true; - } - } - else { - open_ts_tag = true; // first test case ==> first test suite - } - - if(open_ts_tag) { - xml.startElement("TestSuite"); - xml.writeAttribute("name", in.m_test_suite); - } - - tc = ∈ - xml.startElement("TestCase") - .writeAttribute("name", in.m_name) - .writeAttribute("filename", skipPathFromFilename(in.m_file)) - .writeAttribute("line", line(in.m_line)) - .writeAttribute("description", in.m_description); - - if(Approx(in.m_timeout) != 0) - xml.writeAttribute("timeout", in.m_timeout); - if(in.m_may_fail) - xml.writeAttribute("may_fail", true); - if(in.m_should_fail) - xml.writeAttribute("should_fail", true); - } - - // ========================================================================================= - // WHAT FOLLOWS ARE OVERRIDES OF THE VIRTUAL METHODS OF THE REPORTER INTERFACE - // ========================================================================================= - - void report_query(const QueryData& in) override { - test_run_start(); - if(opt.list_reporters) { - for(auto& curr : getReporters()) - xml.scopedElement("Reporter") - .writeAttribute("priority", curr.first.first) - .writeAttribute("name", curr.first.second); - } else if(opt.count || opt.list_test_cases) { - for(unsigned i = 0; i < in.num_data; ++i) - xml.scopedElement("TestCase").writeAttribute("name", in.data[i]); - xml.scopedElement("OverallResultsTestCases") - .writeAttribute("unskipped", in.run_stats->numTestCasesPassingFilters); - } else if(opt.list_test_suites) { - for(unsigned i = 0; i < in.num_data; ++i) - xml.scopedElement("TestSuite").writeAttribute("name", in.data[i]); - xml.scopedElement("OverallResultsTestCases") - .writeAttribute("unskipped", in.run_stats->numTestCasesPassingFilters); - xml.scopedElement("OverallResultsTestSuites") - .writeAttribute("unskipped", in.run_stats->numTestSuitesPassingFilters); - } - xml.endElement(); - } - - void test_run_start() override { - // remove .exe extension - mainly to have the same output on UNIX and Windows - std::string binary_name = skipPathFromFilename(opt.binary_name.c_str()); -#ifdef DOCTEST_PLATFORM_WINDOWS - if(binary_name.rfind(".exe") != std::string::npos) - binary_name = binary_name.substr(0, binary_name.length() - 4); -#endif // DOCTEST_PLATFORM_WINDOWS - - xml.startElement("doctest").writeAttribute("binary", binary_name); - if(opt.no_version == false) - xml.writeAttribute("version", DOCTEST_VERSION_STR); - - // only the consequential ones (TODO: filters) - xml.scopedElement("Options") - .writeAttribute("order_by", opt.order_by.c_str()) - .writeAttribute("rand_seed", opt.rand_seed) - .writeAttribute("first", opt.first) - .writeAttribute("last", opt.last) - .writeAttribute("abort_after", opt.abort_after) - .writeAttribute("subcase_filter_levels", opt.subcase_filter_levels) - .writeAttribute("case_sensitive", opt.case_sensitive) - .writeAttribute("no_throw", opt.no_throw) - .writeAttribute("no_skip", opt.no_skip); - } - - void test_run_end(const TestRunStats& p) override { - if(tc) // the TestSuite tag - only if there has been at least 1 test case - xml.endElement(); - - xml.scopedElement("OverallResultsAsserts") - .writeAttribute("successes", p.numAsserts - p.numAssertsFailed) - .writeAttribute("failures", p.numAssertsFailed); - - xml.startElement("OverallResultsTestCases") - .writeAttribute("successes", - p.numTestCasesPassingFilters - p.numTestCasesFailed) - .writeAttribute("failures", p.numTestCasesFailed); - if(opt.no_skipped_summary == false) - xml.writeAttribute("skipped", p.numTestCases - p.numTestCasesPassingFilters); - xml.endElement(); - - xml.endElement(); - } - - void test_case_start(const TestCaseData& in) override { - test_case_start_impl(in); - xml.ensureTagClosed(); - } - - void test_case_end(const CurrentTestCaseStats& st) override { - xml.startElement("OverallResultsAsserts") - .writeAttribute("successes", - st.numAssertsCurrentTest - st.numAssertsFailedCurrentTest) - .writeAttribute("failures", st.numAssertsFailedCurrentTest); - if(opt.duration) - xml.writeAttribute("duration", st.seconds); - if(tc->m_expected_failures) - xml.writeAttribute("expected_failures", tc->m_expected_failures); - xml.endElement(); - - xml.endElement(); - } - - void test_case_exception(const TestCaseException& e) override { - xml.scopedElement("Exception") - .writeAttribute("crash", e.is_crash) - .writeText(e.error_string.c_str()); - } - - void subcase_start(const SubcaseSignature& in) override { - xml.startElement("SubCase") - .writeAttribute("name", in.m_name) - .writeAttribute("filename", skipPathFromFilename(in.m_file)) - .writeAttribute("line", line(in.m_line)); - } - - void subcase_end() override { xml.endElement(); } - - void log_assert(const AssertData& rb) override { - if(!rb.m_failed && !opt.success) - return; - - std::lock_guard lock(mutex); - - xml.startElement("Expression") - .writeAttribute("success", !rb.m_failed) - .writeAttribute("type", assertString(rb.m_at)) - .writeAttribute("filename", skipPathFromFilename(rb.m_file)) - .writeAttribute("line", line(rb.m_line)); - - xml.scopedElement("Original").writeText(rb.m_expr); - - if(rb.m_threw) - xml.scopedElement("Exception").writeText(rb.m_exception.c_str()); - - if(rb.m_at & (assertType::is_throws_as | assertType::is_throws_with)) { - xml.scopedElement("ExpectedException").writeText(rb.m_exception_type); - } else if((rb.m_at & assertType::is_normal) && !rb.m_threw) { - xml.scopedElement("Expanded").writeText(rb.m_decomp.c_str()); - } - - log_contexts(); - - xml.endElement(); - } - - void log_message(const MessageData& mb) override { - std::lock_guard lock(mutex); - - xml.startElement("Message") - .writeAttribute("type", failureString(mb.m_severity)) - .writeAttribute("filename", skipPathFromFilename(mb.m_file)) - .writeAttribute("line", line(mb.m_line)); - - xml.scopedElement("Text").writeText(mb.m_string.c_str()); - - log_contexts(); - - xml.endElement(); - } - - void test_case_skipped(const TestCaseData& in) override { - if(opt.no_skipped_summary == false) { - test_case_start_impl(in); - xml.writeAttribute("skipped", "true"); - xml.endElement(); - } - } - }; - - DOCTEST_REGISTER_REPORTER("xml", 0, XmlReporter); - - struct Whitespace - { - int nrSpaces; - explicit Whitespace(int nr) - : nrSpaces(nr) {} - }; - - std::ostream& operator<<(std::ostream& out, const Whitespace& ws) { - if(ws.nrSpaces != 0) - out << std::setw(ws.nrSpaces) << ' '; - return out; - } - - struct ConsoleReporter : public IReporter - { - std::ostream& s; - bool hasLoggedCurrentTestStart; - std::vector subcasesStack; - std::mutex mutex; - - // caching pointers/references to objects of these types - safe to do - const ContextOptions& opt; - const TestCaseData* tc; - - ConsoleReporter(const ContextOptions& co) - : s(*co.cout) - , opt(co) {} - - ConsoleReporter(const ContextOptions& co, std::ostream& ostr) - : s(ostr) - , opt(co) {} - - // ========================================================================================= - // WHAT FOLLOWS ARE HELPERS USED BY THE OVERRIDES OF THE VIRTUAL METHODS OF THE INTERFACE - // ========================================================================================= - - void separator_to_stream() { - s << Color::Yellow - << "===============================================================================" - "\n"; - } - - const char* getSuccessOrFailString(bool success, assertType::Enum at, - const char* success_str) { - if(success) - return success_str; - return failureString(at); - } - - Color::Enum getSuccessOrFailColor(bool success, assertType::Enum at) { - return success ? Color::BrightGreen : - (at & assertType::is_warn) ? Color::Yellow : Color::Red; - } - - void successOrFailColoredStringToStream(bool success, assertType::Enum at, - const char* success_str = "SUCCESS") { - s << getSuccessOrFailColor(success, at) - << getSuccessOrFailString(success, at, success_str) << ": "; - } - - void log_contexts() { - int num_contexts = get_num_active_contexts(); - if(num_contexts) { - auto contexts = get_active_contexts(); - - s << Color::None << " logged: "; - for(int i = 0; i < num_contexts; ++i) { - s << (i == 0 ? "" : " "); - contexts[i]->stringify(&s); - s << "\n"; - } - } - - s << "\n"; - } - - void logTestStart() { - if(hasLoggedCurrentTestStart) - return; - - separator_to_stream(); - file_line_to_stream(s, tc->m_file, tc->m_line, "\n"); - if(tc->m_description) - s << Color::Yellow << "DESCRIPTION: " << Color::None << tc->m_description << "\n"; - if(tc->m_test_suite && tc->m_test_suite[0] != '\0') - s << Color::Yellow << "TEST SUITE: " << Color::None << tc->m_test_suite << "\n"; - if(strncmp(tc->m_name, " Scenario:", 11) != 0) - s << Color::None << "TEST CASE: "; - s << Color::None << tc->m_name << "\n"; - - for(auto& curr : subcasesStack) - if(curr.m_name[0] != '\0') - s << " " << curr.m_name << "\n"; - - s << "\n"; - - hasLoggedCurrentTestStart = true; - } - - void printVersion() { - if(opt.no_version == false) - s << Color::Cyan << "[doctest] " << Color::None << "doctest version is \"" - << DOCTEST_VERSION_STR << "\"\n"; - } - - void printIntro() { - printVersion(); - s << Color::Cyan << "[doctest] " << Color::None - << "run with \"--" DOCTEST_OPTIONS_PREFIX_DISPLAY "help\" for options\n"; - } - - void printHelp() { - int sizePrefixDisplay = static_cast(strlen(DOCTEST_OPTIONS_PREFIX_DISPLAY)); - printVersion(); - // clang-format off - s << Color::Cyan << "[doctest]\n" << Color::None; - s << Color::Cyan << "[doctest] " << Color::None; - s << "boolean values: \"1/on/yes/true\" or \"0/off/no/false\"\n"; - s << Color::Cyan << "[doctest] " << Color::None; - s << "filter values: \"str1,str2,str3\" (comma separated strings)\n"; - s << Color::Cyan << "[doctest]\n" << Color::None; - s << Color::Cyan << "[doctest] " << Color::None; - s << "filters use wildcards for matching strings\n"; - s << Color::Cyan << "[doctest] " << Color::None; - s << "something passes a filter if any of the strings in a filter matches\n"; -#ifndef DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS - s << Color::Cyan << "[doctest]\n" << Color::None; - s << Color::Cyan << "[doctest] " << Color::None; - s << "ALL FLAGS, OPTIONS AND FILTERS ALSO AVAILABLE WITH A \"" DOCTEST_CONFIG_OPTIONS_PREFIX "\" PREFIX!!!\n"; -#endif - s << Color::Cyan << "[doctest]\n" << Color::None; - s << Color::Cyan << "[doctest] " << Color::None; - s << "Query flags - the program quits after them. Available:\n\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "?, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "help, -" DOCTEST_OPTIONS_PREFIX_DISPLAY "h " - << Whitespace(sizePrefixDisplay*0) << "prints this message\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "v, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "version " - << Whitespace(sizePrefixDisplay*1) << "prints the version\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "c, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "count " - << Whitespace(sizePrefixDisplay*1) << "prints the number of matching tests\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ltc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "list-test-cases " - << Whitespace(sizePrefixDisplay*1) << "lists all matching tests by name\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "lts, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "list-test-suites " - << Whitespace(sizePrefixDisplay*1) << "lists all matching test suites\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "lr, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "list-reporters " - << Whitespace(sizePrefixDisplay*1) << "lists all registered reporters\n\n"; - // ================================================================================== << 79 - s << Color::Cyan << "[doctest] " << Color::None; - s << "The available / options/filters are:\n\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "tc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "test-case= " - << Whitespace(sizePrefixDisplay*1) << "filters tests by their name\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "tce, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "test-case-exclude= " - << Whitespace(sizePrefixDisplay*1) << "filters OUT tests by their name\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "sf, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "source-file= " - << Whitespace(sizePrefixDisplay*1) << "filters tests by their file\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "sfe, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "source-file-exclude= " - << Whitespace(sizePrefixDisplay*1) << "filters OUT tests by their file\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ts, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "test-suite= " - << Whitespace(sizePrefixDisplay*1) << "filters tests by their test suite\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "tse, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "test-suite-exclude= " - << Whitespace(sizePrefixDisplay*1) << "filters OUT tests by their test suite\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "sc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "subcase= " - << Whitespace(sizePrefixDisplay*1) << "filters subcases by their name\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "sce, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "subcase-exclude= " - << Whitespace(sizePrefixDisplay*1) << "filters OUT subcases by their name\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "r, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "reporters= " - << Whitespace(sizePrefixDisplay*1) << "reporters to use (console is default)\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "o, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "out= " - << Whitespace(sizePrefixDisplay*1) << "output filename\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ob, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "order-by= " - << Whitespace(sizePrefixDisplay*1) << "how the tests should be ordered\n"; - s << Whitespace(sizePrefixDisplay*3) << " - by [file/suite/name/rand]\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "rs, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "rand-seed= " - << Whitespace(sizePrefixDisplay*1) << "seed for random ordering\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "f, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "first= " - << Whitespace(sizePrefixDisplay*1) << "the first test passing the filters to\n"; - s << Whitespace(sizePrefixDisplay*3) << " execute - for range-based execution\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "l, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "last= " - << Whitespace(sizePrefixDisplay*1) << "the last test passing the filters to\n"; - s << Whitespace(sizePrefixDisplay*3) << " execute - for range-based execution\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "aa, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "abort-after= " - << Whitespace(sizePrefixDisplay*1) << "stop after failed assertions\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "scfl,--" DOCTEST_OPTIONS_PREFIX_DISPLAY "subcase-filter-levels= " - << Whitespace(sizePrefixDisplay*1) << "apply filters for the first levels\n"; - s << Color::Cyan << "\n[doctest] " << Color::None; - s << "Bool options - can be used like flags and true is assumed. Available:\n\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "s, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "success= " - << Whitespace(sizePrefixDisplay*1) << "include successful assertions in output\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "cs, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "case-sensitive= " - << Whitespace(sizePrefixDisplay*1) << "filters being treated as case sensitive\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "e, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "exit= " - << Whitespace(sizePrefixDisplay*1) << "exits after the tests finish\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "d, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "duration= " - << Whitespace(sizePrefixDisplay*1) << "prints the time duration of each test\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nt, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-throw= " - << Whitespace(sizePrefixDisplay*1) << "skips exceptions-related assert checks\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ne, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-exitcode= " - << Whitespace(sizePrefixDisplay*1) << "returns (or exits) always with success\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nr, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-run= " - << Whitespace(sizePrefixDisplay*1) << "skips all runtime doctest operations\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nv, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-version= " - << Whitespace(sizePrefixDisplay*1) << "omit the framework version in the output\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-colors= " - << Whitespace(sizePrefixDisplay*1) << "disables colors in output\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "fc, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "force-colors= " - << Whitespace(sizePrefixDisplay*1) << "use colors even when not in a tty\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nb, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-breaks= " - << Whitespace(sizePrefixDisplay*1) << "disables breakpoints in debuggers\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "ns, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-skip= " - << Whitespace(sizePrefixDisplay*1) << "don't skip test cases marked as skip\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "gfl, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "gnu-file-line= " - << Whitespace(sizePrefixDisplay*1) << ":n: vs (n): for line numbers in output\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "npf, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-path-filenames= " - << Whitespace(sizePrefixDisplay*1) << "only filenames and no paths in output\n"; - s << " -" DOCTEST_OPTIONS_PREFIX_DISPLAY "nln, --" DOCTEST_OPTIONS_PREFIX_DISPLAY "no-line-numbers= " - << Whitespace(sizePrefixDisplay*1) << "0 instead of real line numbers in output\n"; - // ================================================================================== << 79 - // clang-format on - - s << Color::Cyan << "\n[doctest] " << Color::None; - s << "for more information visit the project documentation\n\n"; - } - - void printRegisteredReporters() { - printVersion(); - s << Color::Cyan << "[doctest] " << Color::None << "listing all registered reporters\n"; - for(auto& curr : getReporters()) - s << "priority: " << std::setw(5) << curr.first.first - << " name: " << curr.first.second << "\n"; - } - - void list_query_results() { - separator_to_stream(); - if(opt.count || opt.list_test_cases) { - s << Color::Cyan << "[doctest] " << Color::None - << "unskipped test cases passing the current filters: " - << g_cs->numTestCasesPassingFilters << "\n"; - } else if(opt.list_test_suites) { - s << Color::Cyan << "[doctest] " << Color::None - << "unskipped test cases passing the current filters: " - << g_cs->numTestCasesPassingFilters << "\n"; - s << Color::Cyan << "[doctest] " << Color::None - << "test suites with unskipped test cases passing the current filters: " - << g_cs->numTestSuitesPassingFilters << "\n"; - } - } - - // ========================================================================================= - // WHAT FOLLOWS ARE OVERRIDES OF THE VIRTUAL METHODS OF THE REPORTER INTERFACE - // ========================================================================================= - - void report_query(const QueryData& in) override { - if(opt.version) { - printVersion(); - } else if(opt.help) { - printHelp(); - } else if(opt.list_reporters) { - printRegisteredReporters(); - } else if(opt.count || opt.list_test_cases) { - if(opt.list_test_cases) { - s << Color::Cyan << "[doctest] " << Color::None - << "listing all test case names\n"; - separator_to_stream(); - } - - for(unsigned i = 0; i < in.num_data; ++i) - s << Color::None << in.data[i] << "\n"; - - separator_to_stream(); - - s << Color::Cyan << "[doctest] " << Color::None - << "unskipped test cases passing the current filters: " - << g_cs->numTestCasesPassingFilters << "\n"; - - } else if(opt.list_test_suites) { - s << Color::Cyan << "[doctest] " << Color::None << "listing all test suites\n"; - separator_to_stream(); - - for(unsigned i = 0; i < in.num_data; ++i) - s << Color::None << in.data[i] << "\n"; - - separator_to_stream(); - - s << Color::Cyan << "[doctest] " << Color::None - << "unskipped test cases passing the current filters: " - << g_cs->numTestCasesPassingFilters << "\n"; - s << Color::Cyan << "[doctest] " << Color::None - << "test suites with unskipped test cases passing the current filters: " - << g_cs->numTestSuitesPassingFilters << "\n"; - } - } - - void test_run_start() override { printIntro(); } - - void test_run_end(const TestRunStats& p) override { - separator_to_stream(); - - const bool anythingFailed = p.numTestCasesFailed > 0 || p.numAssertsFailed > 0; - s << Color::Cyan << "[doctest] " << Color::None << "test cases: " << std::setw(6) - << p.numTestCasesPassingFilters << " | " - << ((p.numTestCasesPassingFilters == 0 || anythingFailed) ? Color::None : - Color::Green) - << std::setw(6) << p.numTestCasesPassingFilters - p.numTestCasesFailed << " passed" - << Color::None << " | " << (p.numTestCasesFailed > 0 ? Color::Red : Color::None) - << std::setw(6) << p.numTestCasesFailed << " failed" << Color::None << " | "; - if(opt.no_skipped_summary == false) { - const int numSkipped = p.numTestCases - p.numTestCasesPassingFilters; - s << (numSkipped == 0 ? Color::None : Color::Yellow) << std::setw(6) << numSkipped - << " skipped" << Color::None; - } - s << "\n"; - s << Color::Cyan << "[doctest] " << Color::None << "assertions: " << std::setw(6) - << p.numAsserts << " | " - << ((p.numAsserts == 0 || anythingFailed) ? Color::None : Color::Green) - << std::setw(6) << (p.numAsserts - p.numAssertsFailed) << " passed" << Color::None - << " | " << (p.numAssertsFailed > 0 ? Color::Red : Color::None) << std::setw(6) - << p.numAssertsFailed << " failed" << Color::None << " |\n"; - s << Color::Cyan << "[doctest] " << Color::None - << "Status: " << (p.numTestCasesFailed > 0 ? Color::Red : Color::Green) - << ((p.numTestCasesFailed > 0) ? "FAILURE!" : "SUCCESS!") << Color::None << std::endl; - } - - void test_case_start(const TestCaseData& in) override { - hasLoggedCurrentTestStart = false; - tc = ∈ - } - - void test_case_end(const CurrentTestCaseStats& st) override { - // log the preamble of the test case only if there is something - // else to print - something other than that an assert has failed - if(opt.duration || - (st.failure_flags && st.failure_flags != TestCaseFailureReason::AssertFailure)) - logTestStart(); - - if(opt.duration) - s << Color::None << std::setprecision(6) << std::fixed << st.seconds - << " s: " << tc->m_name << "\n"; - - if(st.failure_flags & TestCaseFailureReason::Timeout) - s << Color::Red << "Test case exceeded time limit of " << std::setprecision(6) - << std::fixed << tc->m_timeout << "!\n"; - - if(st.failure_flags & TestCaseFailureReason::ShouldHaveFailedButDidnt) { - s << Color::Red << "Should have failed but didn't! Marking it as failed!\n"; - } else if(st.failure_flags & TestCaseFailureReason::ShouldHaveFailedAndDid) { - s << Color::Yellow << "Failed as expected so marking it as not failed\n"; - } else if(st.failure_flags & TestCaseFailureReason::CouldHaveFailedAndDid) { - s << Color::Yellow << "Allowed to fail so marking it as not failed\n"; - } else if(st.failure_flags & TestCaseFailureReason::DidntFailExactlyNumTimes) { - s << Color::Red << "Didn't fail exactly " << tc->m_expected_failures - << " times so marking it as failed!\n"; - } else if(st.failure_flags & TestCaseFailureReason::FailedExactlyNumTimes) { - s << Color::Yellow << "Failed exactly " << tc->m_expected_failures - << " times as expected so marking it as not failed!\n"; - } - if(st.failure_flags & TestCaseFailureReason::TooManyFailedAsserts) { - s << Color::Red << "Aborting - too many failed asserts!\n"; - } - s << Color::None; - } - - void test_case_exception(const TestCaseException& e) override { - logTestStart(); - - file_line_to_stream(s, tc->m_file, tc->m_line, " "); - successOrFailColoredStringToStream(false, e.is_crash ? assertType::is_require : - assertType::is_check); - s << Color::Red << (e.is_crash ? "test case CRASHED: " : "test case THREW exception: ") - << Color::Cyan << e.error_string << "\n"; - - int num_stringified_contexts = get_num_stringified_contexts(); - if(num_stringified_contexts) { - auto stringified_contexts = get_stringified_contexts(); - s << Color::None << " logged: "; - for(int i = num_stringified_contexts - 1; i >= 0; --i) { - s << (i == num_stringified_contexts - 1 ? "" : " ") - << stringified_contexts[i] << "\n"; - } - } - s << "\n" << Color::None; - } - - void subcase_start(const SubcaseSignature& subc) override { - subcasesStack.push_back(subc); - hasLoggedCurrentTestStart = false; - } - - void subcase_end() override { - subcasesStack.pop_back(); - hasLoggedCurrentTestStart = false; - } - - void log_assert(const AssertData& rb) override { - if(!rb.m_failed && !opt.success) - return; - - std::lock_guard lock(mutex); - - logTestStart(); - - file_line_to_stream(s, rb.m_file, rb.m_line, " "); - successOrFailColoredStringToStream(!rb.m_failed, rb.m_at); - if((rb.m_at & (assertType::is_throws_as | assertType::is_throws_with)) == - 0) //!OCLINT bitwise operator in conditional - s << Color::Cyan << assertString(rb.m_at) << "( " << rb.m_expr << " ) " - << Color::None; - - if(rb.m_at & assertType::is_throws) { //!OCLINT bitwise operator in conditional - s << (rb.m_threw ? "threw as expected!" : "did NOT throw at all!") << "\n"; - } else if(rb.m_at & - assertType::is_throws_as) { //!OCLINT bitwise operator in conditional - s << Color::Cyan << assertString(rb.m_at) << "( " << rb.m_expr << ", " - << rb.m_exception_type << " ) " << Color::None - << (rb.m_threw ? (rb.m_threw_as ? "threw as expected!" : - "threw a DIFFERENT exception: ") : - "did NOT throw at all!") - << Color::Cyan << rb.m_exception << "\n"; - } else if(rb.m_at & - assertType::is_throws_with) { //!OCLINT bitwise operator in conditional - s << Color::Cyan << assertString(rb.m_at) << "( " << rb.m_expr << ", \"" - << rb.m_exception_type << "\" ) " << Color::None - << (rb.m_threw ? (!rb.m_failed ? "threw as expected!" : - "threw a DIFFERENT exception: ") : - "did NOT throw at all!") - << Color::Cyan << rb.m_exception << "\n"; - } else if(rb.m_at & assertType::is_nothrow) { //!OCLINT bitwise operator in conditional - s << (rb.m_threw ? "THREW exception: " : "didn't throw!") << Color::Cyan - << rb.m_exception << "\n"; - } else { - s << (rb.m_threw ? "THREW exception: " : - (!rb.m_failed ? "is correct!\n" : "is NOT correct!\n")); - if(rb.m_threw) - s << rb.m_exception << "\n"; - else - s << " values: " << assertString(rb.m_at) << "( " << rb.m_decomp << " )\n"; - } - - log_contexts(); - } - - void log_message(const MessageData& mb) override { - std::lock_guard lock(mutex); - - logTestStart(); - - file_line_to_stream(s, mb.m_file, mb.m_line, " "); - s << getSuccessOrFailColor(false, mb.m_severity) - << getSuccessOrFailString(mb.m_severity & assertType::is_warn, mb.m_severity, - "MESSAGE") << ": "; - s << Color::None << mb.m_string << "\n"; - log_contexts(); - } - - void test_case_skipped(const TestCaseData&) override {} - }; - - DOCTEST_REGISTER_REPORTER("console", 0, ConsoleReporter); - -#ifdef DOCTEST_PLATFORM_WINDOWS - struct DebugOutputWindowReporter : public ConsoleReporter - { - DOCTEST_THREAD_LOCAL static std::ostringstream oss; - - DebugOutputWindowReporter(const ContextOptions& co) - : ConsoleReporter(co, oss) {} - -#define DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(func, type, arg) \ - void func(type arg) override { \ - bool with_col = g_no_colors; \ - g_no_colors = false; \ - ConsoleReporter::func(arg); \ - DOCTEST_OUTPUT_DEBUG_STRING(oss.str().c_str()); \ - oss.str(""); \ - g_no_colors = with_col; \ - } - - DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_run_start, DOCTEST_EMPTY, DOCTEST_EMPTY) - DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_run_end, const TestRunStats&, in) - DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_start, const TestCaseData&, in) - DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_end, const CurrentTestCaseStats&, in) - DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_exception, const TestCaseException&, in) - DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(subcase_start, const SubcaseSignature&, in) - DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(subcase_end, DOCTEST_EMPTY, DOCTEST_EMPTY) - DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(log_assert, const AssertData&, in) - DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(log_message, const MessageData&, in) - DOCTEST_DEBUG_OUTPUT_REPORTER_OVERRIDE(test_case_skipped, const TestCaseData&, in) - }; - - DOCTEST_THREAD_LOCAL std::ostringstream DebugOutputWindowReporter::oss; -#endif // DOCTEST_PLATFORM_WINDOWS - - // the implementation of parseFlag() - bool parseFlagImpl(int argc, const char* const* argv, const char* pattern) { - for(int i = argc - 1; i >= 0; --i) { - auto temp = std::strstr(argv[i], pattern); - if(temp && strlen(temp) == strlen(pattern)) { - // eliminate strings in which the chars before the option are not '-' - bool noBadCharsFound = true; //!OCLINT prefer early exits and continue - while(temp != argv[i]) { - if(*--temp != '-') { - noBadCharsFound = false; - break; - } - } - if(noBadCharsFound && argv[i][0] == '-') - return true; - } - } - return false; - } - - // locates a flag on the command line - bool parseFlag(int argc, const char* const* argv, const char* pattern) { -#ifndef DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS - // offset (normally 3 for "dt-") to skip prefix - if(parseFlagImpl(argc, argv, pattern + strlen(DOCTEST_CONFIG_OPTIONS_PREFIX))) - return true; -#endif // DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS - return parseFlagImpl(argc, argv, pattern); - } - - // the implementation of parseOption() - bool parseOptionImpl(int argc, const char* const* argv, const char* pattern, String& res) { - for(int i = argc - 1; i >= 0; --i) { - auto temp = std::strstr(argv[i], pattern); - if(temp) { //!OCLINT prefer early exits and continue - // eliminate matches in which the chars before the option are not '-' - bool noBadCharsFound = true; - auto curr = argv[i]; - while(curr != temp) { - if(*curr++ != '-') { - noBadCharsFound = false; - break; - } - } - if(noBadCharsFound && argv[i][0] == '-') { - temp += strlen(pattern); - const unsigned len = strlen(temp); - if(len) { - res = temp; - return true; - } - } - } - } - return false; - } - - // parses an option and returns the string after the '=' character - bool parseOption(int argc, const char* const* argv, const char* pattern, String& res, - const String& defaultVal = String()) { - res = defaultVal; -#ifndef DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS - // offset (normally 3 for "dt-") to skip prefix - if(parseOptionImpl(argc, argv, pattern + strlen(DOCTEST_CONFIG_OPTIONS_PREFIX), res)) - return true; -#endif // DOCTEST_CONFIG_NO_UNPREFIXED_OPTIONS - return parseOptionImpl(argc, argv, pattern, res); - } - - // parses a comma separated list of words after a pattern in one of the arguments in argv - bool parseCommaSepArgs(int argc, const char* const* argv, const char* pattern, - std::vector& res) { - String filtersString; - if(parseOption(argc, argv, pattern, filtersString)) { - // tokenize with "," as a separator - // cppcheck-suppress strtokCalled - DOCTEST_CLANG_SUPPRESS_WARNING_WITH_PUSH("-Wdeprecated-declarations") - auto pch = std::strtok(filtersString.c_str(), ","); // modifies the string - while(pch != nullptr) { - if(strlen(pch)) - res.push_back(pch); - // uses the strtok() internal state to go to the next token - // cppcheck-suppress strtokCalled - pch = std::strtok(nullptr, ","); - } - DOCTEST_CLANG_SUPPRESS_WARNING_POP - return true; - } - return false; - } - - enum optionType - { - option_bool, - option_int - }; - - // parses an int/bool option from the command line - bool parseIntOption(int argc, const char* const* argv, const char* pattern, optionType type, - int& res) { - String parsedValue; - if(!parseOption(argc, argv, pattern, parsedValue)) - return false; - - if(type == 0) { - // boolean - const char positive[][5] = {"1", "true", "on", "yes"}; // 5 - strlen("true") + 1 - const char negative[][6] = {"0", "false", "off", "no"}; // 6 - strlen("false") + 1 - - // if the value matches any of the positive/negative possibilities - for(unsigned i = 0; i < 4; i++) { - if(parsedValue.compare(positive[i], true) == 0) { - res = 1; //!OCLINT parameter reassignment - return true; - } - if(parsedValue.compare(negative[i], true) == 0) { - res = 0; //!OCLINT parameter reassignment - return true; - } - } - } else { - // integer - // TODO: change this to use std::stoi or something else! currently it uses undefined behavior - assumes '0' on failed parse... - int theInt = std::atoi(parsedValue.c_str()); // NOLINT - if(theInt != 0) { - res = theInt; //!OCLINT parameter reassignment - return true; - } - } - return false; - } -} // namespace - -Context::Context(int argc, const char* const* argv) - : p(new detail::ContextState) { - parseArgs(argc, argv, true); - if(argc) - p->binary_name = argv[0]; -} - -Context::~Context() { - if(g_cs == p) - g_cs = nullptr; - delete p; -} - -void Context::applyCommandLine(int argc, const char* const* argv) { - parseArgs(argc, argv); - if(argc) - p->binary_name = argv[0]; -} - -// parses args -void Context::parseArgs(int argc, const char* const* argv, bool withDefaults) { - using namespace detail; - - // clang-format off - parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "source-file=", p->filters[0]); - parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "sf=", p->filters[0]); - parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "source-file-exclude=",p->filters[1]); - parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "sfe=", p->filters[1]); - parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "test-suite=", p->filters[2]); - parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "ts=", p->filters[2]); - parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "test-suite-exclude=", p->filters[3]); - parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "tse=", p->filters[3]); - parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "test-case=", p->filters[4]); - parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "tc=", p->filters[4]); - parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "test-case-exclude=", p->filters[5]); - parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "tce=", p->filters[5]); - parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "subcase=", p->filters[6]); - parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "sc=", p->filters[6]); - parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "subcase-exclude=", p->filters[7]); - parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "sce=", p->filters[7]); - parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "reporters=", p->filters[8]); - parseCommaSepArgs(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "r=", p->filters[8]); - // clang-format on - - int intRes = 0; - String strRes; - -#define DOCTEST_PARSE_AS_BOOL_OR_FLAG(name, sname, var, default) \ - if(parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name "=", option_bool, intRes) || \ - parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname "=", option_bool, intRes)) \ - p->var = !!intRes; \ - else if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name) || \ - parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname)) \ - p->var = true; \ - else if(withDefaults) \ - p->var = default - -#define DOCTEST_PARSE_INT_OPTION(name, sname, var, default) \ - if(parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name "=", option_int, intRes) || \ - parseIntOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname "=", option_int, intRes)) \ - p->var = intRes; \ - else if(withDefaults) \ - p->var = default - -#define DOCTEST_PARSE_STR_OPTION(name, sname, var, default) \ - if(parseOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX name "=", strRes, default) || \ - parseOption(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX sname "=", strRes, default) || \ - withDefaults) \ - p->var = strRes - - // clang-format off - DOCTEST_PARSE_STR_OPTION("out", "o", out, ""); - DOCTEST_PARSE_STR_OPTION("order-by", "ob", order_by, "file"); - DOCTEST_PARSE_INT_OPTION("rand-seed", "rs", rand_seed, 0); - - DOCTEST_PARSE_INT_OPTION("first", "f", first, 0); - DOCTEST_PARSE_INT_OPTION("last", "l", last, UINT_MAX); - - DOCTEST_PARSE_INT_OPTION("abort-after", "aa", abort_after, 0); - DOCTEST_PARSE_INT_OPTION("subcase-filter-levels", "scfl", subcase_filter_levels, INT_MAX); - - DOCTEST_PARSE_AS_BOOL_OR_FLAG("success", "s", success, false); - DOCTEST_PARSE_AS_BOOL_OR_FLAG("case-sensitive", "cs", case_sensitive, false); - DOCTEST_PARSE_AS_BOOL_OR_FLAG("exit", "e", exit, false); - DOCTEST_PARSE_AS_BOOL_OR_FLAG("duration", "d", duration, false); - DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-throw", "nt", no_throw, false); - DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-exitcode", "ne", no_exitcode, false); - DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-run", "nr", no_run, false); - DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-version", "nv", no_version, false); - DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-colors", "nc", no_colors, false); - DOCTEST_PARSE_AS_BOOL_OR_FLAG("force-colors", "fc", force_colors, false); - DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-breaks", "nb", no_breaks, false); - DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-skip", "ns", no_skip, false); - DOCTEST_PARSE_AS_BOOL_OR_FLAG("gnu-file-line", "gfl", gnu_file_line, !bool(DOCTEST_MSVC)); - DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-path-filenames", "npf", no_path_in_filenames, false); - DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-line-numbers", "nln", no_line_numbers, false); - DOCTEST_PARSE_AS_BOOL_OR_FLAG("no-skipped-summary", "nss", no_skipped_summary, false); - // clang-format on - - if(withDefaults) { - p->help = false; - p->version = false; - p->count = false; - p->list_test_cases = false; - p->list_test_suites = false; - p->list_reporters = false; - } - if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "help") || - parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "h") || - parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "?")) { - p->help = true; - p->exit = true; - } - if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "version") || - parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "v")) { - p->version = true; - p->exit = true; - } - if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "count") || - parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "c")) { - p->count = true; - p->exit = true; - } - if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "list-test-cases") || - parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "ltc")) { - p->list_test_cases = true; - p->exit = true; - } - if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "list-test-suites") || - parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "lts")) { - p->list_test_suites = true; - p->exit = true; - } - if(parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "list-reporters") || - parseFlag(argc, argv, DOCTEST_CONFIG_OPTIONS_PREFIX "lr")) { - p->list_reporters = true; - p->exit = true; - } -} - -// allows the user to add procedurally to the filters from the command line -void Context::addFilter(const char* filter, const char* value) { setOption(filter, value); } - -// allows the user to clear all filters from the command line -void Context::clearFilters() { - for(auto& curr : p->filters) - curr.clear(); -} - -// allows the user to override procedurally the int/bool options from the command line -void Context::setOption(const char* option, int value) { - setOption(option, toString(value).c_str()); -} - -// allows the user to override procedurally the string options from the command line -void Context::setOption(const char* option, const char* value) { - auto argv = String("-") + option + "=" + value; - auto lvalue = argv.c_str(); - parseArgs(1, &lvalue); -} - -// users should query this in their main() and exit the program if true -bool Context::shouldExit() { return p->exit; } - -void Context::setAsDefaultForAssertsOutOfTestCases() { g_cs = p; } - -void Context::setAssertHandler(detail::assert_handler ah) { p->ah = ah; } - -// the main function that does all the filtering and test running -int Context::run() { - using namespace detail; - - // save the old context state in case such was setup - for using asserts out of a testing context - auto old_cs = g_cs; - // this is the current contest - g_cs = p; - is_running_in_test = true; - - g_no_colors = p->no_colors; - p->resetRunData(); - - // stdout by default - p->cout = &std::cout; - p->cerr = &std::cerr; - - // or to a file if specified - std::fstream fstr; - if(p->out.size()) { - fstr.open(p->out.c_str(), std::fstream::out); - p->cout = &fstr; - } - - auto cleanup_and_return = [&]() { - if(fstr.is_open()) - fstr.close(); - - // restore context - g_cs = old_cs; - is_running_in_test = false; - - // we have to free the reporters which were allocated when the run started - for(auto& curr : p->reporters_currently_used) - delete curr; - p->reporters_currently_used.clear(); - - if(p->numTestCasesFailed && !p->no_exitcode) - return EXIT_FAILURE; - return EXIT_SUCCESS; - }; - - DOCTEST_REGISTER_REPORTER("console", 0, ConsoleReporter); - - // setup default reporter if none is given through the command line - if(p->filters[8].empty()) - p->filters[8].push_back("console"); - - // check to see if any of the registered reporters has been selected - for(auto& curr : getReporters()) { - if(matchesAny(curr.first.second.c_str(), p->filters[8], false, p->case_sensitive)) - p->reporters_currently_used.push_back(curr.second(*g_cs)); - } - -#ifdef DOCTEST_PLATFORM_WINDOWS - if(isDebuggerActive()) - p->reporters_currently_used.push_back(new DebugOutputWindowReporter(*g_cs)); -#endif // DOCTEST_PLATFORM_WINDOWS - - // handle version, help and no_run - if(p->no_run || p->version || p->help || p->list_reporters) { - DOCTEST_ITERATE_THROUGH_REPORTERS(report_query, QueryData()); - - return cleanup_and_return(); - } - - std::vector testArray; - for(auto& curr : getRegisteredTests()) - testArray.push_back(&curr); - p->numTestCases = testArray.size(); - - // sort the collected records - if(!testArray.empty()) { - if(p->order_by.compare("file", true) == 0) { - std::sort(testArray.begin(), testArray.end(), fileOrderComparator); - } else if(p->order_by.compare("suite", true) == 0) { - std::sort(testArray.begin(), testArray.end(), suiteOrderComparator); - } else if(p->order_by.compare("name", true) == 0) { - std::sort(testArray.begin(), testArray.end(), nameOrderComparator); - } else if(p->order_by.compare("rand", true) == 0) { - std::srand(p->rand_seed); - - // random_shuffle implementation - const auto first = &testArray[0]; - for(size_t i = testArray.size() - 1; i > 0; --i) { - int idxToSwap = std::rand() % (i + 1); // NOLINT - - const auto temp = first[i]; - - first[i] = first[idxToSwap]; - first[idxToSwap] = temp; - } - } - } - - std::set testSuitesPassingFilt; - - bool query_mode = p->count || p->list_test_cases || p->list_test_suites; - std::vector queryResults; - - if(!query_mode) - DOCTEST_ITERATE_THROUGH_REPORTERS(test_run_start, DOCTEST_EMPTY); - - // invoke the registered functions if they match the filter criteria (or just count them) - for(auto& curr : testArray) { - const auto& tc = *curr; - - bool skip_me = false; - if(tc.m_skip && !p->no_skip) - skip_me = true; - - if(!matchesAny(tc.m_file, p->filters[0], true, p->case_sensitive)) - skip_me = true; - if(matchesAny(tc.m_file, p->filters[1], false, p->case_sensitive)) - skip_me = true; - if(!matchesAny(tc.m_test_suite, p->filters[2], true, p->case_sensitive)) - skip_me = true; - if(matchesAny(tc.m_test_suite, p->filters[3], false, p->case_sensitive)) - skip_me = true; - if(!matchesAny(tc.m_name, p->filters[4], true, p->case_sensitive)) - skip_me = true; - if(matchesAny(tc.m_name, p->filters[5], false, p->case_sensitive)) - skip_me = true; - - if(!skip_me) - p->numTestCasesPassingFilters++; - - // skip the test if it is not in the execution range - if((p->last < p->numTestCasesPassingFilters && p->first <= p->last) || - (p->first > p->numTestCasesPassingFilters)) - skip_me = true; - - if(skip_me) { - if(!query_mode) - DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_skipped, tc); - continue; - } - - // do not execute the test if we are to only count the number of filter passing tests - if(p->count) - continue; - - // print the name of the test and don't execute it - if(p->list_test_cases) { - queryResults.push_back(tc.m_name); - continue; - } - - // print the name of the test suite if not done already and don't execute it - if(p->list_test_suites) { - if((testSuitesPassingFilt.count(tc.m_test_suite) == 0) && tc.m_test_suite[0] != '\0') { - queryResults.push_back(tc.m_test_suite); - testSuitesPassingFilt.insert(tc.m_test_suite); - p->numTestSuitesPassingFilters++; - } - continue; - } - - // execute the test if it passes all the filtering - { - p->currentTest = &tc; - - p->failure_flags = TestCaseFailureReason::None; - p->seconds = 0; - - // reset atomic counters - p->numAssertsFailedCurrentTest_atomic = 0; - p->numAssertsCurrentTest_atomic = 0; - - p->subcasesPassed.clear(); - - DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_start, tc); - - p->timer.start(); - - do { - // reset some of the fields for subcases (except for the set of fully passed ones) - p->should_reenter = false; - p->subcasesCurrentLevel = 0; - p->subcasesEnteredLevels.clear(); - - // reset stuff for logging with INFO() - p->stringifiedContexts.clear(); - -#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS - try { -#endif // DOCTEST_CONFIG_NO_EXCEPTIONS - FatalConditionHandler fatalConditionHandler; // Handle signals - // execute the test - tc.m_test(); - fatalConditionHandler.reset(); -#ifndef DOCTEST_CONFIG_NO_EXCEPTIONS - } catch(const TestFailureException&) { - p->failure_flags |= TestCaseFailureReason::AssertFailure; - } catch(...) { - DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_exception, - {translateActiveException(), false}); - p->failure_flags |= TestCaseFailureReason::Exception; - } -#endif // DOCTEST_CONFIG_NO_EXCEPTIONS - - // exit this loop if enough assertions have failed - even if there are more subcases - if(p->abort_after > 0 && - p->numAssertsFailed + p->numAssertsFailedCurrentTest_atomic >= p->abort_after) { - p->should_reenter = false; - p->failure_flags |= TestCaseFailureReason::TooManyFailedAsserts; - } - } while(p->should_reenter == true); - - p->finalizeTestCaseData(); - - DOCTEST_ITERATE_THROUGH_REPORTERS(test_case_end, *g_cs); - - p->currentTest = nullptr; - - // stop executing tests if enough assertions have failed - if(p->abort_after > 0 && p->numAssertsFailed >= p->abort_after) - break; - } - } - - if(!query_mode) { - DOCTEST_ITERATE_THROUGH_REPORTERS(test_run_end, *g_cs); - } else { - QueryData qdata; - qdata.run_stats = g_cs; - qdata.data = queryResults.data(); - qdata.num_data = unsigned(queryResults.size()); - DOCTEST_ITERATE_THROUGH_REPORTERS(report_query, qdata); - } - - return cleanup_and_return(); -} - -DOCTEST_DEFINE_DEFAULTS(CurrentTestCaseStats); - -DOCTEST_DEFINE_DEFAULTS(TestRunStats); - -IReporter::~IReporter() = default; - -int IReporter::get_num_active_contexts() { return detail::g_infoContexts.size(); } -const IContextScope* const* IReporter::get_active_contexts() { - return get_num_active_contexts() ? &detail::g_infoContexts[0] : nullptr; -} - -int IReporter::get_num_stringified_contexts() { return detail::g_cs->stringifiedContexts.size(); } -const String* IReporter::get_stringified_contexts() { - return get_num_stringified_contexts() ? &detail::g_cs->stringifiedContexts[0] : nullptr; -} - -namespace detail { - void registerReporterImpl(const char* name, int priority, reporterCreatorFunc c) { - getReporters().insert(reporterMap::value_type(reporterMap::key_type(priority, name), c)); - } -} // namespace detail - -// see these issues on the reasoning for this: -// - https://github.com/onqtam/doctest/issues/143#issuecomment-414418903 -// - https://github.com/onqtam/doctest/issues/126 -void DOCTEST_FIX_FOR_MACOS_LIBCPP_IOSFWD_STRING_LINK_ERRORS() { std::cout << std::string(); } - -} // namespace doctest - -#endif // DOCTEST_CONFIG_DISABLE - -#ifdef DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN -DOCTEST_MSVC_SUPPRESS_WARNING_WITH_PUSH(4007) // 'function' : must be 'attribute' - see issue #182 -int main(int argc, char** argv) { return doctest::Context(argc, argv).run(); } -DOCTEST_MSVC_SUPPRESS_WARNING_POP -#endif // DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN - -DOCTEST_CLANG_SUPPRESS_WARNING_POP -DOCTEST_MSVC_SUPPRESS_WARNING_POP -DOCTEST_GCC_SUPPRESS_WARNING_POP - -#endif // DOCTEST_LIBRARY_IMPLEMENTATION -#endif // DOCTEST_CONFIG_IMPLEMENT diff --git a/lib/ArduinoStreamUtils/extras/test/main.cpp b/lib/ArduinoStreamUtils/extras/test/main.cpp deleted file mode 100644 index dcfcaba1..00000000 --- a/lib/ArduinoStreamUtils/extras/test/main.cpp +++ /dev/null @@ -1,6 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#define DOCTEST_CONFIG_IMPLEMENT_WITH_MAIN -#include "doctest.h" diff --git a/lib/ArduinoStreamUtils/keywords.txt b/lib/ArduinoStreamUtils/keywords.txt deleted file mode 100644 index 9f91ccef..00000000 --- a/lib/ArduinoStreamUtils/keywords.txt +++ /dev/null @@ -1,13 +0,0 @@ -BufferingPrint KEYWORD1 -LoggingClient KEYWORD1 -LoggingPrint KEYWORD1 -LoggingStream KEYWORD1 -ReadBufferingClient KEYWORD1 -ReadBufferingStream KEYWORD1 -ReadLoggingClient KEYWORD1 -ReadLoggingStream KEYWORD1 -ReadThrottlingStream KEYWORD1 -WriteBufferingClient KEYWORD1 -WriteBufferingStream KEYWORD1 -WriteLoggingClient KEYWORD1 -WriteLoggingStream KEYWORD1 \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/library.properties b/lib/ArduinoStreamUtils/library.properties deleted file mode 100644 index 00cb5887..00000000 --- a/lib/ArduinoStreamUtils/library.properties +++ /dev/null @@ -1,11 +0,0 @@ -name=StreamUtils -version=1.6.1 -author=Benoit Blanchon -maintainer=Benoit Blanchon -sentence=💪 Power-ups for Arduino streams -paragraph=Enhances existing streams with logging, buffering, error correction, and more! Works with Serial, SoftwareSerial, WiFiClient... -category=Other -url=https://github.com/bblanchon/ArduinoStreamUtils -architectures=* -repository=https://github.com/bblanchon/ArduinoStreamUtils.git -license=MIT diff --git a/lib/ArduinoStreamUtils/src/StreamUtils.h b/lib/ArduinoStreamUtils/src/StreamUtils.h deleted file mode 100644 index 39637e3a..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils.h +++ /dev/null @@ -1,7 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "StreamUtils.hpp" - -using namespace StreamUtils; \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils.hpp b/lib/ArduinoStreamUtils/src/StreamUtils.hpp deleted file mode 100644 index f24f78e9..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils.hpp +++ /dev/null @@ -1,28 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#include "StreamUtils/Clients/HammingClient.hpp" -#include "StreamUtils/Clients/HammingDecodingClient.hpp" -#include "StreamUtils/Clients/HammingEncodingClient.hpp" -#include "StreamUtils/Clients/LoggingClient.hpp" -#include "StreamUtils/Clients/ReadBufferingClient.hpp" -#include "StreamUtils/Clients/ReadLoggingClient.hpp" -#include "StreamUtils/Clients/WriteBufferingClient.hpp" -#include "StreamUtils/Clients/WriteLoggingClient.hpp" -#include "StreamUtils/Prints/BufferingPrint.hpp" -#include "StreamUtils/Prints/HammingPrint.hpp" -#include "StreamUtils/Prints/LoggingPrint.hpp" -#include "StreamUtils/Prints/StringPrint.hpp" -#include "StreamUtils/Streams/EepromStream.hpp" -#include "StreamUtils/Streams/HammingDecodingStream.hpp" -#include "StreamUtils/Streams/HammingEncodingStream.hpp" -#include "StreamUtils/Streams/HammingStream.hpp" -#include "StreamUtils/Streams/LoggingStream.hpp" -#include "StreamUtils/Streams/ReadBufferingStream.hpp" -#include "StreamUtils/Streams/ReadLoggingStream.hpp" -#include "StreamUtils/Streams/ReadThrottlingStream.hpp" -#include "StreamUtils/Streams/StringStream.hpp" -#include "StreamUtils/Streams/WriteBufferingStream.hpp" -#include "StreamUtils/Streams/WriteLoggingStream.hpp" -#include "StreamUtils/Streams/WriteWaitingStream.hpp" diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Buffers/CharArray.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Buffers/CharArray.hpp deleted file mode 100644 index c16f4548..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Buffers/CharArray.hpp +++ /dev/null @@ -1,57 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include -#include // size_t -#include // memcpy - -namespace StreamUtils { - -template -class CharArray { - public: - CharArray(size_t size, TAllocator allocator = TAllocator()) - : _allocator(allocator) { - _data = reinterpret_cast(_allocator.allocate(size)); - _size = _data ? size : 0; - } - - CharArray(const CharArray &src) : CharArray(src._size, src._allocator) { - if (_data != nullptr) - memcpy(_data, src._data, _size); - } - - ~CharArray() { - _allocator.deallocate(_data); - } - - size_t size() const { - return _size; - } - - operator bool() const { - return _size > 0; - } - - char *operator&() { - return _data; - } - - char &operator[](size_t i) { - return _data[i]; - } - - char operator[](size_t i) const { - return _data[i]; - } - - protected: - TAllocator _allocator; - char *_data; - size_t _size; -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Buffers/CircularBuffer.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Buffers/CircularBuffer.hpp deleted file mode 100644 index c2f210af..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Buffers/CircularBuffer.hpp +++ /dev/null @@ -1,101 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include - -#include "CharArray.hpp" - -namespace StreamUtils { - -template -class CircularBuffer { - public: - CircularBuffer(size_t capacity, TAllocator allocator = TAllocator()) - : _data(capacity, allocator) { - _begin = _end = _size = 0; - } - - CircularBuffer(const CircularBuffer &src) - : CircularBuffer(src._data.size(), src._allocator) { - if (_data) { - _begin = src._begin; - _end = src._end; - _size = src._size; - } - } - - size_t available() const { - return _size; - } - - size_t capacity() const { - return _data.size(); - } - - void clear() { - _begin = _end = _size = 0; - } - - bool isEmpty() const { - return _size == 0; - } - - bool isFull() const { - return _size == _data.size(); - } - - char peek() const { - assert(_size > 0); - return _data[_begin]; - } - - char read() { - assert(_size > 0); - char result = _data[_begin]; - _begin = (_begin + 1) % _data.size(); - _size--; - return result; - } - - size_t readBytes(char *data, size_t size) { - // don't read more that available - if (size > _size) - size = _size; - - for (size_t i = 0; i < size; i++) - data[i] = read(); - - return size; - } - - size_t write(uint8_t data) { - assert(_size < _data.size()); - _data[_end] = data; - _end = (_end + 1) % _data.size(); - _size++; - return 1; - } - - size_t write(const uint8_t *data, size_t size) { - // don't read more that available - size_t roomLeft = _data.size() - _size; - if (size > roomLeft) - size = roomLeft; - - for (size_t i = 0; i < size; i++) - write(data[i]); - - return size; - } - - private: - CharArray _data; - size_t _size; - size_t _begin; - size_t _end; -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Buffers/LinearBuffer.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Buffers/LinearBuffer.hpp deleted file mode 100644 index 10c108f6..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Buffers/LinearBuffer.hpp +++ /dev/null @@ -1,111 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include -#include - -#include "../Helpers.hpp" -#include "CharArray.hpp" - -namespace StreamUtils { - -template -class LinearBuffer { - public: - LinearBuffer(size_t capacity, TAllocator allocator = TAllocator()) - : _data(capacity, allocator) { - _begin = _data ? &_data : nullptr; - _end = _begin; - } - - LinearBuffer(const LinearBuffer &src) : _data(src._data) { - if (_data) { - memcpy(&_data, src._begin, src.available()); - _begin = &_data; - _end = &_data + src.available(); - } else { - _begin = nullptr; - _end = nullptr; - } - } - - size_t available() const { - return _end - _begin; - } - - size_t capacity() const { - return _data.size(); - } - - void clear() { - _begin = _end = _data; - } - - bool isEmpty() const { - return available() == 0; - } - - bool isFull() const { - return available() == capacity(); - } - - operator bool() const { - return _data; - } - - char peek() const { - return *_begin; - } - - char read() { - return *_begin++; - } - - size_t readBytes(char *dstPtr, size_t dstSize) { - size_t srcSize = available(); - size_t n = srcSize < dstSize ? srcSize : dstSize; - memcpy(dstPtr, _begin, n); - _begin += n; - return n; - } - - size_t write(uint8_t data) { - assert(!isFull()); - *_end++ = data; - return 1; - } - - size_t write(const uint8_t *data, size_t size) { - size_t roomLeft = capacity() - available(); - if (size > roomLeft) - size = roomLeft; - memcpy(_end, data, size); - _end += size; - return size; - } - - template // Stream or Client - void reloadFrom(TTarget &source, size_t size) { - if (size > _data.size()) - size = _data.size(); - size_t n = readOrReadBytes(source, &_data, size); - _begin = &_data; - _end = &_data + n; - } - - void flushInto(Print &destination) { - if (_begin != _end) - destination.write(_begin, _end - _begin); - _begin = _end = &_data; - } - - private: - CharArray _data; - char *_begin; - char *_end; -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Clients/ClientProxy.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Clients/ClientProxy.hpp deleted file mode 100644 index 23a9cc09..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Clients/ClientProxy.hpp +++ /dev/null @@ -1,105 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include - -#include "../Configuration.hpp" -#include "../Streams/StreamProxy.hpp" - -namespace StreamUtils { - -template -class ClientProxy : public Client { - public: - explicit ClientProxy(Client &upstream, ReadPolicy reader = ReadPolicy(), - WritePolicy writer = WritePolicy(), - ConnectPolicy connection = ConnectPolicy()) - : _target(upstream), - _reader(reader), - _writer(Polyfills::move(writer)), - _connection(connection) {} - - ClientProxy(const ClientProxy &other) - : _target(other._target), - _reader(other._reader), - _writer(other._writer), - _connection(other._connection) {} - - ~ClientProxy() { - _writer.implicitFlush(_target); - } - - // --- Print --- - - size_t write(const uint8_t *buffer, size_t size) override { - return _writer.write(_target, buffer, size); - } - - size_t write(uint8_t data) override { - return _writer.write(_target, data); - } - - using Print::write; - - // --- Stream --- - - int available() override { - return _reader.available(_target); - } - - int read() override { - return _reader.read(_target); - } - - int peek() override { - return _reader.peek(_target); - } - -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - size_t readBytes(char *buffer, size_t size) override { - return _reader.readBytes(_target, buffer, size); - } -#endif - - // --- Client --- - - int connect(IPAddress ip, uint16_t port) override { - return _connection.connect(_target, ip, port); - } - - int connect(const char *ip, uint16_t port) override { - return _connection.connect(_target, ip, port); - } - - uint8_t connected() override { - return _connection.connected(_target); - } - - void stop() override { - _writer.implicitFlush(_target); - _connection.stop(_target); - } - - operator bool() override { - return _connection.operator_bool(_target); - } - - int read(uint8_t *buf, size_t size) override { - return _reader.read(_target, buf, size); - } - - void flush() override { - _writer.flush(_target); - } - - protected: - Client &_target; - ReadPolicy _reader; - WritePolicy _writer; - ConnectPolicy _connection; -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Clients/HammingClient.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Clients/HammingClient.hpp deleted file mode 100644 index 99442397..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Clients/HammingClient.hpp +++ /dev/null @@ -1,23 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/ConnectForwardingPolicy.hpp" -#include "../Policies/HammingDecodingPolicy.hpp" -#include "../Policies/HammingEncodingPolicy.hpp" -#include "../Ports/DefaultAllocator.hpp" -#include "ClientProxy.hpp" - -namespace StreamUtils { - -template -using BasicHammingClient = ClientProxy, - HammingEncodingPolicy, - ConnectForwardingPolicy>; - -template -using HammingClient = BasicHammingClient; - -} // namespace StreamUtils diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Clients/HammingDecodingClient.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Clients/HammingDecodingClient.hpp deleted file mode 100644 index ab4de20a..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Clients/HammingDecodingClient.hpp +++ /dev/null @@ -1,24 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/ConnectForwardingPolicy.hpp" -#include "../Policies/HammingDecodingPolicy.hpp" -#include "../Policies/WriteForwardingPolicy.hpp" -#include "../Ports/DefaultAllocator.hpp" -#include "ClientProxy.hpp" - -namespace StreamUtils { - -template -using BasicHammingDecodingClient = - ClientProxy, WriteForwardingPolicy, - ConnectForwardingPolicy>; - -template -using HammingDecodingClient = - BasicHammingDecodingClient; - -} // namespace StreamUtils diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Clients/HammingEncodingClient.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Clients/HammingEncodingClient.hpp deleted file mode 100644 index d341b060..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Clients/HammingEncodingClient.hpp +++ /dev/null @@ -1,24 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/ConnectForwardingPolicy.hpp" -#include "../Policies/HammingEncodingPolicy.hpp" -#include "../Policies/ReadForwardingPolicy.hpp" -#include "../Ports/DefaultAllocator.hpp" -#include "ClientProxy.hpp" - -namespace StreamUtils { - -template -using BasicHammingEncodingClient = - ClientProxy, - ConnectForwardingPolicy>; - -template -using HammingEncodingClient = - BasicHammingEncodingClient; - -} // namespace StreamUtils diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Clients/LoggingClient.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Clients/LoggingClient.hpp deleted file mode 100644 index c3c8bcbe..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Clients/LoggingClient.hpp +++ /dev/null @@ -1,23 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/ConnectForwardingPolicy.hpp" -#include "../Policies/ReadLoggingPolicy.hpp" -#include "../Policies/WriteLoggingPolicy.hpp" -#include "ClientProxy.hpp" - -namespace StreamUtils { - -struct LoggingClient : ClientProxy { - LoggingClient(Client &target, Print &log) - : ClientProxy(target, ReadLoggingPolicy{log}, - WriteLoggingPolicy{log}, - ConnectForwardingPolicy{}) {} -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Clients/MemoryClient.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Clients/MemoryClient.hpp deleted file mode 100644 index 2e2447dd..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Clients/MemoryClient.hpp +++ /dev/null @@ -1,92 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include - -#include "../Buffers/CircularBuffer.hpp" -#include "../Configuration.hpp" -#include "../Ports/DefaultAllocator.hpp" -#include "../Streams/MemoryStream.hpp" - -namespace StreamUtils { - -template -class BasicMemoryClient : public Client { - public: - BasicMemoryClient(size_t capacity, TAllocator allocator = TAllocator()) - : _stream(capacity, allocator), _connected(false) {} - - BasicMemoryClient(const BasicMemoryClient &src) : _stream(src._stream) {} - - // --- Print --- - - size_t write(uint8_t data) override { - return _stream.write(data); - } - - size_t write(const uint8_t *data, size_t size) override { - return _stream.write(data, size); - } - - // --- Stream --- - - int available() override { - return _stream.available(); - } - - int peek() override { - return _stream.peek(); - } - - int read() override { - return _stream.read(); - } - -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - size_t readBytes(char *data, size_t size) override { - return _stream.readBytes(data, size); - } -#endif - - void flush() override { - _stream.flush(); - } - - // --- Client --- - - int connect(IPAddress, uint16_t) override { - _connected = true; - return 1; - } - - int connect(const char *, uint16_t) override { - _connected = true; - return 1; - } - - uint8_t connected() override { - return _connected; - } - - void stop() override { - _connected = false; - } - - operator bool() override { - return true; - } - - int read(uint8_t *buf, size_t size) override { - return _stream.readBytes(reinterpret_cast(buf), size); - } - - private: - BasicMemoryStream _stream; - bool _connected; -}; -using MemoryClient = BasicMemoryClient; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Clients/ReadBufferingClient.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Clients/ReadBufferingClient.hpp deleted file mode 100644 index b3b864eb..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Clients/ReadBufferingClient.hpp +++ /dev/null @@ -1,30 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/ConnectForwardingPolicy.hpp" -#include "../Policies/ReadBufferingPolicy.hpp" -#include "../Policies/WriteForwardingPolicy.hpp" -#include "../Ports/DefaultAllocator.hpp" -#include "ClientProxy.hpp" - -namespace StreamUtils { - -template -class BasicReadBufferingClient - : public ClientProxy, WriteForwardingPolicy, - ConnectForwardingPolicy> { - using base_type = ClientProxy, - WriteForwardingPolicy, ConnectForwardingPolicy>; - - public: - explicit BasicReadBufferingClient(Client &target, size_t capacity, - TAllocator allocator = TAllocator()) - : base_type(target, ReadBufferingPolicy{capacity, allocator}, - WriteForwardingPolicy{}, ConnectForwardingPolicy{}) {} -}; - -using ReadBufferingClient = BasicReadBufferingClient; -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Clients/ReadLoggingClient.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Clients/ReadLoggingClient.hpp deleted file mode 100644 index 627af07b..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Clients/ReadLoggingClient.hpp +++ /dev/null @@ -1,23 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/ConnectForwardingPolicy.hpp" -#include "../Policies/ReadLoggingPolicy.hpp" -#include "../Policies/WriteForwardingPolicy.hpp" -#include "ClientProxy.hpp" - -namespace StreamUtils { - -struct ReadLoggingClient : ClientProxy { - ReadLoggingClient(Client &target, Print &log) - : ClientProxy(target, ReadLoggingPolicy{log}, - WriteForwardingPolicy{}, - ConnectForwardingPolicy{}) {} -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Clients/SpyingClient.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Clients/SpyingClient.hpp deleted file mode 100644 index eaba9af5..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Clients/SpyingClient.hpp +++ /dev/null @@ -1,21 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/ConnectSpyingPolicy.hpp" -#include "../Policies/ReadSpyingPolicy.hpp" -#include "../Policies/WriteSpyingPolicy.hpp" -#include "ClientProxy.hpp" - -namespace StreamUtils { - -struct SpyingClient - : ClientProxy { - SpyingClient(Client &target, Print &log) - : ClientProxy( - target, {log}, {log}, {log}) {} -}; - -} // namespace StreamUtils diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Clients/WriteBufferingClient.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Clients/WriteBufferingClient.hpp deleted file mode 100644 index 4f207cb9..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Clients/WriteBufferingClient.hpp +++ /dev/null @@ -1,29 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/ConnectForwardingPolicy.hpp" -#include "../Policies/ReadForwardingPolicy.hpp" -#include "../Policies/WriteBufferingPolicy.hpp" -#include "../Ports/DefaultAllocator.hpp" -#include "ClientProxy.hpp" - -namespace StreamUtils { - -template -struct BasicWriteBufferingClient - : ClientProxy, - ConnectForwardingPolicy> { - explicit BasicWriteBufferingClient(Client &target, size_t capacity, - TAllocator allocator = TAllocator()) - : ClientProxy, - ConnectForwardingPolicy>( - target, ReadForwardingPolicy{}, - WriteBufferingPolicy{capacity, allocator}, - ConnectForwardingPolicy{}) {} -}; - -using WriteBufferingClient = BasicWriteBufferingClient; -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Clients/WriteLoggingClient.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Clients/WriteLoggingClient.hpp deleted file mode 100644 index 5b07a179..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Clients/WriteLoggingClient.hpp +++ /dev/null @@ -1,24 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/ConnectForwardingPolicy.hpp" -#include "../Policies/ReadForwardingPolicy.hpp" -#include "../Policies/WriteLoggingPolicy.hpp" -#include "ClientProxy.hpp" - -namespace StreamUtils { - -struct WriteLoggingClient - : ClientProxy { - WriteLoggingClient(Client &target, Print &log) - : ClientProxy(target, ReadForwardingPolicy{}, - WriteLoggingPolicy{log}, - ConnectForwardingPolicy{}) {} -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Clients/WriteWaitingClient.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Clients/WriteWaitingClient.hpp deleted file mode 100644 index 3e1894ca..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Clients/WriteWaitingClient.hpp +++ /dev/null @@ -1,30 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/ConnectForwardingPolicy.hpp" -#include "../Policies/ReadForwardingPolicy.hpp" -#include "../Policies/WriteWaitingPolicy.hpp" -#include "ClientProxy.hpp" - -namespace StreamUtils { - -struct WriteWaitingClient - : ClientProxy { - WriteWaitingClient(Client &target, Polyfills::function wait = yield) - : ClientProxy( - target, ReadForwardingPolicy{}, - WriteWaitingPolicy{Polyfills::move(wait)}, - ConnectForwardingPolicy{}) {} - - void setTimeout(unsigned long timeout) { - Client::setTimeout(timeout); - _writer.setTimeout(timeout); - } -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Configuration.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Configuration.hpp deleted file mode 100644 index ec149566..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Configuration.hpp +++ /dev/null @@ -1,53 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#ifndef STREAMUTILS_PRINT_FLUSH_EXISTS -#if defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_SAMD) || \ - defined(ARDUINO_ARCH_AVR) -#define STREAMUTILS_PRINT_FLUSH_EXISTS 1 -#else -#define STREAMUTILS_PRINT_FLUSH_EXISTS 0 -#endif -#endif - -#ifndef STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL -#if defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32) || \ - defined(ARDUINO_ARCH_STM32) -#define STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL 1 -#else -#define STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL 0 -#endif -#endif - -#ifndef STREAMUTILS_ENABLE_EEPROM -#if defined(ARDUINO_ARCH_AVR) || defined(ARDUINO_ARCH_ESP8266) || \ - defined(ARDUINO_ARCH_ESP32) || defined(ARDUINO_ARCH_STM32) || \ - defined(CORE_TEENSY) -#define STREAMUTILS_ENABLE_EEPROM 1 -#else -#define STREAMUTILS_ENABLE_EEPROM 0 -#endif -#endif - -#ifndef STREAMUTILS_USE_EEPROM_COMMIT -#if defined(ARDUINO_ARCH_ESP8266) || defined(ARDUINO_ARCH_ESP32) -#define STREAMUTILS_USE_EEPROM_COMMIT 1 -#else -#define STREAMUTILS_USE_EEPROM_COMMIT 0 -#endif -#endif - -#ifndef STREAMUTILS_USE_EEPROM_UPDATE -#if defined(ARDUINO_ARCH_AVR) || defined(CORE_TEENSY) -#define STREAMUTILS_USE_EEPROM_UPDATE 1 -#else -#define STREAMUTILS_USE_EEPROM_UPDATE 0 -#endif -#endif - -#ifndef STREAMUTILS_STACK_BUFFER_MAX_SIZE -#define STREAMUTILS_STACK_BUFFER_MAX_SIZE 32 -#endif \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Helpers.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Helpers.hpp deleted file mode 100644 index 9bd219c7..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Helpers.hpp +++ /dev/null @@ -1,17 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -namespace StreamUtils { - -inline size_t readOrReadBytes(Stream &stream, char *buffer, size_t size) { - return stream.readBytes(buffer, size); -} - -inline size_t readOrReadBytes(Client &client, char *buffer, size_t size) { - return client.read(reinterpret_cast(buffer), size); -} - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/ConnectForwardingPolicy.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Policies/ConnectForwardingPolicy.hpp deleted file mode 100644 index 1580eee4..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/ConnectForwardingPolicy.hpp +++ /dev/null @@ -1,35 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include - -#include "../Configuration.hpp" - -namespace StreamUtils { - -struct ConnectForwardingPolicy { - int connect(Client& target, const IPAddress& ip, uint16_t port) { - return target.connect(ip, port); - } - - int connect(Client& target, const char* ip, uint16_t port) { - return target.connect(ip, port); - } - - uint8_t connected(Client& target) { - return target.connected(); - } - - void stop(Client& target) { - target.stop(); - } - - bool operator_bool(Client& target) { - return target.operator bool(); - } -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/ConnectSpyingPolicy.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Policies/ConnectSpyingPolicy.hpp deleted file mode 100644 index c004ba02..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/ConnectSpyingPolicy.hpp +++ /dev/null @@ -1,68 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include - -namespace StreamUtils { - -class ConnectSpyingPolicy { - public: - ConnectSpyingPolicy(Print& log) : _log(log) {} - - int connect(Client& target, const IPAddress& ip, uint16_t port) { - _log.print("connect('"); - _log.print(ip); - _log.print("', "); - _log.print(port); - _log.print(") -> "); - - int result = target.connect(ip, port); - _log.println(result); - - return result; - } - - int connect(Client& target, const char* ip, uint16_t port) { - _log.print("connect('"); - _log.print(ip); - _log.print("', "); - _log.print(port); - _log.print(") -> "); - - int result = target.connect(ip, port); - _log.println(result); - - return result; - } - - uint8_t connected(Client& target) { - _log.print("connected() -> "); - - uint8_t result = target.connected(); - _log.println(result); - - return result; - } - - void stop(Client& target) { - _log.print("stop()"); - target.stop(); - } - - bool operator_bool(Client& target) { - _log.print("operator bool() -> "); - - bool result = target.operator bool(); - _log.println(result ? "true" : "false"); - - return result; - } - - private: - Print& _log; -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/HammingDecodingPolicy.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Policies/HammingDecodingPolicy.hpp deleted file mode 100644 index 37bb2ffe..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/HammingDecodingPolicy.hpp +++ /dev/null @@ -1,137 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#if defined(WIN32) || defined(__WIN32) || defined(__WIN32__) -#include -#else -#include -#endif - -#include -#include - -#include "../Configuration.hpp" -#include "../Helpers.hpp" - -namespace StreamUtils { - -template -class HammingDecodingPolicy; - -template -class HammingDecodingPolicy<7, 4, TAllocator> { - const static size_t sizeAllowedOnStack = STREAMUTILS_STACK_BUFFER_MAX_SIZE; - - public: - HammingDecodingPolicy(TAllocator allocator = TAllocator()) - : _allocator(allocator) {} - - int available(Stream &stream) { - int n = stream.available(); - if (_remainder >= 0) - n++; - return n / 2; - } - - template // Stream or Client - int read(TTarget &target) { - if (_remainder < 0) { - _remainder = target.read(); - if (_remainder < 0) - return -1; - } - int c = target.read(); - if (c < 0) - return -1; - int result = decode(_remainder, c); - _remainder = -1; - return result; - } - - int peek(Stream &stream) { - if (_remainder < 0) { - _remainder = stream.read(); - if (_remainder < 0) - return -1; - } - int c = stream.peek(); - if (c < 0) - return -1; - return decode(_remainder, c); - } - - size_t readBytes(Stream &stream, char *buffer, size_t size) { - return doReadBytes(stream, buffer, size); - } - - int read(Client &client, uint8_t *buffer, size_t size) { - return doReadBytes(client, reinterpret_cast(buffer), size); - } - - private: - // Decode 7-bits to 4-bits using Hamming(7,4) - uint8_t decode(uint8_t input) { - // table is packed: each element contains two 4-bits values - static uint8_t table[] = { - 0x00, 0x03, 0x05, 0xE7, 0x09, 0xEB, 0xED, 0xEE, 0x03, 0x33, 0x4D, - 0x63, 0x8D, 0xA3, 0xDD, 0xED, 0x05, 0x2B, 0x55, 0x65, 0x8B, 0xBB, - 0xC5, 0xEB, 0x81, 0x63, 0x65, 0x66, 0x88, 0x8B, 0x8D, 0x6F, 0x09, - 0x27, 0x47, 0x77, 0x99, 0xA9, 0xC9, 0xE7, 0x41, 0xA3, 0x44, 0x47, - 0xA9, 0xAA, 0x4D, 0xAF, 0x21, 0x22, 0xC5, 0x27, 0xC9, 0x2B, 0xCC, - 0xCF, 0x11, 0x21, 0x41, 0x6F, 0x81, 0xAF, 0xCF, 0xFF}; - uint8_t elem = table[input / 2]; - if (input % 2) - return elem & 0x0f; - - else - return elem >> 4; - } - - uint8_t decode(uint8_t first, uint8_t second) { - return decode(first) << 4 | decode(second); - } - - template // Stream or Client - size_t doReadBytes(TTarget &target, char *output, size_t outputSize) { - char *buffer; - size_t bufferSize = outputSize * 2; - - if (bufferSize > sizeAllowedOnStack) { - buffer = static_cast(_allocator.allocate(bufferSize)); - if (!buffer) { - // allocation failed => use the input buffer - bufferSize = outputSize; - buffer = output; - } - } else { - buffer = static_cast(alloca(bufferSize)); - } - - size_t loadedSize = 0; - if (_remainder >= 0) - buffer[loadedSize++] = _remainder; - - loadedSize += - readOrReadBytes(target, buffer + loadedSize, bufferSize - loadedSize); - for (size_t i = 0; i < loadedSize / 2; i++) - output[i] = decode(buffer[2 * i], buffer[2 * i + 1]); - - if (loadedSize % 2) - _remainder = buffer[loadedSize - 1]; - else - _remainder = -1; - - if (bufferSize > sizeAllowedOnStack) - _allocator.deallocate(buffer); - - return loadedSize / 2; - } - - TAllocator _allocator; - char _remainder = -1; -}; - -} // namespace StreamUtils diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/HammingEncodingPolicy.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Policies/HammingEncodingPolicy.hpp deleted file mode 100644 index f7d281ec..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/HammingEncodingPolicy.hpp +++ /dev/null @@ -1,116 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#if defined(WIN32) || defined(__WIN32) || defined(__WIN32__) -#include -#else -#include -#endif - -#include "../Configuration.hpp" - -namespace StreamUtils { - -template -class HammingEncodingPolicy; - -template -class HammingEncodingPolicy<7, 4, TAllocator> { - const static size_t sizeAllowedOnStack = STREAMUTILS_STACK_BUFFER_MAX_SIZE; - - public: - HammingEncodingPolicy(TAllocator allocator = TAllocator()) - : _allocator(allocator) {} - - size_t write(Print &target, const uint8_t *data, size_t size) { - if (!flushRemainder(target)) - return 0; - - size_t bufferSize = size * 2; - uint8_t *buffer; - if (bufferSize > sizeAllowedOnStack) { - buffer = static_cast(_allocator.allocate(bufferSize)); - if (!buffer) { - bufferSize = sizeAllowedOnStack; - buffer = static_cast(alloca(bufferSize)); - } - } else { - buffer = static_cast(alloca(bufferSize)); - } - - for (size_t i = 0, j = 0; j < bufferSize; i++) { - buffer[j++] = encode(data[i] >> 4); - buffer[j++] = encode(data[i] & 0x0f); - } - size_t n = target.write(buffer, bufferSize); - if (n & 1) { - _remainder = buffer[n]; - ++n; - } - - if (bufferSize > sizeAllowedOnStack) - _allocator.deallocate(buffer); - - return n / 2; - } - - size_t write(Print &target, uint8_t data) { - uint8_t first = encode(data >> 4); - uint8_t second = encode(data & 0x0f); - - if (!flushRemainder(target)) - return 0; - - if (!target.write(first)) - return 0; - - if (!target.write(second)) - _remainder = second; - - return 1; - } - - void flush(Stream &target) { - flushRemainder(target); - target.flush(); - } - - void flush(Print &target) { - flushRemainder(target); -#if STREAMUTILS_PRINT_FLUSH_EXISTS - target.flush(); -#endif - } - - void implicitFlush(Print &target) { - flushRemainder(target); - } - - private: - // Encode 4-bits to 7-bits using Hamming(7,4) - uint8_t encode(uint8_t input) { - static uint8_t table[] = {0x00, 0x71, 0x62, 0x13, 0x54, 0x25, 0x36, 0x47, - 0x38, 0x49, 0x5A, 0x2B, 0x6C, 0x1D, 0x0E, 0x7F}; - return table[input]; - } - - template - bool flushRemainder(TTarget &target) { - if (_remainder < 0) - return true; - - if (!target.write(_remainder)) - return false; - - _remainder = -1; - return true; - } - - TAllocator _allocator; - int16_t _remainder = -1; -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/ReadBufferingPolicy.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Policies/ReadBufferingPolicy.hpp deleted file mode 100644 index 10bc3305..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/ReadBufferingPolicy.hpp +++ /dev/null @@ -1,97 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include - -#include "../Buffers/LinearBuffer.hpp" -#include "../Helpers.hpp" - -namespace StreamUtils { - -template -struct ReadBufferingPolicy { - ReadBufferingPolicy(size_t capacity, TAllocator allocator = TAllocator()) - : _buffer(capacity, allocator) {} - - ReadBufferingPolicy(const ReadBufferingPolicy &other) - : _buffer(other._buffer) {} - - int available(Stream &stream) { - return stream.available() + _buffer.available(); - } - - template // Stream or Client - int read(TTarget &target) { - if (!_buffer) - return target.read(); - - if (_buffer.available() > 0) - return _buffer.read(); - - size_t avail = static_cast(target.available()); - if (avail <= 1) - return target.read(); - - _buffer.reloadFrom(target, avail); - return _buffer.read(); - } - - int peek(Stream &stream) { - return isEmpty() ? stream.peek() : _buffer.peek(); - } - - size_t readBytes(Stream &stream, char *buffer, size_t size) { - return doReadBytes(stream, buffer, size); - } - - int read(Client &client, uint8_t *buffer, size_t size) { - return doReadBytes(client, reinterpret_cast(buffer), size); - } - - private: - bool isEmpty() const { - return _buffer.available() == 0; - } - - LinearBuffer _buffer; - - template // Stream or Client - size_t doReadBytes(TTarget &target, char *buffer, size_t size) { - if (!_buffer) - return readOrReadBytes(target, buffer, size); - - size_t result = 0; - - // can we read from buffer? - if (_buffer.available() > 0) { - size_t bytesRead = _buffer.readBytes(buffer, size); - result += bytesRead; - buffer += bytesRead; - size -= bytesRead; - } - - // still something to read? - if (size > 0) { - // (at this point, the buffer is empty) - - size_t avail = static_cast(target.available()); - - // should we use the buffer? - if (avail > size && size < _buffer.capacity()) { - _buffer.reloadFrom(target, avail); - size_t bytesRead = _buffer.readBytes(buffer, size); - result += bytesRead; - } else { - // we can bypass the buffer - result += readOrReadBytes(target, buffer, size); - } - } - - return result; - } -}; // namespace StreamUtils - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/ReadForwardingPolicy.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Policies/ReadForwardingPolicy.hpp deleted file mode 100644 index 02138aba..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/ReadForwardingPolicy.hpp +++ /dev/null @@ -1,33 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include - -namespace StreamUtils { - -struct ReadForwardingPolicy { - int available(Stream &target) { - return target.available(); - } - - int read(Stream &target) { - return target.read(); - } - - int peek(Stream &target) { - return target.peek(); - } - - size_t readBytes(Stream &target, char *buffer, size_t size) { - return target.readBytes(buffer, size); - } - - int read(Client &target, uint8_t *buffer, size_t size) { - return target.read(buffer, size); - } -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/ReadLoggingPolicy.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Policies/ReadLoggingPolicy.hpp deleted file mode 100644 index ce614c34..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/ReadLoggingPolicy.hpp +++ /dev/null @@ -1,46 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include - -namespace StreamUtils { - -class ReadLoggingPolicy { - public: - ReadLoggingPolicy(Print &log) : _log(log) {} - - int available(Stream &stream) { - return stream.available(); - } - - int read(Stream &stream) { - int result = stream.read(); - if (result >= 0) - _log.write(result); - return result; - } - - int peek(Stream &stream) { - return stream.peek(); - } - - size_t readBytes(Stream &stream, char *buffer, size_t size) { - size_t result = stream.readBytes(buffer, size); - _log.write(buffer, result); - return result; - } - - int read(Client &client, uint8_t *buffer, size_t size) { - int result = client.read(buffer, size); - _log.write(buffer, result); - return result; - } - - private: - Print &_log; -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/ReadSpyingPolicy.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Policies/ReadSpyingPolicy.hpp deleted file mode 100644 index 0cfb6ac2..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/ReadSpyingPolicy.hpp +++ /dev/null @@ -1,64 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include - -namespace StreamUtils { - -class ReadSpyingPolicy { - public: - ReadSpyingPolicy(Print &log) : _log(log) {} - - int available(Stream &target) { - int result = target.available(); - _log.print("available() -> "); - _log.println(result); - return result; - } - - int read(Stream &target) { - int result = target.read(); - _log.print("read() -> "); - _log.println(result); - return result; - } - - int peek(Stream &target) { - int result = target.peek(); - _log.print("peek() -> "); - _log.println(result); - return result; - } - - size_t readBytes(Stream &target, char *buffer, size_t size) { - size_t result = target.readBytes(buffer, size); - _log.print("readBytes("); - _log.print(size); - _log.print(") -> "); - _log.print(result); - if (size > result) - _log.print(" [timeout]"); - _log.println(); - return result; - } - - int read(Client &target, uint8_t *buffer, size_t size) { - int result = target.read(buffer, size); - _log.print("read("); - _log.print(size); - _log.print(") -> "); - _log.print(result); - if (static_cast(size) > result) - _log.print(" [timeout]"); - _log.println(); - return result; - } - - private: - Print &_log; -}; - -} // namespace StreamUtils diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/ReadThrottlingPolicy.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Policies/ReadThrottlingPolicy.hpp deleted file mode 100644 index 51e01a81..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/ReadThrottlingPolicy.hpp +++ /dev/null @@ -1,47 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include - -namespace StreamUtils { - -template -struct ReadThrottlingPolicy { - ReadThrottlingPolicy(TThrottler throttler) : _throttler(throttler) {} - - int available(Stream &stream) { - return stream.available(); - } - - int read(Stream &stream) { - _throttler.throttle(); - return stream.read(); - } - - int peek(Stream &stream) { - _throttler.throttle(); - return stream.peek(); - } - - size_t readBytes(Stream &stream, char *buffer, size_t size) { - for (size_t i = 0; i < size; i++) { - int c = read(stream); - if (c < 0) - return i; - buffer[i] = c; - } - return size; - } - - const TThrottler &throttler() const { - return _throttler; - } - - private: - TThrottler _throttler; -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/WriteBufferingPolicy.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Policies/WriteBufferingPolicy.hpp deleted file mode 100644 index 53a2b974..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/WriteBufferingPolicy.hpp +++ /dev/null @@ -1,78 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include - -#include "../Buffers/LinearBuffer.hpp" -#include "../Configuration.hpp" - -namespace StreamUtils { - -template -struct WriteBufferingPolicy { - public: - WriteBufferingPolicy(size_t capacity, TAllocator allocator) - : _buffer(capacity, allocator) {} - - size_t write(Print &target, const uint8_t *data, size_t size) { - size_t result = 0; - - // continue to fill the buffer? - if (!_buffer.isEmpty()) { - size_t n = _buffer.write(data, size); - data += n; - size -= n; - result += n; - - // time to flush? - if (_buffer.isFull()) { - _buffer.flushInto(target); - } - } - - // something left to write? - if (size > 0) { - // can we bypass the buffer? - if (size >= _buffer.capacity()) { - result += target.write(data, size); - } else { - result += _buffer.write(data, size); - } - } - return result; - } - - size_t write(Print &target, uint8_t data) { - if (!_buffer) - return target.write(data); - - _buffer.write(data); - if (_buffer.isFull()) - _buffer.flushInto(target); - return 1; - } - - void flush(Stream &target) { - _buffer.flushInto(target); - target.flush(); - } - - void flush(Print &target) { - _buffer.flushInto(target); -#if STREAMUTILS_PRINT_FLUSH_EXISTS - target.flush(); -#endif - } - - void implicitFlush(Print &target) { - _buffer.flushInto(target); - } - - private: - LinearBuffer _buffer; -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/WriteForwardingPolicy.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Policies/WriteForwardingPolicy.hpp deleted file mode 100644 index fac36cce..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/WriteForwardingPolicy.hpp +++ /dev/null @@ -1,27 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include -#include - -#include "../Configuration.hpp" - -namespace StreamUtils { - -struct WriteForwardingPolicy { - template - size_t write(Stream &stream, Args... args) { - return stream.write(args...); - } - - void flush(Stream &stream) { - stream.flush(); - } - - void implicitFlush(Stream &) {} -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/WriteLoggingPolicy.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Policies/WriteLoggingPolicy.hpp deleted file mode 100644 index c4378af3..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/WriteLoggingPolicy.hpp +++ /dev/null @@ -1,39 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include -#include "../Configuration.hpp" - -namespace StreamUtils { - -class WriteLoggingPolicy { - public: - WriteLoggingPolicy(Print &log) : _log(log) {} - - size_t write(Print &target, const uint8_t *buffer, size_t size) { - size_t result = target.write(buffer, size); - _log.write(buffer, result); - return result; - } - - size_t write(Print &target, uint8_t c) { - size_t result = target.write(c); - _log.write(c); - return result; - } - - template - void flush(TTarget &target) { - target.flush(); - } - - void implicitFlush(Print &) {} - - private: - Print &_log; -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/WriteSpyingPolicy.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Policies/WriteSpyingPolicy.hpp deleted file mode 100644 index 24ee2f3e..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/WriteSpyingPolicy.hpp +++ /dev/null @@ -1,55 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include - -#include "../Configuration.hpp" - -namespace StreamUtils { - -class WriteSpyingPolicy { - public: - WriteSpyingPolicy(Print &log) : _log(log) {} - - size_t write(Print &stream, const uint8_t *buffer, size_t size) { - _log.print("write('"); - for (size_t i = 0; i < size; i++) { - _log.write(buffer[i]); - } - _log.print("', "); - _log.print(size); - _log.print(") -> "); - - size_t result = stream.write(buffer, size); - _log.println(result); - - return result; - } - - size_t write(Print &stream, uint8_t data) { - _log.print("write('"); - _log.write(data); - _log.print("') -> "); - - size_t result = stream.write(data); - _log.println(result); - - return result; - } - - template - void flush(TTarget &target) { - _log.println("flush()"); - target.flush(); - } - - void implicitFlush(Print &) {} - - private: - Print &_log; -}; - -} // namespace StreamUtils diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/WriteWaitingPolicy.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Policies/WriteWaitingPolicy.hpp deleted file mode 100644 index 744fb80c..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Policies/WriteWaitingPolicy.hpp +++ /dev/null @@ -1,63 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include - -#include "../Buffers/LinearBuffer.hpp" -#include "../Configuration.hpp" -#include "../Polyfills.hpp" - -namespace StreamUtils { - -struct WriteWaitingPolicy { - public: - WriteWaitingPolicy(Polyfills::function wait) - : _wait(Polyfills::move(wait)), _timeout(1000) {} - - size_t write(Print &target, const uint8_t *data, size_t size) { - unsigned long startTime = millis(); - size_t totalWritten = 0; - - for (;;) { - size_t n = target.write(data, size); - size -= n; - data += n; - totalWritten += n; - if (size == 0 || millis() - startTime >= _timeout) - return totalWritten; - _wait(); - } - } - - size_t write(Print &target, uint8_t data) { - unsigned long startTime = millis(); - - for (;;) { - if (target.write(data)) - return 1; - if (millis() - startTime >= _timeout) - return 0; - _wait(); - } - } - - template - void flush(TTarget &target) { - target.flush(); - } - - void implicitFlush(Print &) {} - - void setTimeout(unsigned long timeout) { - _timeout = timeout; - } - - private: - Polyfills::function _wait; - unsigned long _timeout; -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Polyfills.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Polyfills.hpp deleted file mode 100644 index aa4b50bc..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Polyfills.hpp +++ /dev/null @@ -1,60 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -namespace StreamUtils { -namespace Polyfills { - -template -struct remove_reference { - using type = T; -}; - -template -struct remove_reference { - using type = T; -}; - -template -typename remove_reference::type &&move(T &&t) { - return static_cast::type &&>(t); -} - -// poor man's std::function -class function { - struct callable_base { - virtual void operator()() = 0; - virtual ~callable_base() {} - }; - - template - struct callable : callable_base { - Functor functor; - callable(Functor functor) : functor(functor) {} - virtual void operator()() { - functor(); - } - }; - - callable_base *_callable; - - public: - template - function(Functor f) { - _callable = new callable(f); - } - function(function &&src) { - _callable = src._callable, src._callable = 0; - } - ~function() { - delete _callable; - } - void operator()() const { - (*_callable)(); - } -}; - -} // namespace Polyfills -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Ports/ArduinoThrottler.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Ports/ArduinoThrottler.hpp deleted file mode 100644 index 0efda001..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Ports/ArduinoThrottler.hpp +++ /dev/null @@ -1,29 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -namespace StreamUtils { - -class ArduinoThrottler { - public: - ArduinoThrottler(uint32_t rate) : _interval(1000000 / rate), _last(0) {} - - void throttle() { - auto now = micros(); - auto elapsed = now - _last; - - if (elapsed < _interval) { - delayMicroseconds(_interval - elapsed); - } - - _last = now; - } - - private: - unsigned long _interval; - unsigned long _last; -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Ports/DefaultAllocator.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Ports/DefaultAllocator.hpp deleted file mode 100644 index e3bf1541..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Ports/DefaultAllocator.hpp +++ /dev/null @@ -1,21 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -namespace StreamUtils { - -#include // malloc, free, size_t - -struct DefaultAllocator { - void* allocate(size_t n) { - return malloc(n); - } - - void deallocate(void* p) { - free(p); - } -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Prints/BufferingPrint.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Prints/BufferingPrint.hpp deleted file mode 100644 index 904ba219..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Prints/BufferingPrint.hpp +++ /dev/null @@ -1,22 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/WriteBufferingPolicy.hpp" -#include "../Ports/DefaultAllocator.hpp" -#include "PrintProxy.hpp" - -namespace StreamUtils { - -template -struct BasicBufferingPrint : PrintProxy> { - explicit BasicBufferingPrint(Print &upstream, size_t capacity, - TAllocator allocator = TAllocator()) - : PrintProxy>(upstream, - {capacity, allocator}) {} -}; - -using BufferingPrint = BasicBufferingPrint; -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Prints/HammingPrint.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Prints/HammingPrint.hpp deleted file mode 100644 index 9d0236ab..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Prints/HammingPrint.hpp +++ /dev/null @@ -1,19 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/HammingEncodingPolicy.hpp" -#include "../Ports/DefaultAllocator.hpp" -#include "PrintProxy.hpp" - -namespace StreamUtils { - -template -using BasicHammingPrint = PrintProxy>; - -template -using HammingPrint = BasicHammingPrint; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Prints/LoggingPrint.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Prints/LoggingPrint.hpp deleted file mode 100644 index cfd33741..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Prints/LoggingPrint.hpp +++ /dev/null @@ -1,17 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/WriteLoggingPolicy.hpp" -#include "PrintProxy.hpp" - -namespace StreamUtils { - -struct LoggingPrint : PrintProxy { - LoggingPrint(Print &upstream, Print &log) - : PrintProxy(upstream, {log}) {} -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Prints/PrintProxy.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Prints/PrintProxy.hpp deleted file mode 100644 index fcb6860e..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Prints/PrintProxy.hpp +++ /dev/null @@ -1,50 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include - -#include "../Configuration.hpp" -#include "../Polyfills.hpp" - -namespace StreamUtils { - -template -class PrintProxy : public Print { - public: - explicit PrintProxy(Print &upstream, WritePolicy writer = WritePolicy{}) - : _target(upstream), _writer(Polyfills::move(writer)) {} - - PrintProxy(const PrintProxy &other) - : _target(other._target), _writer(other._writer) {} - - ~PrintProxy() { - _writer.implicitFlush(_target); - } - - size_t write(const uint8_t *buffer, size_t size) override { - return _writer.write(_target, buffer, size); - } - - size_t write(uint8_t data) override { - return _writer.write(_target, data); - } - -#if STREAMUTILS_PRINT_FLUSH_EXISTS - void flush() override { -#else - void flush() { -#endif - _writer.flush(_target); - } - - using Print::write; - - protected: - Print &_target; - WritePolicy _writer; -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Prints/SpyingPrint.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Prints/SpyingPrint.hpp deleted file mode 100644 index c8262ef1..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Prints/SpyingPrint.hpp +++ /dev/null @@ -1,17 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/WriteSpyingPolicy.hpp" -#include "PrintProxy.hpp" - -namespace StreamUtils { - -struct SpyingPrint : PrintProxy { - SpyingPrint(Print &target, Print &log) - : PrintProxy(target, WriteSpyingPolicy{log}) {} -}; - -} // namespace StreamUtils diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Prints/StringPrint.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Prints/StringPrint.hpp deleted file mode 100644 index 0f344980..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Prints/StringPrint.hpp +++ /dev/null @@ -1,52 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include -#include - -#include "../Polyfills.hpp" - -namespace StreamUtils { - -class StringPrint : public Print { - public: - StringPrint() {} - - explicit StringPrint(String str) : _str(Polyfills::move(str)) {} - - size_t write(const uint8_t* p, size_t n) override { - for (size_t i = 0; i < n; i++) { - uint8_t c = p[i]; - if (c == 0) - return i; - write(c); - } - return n; - } - - size_t write(uint8_t c) override { - if (c == 0) - return 0; - _str += static_cast(c); - return 1; - } - - const String& str() const { - return _str; - } - - void str(String str) { - _str = Polyfills::move(str); - } - - void clear() { - _str = ""; - } - - private: - String _str; -}; -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Prints/WaitingPrint.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Prints/WaitingPrint.hpp deleted file mode 100644 index 05d05b47..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Prints/WaitingPrint.hpp +++ /dev/null @@ -1,22 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/WriteWaitingPolicy.hpp" -#include "PrintProxy.hpp" - -namespace StreamUtils { - -struct WaitingPrint : PrintProxy { - WaitingPrint(Print &target, Polyfills::function wait = yield) - : PrintProxy( - target, WriteWaitingPolicy{Polyfills::move(wait)}) {} - - void setTimeout(unsigned long timeout) { - _writer.setTimeout(timeout); - } -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/EepromStream.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Streams/EepromStream.hpp deleted file mode 100644 index d28bccbd..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/EepromStream.hpp +++ /dev/null @@ -1,76 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Configuration.hpp" - -#if STREAMUTILS_ENABLE_EEPROM - -#include -#include - -namespace StreamUtils { - -class EepromStream : public Stream { - public: - EepromStream(size_t address, size_t size) - : _readAddress(address), _writeAddress(address), _end(address + size) {} - - int available() override { - return _end - _readAddress; - } - - int read() override { - if (_readAddress >= _end) - return -1; - return EEPROM.read(_readAddress++); - } - - int peek() override { - if (_readAddress >= _end) - return -1; - return EEPROM.read(_readAddress); - } - - void flush() override { -#if STREAMUTILS_USE_EEPROM_COMMIT - EEPROM.commit(); -#endif - } - - using Print::write; - - size_t write(const uint8_t *buffer, size_t size) override { - size_t remaining = _end - _writeAddress; - if (size > remaining) - size = remaining; - for (size_t i = 0; i < size; i++) { -#if STREAMUTILS_USE_EEPROM_UPDATE - EEPROM.update(_writeAddress++, buffer[i]); -#else - EEPROM.write(_writeAddress++, buffer[i]); -#endif - } - return size; - } - - size_t write(uint8_t data) override { - if (_writeAddress >= _end) - return 0; -#if STREAMUTILS_USE_EEPROM_UPDATE - EEPROM.update(_writeAddress++, data); -#else - EEPROM.write(_writeAddress++, data); -#endif - return 1; - } - - private: - size_t _readAddress, _writeAddress, _end; -}; - -} // namespace StreamUtils - -#endif diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/HammingDecodingStream.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Streams/HammingDecodingStream.hpp deleted file mode 100644 index 4003eee0..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/HammingDecodingStream.hpp +++ /dev/null @@ -1,22 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/HammingDecodingPolicy.hpp" -#include "../Policies/WriteForwardingPolicy.hpp" -#include "../Ports/DefaultAllocator.hpp" -#include "StreamProxy.hpp" - -namespace StreamUtils { - -template -using BasicHammingDecodingStream = - StreamProxy, WriteForwardingPolicy>; - -template -using HammingDecodingStream = - BasicHammingDecodingStream; - -} // namespace StreamUtils diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/HammingEncodingStream.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Streams/HammingEncodingStream.hpp deleted file mode 100644 index 59a80934..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/HammingEncodingStream.hpp +++ /dev/null @@ -1,22 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/HammingEncodingPolicy.hpp" -#include "../Policies/ReadForwardingPolicy.hpp" -#include "../Ports/DefaultAllocator.hpp" -#include "StreamProxy.hpp" - -namespace StreamUtils { - -template -using BasicHammingEncodingStream = - StreamProxy>; - -template -using HammingEncodingStream = - BasicHammingEncodingStream; - -} // namespace StreamUtils diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/HammingStream.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Streams/HammingStream.hpp deleted file mode 100644 index 68e8f70d..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/HammingStream.hpp +++ /dev/null @@ -1,21 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/HammingDecodingPolicy.hpp" -#include "../Policies/HammingEncodingPolicy.hpp" -#include "../Ports/DefaultAllocator.hpp" -#include "StreamProxy.hpp" - -namespace StreamUtils { - -template -using BasicHammingStream = StreamProxy, - HammingEncodingPolicy>; - -template -using HammingStream = BasicHammingStream; - -} // namespace StreamUtils diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/LoggingStream.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Streams/LoggingStream.hpp deleted file mode 100644 index 3e7e789a..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/LoggingStream.hpp +++ /dev/null @@ -1,19 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/ReadLoggingPolicy.hpp" -#include "../Policies/WriteLoggingPolicy.hpp" -#include "StreamProxy.hpp" - -namespace StreamUtils { - -struct LoggingStream : StreamProxy { - LoggingStream(Stream& target, Print& log) - : StreamProxy( - target, ReadLoggingPolicy{log}, WriteLoggingPolicy{log}) {} -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/MemoryStream.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Streams/MemoryStream.hpp deleted file mode 100644 index 1b027e4f..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/MemoryStream.hpp +++ /dev/null @@ -1,61 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include - -#include "../Buffers/CircularBuffer.hpp" -#include "../Configuration.hpp" -#include "../Ports/DefaultAllocator.hpp" - -namespace StreamUtils { - -template -class BasicMemoryStream : public Stream { - public: - BasicMemoryStream(size_t capacity, TAllocator allocator = TAllocator()) - : _buffer(capacity, allocator) {} - - BasicMemoryStream(const BasicMemoryStream &src) : _buffer(src._buffer) {} - - int available() override { - return static_cast(_buffer.available()); - } - - int peek() override { - return _buffer.isEmpty() ? -1 : _buffer.peek(); - } - - int read() override { - return _buffer.isEmpty() ? -1 : _buffer.read(); - } - -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - size_t readBytes(char *data, size_t size) override { - return _buffer.readBytes(data, size); - } -#endif - - size_t write(uint8_t data) override { - return _buffer.isFull() ? 0 : _buffer.write(data); - } - - size_t write(const uint8_t *data, size_t size) override { - return _buffer.write(data, size); - } - - using Stream::write; - - void flush() override { - _buffer.clear(); - } - - private: - CircularBuffer _buffer; -}; - -using MemoryStream = BasicMemoryStream; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/ReadBufferingStream.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Streams/ReadBufferingStream.hpp deleted file mode 100644 index 11805937..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/ReadBufferingStream.hpp +++ /dev/null @@ -1,28 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/ReadBufferingPolicy.hpp" -#include "../Policies/WriteForwardingPolicy.hpp" -#include "../Ports/DefaultAllocator.hpp" -#include "StreamProxy.hpp" - -namespace StreamUtils { - -template -class BasicReadBufferingStream - : public StreamProxy, - WriteForwardingPolicy> { - using base_type = - StreamProxy, WriteForwardingPolicy>; - - public: - explicit BasicReadBufferingStream(Stream &upstream, size_t capacity, - TAllocator allocator = TAllocator()) - : base_type(upstream, {capacity, allocator}, {}) {} -}; - -using ReadBufferingStream = BasicReadBufferingStream; -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/ReadLoggingStream.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Streams/ReadLoggingStream.hpp deleted file mode 100644 index 50f92b01..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/ReadLoggingStream.hpp +++ /dev/null @@ -1,19 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/ReadLoggingPolicy.hpp" -#include "../Policies/WriteForwardingPolicy.hpp" -#include "StreamProxy.hpp" - -namespace StreamUtils { - -struct ReadLoggingStream - : StreamProxy { - ReadLoggingStream(Stream &target, Print &log) - : StreamProxy( - target, ReadLoggingPolicy{log}, WriteForwardingPolicy{}) {} -}; -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/ReadThrottlingStream.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Streams/ReadThrottlingStream.hpp deleted file mode 100644 index edafd085..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/ReadThrottlingStream.hpp +++ /dev/null @@ -1,35 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/ReadThrottlingPolicy.hpp" -#include "../Policies/WriteForwardingPolicy.hpp" -#include "StreamProxy.hpp" - -#ifdef ARDUINO -#include "../Ports/ArduinoThrottler.hpp" -#endif - -namespace StreamUtils { - -template -class BasicReadThrottlingStream - : public StreamProxy, - WriteForwardingPolicy> { - public: - BasicReadThrottlingStream(Stream& upstream, - TThrottler throttler = TThrottler()) - : StreamProxy, WriteForwardingPolicy>( - upstream, ReadThrottlingPolicy(throttler), {}) {} - - const TThrottler& throttler() const { - return this->_reader.throttler(); - } -}; - -#ifdef ARDUINO -using ReadThrottlingStream = BasicReadThrottlingStream; -#endif -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/SpyingStream.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Streams/SpyingStream.hpp deleted file mode 100644 index c323a543..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/SpyingStream.hpp +++ /dev/null @@ -1,19 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/ReadSpyingPolicy.hpp" -#include "../Policies/WriteSpyingPolicy.hpp" -#include "StreamProxy.hpp" - -namespace StreamUtils { - -struct SpyingStream : StreamProxy { - SpyingStream(Stream &target, Print &log) - : StreamProxy( - target, ReadSpyingPolicy{log}, WriteSpyingPolicy{log}) {} -}; - -} // namespace StreamUtils diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/StreamProxy.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Streams/StreamProxy.hpp deleted file mode 100644 index c2c95226..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/StreamProxy.hpp +++ /dev/null @@ -1,68 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include -#include "../Polyfills.hpp" - -namespace StreamUtils { - -template -class StreamProxy : public Stream { - public: - explicit StreamProxy(Stream &upstream, ReadPolicy reader = ReadPolicy{}, - WritePolicy writer = WritePolicy{}) - : _upstream(upstream), - _reader(reader), - _writer(Polyfills::move(writer)) {} - - StreamProxy(const StreamProxy &other) - : _upstream(other._upstream), - _reader(other._reader), - _writer(other._writer) {} - - ~StreamProxy() { - _writer.implicitFlush(_upstream); - } - - size_t write(const uint8_t *buffer, size_t size) override { - return _writer.write(_upstream, buffer, size); - } - - size_t write(uint8_t data) override { - return _writer.write(_upstream, data); - } - - using Stream::write; - - int available() override { - return _reader.available(_upstream); - } - - int read() override { - return _reader.read(_upstream); - } - - int peek() override { - return _reader.peek(_upstream); - } - - void flush() override { - _writer.flush(_upstream); - } - -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - size_t readBytes(char *buffer, size_t size) override { - return _reader.readBytes(_upstream, buffer, size); - } -#endif - - protected: - Stream &_upstream; - ReadPolicy _reader; - WritePolicy _writer; -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/StringStream.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Streams/StringStream.hpp deleted file mode 100644 index fa89ecf6..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/StringStream.hpp +++ /dev/null @@ -1,77 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include -#include - -#include "../Configuration.hpp" -#include "../Polyfills.hpp" - -namespace StreamUtils { - -class StringStream : public Stream { - public: - StringStream() {} - - explicit StringStream(String str) : _str(Polyfills::move(str)) {} - - size_t write(const uint8_t* p, size_t n) override { - for (size_t i = 0; i < n; i++) { - uint8_t c = p[i]; - if (c == 0) - return i; - write(c); - } - return n; - } - - size_t write(uint8_t c) override { - if (c == 0) - return 0; - _str += static_cast(c); - return 1; - } - - const String& str() const { - return _str; - } - - void str(String str) { - _str = Polyfills::move(str); - } - - int available() override { - return _str.length(); - } - - int read() override { - if (_str.length() == 0) - return -1; - char c = _str[0]; - _str.remove(0, 1); - return c; - } - -#if STREAMUTILS_STREAM_READBYTES_IS_VIRTUAL - size_t readBytes(char* buffer, size_t length) override { - if (length > _str.length()) - length = _str.length(); - _str.toCharArray(buffer, length); - _str.remove(0, length); - return length; - } -#endif - - int peek() override { - return _str.length() > 0 ? _str[0] : -1; - } - - void flush() override {} - - private: - String _str; -}; -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/WriteBufferingStream.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Streams/WriteBufferingStream.hpp deleted file mode 100644 index 92dda084..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/WriteBufferingStream.hpp +++ /dev/null @@ -1,24 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/ReadForwardingPolicy.hpp" -#include "../Policies/WriteBufferingPolicy.hpp" -#include "../Ports/DefaultAllocator.hpp" -#include "StreamProxy.hpp" - -namespace StreamUtils { - -template -struct BasicWriteBufferingStream - : StreamProxy> { - explicit BasicWriteBufferingStream(Stream &upstream, size_t capacity, - TAllocator allocator = TAllocator()) - : StreamProxy>( - upstream, {}, {capacity, allocator}) {} -}; - -using WriteBufferingStream = BasicWriteBufferingStream; -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/WriteLoggingStream.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Streams/WriteLoggingStream.hpp deleted file mode 100644 index 13275aa4..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/WriteLoggingStream.hpp +++ /dev/null @@ -1,20 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/ReadForwardingPolicy.hpp" -#include "../Policies/WriteLoggingPolicy.hpp" -#include "StreamProxy.hpp" - -namespace StreamUtils { - -struct WriteLoggingStream - : StreamProxy { - WriteLoggingStream(Stream &target, Print &log) - : StreamProxy( - target, ReadForwardingPolicy{}, WriteLoggingPolicy{log}) {} -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/WriteWaitingStream.hpp b/lib/ArduinoStreamUtils/src/StreamUtils/Streams/WriteWaitingStream.hpp deleted file mode 100644 index f8c8d5f8..00000000 --- a/lib/ArduinoStreamUtils/src/StreamUtils/Streams/WriteWaitingStream.hpp +++ /dev/null @@ -1,26 +0,0 @@ -// StreamUtils - github.com/bblanchon/ArduinoStreamUtils -// Copyright Benoit Blanchon 2019-2021 -// MIT License - -#pragma once - -#include "../Policies/ReadForwardingPolicy.hpp" -#include "../Policies/WriteWaitingPolicy.hpp" -#include "StreamProxy.hpp" - -namespace StreamUtils { - -struct WriteWaitingStream - : StreamProxy { - WriteWaitingStream(Stream &target, Polyfills::function wait = yield) - : StreamProxy( - target, ReadForwardingPolicy{}, - WriteWaitingPolicy{Polyfills::move(wait)}) {} - - void setTimeout(unsigned long timeout) { - Stream::setTimeout(timeout); - _writer.setTimeout(timeout); - } -}; - -} // namespace StreamUtils \ No newline at end of file diff --git a/lib/ESP8266-StringCommand/StringCommand.cpp b/lib/ESP8266-StringCommand/StringCommand.cpp deleted file mode 100644 index 3d53dcd7..00000000 --- a/lib/ESP8266-StringCommand/StringCommand.cpp +++ /dev/null @@ -1,137 +0,0 @@ -/** - * SerialCommand - A Wiring/Arduino library to tokenize and parse commands - * received over a serial port. - * - * Copyright (C) 2012 Stefan Rado - * Copyright (C) 2011 Steven Cogswell - * http://husks.wordpress.com - * - * Version 20120522 - * - * This library is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this library. If not, see . - */ -#include "StringCommand.h" - -/** - * Constructor makes sure some things are set. - */ -StringCommand::StringCommand() - : commandList(NULL), - commandCount(0), - defaultHandler(NULL), - term('\n'), // default terminator for commands, newline character - last(NULL), - main(NULL) -{ - strcpy(delim, " "); // strtok_r needs a null-terminated string - clearBuffer(); -} - -/** - * Adds a "command" and a handler function to the list of available commands. - * This is used for matching a found token in the buffer, and gives the pointer - * to the handler function to deal with it. - */ -void StringCommand::addCommand(const char *command, void (*function)()) { - #ifdef SERIALCOMMAND_DEBUG - Serial.print("Adding command ("); - Serial.print(commandCount); - Serial.print("): "); - Serial.println(command); - #endif - - commandList = (StringCommandCallback *) realloc(commandList, (commandCount + 1) * sizeof(StringCommandCallback)); - strncpy(commandList[commandCount].command, command, SERIALCOMMAND_MAXCOMMANDLENGTH); - commandList[commandCount].function = function; - commandCount++; -} - -/** - * This sets up a handler to be called in the event that the receveived command string - * isn't in the list of commands. - */ -void StringCommand::setDefaultHandler(void (*function)(const char *)) { - defaultHandler = function; -} - - -/** - * This checks the Serial stream for characters, and assembles them into a buffer. - * When the terminator character (default '\n') is seen, it starts parsing the - * buffer for a prefix command, and calls handlers setup by addCommand() member - */ -void StringCommand::readStr(String sBuffer ) { - sBuffer.toCharArray(buffer, SERIALCOMMAND_BUFFER); - #ifdef SERIALCOMMAND_DEBUG - Serial.print("Received: "); - Serial.println(buffer); - #endif - - char *command = strtok_r(buffer, delim, &last); // Search for command at start of buffer - if (command != NULL) { - boolean matched = false; - for (int i = 0; i < commandCount; i++) { - #ifdef SERIALCOMMAND_DEBUG - Serial.print("Comparing ["); - Serial.print(command); - Serial.print("] to ["); - Serial.print(commandList[i].command); - Serial.println("]"); - #endif - - - - // Compare the found command against the list of known commands for a match - if (strncmp(command, commandList[i].command, SERIALCOMMAND_MAXCOMMANDLENGTH) == 0) { - #ifdef SERIALCOMMAND_DEBUG - Serial.print("Matched Command: "); - Serial.println(command); - #endif - - // Execute the stored handler function for the command - (*commandList[i].function)(); - matched = true; - break; - } - } - - - if (!matched && (defaultHandler != NULL)) { - (*defaultHandler)(command); - } - - - clearBuffer(); - } -} - -/* - * Clear the input buffer. - */ -void StringCommand::clearBuffer() { - buffer[0] = '\0'; - bufPos = 0; -} - -/** - * Retrieve the next token ("word" or "argument") from the command buffer. - * Returns NULL if no more tokens exist. - */ -char *StringCommand::next() { - return strtok_r(NULL, delim, &last); -} - -char *StringCommand::order() { - return strtok_r(buffer, delim, &main); -} diff --git a/lib/ESP8266-StringCommand/StringCommand.h b/lib/ESP8266-StringCommand/StringCommand.h deleted file mode 100644 index b37d5a1a..00000000 --- a/lib/ESP8266-StringCommand/StringCommand.h +++ /dev/null @@ -1,77 +0,0 @@ -/** - * SerialCommand - A Wiring/Arduino library to tokenize and parse commands - * received over a serial port. - * - * Copyright (C) 2012 Stefan Rado - * Copyright (C) 2011 Steven Cogswell - * http://husks.wordpress.com - * - * Version 20120522 - * - * This library is free software: you can redistribute it and/or modify - * it under the terms of the GNU Lesser General Public License as published by - * the Free Software Foundation, either version 3 of the License, or - * (at your option) any later version. - * - * This library is distributed in the hope that it will be useful, - * but WITHOUT ANY WARRANTY; without even the implied warranty of - * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the - * GNU Lesser General Public License for more details. - * - * You should have received a copy of the GNU General Public License - * along with this library. If not, see . - */ -#ifndef StringCommand_h -#define StringCommand_h - -#if defined(WIRING) && WIRING >= 100 - #include -#elif defined(ARDUINO) && ARDUINO >= 100 - #include -#else - #include -#endif -#include - -// Size of the input buffer in bytes (maximum length of one command plus arguments) -#define SERIALCOMMAND_BUFFER 128 //256 -// Maximum length of a command excluding the terminating null -#define SERIALCOMMAND_MAXCOMMANDLENGTH 16 - -// Uncomment the next line to run the library in debug mode (verbose messages) -//#define SERIALCOMMAND_DEBUG - - -class StringCommand { - public: - StringCommand(); // Constructor - void addCommand(const char *command, void(*function)()); // Add a command to the processing dictionary. - void setDefaultHandler(void (*function)(const char *)); // A handler to call when no valid command received. - - void readStr(String sBuffer ); // Main entry point. - void clearBuffer(); // Clears the input buffer. - char *next(); // Returns pointer to next token found in command buffer (for getting arguments to commands). - char *order(); - - private: - // Command/handler dictionary - struct StringCommandCallback { - char command[SERIALCOMMAND_MAXCOMMANDLENGTH + 1]; - void (*function)(); - }; // Data structure to hold Command/Handler function key-value pairs - StringCommandCallback *commandList; // Actual definition for command/handler array - byte commandCount; - - // Pointer to the default handler function - void (*defaultHandler)(const char *); - - char delim[2]; // null-terminated list of character to be used as delimeters for tokenizing (default " ") - char term; // Character that signals end of command (default '\n') - - char buffer[SERIALCOMMAND_BUFFER + 1]; // Buffer of stored characters while waiting for terminator character - byte bufPos; // Current position in the buffer - char *last; // State variable used by strtok_r during processing - char *main; -}; - -#endif //StringCommand_h diff --git a/lib/ESP8266-StringCommand/keywords.txt b/lib/ESP8266-StringCommand/keywords.txt deleted file mode 100644 index c9799b2c..00000000 --- a/lib/ESP8266-StringCommand/keywords.txt +++ /dev/null @@ -1,23 +0,0 @@ -####################################### -# Datatypes (KEYWORD1) -####################################### - -StringCommand KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -addCommand KEYWORD2 -setDefaultHandler KEYWORD2 -readString KEYWORD2 -clearBuffer KEYWORD2 -next KEYWORD2 - -####################################### -# Instances (KEYWORD2) -####################################### - -####################################### -# Constants (LITERAL1) -####################################### diff --git a/lib/ESP8266-StringCommand/readme.md b/lib/ESP8266-StringCommand/readme.md deleted file mode 100644 index 731ee5e2..00000000 --- a/lib/ESP8266-StringCommand/readme.md +++ /dev/null @@ -1,5 +0,0 @@ -StringCommand -============= -Библиотека для ESP8266 позволяющая связать запуск пользовательских функций с строковой переменной. - - diff --git a/lib/GyverFilters/examples/GFilterRA/GFilterRA.ino b/lib/GyverFilters/examples/GFilterRA/GFilterRA.ino deleted file mode 100644 index c6db1517..00000000 --- a/lib/GyverFilters/examples/GFilterRA/GFilterRA.ino +++ /dev/null @@ -1,16 +0,0 @@ -#include "GyverFilters.h" -GFilterRA analog0; // фильтр назовём analog0 - -void setup() { - Serial.begin(9600); - - // установка коэффициента фильтрации (0.0... 1.0). Чем меньше, тем плавнее фильтр - analog0.setCoef(0.01); - - // установка шага фильтрации (мс). Чем меньше, тем резче фильтр - analog0.setStep(10); -} - -void loop() { - Serial.println(analog0.filteredTime(analogRead(0))); -} diff --git a/lib/GyverFilters/examples/GLinear_arrays/GLinear_arrays.ino b/lib/GyverFilters/examples/GLinear_arrays/GLinear_arrays.ino deleted file mode 100644 index 6c407ec4..00000000 --- a/lib/GyverFilters/examples/GLinear_arrays/GLinear_arrays.ino +++ /dev/null @@ -1,32 +0,0 @@ -/* - Пример линейной аппроксимации методом наименьших квадратов - Два массива: по оси Х и по оси У - Линейная аппроксимация повозоляет получить уравнение прямой, - равноудалённой от точек на плоскости ХУ. Удобно для расчёта - роста изменяющейся шумящей величины. Уравнение вида у = A*x + B - В папке с данным примером есть скриншот из excel, - иллюстрирующий работу аппроксимации с такими же исходными -*/ - -// два массива с данными (одинаковой размероности и размера) -int x_array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; -int y_array[] = {1, 5, 2, 8, 3, 9, 10, 5, 15, 12}; - -#include -GLinear test; // указываем тип данных в <> - -void setup() { - Serial.begin(9600); - - // передаём массивы и размер одного из них - test.compute((int*)x_array, (int*)y_array, sizeof(x_array)); - - // Уравнение вида у = A*x + B - Serial.println(test.getA()); // получить коэффициент А - Serial.println(test.getB()); // получить коэффициент В - Serial.println(test.getDelta()); // получить изменение (аппроксимированное) -} - -void loop() { - -} \ No newline at end of file diff --git a/lib/GyverFilters/examples/GLinear_arrays/excel.jpg b/lib/GyverFilters/examples/GLinear_arrays/excel.jpg deleted file mode 100644 index 9cd71117..00000000 Binary files a/lib/GyverFilters/examples/GLinear_arrays/excel.jpg and /dev/null differ diff --git a/lib/GyverFilters/examples/GLinear_running/GLinear_running.ino b/lib/GyverFilters/examples/GLinear_running/GLinear_running.ino deleted file mode 100644 index 575c50dc..00000000 --- a/lib/GyverFilters/examples/GLinear_running/GLinear_running.ino +++ /dev/null @@ -1,34 +0,0 @@ -/* - Пример линейной аппроксимации методом наименьших квадратов - Два массива: по оси Х и по оси У - Наполнение массивов осуществляется динамически: сдвигом и записью в крайнюю ячейку, - то есть аппроксимация по последним ARRAY_SIZE изменениям!! -*/ -#define ARRAY_SIZE 10 // размер пространства для аппроксимации - -// два массива с данными (одинаковой размероности и размера) -int x_array[ARRAY_SIZE] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; // ось x от 1 до 10, допустим СЕКУНД -int y_array[ARRAY_SIZE]; // значения по оси У будем брать с датчика - -#include -GLinear test; // указываем тип данных в <> - -void setup() { - Serial.begin(9600); -} - -void loop() { - for (byte i = 0; i < ARRAY_SIZE - 1; i++) { // счётчик от 0 до ARRAY_SIZE - y_array[i] = y_array[i + 1]; // сдвинуть массив давлений КРОМЕ ПОСЛЕДНЕЙ ЯЧЕЙКИ на шаг назад - } - // последний элемент массива теперь - новое значение (просто с аналог. датчика) - y_array[ARRAY_SIZE - 1] = analogRead(0); - - // передаём массивы и размер одного из них - test.compute((int*)x_array, (int*)y_array, sizeof(x_array)); - - // по нашим исходным данным это будет производная, т.е. "изменение единиц в секунду" - Serial.println(test.getDelta()); // получить изменение (аппроксимированное) - - delay(1000); // секундная задержка -} diff --git a/lib/GyverFilters/examples/alphabeta_example/alphabeta_example.ino b/lib/GyverFilters/examples/alphabeta_example/alphabeta_example.ino deleted file mode 100644 index 8f43b77a..00000000 --- a/lib/GyverFilters/examples/alphabeta_example/alphabeta_example.ino +++ /dev/null @@ -1,24 +0,0 @@ -/* - Пример альфа-бета фильтра -*/ - -#include "GyverFilters.h" - -// параметры: период дискретизации (измерений), process variation, noise variation -GABfilter testFilter(0.08, 40, 1); - -void setup() { - Serial.begin(9600); -} - -void loop() { - delay(80); - int value = analogRead(0); - value += random(2) * random(-1, 2) * random(10, 70); - Serial.print("$"); - Serial.print(value); - Serial.print(" "); - value = testFilter.filtered((int)value); - Serial.print(value); - Serial.println(";"); -} diff --git a/lib/GyverFilters/examples/filters_comparsion/filters_comparsion.ino b/lib/GyverFilters/examples/filters_comparsion/filters_comparsion.ino deleted file mode 100644 index b981993a..00000000 --- a/lib/GyverFilters/examples/filters_comparsion/filters_comparsion.ino +++ /dev/null @@ -1,30 +0,0 @@ -/* - Сравнение калмана и бегущего среднего -*/ -#include "GyverFilters.h" - -// параметры: разброс измерения, разброс оценки, скорость изменения значений -// разброс измерения: шум измерений -// разброс оценки: подстраивается сам, можно поставить таким же как разброс измерения -// скорость изменения значений: 0.001-1, варьировать самому - -GKalman kalman(90, 90, 0.5); -GFilterRA average(0.5, 80); - -void setup() { - Serial.begin(9600); -} - -void loop() { - int value = analogRead(0); - value += random(2) * random(-1, 2) * random(50, 100); - Serial.print("$"); - Serial.print(value); - Serial.print(" "); - - Serial.print((int)kalman.filtered(value)); - Serial.print(" "); - Serial.print((int)average.filtered(value)); - Serial.println(";"); - delay(80); -} diff --git a/lib/GyverFilters/examples/kalman_example/kalman_example.ino b/lib/GyverFilters/examples/kalman_example/kalman_example.ino deleted file mode 100644 index 802307af..00000000 --- a/lib/GyverFilters/examples/kalman_example/kalman_example.ino +++ /dev/null @@ -1,31 +0,0 @@ -/* - Пример простого одномерного фильтра -*/ - -#include "GyverFilters.h" - -// параметры: разброс измерения, разброс оценки, скорость изменения значений -// разброс измерения: шум измерений -// разброс оценки: подстраивается сам, можно поставить таким же как разброс измерения -// скорость изменения значений: 0.001-1, варьировать самому - -GKalman testFilter(40, 40, 0.5); - -// также может быть объявлен как (разброс измерения, скорость изменения значений) -// GKalman testFilter(40, 0.5); - -void setup() { - Serial.begin(9600); -} - -void loop() { - delay(80); - int value = analogRead(0); - value += random(2) * random(-1, 2) * random(10, 70); - Serial.print("$"); - Serial.print(value); - Serial.print(" "); - value = testFilter.filtered((int)value); - Serial.print(value); - Serial.println(";"); -} diff --git a/lib/GyverFilters/examples/median3_example/median3_example.ino b/lib/GyverFilters/examples/median3_example/median3_example.ino deleted file mode 100644 index c99176bc..00000000 --- a/lib/GyverFilters/examples/median3_example/median3_example.ino +++ /dev/null @@ -1,21 +0,0 @@ -/* - Пример использования быстрого медианного фильтра 3 порядка -*/ - -#include "GyverFilters.h" -GMedian3 testFilter; // указываем тип данных в <> - -void setup() { - Serial.begin(9600); -} - -void loop() { - int value = analogRead(0); - // добавляем шум "выбросы" - value += random(2) * random(2) * random(-1, 2) * random(50, 250); - Serial.print(value); - Serial.print(','); - value = testFilter.filtered(value); - Serial.println(value); - delay(80); -} diff --git a/lib/GyverFilters/examples/median_example/median_example.ino b/lib/GyverFilters/examples/median_example/median_example.ino deleted file mode 100644 index c3fb0067..00000000 --- a/lib/GyverFilters/examples/median_example/median_example.ino +++ /dev/null @@ -1,23 +0,0 @@ -/* - Пример использования медианного фильтра. -*/ - -#include "GyverFilters.h" - -// указываем размер окна и тип данных в <> -GMedian<10, int> testFilter; - -void setup() { - Serial.begin(9600); -} - -void loop() { - delay(80); - int value = analogRead(0); - // добавляем шум "выбросы" - value += random(2) * random(2) * random(-1, 2) * random(50, 250); - Serial.print(value); - Serial.print(','); - value = testFilter.filtered(value); - Serial.println(value); -} \ No newline at end of file diff --git a/lib/GyverFilters/keywords.txt b/lib/GyverFilters/keywords.txt deleted file mode 100644 index 57f38dbc..00000000 --- a/lib/GyverFilters/keywords.txt +++ /dev/null @@ -1,28 +0,0 @@ -####################################### -# Syntax Coloring Map For GyverFilters -####################################### - -####################################### -# Datatypes (KEYWORD1) -####################################### - -GyverFilters KEYWORD1 -GFilterRA KEYWORD1 -GMedian3 KEYWORD1 -GMedian KEYWORD1 -GABfilter KEYWORD1 -GKalman KEYWORD1 -GLinear KEYWORD1 - -####################################### -# Methods and Functions (KEYWORD2) -####################################### - -setCoef KEYWORD2 -setStep KEYWORD2 -filteredTime KEYWORD2 -filtered KEYWORD2 -setParameters KEYWORD2 -getA KEYWORD2 -getB KEYWORD2 -getDelta KEYWORD2 \ No newline at end of file diff --git a/lib/GyverFilters/library.properties b/lib/GyverFilters/library.properties deleted file mode 100644 index 2c0c881a..00000000 --- a/lib/GyverFilters/library.properties +++ /dev/null @@ -1,9 +0,0 @@ -name=GyverFilters -version=2.1 -author=AlexGyver -maintainer=AlexGyver -sentence=Library with few filters for data. -paragraph=Includes median, running average, AB, simplified Kalman and linear approximation filtering algorithms. -category=Data Processing -url=https://github.com/AlexGyver/GyverLibs -architectures=* \ No newline at end of file diff --git a/lib/GyverFilters/src/GyverFilters.h b/lib/GyverFilters/src/GyverFilters.h deleted file mode 100644 index cb35777c..00000000 --- a/lib/GyverFilters/src/GyverFilters.h +++ /dev/null @@ -1,28 +0,0 @@ -#pragma once -#include -#include -#include -#include -#include -#include - -/* - GyverFilters - библиотека с некоторыми удобными фильтрами. - Документация: https://alexgyver.ru/gyverfilters/ - - GFilterRA - компактная альтернатива фильтра экспоненциальное бегущее среднее (Running Average) - - GMedian3 - быстрый медианный фильтр 3-го порядка (отсекает выбросы) - - GMedian - медианный фильтр N-го порядка. Порядок настраивается в GyverFilters.h - MEDIAN_FILTER_SIZE - - GABfilter - альфа-бета фильтр (разновидность Калмана для одномерного случая) - - GKalman - упрощённый Калман для одномерного случая (на мой взгляд лучший из фильтров) - - GLinear - линейная аппроксимация методом наименьших квадратов для двух массивов - - Версии - - 1.6 от 12.11.2019 - - 1.7: исправлен GLinear - - 1.8: небольшие улучшения - - 2.0: - - Улучшен и исправлен median и median3 - - Улучшен linear - - Смотрите примеры! Использование этих фильтров чуть изменилось - - 2.1: Исправлен расчёт дельты в линейном фильтре -*/ \ No newline at end of file diff --git a/lib/GyverFilters/src/filters/alfaBeta.h b/lib/GyverFilters/src/filters/alfaBeta.h deleted file mode 100644 index 51b09726..00000000 --- a/lib/GyverFilters/src/filters/alfaBeta.h +++ /dev/null @@ -1,37 +0,0 @@ -#pragma once -#include - -// альфа-бета фильтр -class GABfilter { -public: - // период дискретизации (измерений), process variation, noise variation - GABfilter(float delta, float sigma_process, float sigma_noise) {setParameters(delta, sigma_process, sigma_noise);} - - // период дискретизации (измерений), process variation, noise variation - void setParameters(float delta, float sigma_process, float sigma_noise) { - dt = delta; - float lambda = (float)sigma_process * dt * dt / sigma_noise; - float r = (4 + lambda - (float)sqrt(8 * lambda + lambda * lambda)) / 4; - a = (float)1 - r * r; - b = (float)2 * (2 - a) - 4 * (float)sqrt(1 - a); - } - - // возвращает фильтрованное значение - float filtered(float value) { - xm = value; - xk = xk_1 + ((float) vk_1 * dt ); - vk = vk_1; - rk = xm - xk; - xk += (float)a * rk; - vk += (float)( b * rk ) / dt; - xk_1 = xk; - vk_1 = vk; - return xk_1; - } - -private: - float dt; - float xk_1, vk_1, a, b; - float xk, vk, rk; - float xm; -}; \ No newline at end of file diff --git a/lib/GyverFilters/src/filters/kalman.h b/lib/GyverFilters/src/filters/kalman.h deleted file mode 100644 index 10458090..00000000 --- a/lib/GyverFilters/src/filters/kalman.h +++ /dev/null @@ -1,38 +0,0 @@ -#pragma once -#include - -// упрощённый Калман для одномерного случая -class GKalman { -public: - // разброс измерения, разброс оценки, скорость изменения значений - GKalman(float mea_e, float est_e, float q) { setParameters(mea_e, est_e, q); } - - // разброс измерения, скорость изменения значений (разброс измерения принимается равным разбросу оценки) - GKalman(float mea_e, float q) {GKalman::setParameters(mea_e, mea_e, q);} - - // разброс измерения, разброс оценки, скорость изменения значений - void setParameters(float mea_e, float est_e, float q) { - _err_measure = mea_e; - _err_estimate = est_e; - _q = q; - } - - // разброс измерения, скорость изменения значений (разброс измерения принимается равным разбросу оценки) - void setParameters(float mea_e, float q) {setParameters(mea_e, mea_e, q);} - - // возвращает фильтрованное значение - float filtered(float value) { - float _kalman_gain, _current_estimate; - _kalman_gain = _err_estimate / (_err_estimate + _err_measure); - _current_estimate = _last_estimate + _kalman_gain * (value - _last_estimate); - _err_estimate = (1.0 - _kalman_gain)*_err_estimate + fabs(_last_estimate-_current_estimate)*_q; - _last_estimate=_current_estimate; - return _current_estimate; - } - -private: - float _err_measure = 0.0; - float _err_estimate = 0.0; - float _q = 0.0; - float _last_estimate = 0.0; -}; \ No newline at end of file diff --git a/lib/GyverFilters/src/filters/linear.h b/lib/GyverFilters/src/filters/linear.h deleted file mode 100644 index a3f320a2..00000000 --- a/lib/GyverFilters/src/filters/linear.h +++ /dev/null @@ -1,49 +0,0 @@ -#pragma once -#include - -// линейная аппроксимация методом наименьших квадратов -template < typename TYPE > -class GLinear { -public: - GLinear(){}; - void compute(TYPE *x_array, TYPE *y_array, int arrSize) { // аппроксимировать - int32_t sumX = 0, sumY = 0, sumX2 = 0, sumXY = 0; - arrSize /= sizeof(int); - for (int i = 0; i < arrSize; i++) { // для всех элементов массива - sumX += x_array[i]; - sumY += (long)y_array[i]; - sumX2 += x_array[i] * x_array[i]; - sumXY += (long)y_array[i] * x_array[i]; - } - a = (long)arrSize * sumXY; // расчёт коэффициента наклона приямой - a = a - (long)sumX * sumY; - a = (float)a / (arrSize * sumX2 - sumX * sumX); - b = (float)(sumY - (float)a * sumX) / arrSize; - delta = a * (x_array[arrSize-1] - x_array[0]); // расчёт изменения - } - float getA() {return a;} // получить коэффициент А - float getB() {return b;} // получить коэффициент В - float getDelta() {return delta;} // получить аппроксимированное изменение - -private: - float a, b, delta; -}; - -/* -Сам алгоритм выглядит так: -void loop() { - sumX = 0; - sumY = 0; - sumX2 = 0; - sumXY = 0; - for (int i = 0; i < steps; i++) { - sumX += X[i]; - sumY += Y[i]; - sumX2 += X[i] * X[i]; - sumXY += X[i] * Y[i]; - } - a = (steps * sumXY - sumX * sumY) / (steps * sumX2 - sumX * sumX); - b = (sumY - a * sumX) / steps; - int delta = steps * a; -} -*/ \ No newline at end of file diff --git a/lib/GyverFilters/src/filters/median.h b/lib/GyverFilters/src/filters/median.h deleted file mode 100644 index f7580806..00000000 --- a/lib/GyverFilters/src/filters/median.h +++ /dev/null @@ -1,35 +0,0 @@ -#pragma once - -// медианный фильтр N-го порядка -template < int SIZE, typename TYPE > -class GMedian { -public: - TYPE filtered(TYPE newVal) { - buffer[_count] = newVal; - if ((_count < _numRead - 1) && (buffer[_count] > buffer[_count + 1])) { - for (int i = _count; i < _numRead - 1; i++) { - if (buffer[i] > buffer[i + 1]) { - float buff = buffer[i]; - buffer[i] = buffer[i + 1]; - buffer[i + 1] = buff; - } - } - } else { - if ((_count > 0) and (buffer[_count - 1] > buffer[_count])) { - for (int i = _count; i > 0; i--) { - if (buffer[i] < buffer[i - 1]) { - float buff = buffer[i]; - buffer[i] = buffer[i - 1]; - buffer[i - 1] = buff; - } - } - } - } - if (++_count >= _numRead) _count = 0; - return buffer[(int)_numRead / 2]; - } -private: - TYPE buffer[SIZE]; - byte _count = 0; - byte _numRead = SIZE; -}; \ No newline at end of file diff --git a/lib/GyverFilters/src/filters/median3.h b/lib/GyverFilters/src/filters/median3.h deleted file mode 100644 index 8b99cc1e..00000000 --- a/lib/GyverFilters/src/filters/median3.h +++ /dev/null @@ -1,30 +0,0 @@ -#pragma once - -// быстрый медианный фильтр 3-го порядка -template < typename TYPE > -class GMedian3 { -public: - TYPE filtered(TYPE value) { // возвращает фильтрованное значение - buffer[_counter] = value; - if (++_counter > 2) _counter = 0; - - TYPE middle; - - if ((buffer[0] <= buffer[1]) && (buffer[0] <= buffer[2])) { - middle = (buffer[1] <= buffer[2]) ? buffer[1] : buffer[2]; - } - else { - if ((buffer[1] <= buffer[0]) && (buffer[1] <= buffer[2])) { - middle = (buffer[0] <= buffer[2]) ? buffer[0] : buffer[2]; - } - else { - middle = (buffer[0] <= buffer[1]) ? buffer[0] : buffer[1]; - } - } - return middle; - } - -private: - TYPE buffer[3]; - uint8_t _counter = 0; -}; \ No newline at end of file diff --git a/lib/GyverFilters/src/filters/runningAverage.cpp b/lib/GyverFilters/src/filters/runningAverage.cpp deleted file mode 100644 index 8922bfda..00000000 --- a/lib/GyverFilters/src/filters/runningAverage.cpp +++ /dev/null @@ -1,43 +0,0 @@ -#include - -GFilterRA::GFilterRA() {} - -GFilterRA::GFilterRA(float coef, uint16_t interval) { - _coef = coef; - _filterInterval = interval; -} - -GFilterRA::GFilterRA(float coef) { - _coef = coef; -} - -void GFilterRA::setCoef(float coef) { - _coef = coef; -} -void GFilterRA::setStep(uint16_t interval) { - _filterInterval = interval; -} - -//float GFilterRA::filteredTime(int16_t value) { -// if (millis() - _filterTimer >= _filterInterval) { -// _filterTimer = millis(); -// return GFilterRA::filtered(value); -// } -//} - -//float GFilterRA::filteredTime(float value) { -// if (millis() - _filterTimer >= _filterInterval) { -// _filterTimer = millis(); -// return GFilterRA::filtered(value); -// } -//} - -float GFilterRA::filtered(int16_t value) { - _lastValue += (float)(value - _lastValue) * _coef; - return _lastValue; -} - -float GFilterRA::filtered(float value) { - _lastValue += (float)(value - _lastValue) * _coef; - return _lastValue; -} \ No newline at end of file diff --git a/lib/GyverFilters/src/filters/runningAverage.h b/lib/GyverFilters/src/filters/runningAverage.h deleted file mode 100644 index 7910a0fe..00000000 --- a/lib/GyverFilters/src/filters/runningAverage.h +++ /dev/null @@ -1,24 +0,0 @@ -#pragma once -#include - -// экспоненциальное бегущее среднее -class GFilterRA -{ -public: - GFilterRA(); // инициализация фильтра - GFilterRA(float coef); // расширенная инициализация фильтра (коэффициент) - GFilterRA(float coef, uint16_t interval); // расширенная инициализация фильтра (коэффициент, шаг фильтрации) - void setCoef(float coef); // настройка коэффициента фильтрации (0.00 - 1.00). Чем меньше, тем плавнее - void setStep(uint16_t interval); // установка шага фильтрации (мс). Чем меньше, тем резче фильтр - - float filteredTime(int16_t value); // возвращает фильтрованное значение с опорой на встроенный таймер - float filtered(int16_t value); // возвращает фильтрованное значение - - float filteredTime(float value); // возвращает фильтрованное значение с опорой на встроенный таймер - float filtered(float value); // возвращает фильтрованное значение - -private: - float _coef = 0.0, _lastValue = 0.0; - uint32_t _filterTimer = 0; - uint16_t _filterInterval = 0; -}; \ No newline at end of file diff --git a/lib/PZEMSensor/include/PZEMSensor.h b/lib/PZEMSensor/include/PZEMSensor.h deleted file mode 100644 index e29362cc..00000000 --- a/lib/PZEMSensor/include/PZEMSensor.h +++ /dev/null @@ -1,51 +0,0 @@ -#pragma once - -#include - -#include - -#define PZEM_DEFAULT_ADDR 0xF8 - -struct PZEM_Info { - float voltage; - float current; - float power; - float energy; - float freq; - float pf; - uint16_t alarms; - PZEM_Info() : voltage{0}, current{0}, power{0}, energy{0}, freq{0}, pf{0}, alarms{0} {}; -}; - -class PZEMSensor { - public: - PZEMSensor(Stream *serial, uint16_t addr = PZEM_DEFAULT_ADDR); - - ~PZEMSensor(); - PZEM_Info* values(); - bool setAddress(uint8_t addr); - uint8_t getAddress(); - bool setPowerAlarm(uint16_t watts); - bool getPowerAlarm(); - bool reset(); - void search(); - // Get most up to date values from device registers and cache them - bool refresh(); - - private: - void init(void); - - private: - PZEM_Info _values; // Measured values - Stream *_serial; // Serial interface - bool _isSoft; // Is serial interface software - uint8_t _addr; // Device address - uint64_t _lastRead; // Last time values were updated - - void init(uint8_t addr); // Init common to all constructors - uint16_t recieve(uint8_t *resp, uint16_t len); // Receive len bytes into a buffer - bool sendCmd8(uint8_t cmd, uint16_t rAddr, uint16_t val, bool check = false, uint16_t slave_addr = 0xFFFF); // Send 8 byte command - void setCRC(uint8_t *buf, uint16_t len); // Set the CRC for a buffer - bool checkCRC(const uint8_t *buf, uint16_t len); // Check CRC of buffer - uint16_t CRC16(const uint8_t *data, uint16_t len); // Calculate CRC of buffer -}; diff --git a/lib/PZEMSensor/src/PZEMSensor.cpp b/lib/PZEMSensor/src/PZEMSensor.cpp deleted file mode 100644 index cb9d297d..00000000 --- a/lib/PZEMSensor/src/PZEMSensor.cpp +++ /dev/null @@ -1,310 +0,0 @@ -#include "PZEMSensor.h" - -#include - -#define REG_VOLTAGE 0x0000 -#define REG_CURRENT_L 0x0001 -#define REG_CURRENT_H 0X0002 -#define REG_POWER_L 0x0003 -#define REG_POWER_H 0x0004 -#define REG_ENERGY_L 0x0005 -#define REG_ENERGY_H 0x0006 -#define REG_FREQUENCY 0x0007 -#define REG_PF 0x0008 -#define REG_ALARM 0x0009 -#define CMD_RHR 0x03 -#define CMD_RIR 0X04 -#define CMD_WSR 0x06 -#define CMD_CAL 0x41 -#define CMD_REST 0x42 -#define WREG_ALARM_THR 0x0001 -#define WREG_ADDR 0x0002 -#define UPDATE_TIME 200 -#define RESPONSE_SIZE 32 -#define READ_TIMEOUT 100 -#define PZEM_BAUD_RATE 9600 - -#define DEBUG -// Debugging function; -void printBuf(uint8_t *buffer, uint16_t len) { -#ifdef DEBUG - for (uint16_t i = 0; i < len; i++) { - char temp[6]; - sprintf(temp, "%.2x ", buffer[i]); - Serial.print(temp); - } - Serial.println(); -#endif -} - -PZEMSensor::PZEMSensor(Stream *port, uint16_t addr) { - _serial = port; - _addr = addr; - init(); -} - -PZEM_Info *PZEMSensor::values() { - // Update vales if necessary - if (!refresh()) { - _values = PZEM_Info(); - } - return &_values; -} - -/*! - * PZEM004Tv30::sendCmd8 - * - * Prepares the 8 byte command buffer and sends - * - * @param[in] cmd - Command to send (position 1) - * @param[in] rAddr - Register address (postion 2-3) - * @param[in] val - Register value to write (positon 4-5) - * @param[in] check - perform a simple read check after write - * - * @return success -*/ -bool PZEMSensor::sendCmd8(uint8_t cmd, uint16_t rAddr, uint16_t val, bool check, uint16_t slave_addr) { - uint8_t sendBuffer[8]; // Send buffer - uint8_t respBuffer[8]; // Response buffer (only used when check is true) - - if ((slave_addr == 0xFFFF) || - (slave_addr < 0x01) || - (slave_addr > 0xF7)) { - slave_addr = _addr; - } - - sendBuffer[0] = slave_addr; // Set slave address - sendBuffer[1] = cmd; // Set command - - sendBuffer[2] = (rAddr >> 8) & 0xFF; // Set high byte of register address - sendBuffer[3] = (rAddr)&0xFF; // Set low byte =//= - - sendBuffer[4] = (val >> 8) & 0xFF; // Set high byte of register value - sendBuffer[5] = (val)&0xFF; // Set low byte =//= - - setCRC(sendBuffer, 8); // Set CRC of frame - - _serial->write(sendBuffer, 8); // send frame - - if (check) { - if (!recieve(respBuffer, 8)) { // if check enabled, read the response - return false; - } - - // Check if response is same as send - for (uint8_t i = 0; i < 8; i++) { - if (sendBuffer[i] != respBuffer[i]) - return false; - } - } - return true; -} - -bool PZEMSensor::setAddress(uint8_t addr) { - if (addr < 0x01 || addr > 0xF7) // sanity check - return false; - - // Write the new address to the address register - if (!sendCmd8(CMD_WSR, WREG_ADDR, addr, true)) - return false; - - _addr = addr; // If successful, update the current slave address - - return true; -} - -uint8_t PZEMSensor::getAddress() { - return _addr; -} - -bool PZEMSensor::setPowerAlarm(uint16_t watts) { - if (watts > 25000) { // Sanitych check - watts = 25000; - } - - // Write the watts threshold to the Alarm register - if (!sendCmd8(CMD_WSR, WREG_ALARM_THR, watts, true)) - return false; - - return true; -} - -bool PZEMSensor::getPowerAlarm() { - if (!refresh()) // Update vales if necessary - return NAN; // Update did not work, return NAN - - return _values.alarms != 0x0000; -} - -void PZEMSensor::init() { - if (_addr < 0x01 || _addr > 0xF8) { - // Sanity check of address - _addr = PZEM_DEFAULT_ADDR; - } - // Set initial lastRed time so that we read right away - _lastRead = 0; - _lastRead -= UPDATE_TIME; -} - -bool PZEMSensor::refresh() { - static uint8_t response[25]; - if (_lastRead + UPDATE_TIME > millis()) { - return true; - } - // Read 10 registers starting at 0x00 (no check) - sendCmd8(CMD_RIR, 0x00, 0x0A, false); - if (recieve(response, 25) != 25) { // Something went wrong - return false; - } - // Update the current values - _values.voltage = ((uint32_t)response[3] << 8 | // Raw voltage in 0.1V - (uint32_t)response[4]) / - 10.0; - - _values.current = ((uint32_t)response[5] << 8 | // Raw current in 0.001A - (uint32_t)response[6] | - (uint32_t)response[7] << 24 | - (uint32_t)response[8] << 16) / - 1000.0; - - _values.power = ((uint32_t)response[9] << 8 | // Raw power in 0.1W - (uint32_t)response[10] | - (uint32_t)response[11] << 24 | - (uint32_t)response[12] << 16) / - 10.0; - - _values.energy = ((uint32_t)response[13] << 8 | // Raw Energy in 1Wh - (uint32_t)response[14] | - (uint32_t)response[15] << 24 | - (uint32_t)response[16] << 16) / - 1000.0; - - _values.freq = ((uint32_t)response[17] << 8 | // Raw Frequency in 0.1Hz - (uint32_t)response[18]) / - 10.0; - - _values.pf = ((uint32_t)response[19] << 8 | // Raw pf in 0.01 - (uint32_t)response[20]) / - 100.0; - - _values.alarms = ((uint32_t)response[21] << 8 | // Raw alarm value - (uint32_t)response[22]); - - // Record current time as _lastRead - _lastRead = millis(); - return true; -} - -bool PZEMSensor::reset() { - uint8_t buffer[] = {0x00, CMD_REST, 0x00, 0x00}; - uint8_t reply[5]; - buffer[0] = _addr; - - setCRC(buffer, 4); - _serial->write(buffer, 4); - - uint16_t length = recieve(reply, 5); - - if (length == 0 || length == 5) { - return false; - } - - return true; -} - -uint16_t PZEMSensor::recieve(uint8_t *resp, uint16_t len) { - ((SoftwareSerial *)_serial)->listen(); // Start software serial listen - unsigned long startTime = millis(); // Start time for Timeout - uint8_t index = 0; // Bytes we have read - while ((index < len) && (millis() - startTime < READ_TIMEOUT)) { - if (_serial->available() > 0) { - uint8_t c = (uint8_t)_serial->read(); - resp[index++] = c; - } - } - // Check CRC with the number of bytes read - if (!checkCRC(resp, index)) { - return 0; - } - return index; -} - -bool PZEMSensor::checkCRC(const uint8_t *buf, uint16_t len) { - if (len <= 2) // Sanity check - return false; - - uint16_t crc = CRC16(buf, len - 2); // Compute CRC of data - return ((uint16_t)buf[len - 2] | (uint16_t)buf[len - 1] << 8) == crc; -} - -void PZEMSensor::setCRC(uint8_t *buf, uint16_t len) { - if (len <= 2) // Sanity check - return; - - uint16_t crc = CRC16(buf, len - 2); // CRC of data - - // Write high and low byte to last two positions - buf[len - 2] = crc & 0xFF; // Low byte first - buf[len - 1] = (crc >> 8) & 0xFF; // High byte second -} - -// Pre computed CRC table -static const uint16_t crcTable[] PROGMEM = { - 0X0000, 0XC0C1, 0XC181, 0X0140, 0XC301, 0X03C0, 0X0280, 0XC241, - 0XC601, 0X06C0, 0X0780, 0XC741, 0X0500, 0XC5C1, 0XC481, 0X0440, - 0XCC01, 0X0CC0, 0X0D80, 0XCD41, 0X0F00, 0XCFC1, 0XCE81, 0X0E40, - 0X0A00, 0XCAC1, 0XCB81, 0X0B40, 0XC901, 0X09C0, 0X0880, 0XC841, - 0XD801, 0X18C0, 0X1980, 0XD941, 0X1B00, 0XDBC1, 0XDA81, 0X1A40, - 0X1E00, 0XDEC1, 0XDF81, 0X1F40, 0XDD01, 0X1DC0, 0X1C80, 0XDC41, - 0X1400, 0XD4C1, 0XD581, 0X1540, 0XD701, 0X17C0, 0X1680, 0XD641, - 0XD201, 0X12C0, 0X1380, 0XD341, 0X1100, 0XD1C1, 0XD081, 0X1040, - 0XF001, 0X30C0, 0X3180, 0XF141, 0X3300, 0XF3C1, 0XF281, 0X3240, - 0X3600, 0XF6C1, 0XF781, 0X3740, 0XF501, 0X35C0, 0X3480, 0XF441, - 0X3C00, 0XFCC1, 0XFD81, 0X3D40, 0XFF01, 0X3FC0, 0X3E80, 0XFE41, - 0XFA01, 0X3AC0, 0X3B80, 0XFB41, 0X3900, 0XF9C1, 0XF881, 0X3840, - 0X2800, 0XE8C1, 0XE981, 0X2940, 0XEB01, 0X2BC0, 0X2A80, 0XEA41, - 0XEE01, 0X2EC0, 0X2F80, 0XEF41, 0X2D00, 0XEDC1, 0XEC81, 0X2C40, - 0XE401, 0X24C0, 0X2580, 0XE541, 0X2700, 0XE7C1, 0XE681, 0X2640, - 0X2200, 0XE2C1, 0XE381, 0X2340, 0XE101, 0X21C0, 0X2080, 0XE041, - 0XA001, 0X60C0, 0X6180, 0XA141, 0X6300, 0XA3C1, 0XA281, 0X6240, - 0X6600, 0XA6C1, 0XA781, 0X6740, 0XA501, 0X65C0, 0X6480, 0XA441, - 0X6C00, 0XACC1, 0XAD81, 0X6D40, 0XAF01, 0X6FC0, 0X6E80, 0XAE41, - 0XAA01, 0X6AC0, 0X6B80, 0XAB41, 0X6900, 0XA9C1, 0XA881, 0X6840, - 0X7800, 0XB8C1, 0XB981, 0X7940, 0XBB01, 0X7BC0, 0X7A80, 0XBA41, - 0XBE01, 0X7EC0, 0X7F80, 0XBF41, 0X7D00, 0XBDC1, 0XBC81, 0X7C40, - 0XB401, 0X74C0, 0X7580, 0XB541, 0X7700, 0XB7C1, 0XB681, 0X7640, - 0X7200, 0XB2C1, 0XB381, 0X7340, 0XB101, 0X71C0, 0X7080, 0XB041, - 0X5000, 0X90C1, 0X9181, 0X5140, 0X9301, 0X53C0, 0X5280, 0X9241, - 0X9601, 0X56C0, 0X5780, 0X9741, 0X5500, 0X95C1, 0X9481, 0X5440, - 0X9C01, 0X5CC0, 0X5D80, 0X9D41, 0X5F00, 0X9FC1, 0X9E81, 0X5E40, - 0X5A00, 0X9AC1, 0X9B81, 0X5B40, 0X9901, 0X59C0, 0X5880, 0X9841, - 0X8801, 0X48C0, 0X4980, 0X8941, 0X4B00, 0X8BC1, 0X8A81, 0X4A40, - 0X4E00, 0X8EC1, 0X8F81, 0X4F40, 0X8D01, 0X4DC0, 0X4C80, 0X8C41, - 0X4400, 0X84C1, 0X8581, 0X4540, 0X8701, 0X47C0, 0X4680, 0X8641, - 0X8201, 0X42C0, 0X4380, 0X8341, 0X4100, 0X81C1, 0X8081, 0X4040}; - -uint16_t PZEMSensor::CRC16(const uint8_t *data, uint16_t len) { - uint8_t nTemp; // CRC table index - uint16_t crc = 0xFFFF; // Default value - - while (len--) { - nTemp = *data++ ^ crc; - crc >>= 8; - crc ^= (uint16_t)pgm_read_word(&crcTable[nTemp]); - } - return crc; -} - -void PZEMSensor::search() { - static uint8_t response[7]; - for (uint16_t addr = 0x01; addr <= 0xF8; addr++) { - sendCmd8(CMD_RIR, 0x00, 0x01, false, addr); - if (recieve(response, 7) != 7) { - // Something went wrong - continue; - } else { - Serial.print("Device on addr: "); - Serial.print(addr); - } - } -} diff --git a/lib/README b/lib/README deleted file mode 100644 index 6debab1e..00000000 --- a/lib/README +++ /dev/null @@ -1,46 +0,0 @@ - -This directory is intended for project specific (private) libraries. -PlatformIO will compile them to static libraries and link into executable file. - -The source code of each library should be placed in a an own separate directory -("lib/your_library_name/[here are source files]"). - -For example, see a structure of the following two libraries `Foo` and `Bar`: - -|--lib -| | -| |--Bar -| | |--docs -| | |--examples -| | |--src -| | |- Bar.c -| | |- Bar.h -| | |- library.json (optional, custom build options, etc) https://docs.platformio.org/page/librarymanager/config.html -| | -| |--Foo -| | |- Foo.c -| | |- Foo.h -| | -| |- README --> THIS FILE -| -|- platformio.ini -|--src - |- main.c - -and a contents of `src/main.c`: -``` -#include -#include - -int main (void) -{ - ... -} - -``` - -PlatformIO Library Dependency Finder will find automatically dependent -libraries scanning project source files. - -More information about PlatformIO Library Dependency Finder -- https://docs.platformio.org/page/librarymanager/ldf.html diff --git a/lib/TickerScheduler/README.md b/lib/TickerScheduler/README.md deleted file mode 100644 index 33f0182e..00000000 --- a/lib/TickerScheduler/README.md +++ /dev/null @@ -1,81 +0,0 @@ -# TickerScheduler -Simple scheduler for ESP8266 Arduino based on Ticker - -### Initialization - -`TickerScheduler(uint size);` - -| Param | Description | -| --- | --- | -| size | Amount of task Tickers to initialize | - -**Example**: - -`TickerScheduler ts(5)` - - -### Add task - -`boolean add(uint i, uint32_t period, tscallback_t f, boolean shouldFireNow = false); ` - -| Param | Description | -| --- | --- | -| i | Task ID | -| period | Task execution period in ms | -| f | Task callback | -| shouldFireNow| `true` if you want to execute task right after first scheduler update or wait next scheduled start | - -**Returns**: - -`true` - task added sucessfully - -`false` - task was not added - -**Example**: - -`ts.add(0, 3000, sendData)` - -### Execute scheduler in `loop()` - -`ts.update()` - -### Remove task - -`boolean remove(uint i)` - -**Returns**: - -`true` - task removed sucessfully - -`false` - task was not removed - -| Param | Description | -| --- | --- | -| i | Task ID | - -### Enable/Disable task - -`boolean enable(uint i)` - -`boolean disable(uint i)` - -**Returns**: - -`true` - task enabled/disabled sucessfully - -`false` - task was not enabled/disabled - -| Param | Description | -| --- | --- | -| i | Task ID | - -### Enable / disable all tasks - -`void enableAll()` - -`void disableAll()` - -### TODO - -* Task callback parameters support -* ... diff --git a/lib/TickerScheduler/TickerScheduler.cpp b/lib/TickerScheduler/TickerScheduler.cpp deleted file mode 100644 index af47ffa1..00000000 --- a/lib/TickerScheduler/TickerScheduler.cpp +++ /dev/null @@ -1,116 +0,0 @@ -#include "TickerScheduler.h" - -TickerScheduler::TickerScheduler(uint8_t size) -{ - this->items = new TickerSchedulerItem[size]; - this->size = size; -} - -TickerScheduler::~TickerScheduler() -{ - for (uint8_t i = 0; i < this->size; i++) - { - this->remove(i); - yield(); - } - - delete[] this->items; - this->items = NULL; - this->size = 0; -} - -void TickerScheduler::handleTickerFlag(bool * flag) -{ - if (!*flag) - *flag = true; -} - -void TickerScheduler::handleTicker(tscallback_t f, void * arg, bool * flag) -{ - if (*flag) - { - yield(); - *flag = false; - yield(); - f(arg); - yield(); - } -} - -bool TickerScheduler::add(uint8_t i, uint32_t period, tscallback_t f, void* arg, boolean shouldFireNow) -{ - if (i >= this->size || this->items[i].is_used) - return false; - - this->items[i].cb = f; - this->items[i].cb_arg = arg; - this->items[i].flag = shouldFireNow; - this->items[i].period = period; - this->items[i].is_used = true; - - enable(i); - - return true; -} - -bool TickerScheduler::remove(uint8_t i) -{ - if (i >= this->size || !this->items[i].is_used) - return false; - - this->items[i].is_used = false; - this->items[i].t.detach(); - this->items[i].flag = false; - this->items[i].cb = NULL; - - return true; -} - -bool TickerScheduler::disable(uint8_t i) -{ - if (i >= this->size || !this->items[i].is_used) - return false; - - this->items[i].t.detach(); - - return true; -} - -bool TickerScheduler::enable(uint8_t i) -{ - if (i >= this->size || !this->items[i].is_used) - return false; - - bool * flag = &this->items[i].flag; - this->items[i].t.attach_ms(this->items[i].period, TickerScheduler::handleTickerFlag, flag); - - return true; -} - -void TickerScheduler::disableAll() -{ - for (uint8_t i = 0; i < this->size; i++) - disable(i); -} - -void TickerScheduler::enableAll() -{ - for (uint8_t i = 0; i < this->size; i++) - enable(i); -} - -void TickerScheduler::update() -{ - for (uint8_t i = 0; i < this->size; i++) - { - if (this->items[i].is_used) - { - #ifdef ARDUINO_ARCH_AVR - this->items[i].t.Tick(); - #endif - - handleTicker(this->items[i].cb, this->items[i].cb_arg, &this->items[i].flag); - } - yield(); - } -} diff --git a/lib/TickerScheduler/TickerScheduler.h b/lib/TickerScheduler/TickerScheduler.h deleted file mode 100644 index 98ae1f05..00000000 --- a/lib/TickerScheduler/TickerScheduler.h +++ /dev/null @@ -1,91 +0,0 @@ -#ifndef TICKERSCHEDULER_H -#define TICKERSCHEDULER_H - -#if defined(ARDUINO) && ARDUINO >= 100 - #include "Arduino.h" -#endif -#include - - -#ifdef ARDUINO_ARCH_AVR -class Ticker -{ - typedef void(*ticker_callback_t)(bool*); - -private: - bool is_attached = false; - uint32_t period = 0; - uint32_t last_tick = 0; - ticker_callback_t callback; - bool *callback_argument; -public: - void Tick() - { - if (is_attached && millis() - last_tick >= period) - { - callback(callback_argument); - last_tick = millis(); - } - } - - void detach() - { - this->is_attached = true; - } - - template void attach_ms(uint32_t milliseconds, void(*callback)(TArg), TArg arg) - { - this->period = milliseconds; - this->callback = callback; - this->callback_argument = arg; - this->is_attached = true; - } -}; -#endif - -//#ifdef ARDUINO_ARCH_ESP8266 -#include -#include -//#endif - -void tickerFlagHandle(volatile bool * flag); - -#ifdef _GLIBCXX_FUNCTIONAL -typedef std::function tscallback_t; -#else -typedef void(*tscallback_t)(void*); -#endif - -struct TickerSchedulerItem -{ - Ticker t; - bool flag = false; - tscallback_t cb; - void * cb_arg; - uint32_t period; - volatile bool is_used = false; -}; - -class TickerScheduler -{ -private: - uint8_t size; - TickerSchedulerItem *items = NULL; - - void handleTicker(tscallback_t, void *, bool * flag); - static void handleTickerFlag(bool * flag); - -public: - TickerScheduler(uint8_t size); - ~TickerScheduler(); - - bool add(uint8_t i, uint32_t period, tscallback_t, void *, boolean shouldFireNow = false); - bool remove(uint8_t i); - bool enable(uint8_t i); - bool disable(uint8_t i); - void enableAll(); - void disableAll(); - void update(); -}; - -#endif diff --git a/lib/TickerScheduler/example/blink/blink/blink.ino b/lib/TickerScheduler/example/blink/blink/blink.ino deleted file mode 100644 index 49afc470..00000000 --- a/lib/TickerScheduler/example/blink/blink/blink.ino +++ /dev/null @@ -1,29 +0,0 @@ -#include - -#define LED1 4 -#define LED2 5 - -TickerScheduler ts(2); - -void blink1() { - digitalWrite(LED1, !digitalRead(LED1)); -} - -void blink2() { - digitalWrite(LED2, !digitalRead(LED2)); -} - -void setup() { - pinMode(LED1, OUTPUT); - digitalWrite(LED1, LOW); - - pinMode(LED2, OUTPUT); - digitalWrite(LED2, LOW); - - ts.add(0, 1000, [&](void *) { blink1(); }, nullptr, true); - ts.add(1, 3000, [&](void *) { blink2(); }, nullptr, true); -} - -void loop() { - ts.update(); -} diff --git a/partitions_custom.csv b/partitions_custom.csv deleted file mode 100644 index 86202b53..00000000 --- a/partitions_custom.csv +++ /dev/null @@ -1,6 +0,0 @@ -# Name, Type, SubType, Offset, Size, Flags -ota_0, app, ota_0, 0x10000, 0x1A0000 -ota_1, app, ota_1, , 0x1A0000 -otadata, data, ota, 0x350000, 0x2000 -nvs, data, nvs, , 0x6000 -data, data, spiffs, , 0xA8000 \ No newline at end of file diff --git a/platformio.ini b/platformio.ini deleted file mode 100644 index 7db818ce..00000000 --- a/platformio.ini +++ /dev/null @@ -1,146 +0,0 @@ -; PlatformIO Project Configuration File -; -; Build options: build flags, source filter -; Upload options: custom upload port, speed and extra flags -; Library options: dependencies, extra library storages -; Advanced options: extra scripting -; -; Please visit documentation for the other options and examples -; https://docs.platformio.org/page/projectconf.html - - -;============================================================================================== -;To choose firmware please use one of definition: -;esp8266_1mb , esp8266_4mb , esp32_4mb , esp8266_mysensors_4mb , esp32_mysensors_4mb -[platformio] -default_envs = esp8266_4mb - - -;data_esp => esp8266_1mb , esp8266_4mb , esp32_4mb -;data_ms => esp8266_mysensors_4mb , esp32_mysensors_4mb -;data_svelte => new web interface (in progress...) -data_dir = data_svelte -;============================================================================================== - - -[common_env_data] -lib_deps_external = - bblanchon/ArduinoJson @6.18.0 - knolleary/PubSubClient - ESP Async WebServer @1.2.3 - - -lib_deps_internal = - ;ESP Async WebServer - GyverFilters - OneWire - EspSoftwareSerial - - -[env:esp8266_4mb] -build_flags = -Desp8266_4mb="esp8266_4mb" -framework = arduino -board = nodemcuv2 -board_build.ldscript = eagle.flash.4m1m.ld -platform = espressif8266 @2.6.3 -lib_deps = - ${common_env_data.lib_deps_external} - ${common_env_data.lib_deps_internal} - ESPAsyncTCP - ESPAsyncUDP - CTBot @2.1.6 - thomasfredericks/Bounce2 - beegee-tokyo/DHT sensor library for ESPx - adafruit/Adafruit BMP280 Library - adafruit/Adafruit BME280 Library - adafruit/Adafruit CCS811 Library - milesburton/DallasTemperature -monitor_filters = esp8266_exception_decoder -upload_speed = 921600 -monitor_speed = 115200 -board_build.filesystem = littlefs - - -[env:esp8266_1mb] -build_flags = -Desp8266_1mb="esp8266_1mb" -framework = arduino -board = nodemcuv2 -board_build.ldscript = eagle.flash.1m256.ld -platform = espressif8266 @2.6.2 -lib_deps = - ${common_env_data.lib_deps_external} - ${common_env_data.lib_deps_internal} - ESPAsyncTCP - ESPAsyncUDP - CTBot @2.1.6 - thomasfredericks/Bounce2 - beegee-tokyo/DHT sensor library for ESPx - adafruit/Adafruit BMP280 Library - adafruit/Adafruit BME280 Library - adafruit/Adafruit CCS811 Library - milesburton/DallasTemperature -monitor_filters = esp8266_exception_decoder -upload_speed = 921600 -monitor_speed = 115200 - - -[env:esp8266_mysensors_4mb] -build_flags = -Desp8266_mysensors_4mb="esp8266_mysensors_4mb" -framework = arduino -board = nodemcuv2 -board_build.ldscript = eagle.flash.4m1m.ld -platform = espressif8266 @2.6.3 -lib_deps = - ${common_env_data.lib_deps_external} - ${common_env_data.lib_deps_internal} - ESPAsyncTCP - ESPAsyncUDP - CTBot @2.1.6 - MySensors @2.3.2 -monitor_filters = esp8266_exception_decoder -upload_speed = 921600 -monitor_speed = 115200 -board_build.filesystem = littlefs - - -[env:esp32_4mb] -build_flags = -Desp32_4mb="esp32_4mb" -framework = arduino -board = esp32dev -platform = espressif32 @3.3.0 -lib_deps = - ${common_env_data.lib_deps_external} - ${common_env_data.lib_deps_internal} - AsyncTCP - madhephaestus/ESP32Servo - luc-github/ESP32SSDP - ESP32Servo - CTBot @2.1.6 - thomasfredericks/Bounce2 - beegee-tokyo/DHT sensor library for ESPx - adafruit/Adafruit BMP280 Library - adafruit/Adafruit BME280 Library - adafruit/Adafruit CCS811 Library - milesburton/DallasTemperature -monitor_filters = esp32_exception_decoder -upload_speed = 921600 -monitor_speed = 115200 - - -[env:esp32_mysensors_4mb] -build_flags = -Desp32_mysensors_4mb="esp32_mysensors_4mb" -framework = arduino -board = esp32dev -platform = espressif32 @3.3.0 -lib_deps = - ${common_env_data.lib_deps_external} - ${common_env_data.lib_deps_internal} - AsyncTCP - luc-github/ESP32SSDP - CTBot @2.1.6 - ESP32 AnalogWrite - ESP32Servo - MySensors @2.3.2 -monitor_filters = esp32_exception_decoder -upload_speed = 921600 -monitor_speed = 115200 \ No newline at end of file diff --git a/src/BufferExecute.cpp b/src/BufferExecute.cpp deleted file mode 100644 index e7972a03..00000000 --- a/src/BufferExecute.cpp +++ /dev/null @@ -1,213 +0,0 @@ -#include "BufferExecute.h" - -#include "Global.h" -#include "SoftUART.h" -#include "items/test.h" -#include "items/vButtonOut.h" -#include "items/vCountDown.h" -#include "items/vImpulsOut.h" -#include "items/vInput.h" -#include "items/vLogging.h" -#include "items/vOutput.h" -#include "items/vPwmOut.h" -#include "items/vSensorAnalog.h" -#include "items/vSensorBme280.h" -#include "items/vSensorBmp280.h" -#include "items/vSensorCcs811.h" -#include "items/vSensorDallas.h" -#include "items/vSensorDht.h" -#include "items/vSensorNode.h" -#include "items/vSensorPzem.h" -#include "items/vSensorUltrasonic.h" -#include "items/vSensorUptime.h" - -void loopCmdAdd(const String& cmdStr) { - if (cmdStr.endsWith(",")) { - orderBuf += cmdStr; - SerialPrint("I", F("Order add"), cmdStr); -#ifdef EnableUart - if (jsonReadBool(configSetupJson, "uart")) { - if (jsonReadBool(configSetupJson, "uartEvents")) { - if (myUART) { - myUART->print(cmdStr); - SerialPrint("I", F("<=UART"), cmdStr); - } - } - } -#endif - } -} - -void loopCmdExecute() { - if (orderBuf.length()) { - String tmp = selectToMarker(orderBuf, ","); //выделяем первую команду rel 5 1, - sCmd.readStr(tmp); //выполняем - if (tmp != "") { - sCmd.readStr(tmp); - SerialPrint("I", F("Order done L"), tmp); - } - orderBuf = deleteBeforeDelimiter(orderBuf, ","); //осекаем - } -} - -void fileCmdExecute(const String& filename) { - String cmdStr = readFile(filename, 4096); - csvCmdExecute(cmdStr); -} - -void csvCmdExecute(String& cmdStr) { - cmdStr.replace(";", " "); - cmdStr += "\r\n"; - cmdStr.replace("\r\n", "\n"); - cmdStr.replace("\r", "\n"); - int count = 0; - while (cmdStr.length()) { - String buf = selectToMarker(cmdStr, "\n"); - - buf = deleteBeforeDelimiter(buf, " "); //отсечка чекбокса - - count++; - - if (count > 1) { - //SerialPrint("I", "Items", buf); - String order = selectToMarker(buf, " "); //отсечка самой команды - if (order == F("button-out")) { -#ifdef EnableButtonOut - sCmd.addCommand(order.c_str(), buttonOut); -#endif - } else if (order == F("pwm-out")) { -#ifdef EnablePwmOut - sCmd.addCommand(order.c_str(), pwmOut); -#endif - } else if (order == F("button-in")) { -#ifdef EnableButtonIn - sCmd.addCommand(order.c_str(), buttonIn); -#endif - } else if (order == F("input-value")) { -#ifdef EnableInput - sCmd.addCommand(order.c_str(), inputValue); -#endif - } else if (order == F("output-value")) { -#ifdef EnableOutput - sCmd.addCommand(order.c_str(), outputValue); -#endif - } else if (order == F("analog-adc")) { -#ifdef EnableSensorAnalog - sCmd.addCommand(order.c_str(), analogAdc); -#endif - } else if (order == F("ultrasonic-cm")) { -#ifdef EnableSensorUltrasonic - sCmd.addCommand(order.c_str(), ultrasonic); -#endif - } else if (order == F("dallas-temp")) { -#ifdef EnableSensorDallas - sCmd.addCommand(order.c_str(), dallas); -#endif - } else if (order == F("dht")) { -#ifdef EnableSensorDht - sCmd.addCommand(order.c_str(), dhtSensor); -#endif - } else if (order == F("bme280")) { -#ifdef EnableSensorBme280 - sCmd.addCommand(order.c_str(), bme280Sensor); -#endif - } else if (order == F("bmp280")) { -#ifdef EnableSensorBmp280 - sCmd.addCommand(order.c_str(), bmp280Sensor); -#endif - } else if (order == F("ccs811")) { -#ifdef EnableSensorCcs811 - sCmd.addCommand(order.c_str(), ccs811Sensor); -#endif - } else if (order == F("pzem")) { -#ifdef EnableSensorPzem - sCmd.addCommand(order.c_str(), pzemSensor); -#endif - } else if (order == F("uptime")) { -#ifdef EnableSensorUptime - sCmd.addCommand(order.c_str(), uptimeSensor); -#endif - } else if (order == F("logging")) { -#ifdef EnableLogging - sCmd.addCommand(order.c_str(), logging); -#endif - } else if (order == F("impuls-out")) { -#ifdef EnableImpulsOut - sCmd.addCommand(order.c_str(), impuls); -#endif - } else if (order == F("count-down")) { -#ifdef EnableCountDown - sCmd.addCommand(order.c_str(), countDown); -#endif - } else if (order == F("impuls-in")) { -#ifdef EnableImpulsIn - //sCmd.addCommand(order.c_str(), impulsInSensor); -#endif - } else if (order == F("sensor-node")) { -#ifdef EnableSensorNode - sCmd.addCommand(order.c_str(), nodeSensor); -#endif - } - - sCmd.readStr(buf); - } - cmdStr = deleteBeforeDelimiter(cmdStr, "\n"); - } -} - -void spaceCmdExecute(String& cmdStr) { - cmdStr += "\r\n"; - cmdStr.replace("\r\n", "\n"); - cmdStr.replace("\r", "\n"); - while (cmdStr.length()) { - String buf = selectToMarker(cmdStr, "\n"); - if (buf != "") { - sCmd.readStr(buf); - SerialPrint("I", F("Order done W"), buf); - } - cmdStr = deleteBeforeDelimiter(cmdStr, "\n"); - } -} - -//альтернативный вариант распределяющий нагрузку более правильно -void spaceCmdExecute2(String& cmdStr) { - cmdStr += "\r\n"; - cmdStr.replace("\r\n", "\n"); - cmdStr.replace("\r", "\n"); - cmdStr.replace("\n", ","); - cmdStr.replace(",,", ","); - loopCmdAdd(cmdStr); -} - -void addKey(String& key, String& keyNumberTable, int number) { - keyNumberTable += key + " " + String(number) + ","; -} - -int getKeyNum(String& key, String& keyNumberTable) { - String keyNumberTableBuf = keyNumberTable; - - int number = -1; - while (keyNumberTableBuf.length()) { - String tmp = selectToMarker(keyNumberTableBuf, ","); - String keyIncomming = selectToMarker(tmp, " "); - if (keyIncomming == key) { - number = selectToMarkerLast(tmp, " ").toInt(); - } - keyNumberTableBuf = deleteBeforeDelimiter(keyNumberTableBuf, ","); - } - return number; -} - -String getValue(String& key) { - String live = jsonReadStr(configLiveJson, key); - String store = jsonReadStr(configStoreJson, key); - if (live != nullptr) { - return live; - } else if (store != nullptr) { - return store; - } else if (store == nullptr && live == nullptr) { - return "no value"; - } else { - return "data error"; - } -} \ No newline at end of file diff --git a/src/Bus.cpp b/src/Bus.cpp deleted file mode 100644 index eeff8108..00000000 --- a/src/Bus.cpp +++ /dev/null @@ -1,41 +0,0 @@ -#include "Bus.h" -#include "Class/NotAsync.h" -#include "Global.h" - -void busInit() { - myNotAsyncActions->add( - do_BUSSCAN, [&](void*) { - String tmp = i2c_scan(); - if (tmp == "error") { - tmp = i2c_scan(); - Serial.println(tmp); - jsonWriteStr(configLiveJson, "i2c", tmp); - } - else { - Serial.println(tmp); - jsonWriteStr(configLiveJson, "i2c", tmp); - } - }, - nullptr); - SerialPrint("I", F("Bus"), F("Bus Init")); -} - -String i2c_scan() { - String out; - byte count = 0; - Wire.begin(); - for (byte i = 8; i < 120; i++) { - Wire.beginTransmission(i); - if (Wire.endTransmission() == 0) { - count++; - out += String(count) + ". 0x" + String(i, HEX) + "; "; - delay(1); - } - } - if (count == 0) { - return "error"; - } - else { - return out; - } -} \ No newline at end of file diff --git a/src/Class/CallBackTest.cpp b/src/Class/CallBackTest.cpp deleted file mode 100644 index 55252e5e..00000000 --- a/src/Class/CallBackTest.cpp +++ /dev/null @@ -1,49 +0,0 @@ -#include "Class/CallBackTest.h" - -CallBackTest::CallBackTest(){}; - -void CallBackTest::loop() { - count++; - if (count > 5000) { - // Проверяем что переменная содержит указатель - не пустая не null - // и непосредственно вызываем то, на что это указывает - // просто пишем имя - без () - это указатель на фунецию. - // () - вызываем функцию - с пустым набором параметров - - if (_cb != NULL) { - _cb(); - } - //или ровно тоже самое - //if (_cb) _cb(); - - if (_pcb) { - if (_pcb("SomeTextValue")) { - Serial.println("Got true!"); - } else { - Serial.println("Got false!"); - } - } - - count = 0; - } -} - -//передаем внутрь класса функцию любую void функцию без агрументов -void CallBackTest::setCallback(AsyncActionCb cb) { - _cb = cb; -} - -//передаем внутрь класса функцию любую void функцию с аргументами -void CallBackTest::setCallback(AsyncParamActionCb pcb) { - _pcb = pcb; -} -//CallBackTest* CB; - -//CB->setCallback([]() { -// Serial.println("123"); -//}); -// -//CB->setCallback([](const String str) { -// Serial.println(str); -// return true; -//}); \ No newline at end of file diff --git a/src/Class/LineParsing.cpp b/src/Class/LineParsing.cpp deleted file mode 100644 index 9e9e7ac0..00000000 --- a/src/Class/LineParsing.cpp +++ /dev/null @@ -1,2 +0,0 @@ -#include "Class/LineParsing.h" -LineParsing myLineParsing; \ No newline at end of file diff --git a/src/Class/NotAsync.cpp b/src/Class/NotAsync.cpp deleted file mode 100644 index 75c2ce24..00000000 --- a/src/Class/NotAsync.cpp +++ /dev/null @@ -1,30 +0,0 @@ -#include "Class/NotAsync.h" - -NotAsync::NotAsync(uint8_t size) { - this->items = new NotAsyncItem[size]; - this->size = size; -} - -NotAsync::~NotAsync() {} - -void NotAsync::add(uint8_t i, NotAsyncCb f, void* arg) { - this->items[i].cb = f; - this->items[i].cb_arg = arg; - this->items[i].is_used = true; -} - -void NotAsync::loop() { - if (this->items[task].is_used) { - handle(this->items[task].cb, this->items[task].cb_arg); - task = 0; - } -} - -void NotAsync::make(uint8_t task) { - this->task = task; -} - -void NotAsync::handle(NotAsyncCb f, void* arg) { - f(arg); -} -NotAsync* myNotAsyncActions; \ No newline at end of file diff --git a/src/Class/ScenarioClass3.cpp b/src/Class/ScenarioClass3.cpp deleted file mode 100644 index e929636c..00000000 --- a/src/Class/ScenarioClass3.cpp +++ /dev/null @@ -1,35 +0,0 @@ -#include "Class/ScenarioClass3.h" - -#include "MqttClient.h" -#include "RemoteOrdersUdp.h" -Scenario* myScenario; - -void eventGen2(String eventName, String eventValue) { - if (!jsonReadBool(configSetupJson, "scen")) { - return; - } - String event = eventName + " " + eventValue + ","; - eventBuf += event; - - SerialPrint("I", "Event add", eventName + " " + eventValue); - - if (jsonReadBool(configSetupJson, "MqttOut")) { - if (eventName != "timenow") { - publishEvent(eventName, eventValue); - } - } -} - -void streamEventUDP(String event) { -#ifdef UDP_ENABLED - - if (!jsonReadBool(configSetupJson, "snaUdp")) { - return; - } - - if (event.indexOf("timenow") == -1) { - event = "iotm;event:" + event; - asyncUdp.broadcastTo(event.c_str(), 4210); - } -#endif -} \ No newline at end of file diff --git a/src/Class/TCircularBuffer.cpp b/src/Class/TCircularBuffer.cpp deleted file mode 100644 index 51932714..00000000 --- a/src/Class/TCircularBuffer.cpp +++ /dev/null @@ -1,4 +0,0 @@ -#include "Class/TCircularBuffer.h" - -TCircularBuffer *myTCircularBuffer; -TCircularBuffer *myWsBuffer; diff --git a/src/Clock.cpp b/src/Clock.cpp deleted file mode 100644 index 0cb26942..00000000 --- a/src/Clock.cpp +++ /dev/null @@ -1,16 +0,0 @@ -#include "Clock.h" - -#include "Global.h" - -Clock* timeNow; -void clockInit() { - timeNow = new Clock; - timeNow->setNtpPool(jsonReadStr(configSetupJson, "ntp")); - timeNow->setTimezone(jsonReadStr(configSetupJson, "timezone").toInt()); - ts.add( - TIME_SYNC, 30000, [&](void*) { - timeNow->hasSync(); - }, - nullptr, true); - SerialPrint("I", F("NTP"), F("Clock Init")); -} diff --git a/src/FSEditor.cpp b/src/FSEditor.cpp deleted file mode 100644 index 98be53cd..00000000 --- a/src/FSEditor.cpp +++ /dev/null @@ -1,334 +0,0 @@ -#include "FSEditor.h" - -#include "FileSystem.h" - -#define FS_MAXLENGTH_FILEPATH 32 - -const char *excludeListFile = "/.exclude.files"; -typedef struct ExcludeListS { - char *item; - ExcludeListS *next; -} ExcludeList; - -static ExcludeList *excludes = NULL; - -static bool matchWild(const char *pattern, const char *testee) { - const char *nxPat = NULL, *nxTst = NULL; - - while (*testee) { - if ((*pattern == '?') || (*pattern == *testee)) { - pattern++; - testee++; - continue; - } - if (*pattern == '*') { - nxPat = pattern++; - nxTst = testee; - continue; - } - if (nxPat) { - pattern = nxPat + 1; - testee = ++nxTst; - continue; - } - return false; - } - while (*pattern == '*') { - pattern++; - } - return (*pattern == 0); -} - -static bool addExclude(const char *item) { - size_t len = strlen(item); - if (!len) { - return false; - } - ExcludeList *e = (ExcludeList *)malloc(sizeof(ExcludeList)); - if (!e) { - return false; - } - e->item = (char *)malloc(len + 1); - if (!e->item) { - free(e); - return false; - } - memcpy(e->item, item, len + 1); - e->next = excludes; - excludes = e; - return true; -} - -static void loadExcludeList(fs::FS &_fs, const char *filename) { - static char linebuf[FS_MAXLENGTH_FILEPATH]; - fs::File excludeFile = _fs.open(filename, "r"); - if (!excludeFile) { - return; - } - if (excludeFile.isDirectory()) { - excludeFile.close(); - return; - } - if (excludeFile.size() > 0) { - uint8_t idx; - bool isOverflowed = false; - while (excludeFile.available()) { - linebuf[0] = '\0'; - idx = 0; - int lastChar; - do { - lastChar = excludeFile.read(); - if (lastChar != '\r') { - linebuf[idx++] = (char)lastChar; - } - } while ((lastChar >= 0) && (lastChar != '\n') && (idx < FS_MAXLENGTH_FILEPATH)); - - if (isOverflowed) { - isOverflowed = (lastChar != '\n'); - continue; - } - isOverflowed = (idx >= FS_MAXLENGTH_FILEPATH); - linebuf[idx - 1] = '\0'; - if (!addExclude(linebuf)) { - excludeFile.close(); - return; - } - } - } - excludeFile.close(); -} - -static bool isExcluded(fs::FS &_fs, const char *filename) { - if (excludes == NULL) { - loadExcludeList(_fs, excludeListFile); - } - if (strcmp(excludeListFile, filename) == 0) return true; - ExcludeList *e = excludes; - while (e) { - if (matchWild(e->item, filename)) { - return true; - } - e = e->next; - } - return false; -} - -// WEB HANDLER IMPLEMENTATION - -#ifdef ESP32 -FSEditor::FSEditor(const fs::FS &fs, const String &username, const String &password) -#else -FSEditor::FSEditor(const String &username, const String &password, const fs::FS &fs) -#endif - : _fs(fs), _username(username), _password(password), _authenticated(false), _startTime(0) { -} - -bool FSEditor::canHandle(AsyncWebServerRequest *request) { - if (request->url().equalsIgnoreCase("/edit")) { - if (request->method() == HTTP_GET) { - if (request->hasParam("list")) - return true; - if (request->hasParam("edit")) { - request->_tempFile = _fs.open(request->arg("edit"), "r"); - if (!request->_tempFile) { - return false; - } - if (request->_tempFile.isDirectory()) { - request->_tempFile.close(); - return false; - } - } - if (request->hasParam("download")) { - request->_tempFile = _fs.open(request->arg("download"), "r"); - if (!request->_tempFile) { - return false; - } - if (request->_tempFile.isDirectory()) { - request->_tempFile.close(); - return false; - } - } - request->addInterestingHeader("If-Modified-Since"); - return true; - } else if (request->method() == HTTP_POST) - return true; - else if (request->method() == HTTP_DELETE) - return true; - else if (request->method() == HTTP_PUT) - return true; - } - return false; -} - -#ifdef ESP8266 -void FSEditor::getDirList(const String &path, String &output) { - auto dir = _fs.openDir(path.c_str()); - while (dir.next()) { - String fname = dir.fileName(); - if (!path.endsWith("/") && !fname.startsWith("/")) { - fname = "/" + fname; - } - fname = path + fname; - if (isExcluded(_fs, fname.c_str())) { - continue; - } - if (dir.isDirectory()) { - getDirList(fname, output); - continue; - } - if (output != "[") output += ','; - char buf[128]; - sprintf(buf, "{\"type\":\"file\",\"name\":\"%s\",\"size\":%d}", fname.c_str(), dir.fileSize()); - output += buf; - } -} -#else -void FSEditor::getDirList(const String &path, String &output) { - auto dir = _fs.open(path, FILE_READ); - dir.rewindDirectory(); - while (dir.openNextFile()) { - String fname = dir.name(); - if (!path.endsWith("/") && !fname.startsWith("/")) { - fname = "/" + fname; - } - fname = path + fname; - if (isExcluded(_fs, fname.c_str())) { - continue; - } - if (dir.isDirectory()) { - getDirList(fname, output); - continue; - } - if (output != "[") output += ','; - char buf[128]; - sprintf(buf, "{\"type\":\"file\",\"name\":\"%s\",\"size\":%d}", fname.c_str(), dir.size()); - output += buf; - } -} -#endif - -void FSEditor::handleRequest(AsyncWebServerRequest *request) { - if (_username.length() && _password.length() && !request->authenticate(_username.c_str(), _password.c_str())) - return request->requestAuthentication(); - - if (request->method() == HTTP_GET) { - if (request->hasParam("list")) { - if (request->hasParam("list")) { - String path = request->getParam("list")->value(); - String output = "["; - getDirList(path, output); - output += "]"; - request->send(200, "application/json", output); - output = String(); - } - } else if (request->hasParam("edit") || request->hasParam("download")) { -#ifdef ESP8266 - request->send(request->_tempFile, request->_tempFile.fullName(), String(), request->hasParam("download")); -#else - request->send(request->_tempFile, request->_tempFile.name(), String(), request->hasParam("download")); -#endif - } else { - const char *buildTime = __DATE__ " " __TIME__ " GMT"; - if (request->header("If-Modified-Since").equals(buildTime)) { - request->send(304); - } else { - AsyncWebServerResponse *response = request->beginResponse(FileFS, "/edit.htm", "text/html"); - // response->addHeader("Content-Encoding", "gzip"); - response->addHeader("Last-Modified", buildTime); - request->send(response); - } - } - } else if (request->method() == HTTP_DELETE) { - if (request->hasParam("path", true)) { - if (!(_fs.remove(request->getParam("path", true)->value()))) { -#ifdef ESP32 - _fs.rmdir(request->getParam("path", true)->value()); // try rmdir for littlefs -#endif - } - - request->send(200, "", "DELETE: " + request->getParam("path", true)->value()); - } else - request->send(404); - } else if (request->method() == HTTP_POST) { - if (request->hasParam("data", true, true) && _fs.exists(request->getParam("data", true, true)->value())) - request->send(200, "", "UPLOADED: " + request->getParam("data", true, true)->value()); - - else if (request->hasParam("rawname", true) && request->hasParam("raw0", true)) { - String rawnam = request->getParam("rawname", true)->value(); - - if (_fs.exists(rawnam)) _fs.remove(rawnam); // delete it to allow a mode - - int k = 0; - uint16_t i = 0; - fs::File f = _fs.open(rawnam, "a"); - - while (request->hasParam("raw" + String(k), true)) { //raw0 .. raw1 - if (f) { - i += f.print(request->getParam("raw" + String(k), true)->value()); - } - k++; - } - f.close(); - request->send(200, "", "IPADWRITE: " + rawnam + ":" + String(i)); - - } else { - request->send(500); - } - - } else if (request->method() == HTTP_PUT) { - if (request->hasParam("path", true)) { - String filename = request->getParam("path", true)->value(); - if (_fs.exists(filename)) { - request->send(200); - } else { -/*******************************************************/ -#ifdef ESP32 - if (strchr(filename.c_str(), '/')) { - // For file creation, silently make subdirs as needed. If any fail, - // it will be caught by the real file open later on - char *pathStr = strdup(filename.c_str()); - if (pathStr) { - // Make dirs up to the final fnamepart - char *ptr = strchr(pathStr, '/'); - while (ptr) { - *ptr = 0; - _fs.mkdir(pathStr); - *ptr = '/'; - ptr = strchr(ptr + 1, '/'); - } - } - free(pathStr); - } -#endif - /*******************************************************/ - fs::File f = _fs.open(filename, "w"); - if (f) { - f.write((uint8_t)0x00); - f.close(); - request->send(200, "", "CREATE: " + filename); - } else { - request->send(500); - } - } - } else - request->send(400); - } -} - -void FSEditor::handleUpload(AsyncWebServerRequest *request, const String &filename, size_t index, uint8_t *data, size_t len, bool final) { - if (!index) { - if (!_username.length() || request->authenticate(_username.c_str(), _password.c_str())) { - _authenticated = true; - request->_tempFile = _fs.open(filename, "w"); - _startTime = millis(); - } - } - if (_authenticated && request->_tempFile) { - if (len) { - request->_tempFile.write(data, len); - } - if (final) { - request->_tempFile.close(); - } - } -} diff --git a/src/FileSystem.cpp b/src/FileSystem.cpp deleted file mode 100644 index a7f136b2..00000000 --- a/src/FileSystem.cpp +++ /dev/null @@ -1,50 +0,0 @@ -#include "FileSystem.h" - -#include "Global.h" - -#ifdef ESP8266 -bool getInfo(FSInfo& info) { - return FileFS.info(info); -} - -// Информация о ФС -void getFSInfo() { - FSInfo buf; - if (getInfo(buf)) { - //SerialPrint("I", F("FS"), F("Get FS info completed")); - - size_t totalBytes = buf.totalBytes; // всего - size_t usedBytes = buf.usedBytes; // использовано - //size_t maxOpenFiles = buf.maxOpenFiles; // лимит на открые файлы - //size_t blockSize = buf.blockSize; - //size_t pageSize = buf.pageSize; - //size_t maxPathLength = buf.maxPathLength; // лимит на пути и имена файлов - - size_t freeBytes = totalBytes - usedBytes; - float freePer = ((float)freeBytes / totalBytes) * 100; - - jsonWriteStr(configSetupJson, F("freeBytes"), String(freePer) + "% (" + prettyBytes(freeBytes) + ")"); - - //SerialPrint("I", F("FS"), "totalBytes=" + String(totalBytes)); - //SerialPrint("I", F("FS"), "usedBytes=" + String(usedBytes)); - //SerialPrint("I", F("FS"), "maxOpenFiles=" + String(maxOpenFiles)); - //SerialPrint("I", F("FS"), "blockSize=" + String(blockSize)); - //SerialPrint("I", F("FS"), "pageSize=" + String(pageSize)); - //SerialPrint("I", F("FS"), "maxPathLength=" + String(maxPathLength)); - //SerialPrint("I", F("FS"), "freeBytes=" + String(freeBytes)); - //SerialPrint("I", F("FS"), "freePer=" + String(freePer)); - } else { - SerialPrint("E", F("FS"), F("FS info error")); - } -} -#endif - -#ifdef ESP32 -void getFSInfo() { - size_t totalBytes = FileFS.totalBytes(); // всего - size_t usedBytes = FileFS.usedBytes(); // использовано - size_t freeBytes = totalBytes - usedBytes; - float freePer = ((float)freeBytes / totalBytes) * 100; - jsonWriteStr(configSetupJson, F("freeBytes"), String(freePer) + "% (" + prettyBytes(freeBytes) + ")"); -} -#endif diff --git a/src/Global.cpp b/src/Global.cpp deleted file mode 100644 index 60d9e952..00000000 --- a/src/Global.cpp +++ /dev/null @@ -1,95 +0,0 @@ -#include "Global.h" - -#ifdef WS_enable -AsyncWebSocket ws; -AsyncEventSource events; -#endif - -TickerScheduler ts(MYTEST + 1); -WiFiClient espClient; -PubSubClient mqtt(espClient); -StringCommand sCmd; -AsyncWebServer server(80); - -/* - * Global vars - */ - -boolean just_load = true; -boolean telegramInitBeen = false; -boolean savedFromWeb = false; -boolean wsSetupFlag = false; - -// Json -String configSetupJson = "{}"; -String configLiveJson = "{}"; -String configStoreJson = "{}"; -String configOptionJson = "{}"; -String telegramMsgJson = "{}"; - -// Mqtt -String mqttServer = ""; -int mqttPort = 0; -String mqttPrefix = ""; -String mqttUser = ""; -String mqttPass = ""; - -String chipId = ""; -String prex = ""; -String all_widgets = ""; -String scenario = ""; -String mqttRootDevice = ""; - -int mqttConnectAttempts = 0; -bool changeBroker = false; -int currentBroker = 1; - -// web sockets -int wsAttempts = 100; -//char* wsBufChar = ""; - -// orders and events -String orderBuf = ""; -String wsBuf = ""; -String eventBuf = ""; -String mysensorBuf = ""; -String itemsFile = ""; -String itemsLine = ""; - -// key lists and numbers -//========================================= -String impuls_KeyList = ""; -int impuls_EnterCounter = -1; -//========================================= -String buttonOut_KeyList = ""; -int buttonOut_EnterCounter = -1; -//========================================= -String input_KeyList = ""; -int input_EnterCounter = -1; -//========================================= -String output_KeyList = ""; -int output_EnterCounter = -1; -//========================================= -String pwmOut_KeyList = ""; -int pwmOut_EnterCounter = -1; -//========================================= -String countDown_KeyList = ""; -int countDown_EnterCounter = -1; -//========================================= -String logging_KeyList = ""; -int logging_EnterCounter = -1; -//========================================= - -String itemName; -String presetName; - -// Upgrade -String serverIP; - -// Scenario -int scenario_line_status[] = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1}; -int lastVersion; - -boolean busScanFlag = false; -boolean fsCheckFlag = false; -boolean delElementFlag = false; diff --git a/src/Init.cpp b/src/Init.cpp deleted file mode 100644 index 2aed131e..00000000 --- a/src/Init.cpp +++ /dev/null @@ -1,215 +0,0 @@ -#include "Init.h" - -#include "BufferExecute.h" -#include "Class/LineParsing.h" -#include "Cmd.h" -#include "Global.h" -#include "items/vButtonOut.h" -#include "items/vCountDown.h" -#include "items/vImpulsOut.h" -#include "items/vInput.h" -#include "items/vLogging.h" -#include "items/vOutput.h" -#include "items/vPwmOut.h" -#include "items/vSensorAnalog.h" -#include "items/vSensorBme280.h" -#include "items/vSensorBmp280.h" -#include "items/vSensorCcs811.h" -#include "items/vSensorDallas.h" -#include "items/vSensorDht.h" -#include "items/vSensorNode.h" -#include "items/vSensorPzem.h" -#include "items/vSensorUltrasonic.h" -#include "items/vSensorUptime.h" - -void loadConfig() { - configSetupJson = readFile("config.json", 4096); - configSetupJson.replace("\r\n", ""); - - String tmp = readFile("store.json", 4096); - if (tmp != "failed") { - configStoreJson = tmp; - } - configStoreJson.replace("\r\n", ""); - - jsonWriteStr(configSetupJson, "warning1", ""); - jsonWriteStr(configSetupJson, "warning2", ""); - jsonWriteStr(configSetupJson, "warning3", ""); - - jsonWriteStr(configSetupJson, "chipID", chipId); - jsonWriteInt(configSetupJson, "firmware_version", FIRMWARE_VERSION); - jsonWriteStr(configSetupJson, "firmware_name", FIRMWARE_NAME); - - selectBroker(); - - serverIP = jsonReadStr(configSetupJson, "serverip"); - - SerialPrint("I", F("Conf"), F("Config Json Init")); -} - -void espInit() { - deviceInit(); - loadScenario(); - SerialPrint("I", F("esp"), F("esp Init")); -} - -void deviceInit() { - clearVectors(); - -#ifdef LAYOUT_IN_RAM - all_widgets = ""; -#else - removeFile(String("layout.txt")); -#endif - - myLineParsing.clearErrors(); - - fileCmdExecute(String(DEVICE_CONFIG_FILE)); - - int errors = myLineParsing.getPinErrors(); - - if (errors > 0) { - jsonWriteStr(configSetupJson, F("warning3"), F("

Обнаружен неверный номер пина

")); - } else { - jsonWriteStr(configSetupJson, F("warning3"), ""); - } - - savedFromWeb = false; - // publishWidgets(); - // publishState(); -} - -void loadScenario() { - if (jsonReadStr(configSetupJson, "scen") == "1") { - scenario = readFile(String(DEVICE_SCENARIO_FILE), 10240); - scenario.replace("\r\n", "\n"); - scenario.replace("\r", "\n"); - scenario.replace("~\n", ""); - scenario.replace("~", ""); - scenario += "\n"; - if (scenario.startsWith("setup\n")) { - String setup = selectToMarker(scenario, "end\n"); - setup.replace("setup\n", ""); - spaceCmdExecute(setup); - scenario = deleteBeforeDelimiter(scenario, "end\n"); - } - } -} - -void uptime_init() { - ts.add( - UPTIME, 5000, [&](void*) { - handle_uptime(); - }, - nullptr, true); - SerialPrint("I", F("Uptime"), F("Uptime Init")); -} - -void handle_uptime() { - jsonWriteStr(configSetupJson, "uptime", timeNow->getUptime()); -} - -void clearVectors() { -#ifdef EnableLogging - if (myLogging != nullptr) { - myLogging->clear(); - } - logging_KeyList = ""; - logging_EnterCounter = -1; -#endif -#ifdef EnableImpulsOut - if (myImpulsOut != nullptr) { - myImpulsOut->clear(); - } - impuls_KeyList = ""; - impuls_EnterCounter = -1; -#endif - -#ifdef EnableCountDown - if (myCountDown != nullptr) { - myCountDown->clear(); - } - countDown_KeyList = ""; - countDown_EnterCounter = -1; -#endif - -#ifdef EnableButtonOut - if (myButtonOut != nullptr) { - myButtonOut->clear(); - } - buttonOut_KeyList = ""; - buttonOut_EnterCounter = -1; -#endif -#ifdef EnableInput - if (myInput != nullptr) { - myInput->clear(); - } - input_KeyList = ""; - input_EnterCounter = -1; -#endif -#ifdef EnableOutput - if (myOutput != nullptr) { - myOutput->clear(); - } - output_KeyList = ""; - output_EnterCounter = -1; -#endif -#ifdef EnablePwmOut - if (myPwmOut != nullptr) { - myPwmOut->clear(); - } - pwmOut_KeyList = ""; - pwmOut_EnterCounter = -1; -#endif - //================================== -#ifdef EnableSensorDallas - if (mySensorDallas2 != nullptr) { - mySensorDallas2->clear(); - } -#endif -#ifdef EnableSensorUltrasonic - if (mySensorUltrasonic != nullptr) { - mySensorUltrasonic->clear(); - } -#endif -#ifdef EnableSensorAnalog - if (mySensorAnalog != nullptr) { - mySensorAnalog->clear(); - } -#endif -#ifdef EnableSensorDht - if (mySensorDht != nullptr) { - mySensorDht->clear(); - } -#endif -#ifdef EnableSensorBme280 - if (mySensorBme280 != nullptr) { - mySensorBme280->clear(); - } -#endif -#ifdef EnableSensorBmp280 - if (mySensorBmp280 != nullptr) { - mySensorBmp280->clear(); - } -#endif -#ifdef EnableSensorCcs811 - if (mySensorCcs811 != nullptr) { - mySensorCcs811->clear(); - } -#endif -#ifdef EnableSensorPzem - if (mySensorPzem != nullptr) { - mySensorPzem->clear(); - } -#endif -#ifdef EnableSensorUptime - if (mySensorUptime != nullptr) { - mySensorUptime->clear(); - } -#endif -#ifdef EnableSensorNode - if (mySensorNode != nullptr) { - mySensorNode->clear(); - } -#endif -} diff --git a/src/ItemsList.cpp b/src/ItemsList.cpp deleted file mode 100644 index 5b75afb5..00000000 --- a/src/ItemsList.cpp +++ /dev/null @@ -1,266 +0,0 @@ -#include "ItemsList.h" - -#include "Class/NotAsync.h" -#include "FileSystem.h" -#include "Init.h" -#include "Utils/StringUtils.h" - -static const char* firstLine PROGMEM = "Удалить;Тип элемента;Id;Виджет;Имя вкладки;Имя виджета;Позиция виджета"; - -void itemsListInit() { - myNotAsyncActions->add( - do_deviceInit, [&](void*) { - deviceInit(); - }, - nullptr); - - myNotAsyncActions->add( - do_delChoosingItems, [&](void*) { - delChoosingItems(); - }, - nullptr); - - SerialPrint("I", F("Items"), F("Items Init")); -} - -void addItem2(int num) { - File configFile = FileFS.open("/items/items.txt", "r"); - if (!configFile) { - return; - } - configFile.seek(0, SeekSet); - String seachingLine; - int i = 0; - while (configFile.position() != configFile.size()) { - i++; - String item = configFile.readStringUntil('*'); - if (i == num) { - if (i == 1) { - seachingLine = "\n" + item; - } else { - seachingLine = item; - } - break; - } - } - configFile.close(); - - randomSeed(micros()); - unsigned int rnd = random(0, 1000); - seachingLine.replace("id", String(rnd)); - seachingLine.replace("order", String(getNewElementNumber("order.txt"))); - if (seachingLine.indexOf("gpio") != -1) { - seachingLine.replace("gpio", "pin[" + String(getFreePinAll()) + "]"); - } - - addFile(DEVICE_CONFIG_FILE, seachingLine); - //Serial.println(seachingLine); -} - -void addItemAuto(int num, String key, String widget, String descr) { - File configFile = FileFS.open("/items/itemsAuto.txt", "r"); - if (!configFile) { - return; - } - configFile.seek(0, SeekSet); - String seachingLine; - int i = 0; - while (configFile.position() != configFile.size()) { - i++; - String item = configFile.readStringUntil('*'); - if (i == num) { - if (i == 1) { - seachingLine = "\n" + item; - } else { - seachingLine = item; - } - break; - } - } - configFile.close(); - - seachingLine.replace("id", key); - seachingLine.replace("file", widget); - seachingLine.replace("descr", descr); - seachingLine.replace("order", String(getNewElementNumber("order.txt"))); - - addFile(DEVICE_CONFIG_FILE, seachingLine); -} - -bool isItemAdded(String key) { - File configFile = FileFS.open("/" + String(DEVICE_CONFIG_FILE), "r"); - if (!configFile) { - return false; - } - configFile.seek(0, SeekSet); - String seachingLine; - while (configFile.position() != configFile.size()) { - String item = configFile.readStringUntil('\n'); - String foundKey = selectFromMarkerToMarker(item, ";", 2); - if (foundKey == key) { - configFile.close(); - return true; - } - } - configFile.close(); - return false; -} - -void addPreset2(int num) { - File configFile = FileFS.open("/presets/presets.c.txt", "r"); - if (!configFile) { - return; - } - configFile.seek(0, SeekSet); - String config; - int i1 = 0; - while (configFile.position() != configFile.size()) { - i1++; - String item = configFile.readStringUntil('*'); - if (i1 == num) { - if (i1 == 1) { - config = "\n" + item; - } else { - config = item; - } - break; - } - } - configFile.close(); - addFile(DEVICE_CONFIG_FILE, config); - //=========================================================================== - File scenFile = FileFS.open("/presets/presets.s.txt", "r"); - if (!scenFile) { - return; - } - scenFile.seek(0, SeekSet); - String scen; - int i2 = 0; - while (scenFile.position() != scenFile.size()) { - i2++; - String item = scenFile.readStringUntil('*'); - if (i2 == num) { - if (i1 == 1) { - scen = "\n" + item; - } else { - scen = item; - } - break; - } - } - scenFile.close(); - if (readFile(String(DEVICE_SCENARIO_FILE), 2048) == "//") { - removeFile(DEVICE_SCENARIO_FILE); - scen = deleteBeforeDelimiter(scen, "\n"); - addFile(DEVICE_SCENARIO_FILE, scen); - } else { - addFile(DEVICE_SCENARIO_FILE, scen); - } -} - -void delAllItems() { - removeFile(DEVICE_CONFIG_FILE); - addFile(DEVICE_CONFIG_FILE, String(firstLine)); - removeFile(DEVICE_SCENARIO_FILE); - addFile(DEVICE_SCENARIO_FILE, "//"); - removeFile("id.txt"); - removeFile("order.txt"); - removeFile("pins.txt"); -} - -uint8_t getNewElementNumber(String file) { - uint8_t number = readFile(file, 100).toInt(); - number++; - removeFile(file); - addFile(file, String(number)); - return number; -} - -uint8_t getFreePinAll() { -#ifdef ESP8266 - uint8_t pins[] = {0, 12, 13, 14, 15, 16, 1, 2, 3, 4, 5}; -#endif -#ifdef ESP32 - uint8_t pins[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 25, 26, 27, 32, 33, 34, 35, 36, 39}; -#endif - uint8_t array_sz = sizeof(pins) / sizeof(pins[0]); - uint8_t i = getNewElementNumber("pins.txt"); - if (i < array_sz) { - return pins[i]; - } else { - return 0; - } -} - -bool isPinExist(unsigned int num) { - bool ret = false; -#ifdef ESP8266 - unsigned int pins[] = {0, 1, 2, 3, 4, 5, 9, 10, 12, 13, 14, 15, 16}; -#endif -#ifdef ESP32 - unsigned int pins[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12, 13, 14, 15, 16, 17, 18, 19, 21, 22, 23, 25, 26, 27, 32, 33, 34, 35, 36, 39}; -#endif - uint8_t array_sz = sizeof(pins) / sizeof(pins[0]); - for (uint8_t i = 0; i < array_sz; i++) { - if (pins[i] == num) ret = true; - } - return ret; -} - -uint8_t getFreePinAnalog() { -#ifdef ESP8266 - return 0; -#endif -} - -void delChoosingItems() { - File configFile = FileFS.open("/" + String(DEVICE_CONFIG_FILE), "r"); - if (!configFile) { - return; - } - configFile.seek(0, SeekSet); - String finalConf; - bool firstLine = true; - while (configFile.position() != configFile.size()) { - String item = configFile.readStringUntil('\n'); - if (firstLine) { - finalConf += item; - } else { - int checkbox = selectToMarker(item, ";").toInt(); - if (checkbox == 0) { - finalConf += "\n" + item; - } - } - firstLine = false; - } - removeFile(String(DEVICE_CONFIG_FILE)); - addFile(String(DEVICE_CONFIG_FILE), finalConf); - //Serial.println(finalConf); - configFile.close(); -} - -//void delChoosingItemsByNum(int num) { -// File configFile = FileFS.open("/" + String(DEVICE_CONFIG_FILE), "r"); -// if (!configFile) { -// return; -// } -// configFile.seek(0, SeekSet); -// String finalConf; -// -// int i = -1; -// while (configFile.position() != configFile.size()) { -// i++; -// String item = configFile.readStringUntil('\n'); -// if (i == 0) { -// finalConf += item; -// } else { -// if (i != num) { -// finalConf += "\n" + item; -// } -// } -// } -// removeFile(String(DEVICE_CONFIG_FILE)); -// addFile(String(DEVICE_CONFIG_FILE), finalConf); -// Serial.println(finalConf); -// configFile.close(); -//} \ No newline at end of file diff --git a/src/MqttClient.cpp b/src/MqttClient.cpp deleted file mode 100644 index 6543ea15..00000000 --- a/src/MqttClient.cpp +++ /dev/null @@ -1,417 +0,0 @@ -#include "MqttClient.h" - -#include "BufferExecute.h" -#include "Class/NotAsync.h" -#include "Global.h" -#include "Init.h" -#include "items/vLogging.h" -#include "items/vSensorNode.h" - -void mqttInit() { - myNotAsyncActions->add( - do_MQTTPARAMSCHANGED, [&](void*) { - mqttReconnect(); - }, - nullptr); - - mqtt.setCallback(mqttCallback); - - ts.add( - WIFI_MQTT_CONNECTION_CHECK, MQTT_RECONNECT_INTERVAL, - [&](void*) { - if (WiFi.status() == WL_CONNECTED) { - SerialPrint("I", F("WIFI"), F("OK")); - if (mqtt.connected()) { - SerialPrint("I", F("MQTT"), "OK, broker No " + String(currentBroker)); - setLedStatus(LED_OFF); - } else { - SerialPrint("E", F("MQTT"), F("✖ Connection lost")); - mqttConnect(); - } - } else { - SerialPrint("E", F("WIFI"), F("✖ Lost WiFi connection")); - ts.remove(WIFI_MQTT_CONNECTION_CHECK); - startAPMode(); - } - }, - nullptr, true); - - myNotAsyncActions->add( - do_sendScenMQTT, [&](void*) { - String scen = readFile(String(DEVICE_SCENARIO_FILE), 2048); - publishInfo("scen", scen); - }, - nullptr); -} - -void mqttDisconnect() { - SerialPrint("I", F("MQTT"), F("disconnected")); - mqtt.disconnect(); -} - -void mqttReconnect() { - mqttDisconnect(); - mqttConnect(); -} - -void mqttLoop() { - if (!isNetworkActive() || !mqtt.connected()) { - return; - } - mqtt.loop(); -} - -void mqttSubscribe() { - SerialPrint("I", F("MQTT"), F("subscribed")); - SerialPrint("I", "MQTT", mqttRootDevice); - mqtt.subscribe(mqttPrefix.c_str()); - mqtt.subscribe((mqttRootDevice + "/+/control").c_str()); - mqtt.subscribe((mqttRootDevice + "/update").c_str()); - - if (jsonReadBool(configSetupJson, "MqttIn")) { - mqtt.subscribe((mqttPrefix + "/+/+/event").c_str()); - mqtt.subscribe((mqttPrefix + "/+/+/order").c_str()); - mqtt.subscribe((mqttPrefix + "/+/+/info").c_str()); - } -} - -void selectBroker() { - if (changeBroker) { - changeBroker = false; - if (currentBroker == 1) { - getMqttData2(); - } else if (currentBroker == 2) { - getMqttData1(); - } - } else { - if (currentBroker == 1) { - getMqttData1(); - } else if (currentBroker == 2) { - getMqttData2(); - } - } -} - -void getMqttData1() { - currentBroker = 1; - mqttServer = jsonReadStr(configSetupJson, F("mqttServer")); - mqttPort = jsonReadInt(configSetupJson, F("mqttPort")); - mqttPrefix = jsonReadStr(configSetupJson, F("mqttPrefix")); - mqttUser = jsonReadStr(configSetupJson, F("mqttUser")); - mqttPass = jsonReadStr(configSetupJson, F("mqttPass")); - prex = mqttPrefix + "/" + chipId; -} - -void getMqttData2() { - currentBroker = 2; - mqttServer = jsonReadStr(configSetupJson, F("mqttServer2")); - mqttPort = jsonReadInt(configSetupJson, F("mqttPort2")); - mqttPrefix = jsonReadStr(configSetupJson, F("mqttPrefix2")); - mqttUser = jsonReadStr(configSetupJson, F("mqttUser2")); - mqttPass = jsonReadStr(configSetupJson, F("mqttPass2")); - prex = mqttPrefix + "/" + chipId; -} - -bool isSecondBrokerSet() { - bool res = true; - if (jsonReadStr(configSetupJson, F("mqttServer2")) == "") { - res = false; - } - if (jsonReadStr(configSetupJson, F("mqttPrefix2")) == "") { - res = false; - } - return res; -} - -boolean mqttConnect() { - selectBroker(); - bool res = false; - if (mqttServer == "") { - SerialPrint("E", "MQTT", F("mqttServer empty")); - return res; - } - SerialPrint("I", "MQTT", "connection started to broker No " + String(currentBroker)); - - mqttRootDevice = mqttPrefix + "/" + chipId; - - SerialPrint("I", "MQTT", "broker " + mqttServer + ":" + String(mqttPort, DEC)); - SerialPrint("I", "MQTT", "topic " + mqttRootDevice); - setLedStatus(LED_FAST); - mqtt.setServer(mqttServer.c_str(), mqttPort); - - if (!mqtt.connected()) { - bool connected = false; - if (mqttUser != "" && mqttPass != "") { - connected = mqtt.connect(chipId.c_str(), mqttUser.c_str(), mqttPass.c_str()); - SerialPrint("I", F("MQTT"), F("Go to connection with login and password")); - } else if (mqttUser == "" && mqttPass == "") { - connected = mqtt.connect(chipId.c_str()); - SerialPrint("I", F("MQTT"), F("Go to connection without login and password")); - } else { - SerialPrint("E", F("MQTT"), F("✖ Login or password missing")); - return res; - } - - if (connected) { - SerialPrint("I", F("MQTT"), F("✔ connected")); - if (currentBroker == 1) jsonWriteStr(configSetupJson, F("warning4"), F("

Подключено к основному брокеру

")); - if (currentBroker == 2) jsonWriteStr(configSetupJson, F("warning4"), F("

Подключено к резервному брокеру

")); - setLedStatus(LED_OFF); - mqttSubscribe(); - res = true; - } else { - mqttConnectAttempts++; - SerialPrint("E", F("MQTT"), "🡆 Attempt No: " + String(mqttConnectAttempts) + " could't connect, retry in " + String(MQTT_RECONNECT_INTERVAL / 1000) + "s"); - setLedStatus(LED_FAST); - jsonWriteStr(configSetupJson, F("warning4"), F("

Не подключено брокеру

")); - if (mqttConnectAttempts >= CHANGE_BROKER_AFTER) { - mqttConnectAttempts = 0; - if (isSecondBrokerSet()) { - changeBroker = true; - SerialPrint("E", F("MQTT"), "✖ Broker fully missed (" + String(CHANGE_BROKER_AFTER) + " attempts passed), try connect to another one"); - } else { - SerialPrint("E", F("MQTT"), F("Secound broker not seted")); - } - } - } - } - return res; -} - -void mqttCallback(char* topic, uint8_t* payload, size_t length) { - String topicStr = String(topic); - // SerialPrint("I", "=>MQTT", topicStr); - String payloadStr; - payloadStr.reserve(length + 1); - for (size_t i = 0; i < length; i++) { - payloadStr += (char)payload[i]; - } - - // SerialPrint("I", "=>MQTT", payloadStr); - - if (payloadStr.startsWith("HELLO")) { - SerialPrint("I", F("MQTT"), F("Full update")); - publishWidgets(); - publishState(); -#ifdef GATE_MODE - publishTimes(); -#endif -#ifdef EnableLogging - choose_log_date_and_send(); -#endif - } - - else if (topicStr.indexOf("control") != -1) { - String key = selectFromMarkerToMarker(topicStr, "/", 3); - - String order; - order += key; - order += " "; - order += payloadStr; - order += ","; - - loopCmdAdd(order); - - SerialPrint("I", F("=>MQTT"), "Msg from iotmanager app: " + key + " " + payloadStr); - } - - else if (topicStr.indexOf("event") != -1) { - if (!jsonReadBool(configSetupJson, "MqttIn")) { - return; - } - if (topicStr.indexOf(chipId) == -1) { - String devId = selectFromMarkerToMarker(topicStr, "/", 2); - String key = selectFromMarkerToMarker(topicStr, "/", 3); - SerialPrint("I", F("=>MQTT"), "Received event from other device: '" + devId + "' " + key + " " + payloadStr); - String event = key + " " + payloadStr + ","; - eventBuf += event; - } - } - - else if (topicStr.indexOf("order") != -1) { - if (!jsonReadBool(configSetupJson, "MqttIn")) { - return; - } - String devId = selectFromMarkerToMarker(topicStr, "/", 2); - String key = selectFromMarkerToMarker(topicStr, "/", 3); - SerialPrint("I", F("=>MQTT"), "Received direct order " + key + " " + payloadStr); - String order = key + " " + payloadStr + ","; - loopCmdAdd(order); - SerialPrint("I", "Order add", order); - } - - else if (topicStr.indexOf("info") != -1) { - if (topicStr.indexOf("scen") != -1) { - writeFile(String(DEVICE_SCENARIO_FILE), payloadStr); - loadScenario(); - SerialPrint("I", F("=>MQTT"), F("Scenario received")); - } - } -} - -boolean publish(const String& topic, const String& data) { - if (mqtt.beginPublish(topic.c_str(), data.length(), false)) { - mqtt.print(data); - return mqtt.endPublish(); - } - return false; -} - -boolean publishData(const String& topic, const String& data) { - String path = mqttRootDevice + "/" + topic; - if (!publish(path, data)) { - SerialPrint("E", F("MQTT"), F("on publish data")); - return false; - } - return true; -} - -boolean publishChart(const String& topic, const String& data) { - String path = mqttRootDevice + "/" + topic + "/status"; - if (!publish(path, data)) { - SerialPrint("E", F("MQTT"), F("on publish chart")); - return false; - } - return true; -} - -boolean publishControl(String id, String topic, String state) { - String path = mqttPrefix + "/" + id + "/" + topic + "/control"; - return mqtt.publish(path.c_str(), state.c_str(), false); -} - -boolean publishChart_test(const String& topic, const String& data) { - String path = mqttRootDevice + "/" + topic + "/status"; - return mqtt.publish(path.c_str(), data.c_str(), false); -} - -boolean publishStatus(const String& topic, const String& data) { - String path = mqttRootDevice + "/" + topic + "/status"; - String json = "{}"; - jsonWriteStr(json, "status", data); - return mqtt.publish(path.c_str(), json.c_str(), false); -} - -boolean publishAnyJsonKey(const String& topic, const String& key, const String& data) { - String path = mqttRootDevice + "/" + topic + "/status"; - String json = "{}"; - jsonWriteStr(json, key, data); - return mqtt.publish(path.c_str(), json.c_str(), false); -} - -boolean publishEvent(const String& topic, const String& data) { - String path = mqttRootDevice + "/" + topic + "/event"; - return mqtt.publish(path.c_str(), data.c_str(), false); -} - -boolean publishInfo(const String& topic, const String& data) { - String path = mqttRootDevice + "/" + topic + "/info"; - return mqtt.publish(path.c_str(), data.c_str(), false); -} - -#ifdef LAYOUT_IN_RAM -void publishWidgets() { - if (all_widgets != "") { - int counter = 0; - String line; - int psn_1 = 0; - int psn_2; - do { - psn_2 = all_widgets.indexOf("\r\n", psn_1); //\r\n - line = all_widgets.substring(psn_1, psn_2); - line.replace("\n", ""); - line.replace("\r\n", ""); - // jsonWriteStr(line, "id", String(counter)); - // jsonWriteStr(line, "pageId", String(counter)); - counter++; - sendMQTT("config", line); - Serial.println("[V] " + line); - psn_1 = psn_2 + 1; - } while (psn_2 + 2 < all_widgets.length()); - getMemoryLoad("I after send all widgets"); - } -} -#endif - -#ifndef LAYOUT_IN_RAM -void publishWidgets() { - auto file = seekFile("layout.txt"); - if (!file) { - SerialPrint("E", F("MQTT"), F("no file layout.txt")); - return; - } - while (file.available()) { - String payload = file.readStringUntil('\n'); - SerialPrint("I", F("MQTT"), "widgets: " + payload); - publishData("config", payload); - } - file.close(); -} -#endif - -void publishState() { - // берет строку json и ключи превращает в топики а значения колючей в них посылает - String str; - if (configLiveJson != "{}") { - str += configLiveJson; - } - if (configStoreJson != "{}") { - str += "," + configStoreJson; - } - str.replace("{", ""); - str.replace("}", ""); - str.replace("\"", ""); - str += ","; - - while (str.length() != 0) { - String tmp = selectToMarker(str, ","); - - String topic = selectToMarker(tmp, ":"); - String state = deleteBeforeDelimiter(tmp, ":"); - - if (topic != "" && state != "") { - if (topic != "timenow") { - publishStatus(topic, state); - } - } - str = deleteBeforeDelimiter(str, ","); - } -} - -const String getStateStr() { - switch (mqtt.state()) { - case -4: - return F("no respond"); - break; - case -3: - return F("connection was broken"); - break; - case -2: - return F("connection failed"); - break; - case -1: - return F("client disconnected"); - break; - case 0: - return F("client connected"); - break; - case 1: - return F("doesn't support the requested version"); - break; - case 2: - return F("rejected the client identifier"); - break; - case 3: - return F("unable to accept the connection"); - break; - case 4: - return F("wrong username/password"); - break; - case 5: - return F("not authorized to connect"); - break; - default: - return F("unspecified"); - break; - } -} diff --git a/src/MySensorsDataParse.cpp b/src/MySensorsDataParse.cpp deleted file mode 100644 index 10de9fe3..00000000 --- a/src/MySensorsDataParse.cpp +++ /dev/null @@ -1,318 +0,0 @@ -#include "Consts.h" -#ifdef MYSENSORS -#include "Class/NotAsync.h" -#include "ItemsList.h" -#include "MySensorsDataParse.h" -#include "items/vSensorNode.h" - -//для того что бы выключить оригинальный лог нужно перейти в файл библиотеки MyGatewayTransportSerial.cpp -//и заккоментировать строку 36 MY_SERIALDEVICE.print(protocolMyMessage2Serial(message)); - -void loopMySensorsExecute() { - if (mysensorBuf.length()) { - String tmp = selectToMarker(mysensorBuf, ";"); - - String nodeId = selectFromMarkerToMarker(tmp, ",", 0); //node-id - String childSensorId = selectFromMarkerToMarker(tmp, ",", 1); //child-sensor-id - String type = selectFromMarkerToMarker(tmp, ",", 2); //type of var - String command = selectFromMarkerToMarker(tmp, ",", 3); //command - String value = selectFromMarkerToMarker(tmp, ",", 4); //value - - static bool presentBeenStarted = false; - - String key = nodeId + "-" + childSensorId; - static String infoJson = "{}"; - - if (childSensorId == "255") { - if (command == "3") { //это особое внутреннее сообщение - if (type == "11") { //название ноды - SerialPrint("I", "MySensor", "Node name: " + value); - } - if (type == "12") { //версия ноды - SerialPrint("I", "MySensor", "Node version: " + value); - } - } - } else { - if (command == "0") { //это презентация - presentBeenStarted = true; - int num; - String widget; - String descr; - sensorType(type.toInt(), num, widget, descr); - if (jsonReadBool(configSetupJson, "gateAuto")) { - if (!isItemAdded(key)) { - addItemAuto(num, key, widget, descr); - descr.replace("#", " "); - SerialPrint("I", "MySensor", "Add new item: " + key + ": " + descr); - } else { - descr.replace("#", " "); - SerialPrint("I", "MySensor", "Item already exist: " + key + ": " + descr); - } - } else { - descr.replace("#", " "); - SerialPrint("I", "MySensor", "Presentation: " + key + ": " + descr); - } - } - if (command == "1") { //это данные - if (value != "") { - if (presentBeenStarted) { - presentBeenStarted = false; - SerialPrint("I", "MySensor", "!!!Presentation of node: " + nodeId + " completed successfully!!!"); - myNotAsyncActions->make(do_deviceInit); - } - if (mySensorNode != nullptr) { - for (unsigned int i = 0; i < mySensorNode->size(); i++) { - mySensorNode->at(i).onChange(value, key); //вызываем поочередно все экземпляры, там где подойдет там и выполнится - } - } - SerialPrint("I", "MySensor", "node: " + nodeId + ", sensor: " + childSensorId + ", command: " + command + ", type: " + type + ", val: " + value); - } - } - if (command == "2") { //это запрос значения переменной - SerialPrint("I", "MySensor", "Request a variable value"); - } - } - - mysensorBuf = deleteBeforeDelimiter(mysensorBuf, ";"); - } -} - -void sensorType(int index, int &num, String &widget, String &descr) { - switch (index) { - case 0: - descr = F("Door#and#window#sensors"); - widget = F("alarm"); - num = 1; - break; - case 1: - descr = F("Motion#sensors"); - widget = F("alarm"); - num = 1; - break; - case 2: - descr = F("Smoke#sensor"); - widget = F("fillgauge"); - num = 1; - break; - case 3: - descr = F("Binary#device#(on/off)"); - widget = F("toggleBtn"); - num = 2; - break; - case 4: - descr = F("Dimmable#device"); - //to do - //widget = F("range"); - //num = 2; - break; - case 5: - descr = F("Window#covers#or#shades"); - //to do - //widget = F("range"); - //num = 2; - break; - case 6: - descr = F("Temperature#sensor"); - widget = F("anydataTemp"); - num = 1; - break; - case 7: - descr = F("Humidity#sensor"); - widget = F("anydataHum"); - num = 1; - break; - case 8: - descr = F("Pressure#sensor"); - widget = F("anydataPress"); - num = 1; - break; - case 9: - descr = F("Wind#sensor"); - widget = F("anydataTime"); - num = 1; - break; - case 10: - descr = F("Rain#sensor"); - widget = F("anydataTime"); - num = 1; - break; - case 11: - descr = F("UV#sensor"); - widget = F("anydataTime"); - num = 1; - break; - case 12: - descr = F("Weight#sensor"); - widget = F("anydataTime"); - num = 1; - break; - case 13: - descr = F("Power#measuring#device"); - widget = F("anydataWtt"); - num = 1; - break; - case 14: - descr = F("Heater#device"); - widget = F("anydataTemp"); - num = 1; - break; - case 15: - descr = F("Distance#sensor"); - widget = F("anydata"); - num = 1; - break; - case 16: - descr = F("Light#sensor"); - widget = F("anydataTime"); - num = 1; - break; - case 17: - descr = F("Arduino#node#device"); - widget = F("anydata"); - num = 1; - break; - case 18: - descr = F("Arduino#repeating#node#device"); - widget = F("anydata"); - num = 1; - break; - case 19: - descr = F("Lock#device"); - widget = F("toggleBtn"); - num = 2; - break; - case 20: - descr = F("Ir#sender/receiver#device"); - widget = F("toggleBtn"); - num = 2; - break; - case 21: - descr = F("Water#meter"); - widget = F("anydata"); - num = 1; - break; - case 22: - descr = F("Air#quality#sensor"); - widget = F("anydata"); - num = 1; - break; - case 23: - descr = F("Custom#sensor"); - widget = F("anydata"); - num = 1; - break; - case 24: - descr = F("Dust#level#sensor"); - widget = F("anydata"); - num = 1; - break; - case 25: - descr = F("Scene#controller#device"); - widget = F("anydata"); - num = 1; - break; - case 26: - descr = F("RGB#light"); - widget = F("anydata"); - num = 1; - break; - case 27: - descr = F("RGBW#light#(with#separate#white#component)"); - widget = F("anydata"); - num = 1; - break; - case 28: - descr = F("Color#sensor"); - widget = F("anydata"); - num = 1; - break; - case 29: - descr = F("Thermostat/HVAC#device"); - widget = F("anydata"); - num = 1; - break; - case 30: - descr = F("Multimeter#device"); - widget = F("anydataVlt"); - num = 1; - break; - case 31: - descr = F("Sprinkler#device"); - widget = F("anydata"); - num = 1; - break; - case 32: - descr = F("Water#leak#sensor"); - widget = F("alarm"); - num = 1; - break; - case 33: - descr = F("Sound#sensor"); - widget = F("anydata"); - num = 1; - break; - case 34: - descr = F("Vibration#sensor"); - widget = F("anydata"); - num = 1; - break; - case 35: - descr = F("Moisture#sensor"); - widget = F("anydata"); - num = 1; - break; - case 36: - descr = F("LCD#text#device"); - widget = F("anydata"); - num = 1; - break; - case 37: - descr = F("Gas#meter"); - widget = F("anydata"); - num = 1; - break; - case 38: - descr = F("GPS#Sensor"); - widget = F("anydata"); - num = 1; - break; - case 39: - descr = F("Water#quality#sensor"); - widget = F("anydata"); - num = 1; - break; - default: - descr = F("Unknown"); - widget = F("anydata"); - num = 1; - break; - } -} -#endif - -//отличный пример разбора строки -//void test(char *inputString) { -// char *str, *p; -// uint8_t index = 0; -// for (str = strtok_r(inputString, ";", &p); -// str && index < 5; -// str = strtok_r(NULL, ";", &p), index++) { -// switch (index) { -// case 0: -// Serial.println(str); -// break; -// case 1: -// Serial.println(str); -// break; -// case 2: -// Serial.println(str); -// break; -// case 3: -// Serial.println(str); -// break; -// case 4: -// Serial.println(str); -// break; -// } -// } -//} diff --git a/src/MySensorsDataRead.cpp b/src/MySensorsDataRead.cpp deleted file mode 100644 index c981f586..00000000 --- a/src/MySensorsDataRead.cpp +++ /dev/null @@ -1,45 +0,0 @@ -#include "MySensorsDataRead.h" -#ifdef MYSENSORS - -void receive(const MyMessage &message) { - String inMsg = String(message.getSender()) + "," + //node-id - String(message.getSensor()) + "," + //child-sensor-id - String(message.getType()) + "," + //type of var - String(message.getCommand()) + "," + //command - parseToString(message) + ";"; //value - - mysensorBuf += inMsg; -} - -String parseToString(const MyMessage &message) { - String value = "error"; - switch (message.getPayloadType()) { - case 0: //Payload type is string - value = message.getString(); - return value; - case 1: //Payload type is byte - value = String(message.getByte()); - return value; - case 2: //Payload type is INT16 - value = String(message.getInt()); - return value; - case 3: //Payload type is UINT16 - value = String(message.getUInt()); - return value; - case 4: //Payload type is INT32 - value = String(message.getInt()); - return value; - case 5: //Payload type is UINT32 - value = String(message.getUInt()); - return value; - case 6: //Payload type is binary - value = String(message.getBool()); - return value; - case 7: //Payload type is float32 - value = String(message.getFloat()); - return value; - default: - return value; - } -} -#endif \ No newline at end of file diff --git a/src/RemoteOrdersUdp.cpp b/src/RemoteOrdersUdp.cpp deleted file mode 100644 index 0da7b481..00000000 --- a/src/RemoteOrdersUdp.cpp +++ /dev/null @@ -1,110 +0,0 @@ -#include "RemoteOrdersUdp.h" -#include -#include "Global.h" -#include "Class/NotAsync.h" -#include "Init.h" - -#ifdef UDP_ENABLED -AsyncUDP asyncUdp; - -void asyncUdpInit() { - - if (!jsonReadBool(configSetupJson, "snaUdp")) { - return; - } - - if (asyncUdp.listenMulticast(IPAddress(239, 255, 255, 255), 4210)) { - asyncUdp.onPacket([](AsyncUDPPacket packet) { - - //Serial.print("UDP Packet Type: "); - //Serial.println(packet.isBroadcast() ? "Broadcast" : packet.isMulticast() ? "Multicast" : "Unicast"); - // - //Serial.print("From: "); - //Serial.print(packet.remoteIP()); - //Serial.print(":"); - //Serial.println(packet.remotePort()); - // - //Serial.print("To: "); - //Serial.print(packet.localIP()); - //Serial.print(":"); - //Serial.println(packet.localPort()); - //Serial.print(", Length: "); - //Serial.print(packet.length()); - // - //Serial.print(", Data: "); - //Serial.write(packet.data(), packet.length()); - - String data = uint8tToString(packet.data(), packet.length()); - Serial.print("[i] [udp] Packet received: '"); - Serial.print(data); - - if (udpPacketValidation(data)) { - Serial.println("', packet valid"); - udpPacketParse(data); - } - - - //else { - // //Serial.println("', Packet invalid"); - //} - //reply to the client - //String ip = WiFi.localIP().toString(); - //asyncUdp.broadcastTo(ip.c_str(), packet.remotePort()); - //packet.printf(ip.c_str(), packet.length()); - - }); - } - - myNotAsyncActions->add( - do_sendScenUDP, [&](void*) { - - String scen = "iotm;scen:"; - scen += readFile(String(DEVICE_SCENARIO_FILE), 2048); - - asyncUdp.broadcastTo(scen.c_str(), 4210); - - }, - nullptr); - - //ts.add( - //UDP, 10000, [&](void*) { - //Serial.println("sended"); - //asyncUdp.broadcastTo("iotm;Anyone here?", 4210); - //asyncUdp.broadcast("test"); - //asyncUdp.print("Hello Server!"); - //}, - //nullptr, true); - - SerialPrint("I", F("UDP"), F("Udp Init")); - -} - -bool udpPacketValidation(String& data) { - if (data.indexOf("iotm;") != -1) { - return true; - } - else { - return false; - } -} - -void udpPacketParse(String& data) { - if (data.indexOf("scen:") != -1) { - data = deleteBeforeDelimiter(data, ":"); - writeFile(String(DEVICE_SCENARIO_FILE), data); - loadScenario(); - } - else if (data.indexOf("event:") != -1) { - data = deleteBeforeDelimiter(data, ":"); - eventBuf += data; - } -} - -String uint8tToString(uint8_t* data, size_t len) { - String ret; - while (len--) { - ret += (char)*data++; - } - return ret; -} -#endif \ No newline at end of file diff --git a/src/SSDP.cpp b/src/SSDP.cpp deleted file mode 100644 index fb431bbd..00000000 --- a/src/SSDP.cpp +++ /dev/null @@ -1,63 +0,0 @@ -#include "SSDP.h" - -#include "Global.h" - -#ifdef SSDP_ENABLED -#ifdef ESP8266 -#include -#endif -#ifdef ESP32 -#include -#endif - -String xmlNode(String tags, String data); - -String decToHex(uint32_t decValue, byte desiredStringLength); - -void SsdpInit() { - server.on("/description.xml", HTTP_GET, [](AsyncWebServerRequest* request) { - String ssdpSend = F(""); - String ssdpHeder = xmlNode(F("major"), "1"); - ssdpHeder += xmlNode(F("minor"), "0"); - ssdpHeder = xmlNode(F("specVersion"), ssdpHeder); - ssdpHeder += xmlNode(F("URLBase"), "http://" + WiFi.localIP().toString()); - String ssdpDescription = xmlNode(F("deviceType"), F("upnp:rootdevice")); - ssdpDescription += xmlNode(F("friendlyName"), jsonReadStr(configSetupJson, F("name"))); - ssdpDescription += xmlNode(F("presentationURL"), "/"); - ssdpDescription += xmlNode(F("serialNumber"), getChipId()); -#ifdef ESP8266 - ssdpDescription += xmlNode(F("modelName"), F("ESP8266")); -#endif -#ifdef ESP32 - ssdpDescription += xmlNode(F("modelName"), F("ESP32")); -#endif - ssdpDescription += xmlNode(F("modelNumber"), getChipId()); - ssdpDescription += xmlNode(F("modelURL"), F("https://github.com/IoTManagerProject/IoTManager/wiki")); - ssdpDescription += xmlNode(F("manufacturer"), F("Borisenko Dmitry")); - ssdpDescription += xmlNode(F("manufacturerURL"), F("https://github.com/IoTManagerProject/IoTManager")); - ssdpDescription += xmlNode(F("UDN"), "uuid:38323636-4558-4dda-9188-cda0e6" + decToHex(ESP_getChipId(), 6)); - ssdpDescription = xmlNode("device", ssdpDescription); - ssdpHeder += ssdpDescription; - ssdpSend += ssdpHeder; - ssdpSend += ""; - Serial.println("->!!!SSDP Get request received"); - request->send(200, "text/xml", ssdpSend); - }); - //Если версия 2.0.0 закаментируйте следующую строчку - SSDP.setDeviceType(F("upnp:rootdevice")); - SSDP.setSchemaURL(F("description.xml")); - SSDP.begin(); - SerialPrint("I", F("SSDP"), F("Ssdp Init")); -} - -String xmlNode(String tags, String data) { - String temp = "<" + tags + ">" + data + ""; - return temp; -} - -String decToHex(uint32_t decValue, byte desiredStringLength) { - String hexString = String(decValue, HEX); - while (hexString.length() < desiredStringLength) hexString = "0" + hexString; - return hexString; -} -#endif \ No newline at end of file diff --git a/src/Servo/Servs.cpp b/src/Servo/Servs.cpp deleted file mode 100644 index 96ebba91..00000000 --- a/src/Servo/Servs.cpp +++ /dev/null @@ -1,40 +0,0 @@ -#include "Servo/Servos.h" - -Servos myServo; - -Servos::Servos(){}; - -Servo *Servos::create(uint8_t num, uint8_t pin) { - // Ищем среди ранее созданных - for (size_t i = 0; i < _items.size(); i++) { - auto item = _items.at(i); - if (item.num == num) { - if (item.pin != pin) { - item.obj->attach(pin); - item.pin = pin; - }; - return item.obj; - } - } - // Добавляем новый - Servo_t newItem{num, pin}; - newItem.obj = new Servo(); - newItem.obj->attach(pin); - _items.push_back(newItem); - return newItem.obj; -} - -Servo *Servos::get(uint8_t num) { - // Ищем среди ранее созданных - for (size_t i = 0; i < _items.size(); i++) { - auto item = _items.at(i); - if (item.num == num) { - return item.obj; - } - } - return nullptr; -} - -size_t Servos::count() { - return _items.size(); -} diff --git a/src/SetupESP.cpp b/src/SetupESP.cpp deleted file mode 100644 index abf2dcaf..00000000 --- a/src/SetupESP.cpp +++ /dev/null @@ -1,49 +0,0 @@ -#include "SetupESP.h" - -void setupESP() { - File file1 = seekFile("/setup.json"); //читаем первый файл из памяти стримом - File file2 = FileFS.open("/setup.json.tmp", "w"); //открыл второй файл для записи - file2.println("["); - - // WriteBufferingStream bfile2(file2, 64); //записываем стрим во второй файл для записи - // ReadBufferingStream bfile1{file1, 64}; //стримим первый файл - - DynamicJsonDocument doc(1024); - Serial.println("during " + prettyBytes(ESP.getFreeHeap())); - int i = 0; - - file1.find("["); - - do { - i++; - - deserializeJson(doc, file1); - doc["web"]["order"] = i; - serializeJsonPretty(doc, file2); - - file2.println(","); - - // DeserializationError error = - // if (error) { - // Serial.print("json error: "); - // Serial.println(error.f_str()); - // } - - Serial.println( - String(i) + ") " + - doc["type"].as() + " " + - doc["set"]["gpio"].as() + " " + - doc["web"]["order"].as()); - - } while (file1.findUntil(",", "]")); - - file2.println("]"); - - file2.close(); - - // if (cutFile("/setup.json.tmp", "/setup.json")) Serial.println("file overwrited"); - - Serial.println("-------------"); - Serial.println(readFile("/setup.json.tmp", 20000)); - Serial.println("-------------"); -} \ No newline at end of file diff --git a/src/SoftUART.cpp b/src/SoftUART.cpp deleted file mode 100644 index cdf511a9..00000000 --- a/src/SoftUART.cpp +++ /dev/null @@ -1,61 +0,0 @@ -#include "Consts.h" -#ifdef EnableUart -#include "BufferExecute.h" -#include "Global.h" -#include "SoftUART.h" - -#ifdef ESP8266 -SoftwareSerial* myUART = nullptr; -#else -HardwareSerial* myUART = nullptr; -#endif - -void uartInit() { - if (!jsonReadBool(configSetupJson, "uart")) { - return; - } - if (!myUART) { -#ifdef ESP8266 - myUART = new SoftwareSerial(jsonReadInt(configSetupJson, "uartTX"), jsonReadInt(configSetupJson, "uartRX")); - myUART->begin(jsonReadInt(configSetupJson, "uartS")); -#endif -#ifdef ESP32 - myUART = new HardwareSerial(2); - long speed = jsonReadInt(configSetupJson, "uartS"); - int rxPin = jsonReadInt(configSetupJson, "uartRX"); - int txPin = jsonReadInt(configSetupJson, "uartTX"); - myUART->begin(speed, SERIAL_8N1, rxPin, txPin); -#endif - } - SerialPrint("I", F("UART"), F("UART Init")); -} - -void uartHandle() { - if (myUART) { - if (!jsonReadBool(configSetupJson, "uart")) { - return; - } - static String incStr; - if (myUART->available()) { - char inc; - inc = myUART->read(); - incStr += inc; - if (inc == '\n') { - parse(incStr); - incStr = ""; - } - } - } -} - -void parse(String& incStr) { - incStr.replace("\r\n", ""); - incStr.replace("\r", ""); - incStr.replace("\n", ""); - if (incStr.indexOf("set") != -1) { - incStr = deleteBeforeDelimiter(incStr, " "); - loopCmdAdd(incStr); - SerialPrint("I", "=>UART", incStr); - } -} -#endif \ No newline at end of file diff --git a/src/Telegram.cpp b/src/Telegram.cpp deleted file mode 100644 index c5526a07..00000000 --- a/src/Telegram.cpp +++ /dev/null @@ -1,124 +0,0 @@ -#include "Consts.h" -#ifdef EnableTelegram -#include "BufferExecute.h" -#include "Telegram.h" -CTBot* myBot{nullptr}; - -void telegramInit() { - if (isEnableTelegramd()) { - telegramInitBeen = true; - sCmd.addCommand("telegram", sendTelegramMsg); - String token = jsonReadStr(configSetupJson, "telegramApi"); - if (!myBot) { - myBot = new CTBot(); - } -#ifdef ESP32 - myBot->useDNS(true); -#endif - myBot->setTelegramToken(token); - myBot->enableUTF8Encoding(true); - if (myBot->testConnection()) { - SerialPrint("I", F("Telegram"), F("Connected")); - } else { - SerialPrint("E", F("Telegram"), F("Not connected")); - } - SerialPrint("I", F("Telegram"), F("Telegram Init")); - } -} - -void handleTelegram() { - if (telegramInitBeen) { - if (isEnableTelegramd()) { - if (isTelegramInputOn()) { - TBMessage msg; - static unsigned long prevMillis; - unsigned long currentMillis = millis(); - unsigned long difference = currentMillis - prevMillis; - if (difference >= 10000) { - prevMillis = millis(); - if (myBot->getNewMessage(msg)) { - SerialPrint("->", F("Telegram"), "chat ID: " + String(msg.sender.id) + ", msg: " + String(msg.text)); - if (jsonReadBool(configSetupJson, "autos")) { - jsonWriteInt(configSetupJson, "chatId", msg.sender.id); - saveConfig(); - } - telegramMsgParse(String(msg.text)); - } - } - } - } - } -} - -void telegramMsgParse(String msg) { - if (msg.indexOf("set") != -1) { - msg = deleteBeforeDelimiter(msg, "_"); - msg.replace("_", " "); - loopCmdAdd(String(msg) + ","); - myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), "order done"); - SerialPrint("<-", F("Telegram"), "chat ID: " + String(jsonReadInt(configSetupJson, "chatId")) + ", msg: " + String(msg)); - } else if (msg.indexOf("get") != -1) { - msg = deleteBeforeDelimiter(msg, "_"); - myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), getValue(msg)); //jsonReadStr(configLiveJson , msg)); - SerialPrint("<-", F("Telegram"), "chat ID: " + String(jsonReadInt(configSetupJson, "chatId")) + ", msg: " + String(msg)); - } else if (msg.indexOf("all") != -1) { - String list = returnListOfParams(); - myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), list); - SerialPrint("<-", F("Telegram"), "chat ID: " + String(jsonReadInt(configSetupJson, "chatId")) + "\n" + list); - } else { - myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), "ID: " + chipId + ", Name: " + jsonReadStr(configSetupJson, F("name"))); - myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), F("Wrong order, use /all to get all values, /get_id to get value, or /set_id_value to set value")); - } -} - -void sendTelegramMsg() { - String sabject = sCmd.next(); - String msg = sCmd.next(); - if (sabject == "often") { - msg.replace("#", " "); - myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), msg); - SerialPrint("<-", F("Telegram"), "chat ID: " + String(jsonReadInt(configSetupJson, "chatId")) + ", msg: " + msg); - } else { - String prevMsg = jsonReadStr(telegramMsgJson, sabject); - if (prevMsg != msg) { - jsonWriteStr(telegramMsgJson, sabject, msg); - msg.replace("#", " "); - sabject.replace("#", " "); - myBot->sendMessage(jsonReadInt(configSetupJson, "chatId"), msg); - SerialPrint("<-", F("Telegram"), "chat ID: " + String(jsonReadInt(configSetupJson, "chatId")) + ", msg: " + msg); - } - } -} - -bool isEnableTelegramd() { - return jsonReadBool(configSetupJson, "telegonof"); -} - -bool isTelegramInputOn() { - return jsonReadBool(configSetupJson, "teleginput"); -} - -String returnListOfParams() { - String cmdStr = readFile(DEVICE_CONFIG_FILE, 4096); - cmdStr += "\r\n"; - cmdStr.replace("\r\n", "\n"); - cmdStr.replace("\r", "\n"); - int count = 0; - String out; - while (cmdStr.length()) { - String buf = selectToMarker(cmdStr, "\n"); - count++; - if (count > 1) { - String id = selectFromMarkerToMarker(buf, ";", 2); - String value = getValue(id); //jsonReadStr(configLiveJson , id); - String page = selectFromMarkerToMarker(buf, ";", 4); - page.replace("#", " "); - String name = selectFromMarkerToMarker(buf, ";", 5); - name.replace("#", " "); - out += page + " " + " " + name + " " + value + "\n"; - } - cmdStr = deleteBeforeDelimiter(cmdStr, "\n"); - } - return out; -} -#endif \ No newline at end of file diff --git a/src/Tests.cpp b/src/Tests.cpp deleted file mode 100644 index 95264086..00000000 --- a/src/Tests.cpp +++ /dev/null @@ -1,59 +0,0 @@ -#include "Tests.h" - -#include "BufferExecute.h" -#include "Class/TCircularBuffer.h" -#include "Global.h" -#include "ItemsList.h" -#include "Macro.h" -#include "MySensorsDataParse.h" -#include "Utils/StringUtils.h" - -void testsPerform() { - Serial.println("====some tests section===="); - //ТЕСТ КОЛЬЦЕВОГО БУФЕРА============================================================================= - myTCircularBuffer = new TCircularBuffer; - - char* buf = "text"; - - for (int i = 1; i <= 5; i++) { - myTCircularBuffer->push(buf); - } - - char* item; - - while (myTCircularBuffer->pop(item)) { - Serial.println(item); - } - //=================================================================================================== - // String str = "0;1;2;3;4"; - // char* mychar = new char[str.length() + 1]; - // strcpy(mychar, str.c_str()); - // test(mychar); - //=========================================================================== - // String myJson; - // const int capacity = JSON_ARRAY_SIZE(2) + 3 * JSON_OBJECT_SIZE(3); - // StaticJsonBuffer jb; - // JsonArray& arr = jb.createArray(); - // JsonObject& obj1 = jb.createObject(); - // obj1["test1"] = 1; - // obj1["test2"] = 2; - // obj1["test3"] = 3; - // arr.add(obj1); - // arr.printTo(myJson); - // Serial.println(myJson); - // - // - // - //=========================================================================== - // Serial.println(isDigitDotCommaStr("-12552.5555")); - // String str = "Geeks for Geeks "; - // Serial.println(itemsCount2(str, " ")); - // - Serial.println("==========end============"); -} - -void testLoop() { - // char* item; - // myCircularBuffer->pop(item); - // Serial.println(item); -} \ No newline at end of file diff --git a/src/UpgradeFirm.cpp b/src/UpgradeFirm.cpp deleted file mode 100644 index c8e05d83..00000000 --- a/src/UpgradeFirm.cpp +++ /dev/null @@ -1,161 +0,0 @@ -#include "Class/NotAsync.h" -#include "FileSystem.h" -#include "Upgrade.h" -#ifdef ESP8266 -#include "ESP8266.h" -#else -#include -#endif - -#include "Global.h" - -void upgradeInit() { - myNotAsyncActions->add( - do_UPGRADE, [&](void*) { - upgrade_firmware(3); - }, - nullptr); - - myNotAsyncActions->add( - do_GETLASTVERSION, [&](void*) { - getLastVersion(); - }, - nullptr); - - if (isNetworkActive()) { - getLastVersion(); - if (lastVersion > 0) { - SerialPrint("I", F("Update"), "available version: " + String(lastVersion)); - if (lastVersion > FIRMWARE_VERSION) { - jsonWriteStr(configSetupJson, "warning2", F("

Вышла новая версия прошивки, нажмите обновить прошивку

")); - } - } - }; - SerialPrint("I", F("Update"), F("Updater Init")); -} - -void getLastVersion() { - if ((WiFi.status() == WL_CONNECTED)) { - String tmp; -#ifdef esp8266_4mb - tmp = getURL(serverIP + F("/projects/iotmanager/esp8266/esp8266ver/esp8266ver.txt")); -#endif -#ifdef esp32_4mb - tmp = getURL(serverIP + F("/projects/iotmanager/esp32/esp32ver/esp32ver.txt")); -#endif -#ifdef esp8266_mysensors_4mb - tmp = getURL(serverIP + F("/projects/iotmanager/esp8266ms/esp8266ver/esp8266ver.txt")); -#endif -#ifdef esp32_mysensors_4mb - tmp = getURL(serverIP + F("/projects/iotmanager/esp32ms/esp32ver/esp32ver.txt")); -#endif - if (tmp == "error") { - lastVersion = -1; - } else { - lastVersion = tmp.toInt(); - } - } else { - lastVersion = -2; - } - jsonWriteInt(configSetupJson, "last_version", lastVersion); -} - -void upgrade_firmware(int type) { - String scenario_ForUpdate; - String devconfig_ForUpdate; - String configSetup_ForUpdate; - - scenario_ForUpdate = readFile(String(DEVICE_SCENARIO_FILE), 4096); - devconfig_ForUpdate = readFile(String(DEVICE_CONFIG_FILE), 4096); - configSetup_ForUpdate = configSetupJson; - - if (type == 1) { //only build - if (upgradeBuild()) restartEsp(); - } - - else if (type == 2) { //only spiffs - if (upgradeFS()) { - writeFile(String(DEVICE_SCENARIO_FILE), scenario_ForUpdate); - writeFile(String(DEVICE_CONFIG_FILE), devconfig_ForUpdate); - writeFile("config.json", configSetup_ForUpdate); - restartEsp(); - } - } - - else if (type == 3) { //spiffs and build - if (upgradeFS()) { - writeFile(String(DEVICE_SCENARIO_FILE), scenario_ForUpdate); - writeFile(String(DEVICE_CONFIG_FILE), devconfig_ForUpdate); - writeFile("config.json", configSetup_ForUpdate); - saveConfig(); - if (upgradeBuild()) { - restartEsp(); - } - } - } -} - -bool upgradeFS() { - bool ret = false; -#ifndef esp8266_1mb - WiFiClient wifiClient; - Serial.printf("Start upgrade %s, please wait...", FS_NAME); -#ifdef esp8266_4mb - ESPhttpUpdate.rebootOnUpdate(false); - t_httpUpdate_return retFS = ESPhttpUpdate.updateFS(wifiClient, serverIP + F("/projects/iotmanager/esp8266/littlefs/littlefs.bin")); -#endif -#ifdef esp32_4mb - httpUpdate.rebootOnUpdate(false); - HTTPUpdateResult retFS = httpUpdate.updateSpiffs(wifiClient, serverIP + F("/projects/iotmanager/esp32/littlefs/spiffs.bin")); -#endif -#ifdef esp8266_mysensors_4mb - ESPhttpUpdate.rebootOnUpdate(false); - t_httpUpdate_return retFS = ESPhttpUpdate.updateSpiffs(wifiClient, serverIP + F("/projects/iotmanager/esp8266ms/littlefs/littlefs.bin")); -#endif -#ifdef esp32_mysensors_4mb - httpUpdate.rebootOnUpdate(false); - HTTPUpdateResult retFS = httpUpdate.updateSpiffs(wifiClient, serverIP + F("/projects/iotmanager/esp32ms/littlefs/spiffs.bin")); -#endif - if (retFS == HTTP_UPDATE_OK) { //если FS обновилась успешно - SerialPrint("I", F("Update"), F("FS upgrade done!")); - ret = true; - } -#endif - return ret; -} - -bool upgradeBuild() { - bool ret = false; -#ifndef esp8266_1mb - WiFiClient wifiClient; - Serial.println(F("Start upgrade BUILD, please wait...")); -#ifdef esp8266_4mb - ESPhttpUpdate.rebootOnUpdate(false); - t_httpUpdate_return retBuild = ESPhttpUpdate.update(wifiClient, serverIP + F("/projects/iotmanager/esp8266/firmware/firmware.bin")); -#endif -#ifdef esp32_4mb - httpUpdate.rebootOnUpdate(false); - HTTPUpdateResult retBuild = httpUpdate.update(wifiClient, serverIP + F("/projects/iotmanager/esp32/firmware/firmware.bin")); -#endif -#ifdef esp8266_mysensors_4mb - ESPhttpUpdate.rebootOnUpdate(false); - t_httpUpdate_return retBuild = ESPhttpUpdate.update(wifiClient, serverIP + F("/projects/iotmanager/esp8266ms/firmware/firmware.bin")); -#endif -#ifdef esp32_mysensors_4mb - httpUpdate.rebootOnUpdate(false); - HTTPUpdateResult retBuild = httpUpdate.update(wifiClient, serverIP + F("/projects/iotmanager/esp32ms/firmware/firmware.bin")); -#endif - - if (retBuild == HTTP_UPDATE_OK) { //если BUILD обновился успешно - SerialPrint("I", F("Update"), F("BUILD upgrade done!")); - ret = true; - } -#endif - return ret; -} - -void restartEsp() { - Serial.println(F("Restart ESP....")); - delay(1000); - ESP.restart(); -} \ No newline at end of file diff --git a/src/Utils/FileUtils.cpp b/src/Utils/FileUtils.cpp deleted file mode 100644 index 0e225f7e..00000000 --- a/src/Utils/FileUtils.cpp +++ /dev/null @@ -1,208 +0,0 @@ -#include "Utils/FileUtils.h" - -#include "FileSystem.h" -#include "Utils/StringUtils.h" -#include "Utils\SerialPrint.h" - -const String filepath(const String& filename) { - return filename.startsWith("/") ? filename : "/" + filename; -} - -bool fileSystemInit() { - if (!FileFS.begin()) { - SerialPrint("E", F("FS"), F("FS Init ERROR, may be FS was not flashed")); - return false; - } - SerialPrint("I", F("FS"), F("FS Init completed")); - return true; -} - -void removeFile(const String& filename) { - String path = filepath(filename); - if (FileFS.exists(path)) { - if (!FileFS.remove(path)) { - SerialPrint("I", "Files", "remove " + path); - } - } else { - SerialPrint("E", "Files", "not exist" + path); - } -} - -File seekFile(const String& filename, size_t position) { - String path = filepath(filename); - auto file = FileFS.open(path, "r"); - if (!file) { - SerialPrint("[E]", "Files", "open " + path); - } - // поставим курсор в начало файла - file.seek(position, SeekSet); - return file; -} - -const String readFileString(const String& filename, const String& to_find) { - String path = filepath(filename); - String res = "failed"; - auto file = FileFS.open(path, "r"); - if (!file) { - return "failed"; - } - if (file.find(to_find.c_str())) { - res = file.readStringUntil('\n'); - } - file.close(); - return res; -} - -const String addFileLn(const String& filename, const String& str) { - String path = filepath(filename); - auto file = FileFS.open(path, "a"); - if (!file) { - return "failed"; - } - file.println(str); - file.close(); - return "sucсess"; -} - -const String addFile(const String& filename, const String& str) { - String path = filepath(filename); - auto file = FileFS.open(path, "a"); - if (!file) { - return "failed"; - } - file.print(str); - file.close(); - return "sucсess"; -} - -bool copyFile(const String& src, const String& dst, bool overwrite) { - String srcPath = filepath(src); - String dstPath = filepath(dst); - SerialPrint("I", "Files", "copy " + srcPath + " to " + dstPath); - if (!FileFS.exists(srcPath)) { - SerialPrint("[E]", "Files", "not exist: " + srcPath); - return false; - } - if (FileFS.exists(dstPath)) { - if (!overwrite) { - SerialPrint("[E]", "Files", "already exist: " + dstPath); - return false; - } - FileFS.remove(dstPath); - } - auto srcFile = FileFS.open(srcPath, "r"); - auto dstFile = FileFS.open(dstPath, "w"); - - uint8_t buf[512]; - while (srcFile.available()) { - size_t len = srcFile.read(buf, 512); - dstFile.write(buf, len); - } - srcFile.close(); - dstFile.close(); - return true; -} - -const String writeFile(const String& filename, const String& str) { - String path = filepath(filename); - auto file = FileFS.open(path, "w"); - if (!file) { - return "failed"; - } - file.print(str); - file.close(); - return "sucсess"; -} - -const String readFile(const String& filename, size_t max_size) { - String path = filepath(filename); - auto file = FileFS.open(path, "r"); - if (!file) { - return "failed"; - } - size_t size = file.size(); - if (size > max_size) { - file.close(); - return "large"; - } - String temp = file.readString(); - file.close(); - return temp; -} - -size_t countLines(const String filename) { - size_t cnt = -1; - String path = filepath(filename); - auto file = FileFS.open(path, "r"); - if (!file) { - return cnt; - } - file.seek(0, SeekSet); - size_t size = file.size(); - size_t psn; - do { - cnt++; - file.readStringUntil('\n'); - psn = file.position(); - } while (psn < size); - file.close(); - return cnt; -} - -size_t getFileSize(const String filename) { - size_t size = -1; - String filepath(filename); - auto file = FileFS.open(filepath, "r"); - if (!file) { - return size; - } - size = file.size(); - file.close(); - return size; -} - -const String getFSSizeInfo() { - String res; -#ifdef ESP8266 - FSInfo info; - if (FileFS.info(info)) { - res = prettyBytes(info.usedBytes) + " of " + prettyBytes(info.totalBytes); - } else { - res = "error"; - } -#else - res = prettyBytes(FileFS.usedBytes()) + " of " + prettyBytes(FileFS.totalBytes()); -#endif - return res; -} - -const String getConfigFile(uint8_t preset, ConfigType_t type) { - char buf[64]; - sprintf(buf, "/conf/%s%03d.txt", (type == CT_CONFIG) ? "c" : "s", preset); - return String(buf); -} - -bool cutFile(const String& src, const String& dst) { - String srcPath = filepath(src); - String dstPath = filepath(dst); - Serial.println("cut " + srcPath + " to " + dstPath); - if (!FileFS.exists(srcPath)) { - Serial.println("not exist: " + srcPath); - return false; - } - if (FileFS.exists(dstPath)) { - FileFS.remove(dstPath); - } - auto srcFile = FileFS.open(srcPath, "r"); - auto dstFile = FileFS.open(dstPath, "w"); - - uint8_t buf[512]; - while (srcFile.available()) { - size_t len = srcFile.read(buf, 512); - dstFile.write(buf, len); - } - srcFile.close(); - dstFile.close(); - FileFS.remove(srcPath); - return true; -} \ No newline at end of file diff --git a/src/Utils/JsonUtils.cpp b/src/Utils/JsonUtils.cpp deleted file mode 100644 index d30fab20..00000000 --- a/src/Utils/JsonUtils.cpp +++ /dev/null @@ -1,179 +0,0 @@ -#include "Utils/JsonUtils.h" - -#include - -#include "Global.h" -#include "Utils/FileUtils.h" - -//depricated====================================================================== -String jsonReadStr(String& json, String name) { - DynamicJsonDocument doc(JSON_BUFFER_SIZE); - DeserializationError error = deserializeJson(doc, json); - if (error) SerialPrint("EE", F("jsonRead"), error.f_str()); - return doc[name].as(); -} - -boolean jsonReadBool(String& json, String name) { - DynamicJsonDocument doc(JSON_BUFFER_SIZE); - DeserializationError error = deserializeJson(doc, json); - if (error) SerialPrint("EE", F("jsonRead"), error.f_str()); - return doc[name].as(); -} - -int jsonReadInt(String& json, String name) { - DynamicJsonDocument doc(JSON_BUFFER_SIZE); - DeserializationError error = deserializeJson(doc, json); - if (error) SerialPrint("EE", F("jsonRead"), error.f_str()); - return doc[name].as(); -} - -//new============================================================================== -bool jsonRead(String& json, String key, String& value) { - bool ret = true; - DynamicJsonDocument doc(JSON_BUFFER_SIZE); - DeserializationError error = deserializeJson(doc, json); - if (error) { - SerialPrint("EE", F("jsonRead"), error.f_str()); - ret = false; - } else if (!doc.containsKey(key)) { - SerialPrint("EE", F("jsonRead"), key + " missing"); - ret = false; - } - value = doc[key].as(); - return ret; -} - -bool jsonRead(String& json, String key, bool& value) { - bool ret = true; - DynamicJsonDocument doc(JSON_BUFFER_SIZE); - DeserializationError error = deserializeJson(doc, json); - if (error) { - SerialPrint("EE", F("jsonRead"), error.f_str()); - ret = false; - } else if (!doc.containsKey(key)) { - SerialPrint("EE", F("jsonRead"), key + " missing"); - ret = false; - } - value = doc[key].as(); - return ret; -} - -bool jsonRead(String& json, String key, int& value) { - bool ret = true; - DynamicJsonDocument doc(JSON_BUFFER_SIZE); - DeserializationError error = deserializeJson(doc, json); - if (error) { - SerialPrint("EE", F("jsonRead"), error.f_str()); - ret = false; - } else if (!doc.containsKey(key)) { - SerialPrint("EE", F("jsonRead"), key + " missing"); - ret = false; - } - value = doc[key].as(); - return ret; -} -//depricated======================================================================== -String jsonWriteStr(String& json, String name, String value) { - DynamicJsonDocument doc(JSON_BUFFER_SIZE); - DeserializationError error = deserializeJson(doc, json); - if (error) SerialPrint("EE", F("jsonWrite"), error.f_str()); - doc[name] = value; - json = ""; - serializeJson(doc, json); - return json; -} - -String jsonWriteBool(String& json, String name, boolean value) { - DynamicJsonDocument doc(JSON_BUFFER_SIZE); - DeserializationError error = deserializeJson(doc, json); - if (error) SerialPrint("EE", F("jsonWrite"), error.f_str()); - doc[name] = value; - json = ""; - serializeJson(doc, json); - return json; -} - -String jsonWriteInt(String& json, String name, int value) { - DynamicJsonDocument doc(JSON_BUFFER_SIZE); - DeserializationError error = deserializeJson(doc, json); - if (error) SerialPrint("EE", F("jsonWrite"), error.f_str()); - doc[name] = value; - json = ""; - serializeJson(doc, json); - return json; -} - -String jsonWriteFloat(String& json, String name, float value) { - DynamicJsonDocument doc(JSON_BUFFER_SIZE); - DeserializationError error = deserializeJson(doc, json); - if (error) SerialPrint("EE", F("jsonWrite"), error.f_str()); - doc[name] = value; - json = ""; - serializeJson(doc, json); - return json; -} - -//new============================================================================== -bool jsonWriteStr_(String& json, String key, String value) { - bool ret = true; - DynamicJsonDocument doc(JSON_BUFFER_SIZE); - DeserializationError error = deserializeJson(doc, json); - if (error) { - SerialPrint("EE", F("jsonWrite"), error.f_str()); - ret = false; - } - doc[key] = value; - json = ""; - serializeJson(doc, json); - return ret; -} - -bool jsonWriteBool_(String& json, String key, bool value) { - bool ret = true; - DynamicJsonDocument doc(JSON_BUFFER_SIZE); - DeserializationError error = deserializeJson(doc, json); - if (error) { - SerialPrint("EE", F("jsonWrite"), error.f_str()); - ret = false; - } - doc[key] = value; - json = ""; - serializeJson(doc, json); - return ret; -} - -bool jsonWriteInt_(String& json, String key, int value) { - bool ret = true; - DynamicJsonDocument doc(JSON_BUFFER_SIZE); - DeserializationError error = deserializeJson(doc, json); - if (error) { - SerialPrint("EE", F("jsonWrite"), error.f_str()); - ret = false; - } - doc[key] = value; - json = ""; - serializeJson(doc, json); - return ret; -} - -bool jsonWriteFloat_(String& json, String key, float value) { - bool ret = true; - DynamicJsonDocument doc(JSON_BUFFER_SIZE); - DeserializationError error = deserializeJson(doc, json); - if (error) { - SerialPrint("EE", F("jsonWrite"), error.f_str()); - ret = false; - } - doc[key] = value; - json = ""; - serializeJson(doc, json); - return ret; -} -//================================================================================= -void saveConfig() { - writeFile(String("config.json"), configSetupJson); -} - -void saveStore() { - writeFile(String("store.json"), configStoreJson); -} \ No newline at end of file diff --git a/src/Utils/SerialPrint.cpp b/src/Utils/SerialPrint.cpp deleted file mode 100644 index fcf39c46..00000000 --- a/src/Utils/SerialPrint.cpp +++ /dev/null @@ -1,11 +0,0 @@ -#include "Utils\SerialPrint.h" - -#include "Global.h" -#include "WebServer.h" -#include "WebSocket.h" - -void SerialPrint(String errorLevel, String module, String msg) { - String tosend = prettyMillis(millis()) + " [" + errorLevel + "] [" + module + "] " + msg; - Serial.println(tosend); - // wsPublishData(F("log"), tosend); -} \ No newline at end of file diff --git a/src/Utils/StringUtils.cpp b/src/Utils/StringUtils.cpp deleted file mode 100644 index ef2e280c..00000000 --- a/src/Utils/StringUtils.cpp +++ /dev/null @@ -1,142 +0,0 @@ -#include "Utils/StringUtils.h" - -#include "Consts.h" - -String selectToMarkerLast(String str, String found) { - int p = str.lastIndexOf(found); - return str.substring(p + found.length()); -} - -String selectToMarker(String str, String found) { - int p = str.indexOf(found); - return str.substring(0, p); -} - -String extractInner(String str) { - int p1 = str.indexOf("["); - int p2 = str.indexOf("]"); - return str.substring(p1 + 1, p2); -} - -String deleteAfterDelimiter(String str, String found) { - int p = str.indexOf(found); - return str.substring(0, p); -} - -String deleteBeforeDelimiter(String str, String found) { - int p = str.indexOf(found) + found.length(); - return str.substring(p); -} - -String deleteBeforeDelimiterTo(String str, String found) { - int p = str.indexOf(found); - return str.substring(p); -} - -String deleteToMarkerLast(String str, String found) { - int p = str.lastIndexOf(found); - return str.substring(0, p); -} - -String selectToMarkerPlus(String str, String found, int plus) { - int p = str.indexOf(found); - return str.substring(0, p + plus); -} - -String selectFromMarkerToMarker(String str, String tofind, int number) { - if (str.indexOf(tofind) == -1) { - return "not found"; - } - str += tofind; // добавим для корректного поиска - uint8_t i = 0; // Индекс перебора - do { - if (i == number) { - // если индекс совпал с позицией - return selectToMarker(str, tofind); - } - // отбросим проверенный блок до разделителя - str = deleteBeforeDelimiter(str, tofind); - i++; - } while (str.length() != 0); - - return "not found"; -} - -uint8_t hexStringToUint8(String hex) { - uint8_t tmp = strtol(hex.c_str(), NULL, 0); - if (tmp >= 0x00 && tmp <= 0xFF) { - return tmp; - } -} - -uint16_t hexStringToUint16(String hex) { - uint16_t tmp = strtol(hex.c_str(), NULL, 0); - if (tmp >= 0x0000 && tmp <= 0xFFFF) { - return tmp; - } -} - -size_t itemsCount2(String str, const String& separator) { - // если строки поиск нет сразу выход - if (str.indexOf(separator) == -1) { - return 0; - } - // добавим для корректного поиска - str += separator; - size_t cnt = 0; - while (str.length()) { - // отбросим проверенный блок до разделителя - str = deleteBeforeDelimiter(str, separator); - cnt++; - } - return cnt; -} - -size_t itemsCount(String& str, const char* delim) { - size_t cnt = 0; - char* cstr = new char[str.length() + 1]; - strcpy(cstr, str.c_str()); - char* token; - while ((token = strtok_r(cstr, delim, &cstr))) { - cnt++; - //printf("%s\n", token); - } - delete[] cstr; - return cnt; -} - -char* stringToChar(String& str) { - char* mychar = new char[str.length() + 1]; - strcpy(mychar, str.c_str()); - return mychar; -} - -boolean isDigitStr(const String& str) { - for (size_t i = 0; i < str.length(); i++) { - if (!isDigit(str.charAt(i))) { - return false; - } - } - return str.length(); -} - -boolean isDigitDotCommaStr(const String& str) { - for (size_t i = 0; i < str.length(); i++) { - char latter = str.charAt(i); - if (!isDigit(latter) && latter != '.' && latter != '-') { - return false; - } - } - return true; -} - -String prettyBytes(size_t size) { - if (size < 1024) - return String(size) + "b"; - else if (size < (1024 * 1024)) - return String(size / 1024.0) + "kB"; - else if (size < (1024 * 1024 * 1024)) - return String(size / 1024.0 / 1024.0) + "MB"; - else - return String(size / 1024.0 / 1024.0 / 1024.0) + "GB"; -} diff --git a/src/Utils/SysUtils.cpp b/src/Utils/SysUtils.cpp deleted file mode 100644 index a9f507a1..00000000 --- a/src/Utils/SysUtils.cpp +++ /dev/null @@ -1,250 +0,0 @@ -#include "Utils/SysUtils.h" - -#include "Global.h" - - -const String getUniqueId(const char* name) { - return String(name) + getMacAddress(); -} - -uint32_t ESP_getChipId(void) { -#ifdef ESP32 - uint32_t id = 0; - for (uint32_t i = 0; i < 17; i = i + 8) { - id |= ((ESP.getEfuseMac() >> (40 - i)) & 0xff) << i; - } - return id; -#else - return ESP.getChipId(); -#endif -} - -uint32_t ESP_getFlashChipId(void) { -#ifdef ESP32 - // Нет аналогичной (без доп.кода) функций в 32 - // надо использовать другой id - варианты есть - return ESP_getChipId(); -#else - return ESP.getFlashChipId(); -#endif -} - -const String getChipId() { - return String(ESP_getChipId()) + "-" + String(ESP_getFlashChipId()); -} - -void setChipId() { - chipId = getChipId(); - SerialPrint("I", "System", "id: " + chipId); -} - -#ifdef ESP8266 -static uint32_t total_memory = 52864; -#else -static uint32_t total_memory = ESP.getHeapSize(); -#endif - -const String printMemoryStatus() { - uint32_t free = ESP.getFreeHeap(); - uint32_t used = total_memory - free; - uint32_t memory_load = (used * 100) / total_memory; - char buf[64]; - sprintf(buf, "used: %d%% free: %s", memory_load, getHeapStats().c_str()); - return String(buf); -} - -#ifdef ESP8266 -const String getHeapStats() { - uint32_t free; - uint16_t max; - uint8_t frag; - ESP.getHeapStats(&free, &max, &frag); - String buf; - buf += prettyBytes(free); - buf += " frag: "; - buf += frag; - buf += '%'; - return buf; -} -#else -const String getHeapStats() { - String buf; - buf = prettyBytes(ESP.getFreeHeap()); - return buf; -} -#endif - -const String getMacAddress() { - uint8_t mac[6]; - char buf[13] = {0}; -#if defined(ESP8266) - WiFi.macAddress(mac); - sprintf(buf, MACSTR, MAC2STR(mac)); -#else - esp_read_mac(mac, ESP_MAC_WIFI_STA); - sprintf(buf, MACSTR, mac[0], mac[1], mac[2], mac[3], mac[4], mac[5]); -#endif - return String(buf); -} - -#ifdef ESP8266 -void setLedStatus(LedStatus_t status) { - if (jsonReadBool(configSetupJson, "blink") == 1) { - pinMode(LED_PIN, OUTPUT); - switch (status) { - case LED_OFF: - noTone(LED_PIN); - digitalWrite(LED_PIN, HIGH); - break; - case LED_ON: - noTone(LED_PIN); - digitalWrite(LED_PIN, LOW); - break; - case LED_SLOW: - tone(LED_PIN, 1); - break; - case LED_FAST: - tone(LED_PIN, 20); - break; - default: - break; - } - } -} -#else -void setLedStatus(LedStatus_t status) { - if (jsonReadBool(configSetupJson, "blink") == 1) { - pinMode(LED_PIN, OUTPUT); - switch (status) { - case LED_OFF: - digitalWrite(LED_PIN, HIGH); - break; - case LED_ON: - digitalWrite(LED_PIN, LOW); - break; - case LED_SLOW: - break; - case LED_FAST: - break; - default: - break; - } - } -} -#endif -//=================================================================== -/* - void web_print (String text) { - if (WiFi.status() == WL_CONNECTED) { - jsonWriteStr(json, "test1", jsonReadStr(json, "test2")); - jsonWriteStr(json, "test2", jsonReadStr(json, "test3")); - jsonWriteStr(json, "test3", jsonReadStr(json, "test4")); - jsonWriteStr(json, "test4", jsonReadStr(json, "test5")); - jsonWriteStr(json, "test5", jsonReadStr(json, "test6")); - - jsonWriteStr(json, "test6", GetTime() + " " + text); - - ws.textAll(json); - } - } -*/ -//=================================================================== -/* - "socket": [ - "ws://{{ip}}/ws" - ], -*/ -//=================================================================== -/* - { - "type": "h4", - "title": "('{{build2}}'=='{{firmware_version}}'?'NEW':'OLD')" - }, -*/ -//=================================================================== -/* - { - "type": "button", - "title": "Конфигурация устройства", - "socket": "test2", - "class": "btn btn-block btn-primary" - }, - { - "type": "hr" - }, - { - "type": "h6", - "title": "{{test1}}" - }, - { - "type": "h6", - "title": "{{test2}}" - }, - { - "type": "h6", - "title": "{{test3}}" - }, - { - "type": "h6", - "title": "{{test4}}" - }, - { - "type": "h6", - "title": "{{test5}}" - }, - { - "type": "h6", - "title": "{{test6}}" - }, - { - "type": "hr" - }, -*/ -//=================================================================== - -/* - String getResetReason(uint8_t core) { - int reason = rtc_get_reset_reason(core); - switch (reason) { - case 1 : return "Power on"; break; //Vbat power on reset - case 3 : return "Software reset digital core"; break; //Software reset digital core - case 4 : return "Legacy watch dog reset digital core"; break; //Legacy watch dog reset digital core - case 5 : return "Deep Sleep reset digital core"; break; //Deep Sleep reset digital core - case 6 : return "Reset by SLC module, reset digital core"; break; //Reset by SLC module, reset digital core - case 7 : return "Timer Group0 Watch dog reset digital core"; break; //Timer Group0 Watch dog reset digital core - case 8 : return "Timer Group1 Watch dog reset digital core"; break; //Timer Group1 Watch dog reset digital core - case 9 : return "RTC Watch dog Reset digital core"; break; // - case 10 : return "Instrusion tested to reset CPU"; break; - case 11 : return "Time Group reset CPU"; break; - case 12 : return "Software reset CPU"; break; - case 13 : return "RTC Watch dog Reset CPU"; break; - case 14 : return "for APP CPU, reseted by PRO CPU"; break; - case 15 : return "Reset when the vdd voltage is not stable"; break; - case 16 : return "RTC Watch dog reset digital core and rtc module"; break; - default : return "NO_MEAN"; - } - } - - - String EspClass::getResetReason(void) { - char buff[32]; - if (resetInfo.reason == REASON_DEFAULT_RST) { // normal startup by power on - strcpy_P(buff, PSTR("Power on")); - } else if (resetInfo.reason == REASON_WDT_RST) { // hardware watch dog reset - strcpy_P(buff, PSTR("Hardware Watchdog")); - } else if (resetInfo.reason == REASON_EXCEPTION_RST) { // exception reset, GPIO status won’t change - strcpy_P(buff, PSTR("Exception")); - } else if (resetInfo.reason == REASON_SOFT_WDT_RST) { // software watch dog reset, GPIO status won’t change - strcpy_P(buff, PSTR("Software Watchdog")); - } else if (resetInfo.reason == REASON_SOFT_RESTART) { // software restart ,system_restart , GPIO status won’t change - strcpy_P(buff, PSTR("Software/System restart")); - } else if (resetInfo.reason == REASON_DEEP_SLEEP_AWAKE) { // wake up from deep-sleep - strcpy_P(buff, PSTR("Deep-Sleep Wake")); - } else if (resetInfo.reason == REASON_EXT_SYS_RST) { // external system reset - strcpy_P(buff, PSTR("External System")); - } else { - strcpy_P(buff, PSTR("Unknown")); - } - return String(buff); - } -*/ diff --git a/src/Utils/TimeUtils.cpp b/src/Utils/TimeUtils.cpp deleted file mode 100644 index 47786861..00000000 --- a/src/Utils/TimeUtils.cpp +++ /dev/null @@ -1,237 +0,0 @@ -#include "Utils/TimeUtils.h" -#include "Global.h" -#include "Utils/StringUtils.h" - -static const uint8_t days_in_month[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; - -//static const char* week_days[7] = { "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat" }; - -// String getTimeUnix() { -// time_t t; -// struct tm* tm; - -// t = time(NULL); -// tm = localtime(&t); -// Serial.printf("%04d/%02d/%02d(%s) %02d:%02d:%02d\n", -// tm->tm_year + 1900, tm->tm_mon + 1, tm->tm_mday, week_days[tm->tm_wday], -// tm->tm_hour, tm->tm_min, tm->tm_sec); -// delay(1000); -// time_t now = time(nullptr); -// if (now < 30000) { -// return "failed"; -// } -// return String(now); -// } - -// String getTime() { -// time_t now = time(nullptr); -// int zone = 3600 * jsonReadStr(configSetupJson, "timezone").toInt(); -// now = now + zone; -// String Time = ""; // Строка для результатов времени -// Time += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017 -// int i = Time.indexOf(":"); //Ишем позицию первого символа : -// Time = Time.substring(i - 2, i + 6); // Выделяем из строки 2 символа перед символом : и 6 символов после -// return Time; // Возврашаем полученное время -// } - -// String getTimeWOsec() { -// time_t now = time(nullptr); -// int zone = 3600 * jsonReadStr(configSetupJson, "timezone").toInt(); -// now = now + zone; -// String Time = ""; // Строка для результатов времени -// Time += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017 -// int i = Time.indexOf(":"); //Ишем позицию первого символа : -// Time = Time.substring(i - 2, i + 3); // Выделяем из строки 2 символа перед символом : и 6 символов после -// return Time; // Возврашаем полученное время -// } - -// String getDate() { -// time_t now = time(nullptr); -// int zone = 3600 * jsonReadStr(configSetupJson, "timezone").toInt(); -// now = now + zone; -// String Data = ""; // Строка для результатов времени -// Data += ctime(&now); // Преобразуем время в строку формата Thu Jan 19 00:55:35 2017 -// Data.replace("\n", ""); -// uint8_t i = Data.lastIndexOf(" "); //Ишем позицию последнего символа пробел -// String Time = Data.substring(i - 8, i + 1); // Выделяем время и пробел -// Data.replace(Time, ""); // Удаляем из строки 8 символов времени и пробел -// return Data; // Возврашаем полученную дату -// } - -// String getDateDigitalFormated() { -// String date = getDate(); - -// date = deleteBeforeDelimiter(date, " "); - -// date.replace("Jan", "01"); -// date.replace("Feb", "02"); -// date.replace("Mar", "03"); -// date.replace("Apr", "04"); -// date.replace("May", "05"); -// date.replace("Jun", "06"); -// date.replace("Jul", "07"); -// date.replace("Aug", "08"); -// date.replace("Sep", "09"); -// date.replace("Oct", "10"); -// date.replace("Nov", "11"); -// date.replace("Dec", "12"); - -// String month = date.substring(0, 2); -// String day = date.substring(3, 5); -// String year = date.substring(8, 10); - -// String out = day; -// out += "."; -// out += month; -// out += "."; -// out += year; - -// return out; -// } - -// int timeToMin(String Time) { -// //"00:00:00" время в секунды -// long min = selectToMarker(Time, ":").toInt() * 60; //общее количество секунд в полных часах -// Time = deleteBeforeDelimiter(Time, ":"); // Теперь здесь минуты секунды -// min += selectToMarker(Time, ":").toInt(); // Добавим секунды из полных минут -// return min; -// } - -static const char* TIME_FORMAT PROGMEM = "%02d:%02d:%02d"; -static const char* TIME_FORMAT_WITH_DAYS PROGMEM = "%dd %02d:%02d"; - -const String prettySeconds(unsigned long time_s) { - unsigned long tmp = time_s; - unsigned long seconds; - unsigned long minutes; - unsigned long hours; - unsigned long days; - seconds = tmp % 60; - tmp = tmp / 60; - - minutes = tmp % 60; - tmp = tmp / 60; - - hours = tmp % 24; - days = tmp / 24; - - char buf[32]; - - if (days) { - sprintf_P(buf, TIME_FORMAT_WITH_DAYS, days, hours, minutes, seconds); - } - else { - sprintf_P(buf, TIME_FORMAT, hours, minutes, seconds); - } - return String(buf); -} - -const String prettyMillis(unsigned long time_ms) { - return prettySeconds(time_ms / 1000); -} - -unsigned long millis_since(unsigned long sinse) { - return millis_passed(sinse, millis()); -} - -unsigned long millis_passed(unsigned long start, unsigned long finish) { - unsigned long result = 0; - if (start <= finish) { - unsigned long passed = finish - start; - if (passed <= __LONG_MAX__) { - result = static_cast(passed); - } - else { - result = static_cast((__LONG_MAX__ - finish) + start + 1u); - } - } - else { - unsigned long passed = start - finish; - if (passed <= __LONG_MAX__) { - result = static_cast(passed); - result = -1 * result; - } - else { - result = static_cast((__LONG_MAX__ - start) + finish + 1u); - result = -1 * result; - } - } - return result; -} - -int getOffsetInSeconds(int timezone) { - return getOffsetInMinutes(timezone) * ONE_MINUTE_s; -} - -int getOffsetInMinutes(int timezone) { - return timezone * ONE_HOUR_m; -} - -void breakEpochToTime(unsigned long epoch, Time_t& tm) { - // break the given time_input into time components - // this is a more compact version of the C library localtime function - - unsigned long time = epoch; - tm.second = time % 60; - time /= 60; // now it is minutes - tm.minute = time % 60; - time /= 60; // now it is hours - tm.hour = time % 24; - time /= 24; // now it is days - tm.days = time; - tm.day_of_week = ((time + 4) % 7) + 1; // Sunday is day 1 - - uint8_t year = 0; - unsigned long days = 0; - - while ((unsigned)(days += (LEAP_YEAR(year) ? 366 : 365)) <= time) { - year++; - } - tm.year = year - 30; - - days -= LEAP_YEAR(year) ? 366 : 365; - time -= days; // now it is days in this year, starting at 0 - tm.day_of_year = time; - - uint8_t month; - uint8_t month_length; - for (month = 0; month < 12; month++) { - if (1 == month) { // february - if (LEAP_YEAR(year)) { - month_length = 29; - } - else { - month_length = 28; - } - } - else { - month_length = days_in_month[month]; - } - - if (time >= month_length) { - time -= month_length; - } - else { - break; - } - } - tm.month = month + 1; // jan is month 1 - tm.day_of_month = time + 1; // day of month - tm.valid = (epoch > MIN_DATETIME); -} - -void timeInit() { - ts.add( - TIME, 1000, [&](void*) { - String timenow = timeNow->getTimeWOsec(); - static String prevTime; - if (prevTime != timenow) { - prevTime = timenow; - jsonWriteStr(configLiveJson, "timenow", timenow); - eventGen2("timenow", timenow); - SerialPrint("I", F("NTP"), timenow); - } - }, - nullptr, true); - SerialPrint("I", F("NTP"), F("Handle time init")); -} diff --git a/src/Utils/WebUtils.cpp b/src/Utils/WebUtils.cpp deleted file mode 100644 index 9c0c82b3..00000000 --- a/src/Utils/WebUtils.cpp +++ /dev/null @@ -1,87 +0,0 @@ -#include "Utils/WebUtils.h" - -#include "ESPAsyncWebServer.h" - -String getURL(const String& urls) { - String res = ""; - HTTPClient http; - http.begin(espClient, urls); - int httpCode = http.GET(); - if (httpCode == HTTP_CODE_OK) { - res = http.getString(); - } else { - res = "error"; - } - http.end(); - return res; -} - -const String getMethodName(AsyncWebServerRequest* request) { - String res = F("UNKNOWN"); - if (request->method() == HTTP_GET) - res = F("GET"); - else if (request->method() == HTTP_POST) - res = F("POST"); - else if (request->method() == HTTP_DELETE) - res = F("DELETE"); - else if (request->method() == HTTP_PUT) - res = F("PUT"); - else if (request->method() == HTTP_PATCH) - res = F("PATCH"); - else if (request->method() == HTTP_HEAD) - res = F("HEAD"); - else if (request->method() == HTTP_OPTIONS) - res = F("OPTIONS"); - return res; -} - -const String getRequestInfo(AsyncWebServerRequest* request) { - String res = getMethodName(request); - res += ' '; - res += "http://"; - res += request->host(); - res += request->url(); - res += '\n'; - if (request->contentLength()) { - res += "content-type: "; - res += request->contentType(); - res += " content-lenght: "; - res += prettyBytes(request->contentLength()); - res += '\n'; - } - - if (request->headers()) { - res += "headers:\n"; - for (size_t i = 0; i < request->headers(); i++) { - AsyncWebHeader* h = request->getHeader(i); - res += h->name(); - res += '='; - res += h->value(); - res += '\n'; - } - } - - if (request->params()) { - res += "params:\n"; - for (size_t i = 0; i < request->params(); i++) { - AsyncWebParameter* p = request->getParam(i); - if (p->isFile()) { - res += "FILE"; - } else if (p->isPost()) { - res += "POST"; - } else { - res += "GET"; - } - res += ' '; - res += p->name(); - res += ':'; - res += p->value(); - if (p->isFile()) { - res += " size:"; - res += p->size(); - } - res += '\n'; - } - } - return res; -} diff --git a/src/Utils/WiFiUtils.cpp b/src/Utils/WiFiUtils.cpp deleted file mode 100644 index 2a3c1acf..00000000 --- a/src/Utils/WiFiUtils.cpp +++ /dev/null @@ -1,173 +0,0 @@ -#include "Utils/WiFiUtils.h" -#include "FileSystem.h" - -void routerConnect() { - WiFi.setAutoConnect(false); - WiFi.persistent(false); - - setLedStatus(LED_SLOW); - WiFi.mode(WIFI_STA); - byte tries = 40; - - String _ssid = jsonReadStr(configSetupJson, "routerssid"); - String _password = jsonReadStr(configSetupJson, "routerpass"); - - if (_ssid == "" && _password == "") { - WiFi.begin(); - } else { - WiFi.begin(_ssid.c_str(), _password.c_str()); -#ifdef ESP32 - WiFi.setTxPower(WIFI_POWER_19_5dBm); -#else - WiFi.setOutputPower(20.5); -#endif - SerialPrint("I", "WIFI", "ssid: " + _ssid); - SerialPrint("I", "WIFI", "pass: " + _password); - } - - while (--tries && WiFi.status() != WL_CONNECTED) { - if (WiFi.status() == WL_CONNECT_FAILED) { - SerialPrint("E", "WIFI", "password is not correct"); - tries = 1; - jsonWriteInt(configOptionJson, "pass_status", 1); - } - Serial.print("."); - delay(1000); - } - - if (WiFi.status() != WL_CONNECTED) { - Serial.println(""); - startAPMode(); - } else { - Serial.println(""); - SerialPrint("I", "WIFI", "http://" + WiFi.localIP().toString()); - jsonWriteStr(configSetupJson, "ip", WiFi.localIP().toString()); - setLedStatus(LED_OFF); - mqttInit(); - } - SerialPrint("I", F("WIFI"), F("Network Init")); -} - -bool startAPMode() { - setLedStatus(LED_ON); - SerialPrint("I", "WIFI", "AP Mode"); - - WiFi.disconnect(); - WiFi.mode(WIFI_AP); - - String _ssidAP = jsonReadStr(configSetupJson, "apssid"); - String _passwordAP = jsonReadStr(configSetupJson, "appass"); - - WiFi.softAP(_ssidAP.c_str(), _passwordAP.c_str()); - IPAddress myIP = WiFi.softAPIP(); - - SerialPrint("I", "WIFI", "AP IP: " + myIP.toString()); - jsonWriteStr(configSetupJson, "ip", myIP.toString()); - - //if (jsonReadInt(configOptionJson, "pass_status") != 1) { - ts.add( - WIFI_SCAN, 10 * 1000, [&](void*) { - String sta_ssid = jsonReadStr(configSetupJson, "routerssid"); - - SerialPrint("I", "WIFI", "scanning for " + sta_ssid); - - if (RouterFind(sta_ssid)) { - ts.remove(WIFI_SCAN); - WiFi.scanDelete(); - routerConnect(); - } - }, - nullptr, true); - //} - return true; -} - -boolean RouterFind(String ssid) { - bool res = false; - int n = WiFi.scanComplete(); - SerialPrint("I", "WIFI", "scan result: " + String(n, DEC)); - - if (n == -2) { //Сканирование не было запущено, запускаем - SerialPrint("I", "WIFI", "start scanning"); - WiFi.scanNetworks(true, false); //async, show_hidden - } - - else if (n == -1) { //Сканирование все еще выполняется - SerialPrint("I", "WIFI", "scanning in progress"); - } - - else if (n == 0) { //ни одна сеть не найдена - SerialPrint("I", "WIFI", "no networks found"); - WiFi.scanNetworks(true, false); - } - - else if (n > 0) { - for (int8_t i = 0; i < n; i++) { - if (WiFi.SSID(i) == ssid) { - res = true; - } - SerialPrint("I", "WIFI", (res ? "*" : "") + String(i, DEC) + ") " + WiFi.SSID(i)); - } - } - WiFi.scanDelete(); - return res; -} - -boolean isNetworkActive() { - return WiFi.status() == WL_CONNECTED; -} - -uint8_t RSSIquality() { - uint8_t res = 0; - if (WiFi.status() == WL_CONNECTED) { - int rssi = WiFi.RSSI(); - if (rssi >= -50) { - res = 6; //"Excellent"; - } else if (rssi < -50 && rssi >= -60) { - res = 5; //"Very good"; - } else if (rssi < -60 && rssi >= -70) { - res = 4; //"Good"; - } else if (rssi < -70 && rssi >= -80) { - res = 3; //"Low"; - } else if (rssi < -80 && rssi > -100) { - res = 2; //"Very low"; - } else if (rssi <= -100) { - res = 1; //"No signal"; - } - } - return res; -} - -void wifiSignalInit() { - ts.add( - SYGNAL, 1000 * 60, [&](void*) { - SerialPrint("I", "System", printMemoryStatus()); - - getFSInfo(); - - switch (RSSIquality()) { - case 0: - jsonWriteStr(configSetupJson, F("signal"), F("Уровень WiFi сигнала: не подключено к роутеру")); - break; - case 1: - jsonWriteStr(configSetupJson, F("signal"), F("Уровень WiFi сигнала: нет сигнала")); - break; - case 2: - jsonWriteStr(configSetupJson, F("signal"), F("Уровень WiFi сигнала: очень низкий")); - break; - case 3: - jsonWriteStr(configSetupJson, F("signal"), F("Уровень WiFi сигнала: низкий")); - break; - case 4: - jsonWriteStr(configSetupJson, F("signal"), F("Уровень WiFi сигнала: хороший")); - break; - case 5: - jsonWriteStr(configSetupJson, F("signal"), F("Уровень WiFi сигнала: очень хороший")); - break; - case 6: - jsonWriteStr(configSetupJson, F("signal"), F("Уровень WiFi сигнала: отличный")); - break; - } - }, - nullptr, true); -} diff --git a/src/Utils/statUtils.cpp b/src/Utils/statUtils.cpp deleted file mode 100644 index b7e7c690..00000000 --- a/src/Utils/statUtils.cpp +++ /dev/null @@ -1,316 +0,0 @@ -#include "Utils/StatUtils.h" - -#include -#include - -#include "Global.h" -#include "ItemsList.h" - -#ifdef ESP32 -#include -#endif - -String ESP_getResetReason(void); - -void initSt() { - addNewDevice(); - decide(); - if (TELEMETRY_UPDATE_INTERVAL_MIN) { - ts.add( - STATISTICS, TELEMETRY_UPDATE_INTERVAL_MIN * 60000, [&](void*) { - static bool secondTime = false; - if (secondTime) getNextNumber("totalhrs.txt"); - secondTime = true; - updateDeviceStatus(); - }, - nullptr, true); - } - SerialPrint("I", F("Stat"), F("Stat Init")); -} - -void decide() { - if ((WiFi.status() == WL_CONNECTED)) { - uint8_t cnt = getNextNumber("stat.txt"); - SerialPrint("I", "Stat", "Total resets number: " + String(cnt)); - if (cnt <= 3) { - Serial.println("(get)"); - getPsn(); - } - else { - if (cnt % 5) { - Serial.println("(skip)"); - } - else { - Serial.println("(get)"); - getPsn(); - } - } - } -} - -void getPsn() { - String res = getURL(F("http://ipinfo.io/?token=c60f88583ad1a4")); - if (res != "") { - String line = jsonReadStr(res, "loc"); - String lat = selectToMarker(line, ","); - String lon = deleteBeforeDelimiter(line, ","); - String geo = jsonReadStr(res, "city") + ", " + jsonReadStr(res, "country") + ", " + jsonReadStr(res, "region"); - updateDevicePsn(lat, lon, "0", geo); - } -} - -String addNewDevice() { - String ret; - if ((WiFi.status() == WL_CONNECTED)) { - WiFiClient client; - HTTPClient http; - String json = "{}"; - String mac = WiFi.macAddress().c_str(); - //============================================== - jsonWriteStr(json, "uniqueId", mac); - jsonWriteStr(json, "name", FIRMWARE_NAME); - jsonWriteStr(json, "model", getChipId()); - //============================================== - http.begin(client, serverIP + F(":8082/api/devices/")); - http.setAuthorization("admin", "admin"); - http.addHeader("Content-Type", "application/json"); - int httpCode = http.POST(json); - if (httpCode > 0) { - ret = httpCode; - if (httpCode == HTTP_CODE_OK) { - String payload = http.getString(); - ret += " " + payload; - //saveId("statid.txt", jsonReadInt(payload, "id")); - } - } - else { - ret = http.errorToString(httpCode).c_str(); - } - http.end(); - } - SerialPrint("I", "Stat", "New device registaration: " + ret); - return ret; -} - -String updateDevicePsn(String lat, String lon, String accur, String geo) { - String ret; - if ((WiFi.status() == WL_CONNECTED)) { - float latfl = lat.toFloat(); - float lonfl = lon.toFloat(); - randomSeed(micros()); - float c = random(2, 9); - if (c > 5) { - latfl = latfl + (c / 100); - lonfl = lonfl + (c / 100); - } - else { - latfl = latfl - (c / 100); - lonfl = lonfl - (c / 100); - } - WiFiClient client; - HTTPClient http; - http.begin(client, serverIP + F(":5055/")); - http.setAuthorization("admin", "admin"); - http.addHeader("Content-Type", "application/json"); - String mac = WiFi.macAddress().c_str(); - int httpCode = http.POST("?id=" + mac + - "&lat=" + String(latfl) + - "&lon=" + String(lonfl) + - "&accuracy=" + accur + ""); - if (httpCode > 0) { - ret = httpCode; - if (httpCode == HTTP_CODE_OK) { - String payload = http.getString(); - ret += " " + payload; - } - } - else { - ret = http.errorToString(httpCode).c_str(); - } - http.end(); - } - SerialPrint("I", "Stat", "Update device psn: " + ret); - return ret; -} - -String updateDeviceStatus() { - String ret; - if ((WiFi.status() == WL_CONNECTED)) { - WiFiClient client; - HTTPClient http; - http.begin(client, serverIP + F(":5055/")); - http.setAuthorization("admin", "admin"); - http.addHeader("Content-Type", "application/json"); - String mac = WiFi.macAddress().c_str(); - int httpCode = http.POST("?id=" + mac + - "&resetReason=" + ESP_getResetReason() + - "&uptime=" + timeNow->getUptime() + - "&uptimeTotal=" + getUptimeTotal() + - "&version=" + FIRMWARE_VERSION + - "&resetsTotal=" + String(getCurrentNumber("stat.txt")) + - "&heap=" + String(ESP.getFreeHeap()) + ""); - if (httpCode > 0) { - ret = httpCode; - if (httpCode == HTTP_CODE_OK) { - String payload = http.getString(); - ret += " " + payload; - } - } - else { - ret = http.errorToString(httpCode).c_str(); - } - http.end(); - } - SerialPrint("I", "Stat", "Update device data: " + ret); - return ret; -} - -String getUptimeTotal() { - uint8_t hrs = getCurrentNumber("totalhrs.txt"); - String hrsStr = prettySeconds(hrs * 60 * 60); - SerialPrint("I", "Stat", "Total running time: " + hrsStr); - return hrsStr; -} - -uint8_t getNextNumber(String file) { - uint8_t number = readFile(file, 100).toInt(); - number++; - removeFile(file); - addFile(file, String(number)); - return number; -} - -uint8_t getCurrentNumber(String file) { - uint8_t number = readFile(file, 100).toInt(); - return number; -} - -#ifdef ESP8266 -String ESP_getResetReason(void) { - return ESP.getResetReason(); -} -#else -String ESP32GetResetReason(uint32_t cpu_no) { - // tools\sdk\include\esp32\rom\rtc.h - switch (rtc_get_reset_reason((RESET_REASON)cpu_no)) { - case POWERON_RESET: - return F("Vbat power on reset"); // 1 - case SW_RESET: - return F("Software reset digital core"); // 3 - case OWDT_RESET: - return F("Legacy watch dog reset digital core"); // 4 - case DEEPSLEEP_RESET: - return F("Deep Sleep reset digital core"); // 5 - case SDIO_RESET: - return F("Reset by SLC module, reset digital core"); // 6 - case TG0WDT_SYS_RESET: - return F("Timer Group0 Watch dog reset digital core"); // 7 - case TG1WDT_SYS_RESET: - return F("Timer Group1 Watch dog reset digital core"); // 8 - case RTCWDT_SYS_RESET: - return F("RTC Watch dog Reset digital core"); // 9 - case INTRUSION_RESET: - return F("Instrusion tested to reset CPU"); // 10 - case TGWDT_CPU_RESET: - return F("Time Group reset CPU"); // 11 - case SW_CPU_RESET: - return F("Software reset CPU"); // 12 - case RTCWDT_CPU_RESET: - return F("RTC Watch dog Reset CPU"); // 13 - case EXT_CPU_RESET: - return F("or APP CPU, reseted by PRO CPU"); // 14 - case RTCWDT_BROWN_OUT_RESET: - return F("Reset when the vdd voltage is not stable"); // 15 - case RTCWDT_RTC_RESET: - return F("RTC Watch dog reset digital core and rtc module"); // 16 - default: - return F("NO_MEAN"); // 0 - } -} - -String ESP_getResetReason(void) { - return ESP32GetResetReason(0); // CPU 0 -} -#endif -//String getUptimeTotal() { -// static int hrs; -// EEPROM.begin(512); -// hrs = eeGetInt(0); -// SerialPrint("I","Stat","Total running hrs: " + String(hrs)); -// String hrsStr = prettySeconds(hrs * 60 * 60); -// SerialPrint("I","Stat","Total running hrs (f): " + hrsStr); -// return hrsStr; -//} -//int plusOneHour() { -// static int hrs; -// EEPROM.begin(512); -// hrs = eeGetInt(0); -// hrs++; -// eeWriteInt(0, hrs); -// return hrs; -//} -// -//void eeWriteInt(int pos, int val) { -// byte* p = (byte*)&val; -// EEPROM.write(pos, *p); -// EEPROM.write(pos + 1, *(p + 1)); -// EEPROM.write(pos + 2, *(p + 2)); -// EEPROM.write(pos + 3, *(p + 3)); -// EEPROM.commit(); -//} -// -//int eeGetInt(int pos) { -// int val; -// byte* p = (byte*)&val; -// *p = EEPROM.read(pos); -// *(p + 1) = EEPROM.read(pos + 1); -// *(p + 2) = EEPROM.read(pos + 2); -// *(p + 3) = EEPROM.read(pos + 3); -// if (val < 0) { -// return 0; -// } else { -// return val; -// } -//} -//========for updating list of device================= -/* -void updateDeviceList() { - if ((WiFi.status() == WL_CONNECTED)) { - WiFiClient client; - HTTPClient http; - String json = "{}"; - String mac = WiFi.macAddress().c_str(); - //=============================================== - jsonWriteStr(json, "uniqueId", mac); - jsonWriteStr(json, "name", FIRMWARE_NAME); - jsonWriteStr(json, "model", FIRMWARE_VERSION); - jsonWriteInt(json, "id", getId("statid.txt")); - //=============================================== - http.begin(client, "http://") + serverIP + F(":8082/api/devices/" + mac + "/"); - http.setAuthorization("admin", "admin"); - http.addHeader("Content-Type", "application/json"); - int httpCode = http.PUT(json); - if (httpCode > 0) { - Serial.printf("update Device List... code: %d\n", httpCode); - if (httpCode == HTTP_CODE_OK) { - const String& payload = http.getString(); - Serial.println("received payload:\n<<"); - Serial.println(payload); - Serial.println(">>"); - } - } else { - Serial.printf("[HTTP] POST... failed, error: %s\n", http.errorToString(httpCode).c_str()); - } - http.end(); - } -} - -void saveId(String file, int id) { - removeFile(file); - addFile(file, String(id)); -} - -int getId(String file) { - return readFile(file, 100).toInt(); -} -*/ \ No newline at end of file diff --git a/src/Web.cpp b/src/Web.cpp deleted file mode 100644 index 9899ee30..00000000 --- a/src/Web.cpp +++ /dev/null @@ -1,419 +0,0 @@ -#include "Web.h" - -#include "BufferExecute.h" -#include "Class/NotAsync.h" -#include "Global.h" -#include "Init.h" -#include "ItemsList.h" -#include "RemoteOrdersUdp.h" -#include "SoftUART.h" -#include "Telegram.h" -#include "items/vLogging.h" - -bool parseRequestForPreset(AsyncWebServerRequest* request, uint8_t& preset) { - if (request->hasArg("preset")) { - preset = request->getParam("preset")->value().toInt(); - return true; - } - return false; -} - -void web_init() { - server.on("/set", HTTP_GET, [](AsyncWebServerRequest* request) { - //==============================set.device.json==================================================================================================== - if (request->hasArg(F("addItem"))) { - addItem2(request->getParam("addItem")->value().toInt()); - request->redirect("/?set.device"); - } - - if (request->hasArg(F("addPreset"))) { - addPreset2(request->getParam(F("addPreset"))->value().toInt()); - - jsonWriteStr(configSetupJson, F("warning1"), F("

Требуется перезагрузка

")); - - request->redirect(F("/?set.device")); - } - - if (request->hasArg(F("delChoosingItems"))) { - jsonWriteStr(configSetupJson, F("warning1"), F("

Требуется перезагрузка

")); - myNotAsyncActions->make(do_delChoosingItems); - request->send(200); - } - - if (request->hasArg(F("delAllItems"))) { - delAllItems(); -#ifdef EnableLogging - cleanLogAndData(); -#endif - jsonWriteStr(configSetupJson, F("warning1"), F("

Требуется перезагрузка

")); - request->redirect(F("/?set.device")); - } - - if (request->hasArg(F("saveItems"))) { - myNotAsyncActions->make(do_deviceInit); - savedFromWeb = true; - request->send(200); - } - - if (request->hasArg(F("scen"))) { - bool value = request->getParam(F("scen"))->value().toInt(); - jsonWriteBool(configSetupJson, F("scen"), value); - saveConfig(); - loadScenario(); - request->send(200); - } - - if (request->hasArg(F("sceninit"))) { - loadScenario(); - request->send(200); - } - - if (request->hasArg(F("MqttIn"))) { - bool value = request->getParam(F("MqttIn"))->value().toInt(); - jsonWriteBool(configSetupJson, "MqttIn", value); - saveConfig(); - mqtt.subscribe((mqttPrefix + "/+/+/event").c_str()); - mqtt.subscribe((mqttPrefix + "/+/+/info").c_str()); - request->send(200); - } - - if (request->hasArg(F("MqttOut"))) { - bool value = request->getParam(F("MqttOut"))->value().toInt(); - jsonWriteBool(configSetupJson, F("MqttOut"), value); - saveConfig(); - request->send(200); - } - - if (request->hasArg(F("scenMqtt"))) { - myNotAsyncActions->make(do_sendScenMQTT); - request->send(200); - } - - if (request->hasArg(F("cleanlog"))) { -#ifdef EnableLogging - cleanLogAndData(); -#endif - request->send(200); - } - - //==============================wifi settings============================================= - if (request->hasArg(F("devname"))) { - jsonWriteStr(configSetupJson, F("name"), request->getParam(F("devname"))->value()); - saveConfig(); - request->send(200); - } - - if (request->hasArg(F("routerssid"))) { - jsonWriteStr(configSetupJson, F("routerssid"), request->getParam(F("routerssid"))->value()); - saveConfig(); - request->send(200); - } - - if (request->hasArg(F("routerpass"))) { - jsonWriteStr(configSetupJson, F("routerpass"), request->getParam(F("routerpass"))->value()); - saveConfig(); - request->send(200); - } - - if (request->hasArg(F("apssid"))) { - jsonWriteStr(configSetupJson, F("apssid"), request->getParam(F("apssid"))->value()); - saveConfig(); - request->send(200, "text/text", "OK"); - } - - if (request->hasArg(F("appass"))) { - jsonWriteStr(configSetupJson, F("appass"), request->getParam(F("appass"))->value()); - saveConfig(); - request->send(200); - } - - if (request->hasArg(F("weblogin"))) { - jsonWriteStr(configSetupJson, F("weblogin"), request->getParam(F("weblogin"))->value()); - saveConfig(); - request->send(200); - } - - if (request->hasArg(F("webpass"))) { - jsonWriteStr(configSetupJson, F("webpass"), request->getParam(F("webpass"))->value()); - saveConfig(); - request->send(200); - } - - if (request->hasArg(F("timezone"))) { - String timezoneStr = request->getParam(F("timezone"))->value(); - jsonWriteStr(configSetupJson, F("timezone"), timezoneStr); - saveConfig(); - timeNow->setTimezone(timezoneStr.toInt()); - request->send(200); - } - - if (request->hasArg(F("ntp"))) { - String ntpStr = request->getParam(F("ntp"))->value(); - jsonWriteStr(configSetupJson, F("ntp"), ntpStr); - saveConfig(); - timeNow->setNtpPool(ntpStr); - request->send(200); - } - - if (request->hasArg(F("blink"))) { - bool value = request->getParam(F("blink"))->value().toInt(); - jsonWriteBool(configSetupJson, F("blink"), value); - saveConfig(); - request->send(200); - } - - if (request->hasArg(F("reqReset"))) { - String tmp = "{}"; - jsonWriteStr(tmp, "title", F("Вы действительно хотите перезагрузить устройство?Идет перезагрузка устройства')\">Перезагрузить")); - jsonWriteStr(tmp, "class", "pop-up"); - request->send(200, "text/html", tmp); - } - - if (request->hasArg(F("reset"))) { - ESP.restart(); - request->send(200); - } - - //==============================mqtt settings============================================= - // primary - if (request->hasArg(F("mqttServer"))) { - jsonWriteStr(configSetupJson, F("mqttServer"), request->getParam(F("mqttServer"))->value()); - saveConfig(); - myNotAsyncActions->make(do_MQTTPARAMSCHANGED); - request->send(200); - } - if (request->hasArg(F("mqttPort"))) { - int port = (request->getParam(F("mqttPort"))->value()).toInt(); - jsonWriteInt(configSetupJson, F("mqttPort"), port); - saveConfig(); - myNotAsyncActions->make(do_MQTTPARAMSCHANGED); - request->send(200); - } - if (request->hasArg(F("mqttPrefix"))) { - jsonWriteStr(configSetupJson, F("mqttPrefix"), request->getParam(F("mqttPrefix"))->value()); - saveConfig(); - myNotAsyncActions->make(do_MQTTPARAMSCHANGED); - request->send(200); - } - if (request->hasArg(F("mqttUser"))) { - jsonWriteStr(configSetupJson, F("mqttUser"), request->getParam(F("mqttUser"))->value()); - saveConfig(); - myNotAsyncActions->make(do_MQTTPARAMSCHANGED); - request->send(200); - } - if (request->hasArg(F("mqttPass"))) { - jsonWriteStr(configSetupJson, F("mqttPass"), request->getParam(F("mqttPass"))->value()); - saveConfig(); - myNotAsyncActions->make(do_MQTTPARAMSCHANGED); - request->send(200); - } - // secondary - if (request->hasArg(F("mqttServer2"))) { - jsonWriteStr(configSetupJson, F("mqttServer2"), request->getParam(F("mqttServer2"))->value()); - saveConfig(); - myNotAsyncActions->make(do_MQTTPARAMSCHANGED); - request->send(200); - } - if (request->hasArg(F("mqttPort2"))) { - int port = (request->getParam(F("mqttPort2"))->value()).toInt(); - jsonWriteInt(configSetupJson, F("mqttPort2"), port); - saveConfig(); - myNotAsyncActions->make(do_MQTTPARAMSCHANGED); - request->send(200); - } - if (request->hasArg(F("mqttPrefix2"))) { - jsonWriteStr(configSetupJson, F("mqttPrefix2"), request->getParam(F("mqttPrefix2"))->value()); - saveConfig(); - myNotAsyncActions->make(do_MQTTPARAMSCHANGED); - request->send(200); - } - if (request->hasArg(F("mqttUser2"))) { - jsonWriteStr(configSetupJson, F("mqttUser2"), request->getParam(F("mqttUser2"))->value()); - saveConfig(); - myNotAsyncActions->make(do_MQTTPARAMSCHANGED); - request->send(200); - } - if (request->hasArg(F("mqttPass2"))) { - jsonWriteStr(configSetupJson, F("mqttPass2"), request->getParam(F("mqttPass2"))->value()); - saveConfig(); - myNotAsyncActions->make(do_MQTTPARAMSCHANGED); - request->send(200); - } - - if (request->hasArg("mqttsend")) { - // myNotAsyncActions->make(do_MQTTUDP); - request->send(200); - } - - if (request->hasArg("mqttcheck")) { - String buf = "" + getStateStr(); - - String payload = "{}"; - jsonWriteStr(payload, "title", buf); - jsonWriteStr(payload, "class", "pop-up"); - - request->send(200, "text/html", payload); - } - - //==============================telegram settings============================================= - if (request->hasArg("telegramApi")) { - jsonWriteStr(configSetupJson, "telegramApi", request->getParam("telegramApi")->value()); - saveConfig(); - request->send(200); - } - if (request->hasArg("autos")) { - bool value = request->getParam("autos")->value().toInt(); - jsonWriteBool(configSetupJson, "autos", value); - saveConfig(); - request->send(200); - } - if (request->hasArg("chatId")) { - jsonWriteStr(configSetupJson, "chatId", request->getParam("chatId")->value()); - saveConfig(); - request->send(200); - } - if (request->hasArg("telegonof")) { - bool value = request->getParam("telegonof")->value().toInt(); - jsonWriteBool(configSetupJson, "telegonof", value); - saveConfig(); - request->send(200); - } - if (request->hasArg("teleginput")) { - bool value = request->getParam("teleginput")->value().toInt(); - jsonWriteBool(configSetupJson, "teleginput", value); - saveConfig(); - request->send(200); - } - - //==============================utilities settings============================================= - if (request->hasArg("i2c")) { - myNotAsyncActions->make(do_BUSSCAN); - request->redirect("/?set.utilities"); - } - if (request->hasArg("uart")) { - bool value = request->getParam("uart")->value().toInt(); - jsonWriteBool(configSetupJson, "uart", value); - saveConfig(); -#ifdef EnableUart - uartInit(); -#endif - request->send(200); - } - if (request->hasArg("uartEvents")) { - bool value = request->getParam("uartEvents")->value().toInt(); - jsonWriteBool(configSetupJson, "uartEvents", value); - saveConfig(); - request->send(200); - } - if (request->hasArg("uartS")) { - jsonWriteStr(configSetupJson, "uartS", request->getParam("uartS")->value()); - saveConfig(); -#ifdef EnableUart - uartInit(); -#endif - request->send(200); - } - if (request->hasArg("uartTX")) { - jsonWriteStr(configSetupJson, "uartTX", request->getParam("uartTX")->value()); - saveConfig(); -#ifdef EnableUart - uartInit(); -#endif - request->send(200); - } - if (request->hasArg("uartRX")) { - jsonWriteStr(configSetupJson, "uartRX", request->getParam("uartRX")->value()); - saveConfig(); -#ifdef EnableUart - uartInit(); -#endif - request->send(200); - } - - //==============================developer settings============================================= - if (request->hasArg("serverip")) { - jsonWriteStr(configSetupJson, "serverip", request->getParam("serverip")->value()); - saveConfig(); - serverIP = jsonReadStr(configSetupJson, "serverip"); - request->send(200); - } - // set?order=button_1 - if (request->hasArg("order")) { - String order = request->getParam("order")->value(); - order.replace("_", " "); - loopCmdAdd(order + ","); - request->send(200, "text/html", order); - } - - if (request->hasArg("grafmax")) { - int value = request->getParam("grafmax")->value().toInt(); - jsonWriteInt(configSetupJson, "grafmax", value); - saveConfig(); - request->send(200); - } - - // gate mode - - if (request->hasArg("gateAuto")) { - bool value = request->getParam("gateAuto")->value().toInt(); - jsonWriteBool(configSetupJson, "gateAuto", value); - saveConfig(); - request->send(200); - } - }); - - // server.on("/del", HTTP_GET, [](AsyncWebServerRequest* request) { - // if (request->hasArg("file") && request->hasArg("line")) { - // String fileName = request->getParam("file")->value(); - // Serial.println(fileName); - // int line = request->getParam("line")->value().toInt(); - // Serial.println(line); - // myNotAsyncActions->make(do_delChoosingItems); - // request->redirect(F("/?set.device")); - // } - // }); - - server.on("/check", HTTP_GET, [](AsyncWebServerRequest* request) { - myNotAsyncActions->make(do_GETLASTVERSION); - SerialPrint("I", "Update", "firmware version: " + String(lastVersion)); - - String msg = ""; - - if (USE_OTA) { - if (lastVersion == FIRMWARE_VERSION) { - msg = F("Актуальная версия прошивки уже установлена."); - } else if (lastVersion > FIRMWARE_VERSION) { - msg = F("Новая версия прошивкиИдет обновление прошивки, после обновления страница перезагрузится автоматически...')\">Установить"); - } else if (lastVersion == -1) { - msg = F("Cервер не найден. Попробуйте повторить позже..."); - } else if (lastVersion == -2) { - msg = F("Устройство не подключено к роутеру!"); - } else if (lastVersion < FIRMWARE_VERSION) { - msg = F("Ошибка версии. Попробуйте повторить позже..."); - } - } else { - msg = F("Обновление невозможно, память устройства 1 мб"); - } - - String tmp = "{}"; - jsonWriteStr(tmp, "title", "" + msg); - jsonWriteStr(tmp, "class", "pop-up"); - request->send(200, "text/html", tmp); - }); - - /* - * Upgrade - */ - server.on("/upgrade", HTTP_GET, [](AsyncWebServerRequest* request) { - myNotAsyncActions->make(do_UPGRADE); - request->send(200, "text/html"); - }); - - SerialPrint("I", F("Web"), F("WebAdmin Init")); -} - -void setConfigParam(const char* param, const String& value) { - SerialPrint("I", "Web", "set " + String(param) + ": " + value); - jsonWriteStr(configSetupJson, param, value); - saveConfig(); -} \ No newline at end of file diff --git a/src/WebServer.cpp b/src/WebServer.cpp deleted file mode 100644 index ddb2f680..00000000 --- a/src/WebServer.cpp +++ /dev/null @@ -1,230 +0,0 @@ -#include "WebServer.h" - -#include "BufferExecute.h" -#include "Class/NotAsync.h" -#include "FSEditor.h" -#include "Utils/FileUtils.h" -#include "Utils/WebUtils.h" -#include "WebSocket.h" - -AsyncWebSocket ws("/ws"); -AsyncEventSource events("/events"); - -void HttpServerinit() { - String login = jsonReadStr(configSetupJson, "weblogin"); - String pass = jsonReadStr(configSetupJson, "webpass"); -#ifdef ESP32 - server.addHandler(new FSEditor(FileFS, login, pass)); -#else - server.addHandler(new FSEditor(login, pass)); -#endif - - //#ifdef CORS_DEBUG - DefaultHeaders::Instance().addHeader(F("Access-Control-Allow-Origin"), F("*")); - DefaultHeaders::Instance().addHeader(F("Access-Control-Allow-Headers"), F("content-type")); - //#endif - - // server.sendHeader("Access-Control-Allow-Origin", "*"); - server.serveStatic("/css/", FileFS, "/css/").setCacheControl("max-age=600"); - server.serveStatic("/js/", FileFS, "/js/").setCacheControl("max-age=600"); - server.serveStatic("/favicon.ico", FileFS, "/favicon.ico").setCacheControl("max-age=600"); - server.serveStatic("/icon.jpeg", FileFS, "/icon.jpeg").setCacheControl("max-age=600"); - server.serveStatic("/edit", FileFS, "/edit").setCacheControl("max-age=600"); - -#ifdef svelte - server.serveStatic("/", FileFS, "/").setDefaultFile("index.html").setAuthentication(login.c_str(), pass.c_str()); -#else - server.serveStatic("/", FileFS, "/").setDefaultFile("index.htm").setAuthentication(login.c_str(), pass.c_str()); -#endif - - //server.onNotFound([](AsyncWebServerRequest *request) { - // SerialPrint("[E]", "WebServer", "not found:\n" + getRequestInfo(request)); - // request->send(404); - //}); - - server.onNotFound([](AsyncWebServerRequest *request) { - if (request->method() == HTTP_OPTIONS) { - request->send(200); - } else { - request->send(404); - } - }); - - server.onFileUpload([](AsyncWebServerRequest *request, const String &filename, size_t index, uint8_t *data, size_t len, bool final) { - // TODO - if (!index) { - SerialPrint("I", "WebServer", "start upload " + filename); - } - if (final) { - SerialPrint("I", "WebServer", "finish upload: " + prettyBytes(index + len)); - } - }); - - server.on("/file.json", HTTP_GET, [](AsyncWebServerRequest *request) { - String file = readFile("file.json", 1024); - request->send(200, "application/json", file); - }); - - // динамические данные - server.on("/config.live.json", HTTP_GET, [](AsyncWebServerRequest *request) { - request->send(200, "application/json", configLiveJson); - }); - - server.on("/config.store.json", HTTP_GET, [](AsyncWebServerRequest *request) { - request->send(200, "application/json", configStoreJson); - }); - - // данные не являющиеся событиями - server.on("/config.option.json", HTTP_GET, [](AsyncWebServerRequest *request) { - request->send(200, "application/json", configOptionJson); - }); - - // для хранения постоянных данных - server.on("/config.setup.json", HTTP_GET, [](AsyncWebServerRequest *request) { - request->send(200, "application/json", configSetupJson); - }); - - server.on("/cmd", HTTP_GET, [](AsyncWebServerRequest *request) { - String cmdStr = request->getParam("command")->value(); - SerialPrint("I", "WebServer", "do: " + cmdStr); - loopCmdAdd(cmdStr); - request->send(200, "text/html", "OK"); - }); - - server.begin(); - - initOta(); - initMDNS(); - HttpServerinitWS(); - - SerialPrint("I", F("HTTP"), F("HttpServer Init")); -} - -void onWsEvent(AsyncWebSocket *server, AsyncWebSocketClient *client, AwsEventType type, void *arg, uint8_t *data, size_t len) { -#ifdef WEBSOCKET_ENABLED - if (type == WS_EVT_CONNECT) { - SerialPrint("I", F("WS"), F("CONNECTED")); - Serial.printf("ws[%s][%u] connect\n", server->url(), client->id()); - // client->printf(json.c_str(), client->id()); - // client->ping(); - } else if (type == WS_EVT_DISCONNECT) { - Serial.printf("ws[%s][%u] disconnect\n", server->url(), client->id()); - } else if (type == WS_EVT_ERROR) { - Serial.printf("ws[%s][%u] error(%u): %s\n", server->url(), client->id(), *((uint16_t *)arg), (char *)data); - } else if (type == WS_EVT_PONG) { - Serial.printf("ws[%s][%u] pong[%u]: %s\n", server->url(), client->id(), len, (len) ? (char *)data : ""); - } else if (type == WS_EVT_DATA) { - AwsFrameInfo *info = (AwsFrameInfo *)arg; - String msg = ""; - if (info->final && info->index == 0 && info->len == len) { - // the whole message is in a single frame and we got all of it's data - Serial.printf("ws[%s][%u] %s-message[%llu]: ", server->url(), client->id(), (info->opcode == WS_TEXT) ? "text" : "binary", info->len); - - if (info->opcode == WS_TEXT) { - for (size_t i = 0; i < info->len; i++) { - msg += (char)data[i]; - } - } else { - char buff[3]; - for (size_t i = 0; i < info->len; i++) { - sprintf(buff, "%02x ", (uint8_t)data[i]); - msg += buff; - } - } - Serial.printf("%s\n", msg.c_str()); - - if (msg.startsWith("/config")) { - // myNotAsyncActions->make(do_webSocketSendSetup); - // wsSetupFlag = true; - } - - if (info->opcode == WS_TEXT) { - // client->text("{}"); - } else { - // client->binary("{}"); - } - } else { - // message is comprised of multiple frames or the frame is split into multiple packets - if (info->index == 0) { - if (info->num == 0) - Serial.printf("ws[%s][%u] %s-message start\n", server->url(), client->id(), (info->message_opcode == WS_TEXT) ? "text" : "binary"); - Serial.printf("ws[%s][%u] frame[%u] start[%llu]\n", server->url(), client->id(), info->num, info->len); - } - - Serial.printf("ws[%s][%u] frame[%u] %s[%llu - %llu]: ", server->url(), client->id(), info->num, (info->message_opcode == WS_TEXT) ? "text" : "binary", info->index, info->index + len); - - if (info->opcode == WS_TEXT) { - for (size_t i = 0; i < len; i++) { - msg += (char)data[i]; - } - } else { - char buff[3]; - for (size_t i = 0; i < len; i++) { - sprintf(buff, "%02x ", (uint8_t)data[i]); - msg += buff; - } - } - Serial.printf("%s\n", msg.c_str()); - - if ((info->index + len) == info->len) { - Serial.printf("ws[%s][%u] frame[%u] end[%llu]\n", server->url(), client->id(), info->num, info->len); - if (info->final) { - Serial.printf("ws[%s][%u] %s-message end\n", server->url(), client->id(), (info->message_opcode == WS_TEXT) ? "text" : "binary"); - if (info->message_opcode == WS_TEXT) - client->text("I got your text message"); - else - client->binary("I got your binary message"); - } - } - } - } -#endif -} - -void initMDNS() { -#ifdef MDNS_ENABLED - MDNS.addService("http", "tcp", 80); - // TODO Add Adduino OTA -#endif -} - -void initOta() { -#ifdef OTA_UPDATES_ENABLED - ArduinoOTA.onStart([]() { - events.send("Update Start", "ota"); - }); - ArduinoOTA.onEnd([]() { - events.send("Update End", "ota"); - }); - ArduinoOTA.onProgress([](unsigned int progress, unsigned int total) { - char p[32]; - sprintf(p, "Progress: %u%%\n", (progress / (total / 100))); - events.send(p, "ota"); - }); - ArduinoOTA.onError([](ota_error_t error) { - if (error == OTA_AUTH_ERROR) - events.send("Auth Failed", "ota"); - else if (error == OTA_BEGIN_ERROR) - events.send("Begin Failed", "ota"); - else if (error == OTA_CONNECT_ERROR) - events.send("Connect Failed", "ota"); - else if (error == OTA_RECEIVE_ERROR) - events.send("Recieve Failed", "ota"); - else if (error == OTA_END_ERROR) - events.send("End Failed", "ota"); - }); - ArduinoOTA.setHostname(hostName); - ArduinoOTA.begin(); -#endif -} - -void HttpServerinitWS() { -#ifdef WEBSOCKET_ENABLED - ws.onEvent(onWsEvent); - server.addHandler(&ws); - events.onConnect([](AsyncEventSourceClient *client) { - // client->send("", NULL, millis(), 1000); - }); - server.addHandler(&events); -#endif -} diff --git a/src/WebSocket.cpp b/src/WebSocket.cpp deleted file mode 100644 index b88f3324..00000000 --- a/src/WebSocket.cpp +++ /dev/null @@ -1,135 +0,0 @@ -#include "WebSocket.h" - -#include "ArduinoJson.h" -#include "Class/NotAsync.h" -#include "Class/TCircularBuffer.h" -#include "Global.h" - -void wsInit() { - // myWsBuffer = new TCircularBuffer; - // myNotAsyncActions->add( - // do_webSocketSendSetup, [&](void*) { - // delay(100); - // wsSendSetup(); - // }, - // nullptr); -} - -void wsPublishData(String topic, String data) { - if (ws.enabled()) { - if (ws.availableForWriteAll()) { - data = "[" + topic + "]" + data; - ws.textAll(data); - } - } -} - -//отправка setup массива в sockets способом через буфер string, рабочий способ но буфер стринг - плохой метод -void wsSendSetup3() { - File file = seekFile("/setup.json"); - DynamicJsonDocument doc(2048); - int i = 0; - file.find("["); - SerialPrint("I", F("WS"), F("start send config")); - do { - i++; - deserializeJson(doc, file); - wsBuf += doc.as() + "\n"; - } while (file.findUntil(",", "]")); - SerialPrint("I", F("WS"), F("completed send config")); -} - -void loopWsExecute3() { - static int attampts = wsAttempts; - if (wsBuf.length()) { - if (attampts > 0) { - if (ws.availableForWriteAll()) { - String tmp = selectToMarker(wsBuf, "\n"); - wsPublishData("config", tmp); - wsBuf = deleteBeforeDelimiter(wsBuf, "\n"); - attampts = wsAttempts; - } else { - attampts--; - SerialPrint("I", F("WS"), String(attampts)); - } - } else { - SerialPrint("I", F("WS"), F("socket fatal error")); - attampts = wsAttempts; - } - } -} - -//отправка setup массива в sockets способом через кольцевой буфер char -// void wsSendSetup() { -// File file = seekFile("/setup.json"); -// DynamicJsonDocument doc(2048); -// int i = 0; -// file.find("["); -// SerialPrint("I", F("WS"), F("start send config")); -// do { -// i++; -// deserializeJson(doc, file); -// char* element; -// char* element = new char[1024]; -// serializeJson(doc, (char*)element, 1024); -// Serial.println(element); -// -// } while (file.findUntil(",", "]")); -// SerialPrint("I", F("WS"), F("completed send config")); -// -// char* itemsend = "element"; -// myWsBuffer->push(itemsend); -// -// char* item; -// while (myWsBuffer->pop(item)) { -// Serial.println(item); -// } -//} - -// void loopWsExecute() { -// char* item; -// if (myWsBuffer->pop(item)) { -// Serial.println(item); -// } -// } - -//отправка setup массива в sockets способом прямой загрузки в ws buffer -// void wsSendSetupBuffer() { -// File file = seekFile("/setup.json"); -// DynamicJsonDocument doc(2048); -// int i = 0; -// file.find("["); -// SerialPrint("I", F("WS"), F("start send config")); -// do { -// i++; -// deserializeJson(doc, file); -// size_t len = measureJson(doc); -// AsyncWebSocketMessageBuffer* buffer = ws.makeBuffer(len); -// if (buffer) { -// serializeJson(doc, (char*)buffer->get(), len); -// if (ws.enabled()) { -// if (ws.availableForWriteAll()) { -// ws.textAll(buffer); -// } -// } -// } -// // Serial.println(doc.as()); -// } while (file.findUntil(",", "]")); -// SerialPrint("I", F("WS"), F("completed send config")); -//} - -//Пример прямого доступа к web socket buffer переделанный для arduino json 6 -// void sendDataWs() { -// DynamicJsonDocument doc(1024); -// doc["a"] = "abc"; -// doc["b"] = "abcd"; -// doc["c"] = "abcde"; -// doc["d"] = "abcdef"; -// doc["e"] = "abcdefg"; -// size_t len = measureJson(doc); -// AsyncWebSocketMessageBuffer* buffer = ws.makeBuffer(len); -// if (buffer) { -// serializeJson(doc, (char*)buffer->get(), len); -// ws.textAll(buffer); -// } -//} diff --git a/src/Widgets.cpp b/src/Widgets.cpp deleted file mode 100644 index 13c58db1..00000000 --- a/src/Widgets.cpp +++ /dev/null @@ -1,92 +0,0 @@ -#include "Global.h" - - -const String getWidgetFile(const String& name); - -bool loadWidget(const String& filename, String& buf) { - buf = readFile(getWidgetFile(filename), 2048); - bool res = !(buf == "Failed" || buf == "Large"); - if (!res) { - SerialPrint("[E]","Widgets","on load" + filename); - } - return res; -} - -void createWidget(String descr, String page, String order, String filename, String topic) { - String buf = "{}"; - if (!loadWidget(filename, buf)) { - return; - } - descr.replace("#", " "); - page.replace("#", " "); - - jsonWriteStr(buf, "page", page); - jsonWriteStr(buf, "order", order); - jsonWriteStr(buf, "descr", descr); - jsonWriteStr(buf, "topic", prex + "/" + topic); - -#ifdef LAYOUT_IN_RAM - all_widgets += widget + "\r\n"; -#else - addFileLn("layout.txt", buf); -#endif -} - -//TODO Вот эта процедура, и несколько оберток -void createWidgetParam(String widget, String page, String pageNumber, String filename, String topic, - String name1, String param1, String name2, String param2, String name3, String param3) { - String buf = ""; - if (!loadWidget(filename, buf)) { - return; - } - - widget.replace("#", " "); - page.replace("#", " "); - - jsonWriteStr(buf, "page", page); - jsonWriteStr(buf, "order", pageNumber); - jsonWriteStr(buf, "descr", widget); - jsonWriteStr(buf, "topic", prex + "/" + topic); - - if (name1) jsonWriteStr(buf, name1, param1); - if (name2) jsonWriteStr(buf, name2, param2); - if (name3) jsonWriteStr(buf, name3, param3); - -#ifdef LAYOUT_IN_RAM - all_widgets += widget + "\r\n"; -#else - addFileLn("layout.txt", buf); -#endif -} - -void createChart(String widget, String page, String pageNumber, String filename, String topic, - String maxCount) { - String buf = ""; - if (!loadWidget(filename, buf)) { - return; - } - - widget.replace("#", " "); - page.replace("#", " "); - - jsonWriteStr(buf, "page", page); - jsonWriteStr(buf, "order", pageNumber); - //jsonWriteStr(widget, "descr", widget_name); - jsonWriteStr(buf, "series", widget); - jsonWriteStr(buf, "maxCount", maxCount); - jsonWriteStr(buf, "topic", prex + "/" + topic); - -#ifdef LAYOUT_IN_RAM - all_widgets += widget + "\r\n"; -#else - addFileLn("layout.txt", buf); -#endif -} - -void createWidgetByType(String widget, String page, String pageNumber, String type, String topic) { - createWidget(widget, page, pageNumber, getWidgetFile(type), topic); -} - -const String getWidgetFile(const String& name) { - return "/widgets/" + name + ".json"; -} diff --git a/src/items/ButtonInClass.cpp b/src/items/ButtonInClass.cpp deleted file mode 100644 index 7e64aaec..00000000 --- a/src/items/ButtonInClass.cpp +++ /dev/null @@ -1,28 +0,0 @@ -#include "Consts.h" -#ifdef EnableButtonIn -#include "BufferExecute.h" -#include "items/ButtonInClass.h" -//==========================================Модуль физических кнопок======================================== -//button-in switch1 toggle Кнопки Свет 1 pin[2] db[20] -//========================================================================================================== - -boolean but[NUM_BUTTONS]; -Bounce *buttons = new Bounce[NUM_BUTTONS]; - -ButtonInClass myButtonIn; -void buttonIn() { - myButtonIn.update(); - String key = myButtonIn.gkey(); - String pin = myButtonIn.gpin(); - sCmd.addCommand(key.c_str(), buttonInSet); - myButtonIn.init(); - myButtonIn.switchStateSetDefault(); - myButtonIn.clear(); -} - -void buttonInSet() { - String key = sCmd.order(); - String state = sCmd.next(); - myButtonIn.switchChangeVirtual(key, state); -} -#endif \ No newline at end of file diff --git a/src/items/test.cpp b/src/items/test.cpp deleted file mode 100644 index 8e6bf275..00000000 --- a/src/items/test.cpp +++ /dev/null @@ -1,47 +0,0 @@ -//#include "items/test.h" -//#include "BufferExecute.h" -//#include "Class/LineParsing.h" -//#include "Global.h" -// -//// Outside of class -//SensorImpulsIn *pointerToClass; // declare a pointer to SensorImpulsIn class -// -//static void outsideInterruptHandler(void) { // define global handler -// pointerToClass->classInterruptHandler(); // calls class member handler -//} -// -//SensorImpulsIn::SensorImpulsIn(const paramsImpulsIn& paramsImpuls) { -// _paramsImpuls = paramsImpulsIn(paramsImpuls); -// -// pinMode(paramsImpuls.pin, INPUT); -// -// pointerToClass = this; // assign current instance to pointer (IMPORTANT!!!) -// attachInterrupt(digitalPinToInterrupt(_paramsImpuls.pin), outsideInterruptHandler, CHANGE); -//} -// -//MySensorImpulsInVector* mySensorImpulsIn = nullptr; -// -//void SensorImpulsIn::classInterruptHandler(void) { -// localPointerToCallback(digitalRead(_paramsImpuls.pin)); -//} -// -//void impulsInSensor() { -// myLineParsing.update(); -// String key = myLineParsing.gkey(); -// String pin = myLineParsing.gpin(); -// String c = myLineParsing.gc(); -// String k = myLineParsing.gk(); -// myLineParsing.clear(); -// -// static paramsImpulsIn paramsImpuls; -// -// paramsImpuls.key = key; -// paramsImpuls.pin = pin.toInt(); -// paramsImpuls.c = c.toFloat(); -// paramsImpuls.k = k.toFloat(); -// -// static bool firstTime = true; -// if (firstTime) mySensorImpulsIn = new MySensorImpulsInVector(); -// firstTime = false; -// mySensorImpulsIn->push_back(SensorImpulsIn(paramsImpuls)); -//} \ No newline at end of file diff --git a/src/items/vButtonOut.cpp b/src/items/vButtonOut.cpp deleted file mode 100644 index e861d68f..00000000 --- a/src/items/vButtonOut.cpp +++ /dev/null @@ -1,94 +0,0 @@ -#include "Consts.h" -#ifdef EnableButtonOut -#include - -#include "BufferExecute.h" -#include "Class/LineParsing.h" -#include "Global.h" -#include "SoftUART.h" -#include "items/vButtonOut.h" -//this class save data to flash -ButtonOut::ButtonOut(String pin, boolean inv, String key, String type) { - _pin = pin; - _inv = inv; - _key = key; - _type = type; -#ifdef ESP_MODE - if (_pin != "") { - pinMode(_pin.toInt(), OUTPUT); - } - int state = jsonReadInt(configStoreJson, key); //прочитали из памяти - this->execute(String(state)); //установили это состояние -#endif -#ifdef GATE_MODE -//TO DO запросили ноду о состоянии реле -//установили в это состояние кнопку в приложении -//если нода не ответила - кнопку сделать красным цветом -#endif -} -ButtonOut::~ButtonOut() {} - -void ButtonOut::execute(String state) { -#ifdef ESP_MODE - if (state != "" && _pin != "") { - if (state == "change") { - state = String(!digitalRead(_pin.toInt())); - digitalWrite(_pin.toInt(), state.toInt()); - } else { - if (_inv) { - digitalWrite(_pin.toInt(), !state.toInt()); - } else { - digitalWrite(_pin.toInt(), state.toInt()); - } - } - } -#endif -#ifdef GATE_MODE -//отправили ноде команду на вкл выкл -//получили обратную связь - переставили кнопку в приложении -//не получили обратную связь - сделали кнопку красной -#endif - eventGen2(_key, state); - jsonWriteInt(configStoreJson, _key, state.toInt()); - saveStore(); - publishStatus(_key, state); -} - -MyButtonOutVector* myButtonOut = nullptr; - -void buttonOut() { - myLineParsing.update(); - String key = myLineParsing.gkey(); - String pin = myLineParsing.gpin(); - String inv = myLineParsing.ginv(); - String type = myLineParsing.gtype(); - - bool invb = false; - if (inv.toInt() == 1) invb = true; - - myLineParsing.clear(); - - buttonOut_EnterCounter++; - addKey(key, buttonOut_KeyList, buttonOut_EnterCounter); - - static bool firstTime = true; - if (firstTime) myButtonOut = new MyButtonOutVector(); - firstTime = false; - myButtonOut->push_back(ButtonOut(pin, invb, key, type)); - - sCmd.addCommand(key.c_str(), buttonOutExecute); -} - -void buttonOutExecute() { - String key = sCmd.order(); - String state = sCmd.next(); - - int number = getKeyNum(key, buttonOut_KeyList); - - if (myButtonOut != nullptr) { - if (number != -1) { - myButtonOut->at(number).execute(state); - } - } -} -#endif diff --git a/src/items/vCountDown.cpp b/src/items/vCountDown.cpp deleted file mode 100644 index f8607713..00000000 --- a/src/items/vCountDown.cpp +++ /dev/null @@ -1,79 +0,0 @@ -#include "Consts.h" -#ifdef EnableCountDown -#include - -#include "BufferExecute.h" -#include "Class/LineParsing.h" -#include "Global.h" -#include "items/vCountDown.h" - -CountDownClass::CountDownClass(String key) { - _key = key; -} - -CountDownClass::~CountDownClass() {} - -void CountDownClass::execute(unsigned int countDownPeriod) { - _countDownPeriod = countDownPeriod * 1000; - _start = true; -} - -void CountDownClass::loop() { - if (_countDownPeriod > 0 && _start) { - prevMillis = millis(); - sec = (_countDownPeriod / 1000); - _start = false; - } - - difference = millis() - prevMillis; - if (difference > 1000 && _countDownPeriod > 0) { - prevMillis = millis(); - eventGen2(_key, String(sec)); - String time = String(prettyMillis(sec * 1000)); - jsonWriteStr(configLiveJson, _key, time); - publishStatus(_key, time); - sec--; - if (sec < 0) { - _countDownPeriod = 0; - } - } -} - -MyCountDownVector* myCountDown = nullptr; - -void countDown() { - myLineParsing.update(); - String key = myLineParsing.gkey(); - myLineParsing.clear(); - - countDown_EnterCounter++; - addKey(key, countDown_KeyList, countDown_EnterCounter); - - //Serial.println(countDown_EnterCounter); - //Serial.println(countDown_KeyList); - - static bool firstTime = true; - if (firstTime) myCountDown = new MyCountDownVector(); - firstTime = false; - myCountDown->push_back(CountDownClass(key)); - - sCmd.addCommand(key.c_str(), countDownExecute); -} - -void countDownExecute() { - String key = sCmd.order(); - String value = sCmd.next(); - - if (!isDigitStr(value)) { //если значение - текст - value = getValue(value); - } - - int number = getKeyNum(key, countDown_KeyList); - - if (myCountDown != nullptr) { - if (number != -1) { - myCountDown->at(number).execute(value.toInt()); - } - } -} -#endif \ No newline at end of file diff --git a/src/items/vImpulsOut.cpp b/src/items/vImpulsOut.cpp deleted file mode 100644 index 8449a463..00000000 --- a/src/items/vImpulsOut.cpp +++ /dev/null @@ -1,73 +0,0 @@ -#include "Consts.h" -#ifdef EnableImpulsOut -#include "items/vImpulsOut.h" -#include "BufferExecute.h" -#include "Class/LineParsing.h" -#include "Global.h" -#include "BufferExecute.h" -#include - -ImpulsOutClass::ImpulsOutClass(unsigned int impulsPin) { - _impulsPin = impulsPin; - pinMode(impulsPin, OUTPUT); -} - -ImpulsOutClass::~ImpulsOutClass() {} - -void ImpulsOutClass::execute(unsigned long impulsPeriod, unsigned int impulsCount) { - _impulsPeriod = impulsPeriod; - _impulsCount = impulsCount * 2; - _impulsCountBuf = _impulsCount; -} - -void ImpulsOutClass::loop() { - currentMillis = millis(); - difference = currentMillis - prevMillis; - if (_impulsCountBuf > 0) { - if (difference > _impulsPeriod) { - _impulsCountBuf--; - prevMillis = millis(); - yield(); - digitalWrite(_impulsPin, !digitalRead(_impulsPin)); - yield(); - } - } - if (_impulsCountBuf <= 0) { - digitalWrite(_impulsPin, LOW); - } -} - -MyImpulsOutVector* myImpulsOut = nullptr; - -void impuls() { - myLineParsing.update(); - String key = myLineParsing.gkey(); - String pin = myLineParsing.gpin(); - myLineParsing.clear(); - - impuls_EnterCounter++; - addKey(key, impuls_KeyList, impuls_EnterCounter); - - static bool firstTime = true; - if (firstTime) myImpulsOut = new MyImpulsOutVector(); - firstTime = false; - myImpulsOut->push_back(ImpulsOutClass(pin.toInt())); - - sCmd.addCommand(key.c_str(), impulsExecute); -} - -void impulsExecute() { - String key = sCmd.order(); - String impulsPeriod = sCmd.next(); - String impulsCount = sCmd.next(); - - int number = getKeyNum(key, impuls_KeyList); - - if (myImpulsOut != nullptr) { - if (number != -1) { - myImpulsOut->at(number).execute(impulsPeriod.toInt(), impulsCount.toInt()); - } - } -} - -#endif diff --git a/src/items/vInput.cpp b/src/items/vInput.cpp deleted file mode 100644 index 081a7aa1..00000000 --- a/src/items/vInput.cpp +++ /dev/null @@ -1,92 +0,0 @@ -#include "Consts.h" -#ifdef EnableInput -#include - -#include "BufferExecute.h" -#include "Class/LineParsing.h" -#include "Clock.h" -#include "Global.h" -#include "items/vInput.h" - -//this class save date to flash -Input::Input(String key, String widget) { - _key = key; - String value = jsonReadStr(configStoreJson, key); - - if (value == "") { - if (widget.indexOf("Digit") != -1) { - value = "25"; - } - if (widget.indexOf("Time") != -1) { - value = "12:00"; - } - } - - this->execute(value); -} -Input::~Input() {} - -void Input::execute(String value) { - eventGen2(_key, value); - jsonWriteStr(configStoreJson, _key, value); - saveStore(); - publishStatus(_key, value); -} - -MyInputVector* myInput = nullptr; - -void inputValue() { - myLineParsing.update(); - String widget = myLineParsing.gfile(); - String key = myLineParsing.gkey(); - myLineParsing.clear(); - - input_EnterCounter++; - addKey(key, input_KeyList, input_EnterCounter); - - static bool firstTime = true; - if (firstTime) myInput = new MyInputVector(); - firstTime = false; - myInput->push_back(Input(key, widget)); - - sCmd.addCommand(key.c_str(), inputExecute); -} - -void inputExecute() { - String key = sCmd.order(); - String value = sCmd.next(); - - if (!isDigitStr(value)) { //если значение - текст - if (value.indexOf(":") == -1) { //если этот текст не время - if (value.indexOf("++") != -1) { //если тест - инкримент - String prevValue = getValue(key); - if (prevValue != "no value") { - int prevValueInt = prevValue.toInt(); - prevValueInt++; - value = String(prevValueInt); - } - } else if (value.indexOf("--") != -1) { //если тест - дикремент - String prevValue = getValue(key); - if (prevValue != "no value") { - int prevValueInt = prevValue.toInt(); - prevValueInt--; - value = String(prevValueInt); - } - } else { //остальные случаи любого текста - String valueJson = getValue(value); - if (valueJson != "no value") { //если это ключ переменной - value = valueJson; - } - } - } - } - - int number = getKeyNum(key, input_KeyList); - - if (myInput != nullptr) { - if (number != -1) { - myInput->at(number).execute(value); - } - } -} -#endif diff --git a/src/items/vLogging.cpp b/src/items/vLogging.cpp deleted file mode 100644 index 08519009..00000000 --- a/src/items/vLogging.cpp +++ /dev/null @@ -1,233 +0,0 @@ -#include "Consts.h" -#ifdef EnableLogging -#include - -#include "BufferExecute.h" -#include "Class/LineParsing.h" -#include "FileSystem.h" -#include "Global.h" -#include "items/vLogging.h" - -LoggingClass::LoggingClass(String interval, unsigned int maxPoints, String loggingValueKey, String key, String startState, bool savedFromWeb) { - _interval = interval; - _maxPoints = maxPoints; - _loggingValueKey = loggingValueKey; - _key = key; - - if (_interval.indexOf(":") != -1) { - _type = 3; //тип 3 логгирование в указанное время - _intervalSec = 1000; - if (savedFromWeb) { //если было сохранено из веб интерфейса - removeFile("/logs/prv" + _key + ".txt"); - addFile("/logs/prv" + _key + ".txt", startState); - } - SerialPrint("I", "Logging", "at time (" + _interval + ")"); - } else { - if (_interval.toInt() == 0) { - _type = 2; //тип 2 логгирование по событию - SerialPrint("I", "Logging", "by event"); - } else if (_interval.toInt() > 0) { - _type = 1; //тип 1 логгирование через период - _intervalSec = _interval.toInt() * 1000; - SerialPrint("I", "Logging", "periodically (" + _interval + " sec)"); - } - } - - if (_type == 0) SerialPrint("E", "Logging", "type undetermine"); -} - -LoggingClass::~LoggingClass() {} - -void LoggingClass::loop() { - if (_intervalSec > 0) { - currentMillis = millis(); - difference = currentMillis - prevMillis; - if (difference >= _intervalSec) { - prevMillis = millis(); - if (_type == 1) { - execute(""); - } else if (_type == 2) { - } else if (_type == 3) { - String timenow = timeNow->getTimeWOsec(); - static String prevTime; - if (prevTime != timenow) { - prevTime = timenow; - if (_interval == timenow) execute(""); - } - } - } - } -} - -void LoggingClass::execute(String keyOrValue) { - String loggingValue = ""; - if (_type == 1) { //тип 1 логгирование через период - if (getValue(_loggingValueKey) != "no value") { - loggingValue = getValue(_loggingValueKey); - } else { - SerialPrint("E", "Logging", "'" + _loggingValueKey + "' value not found on this device"); - } - } else if (_type == 2) { //тип 2 логгирование по событию - if (isDigitDotCommaStr(keyOrValue)) { //если это число или дробное число - loggingValue = keyOrValue; - } else { //если это ключ - if (getValue(_loggingValueKey) != "no value") { - loggingValue = getValue(keyOrValue); - } else { - SerialPrint("E", "Logging", "This value not found on this device"); - } - } - } else if (_type == 3) { //тип 3 логгирование в указанное время - if (getValue(_loggingValueKey) != "no value") { - float prevValue = readFile("/logs/prv" + _key + ".txt", 100).toFloat(); - float currentValue = getValue(_loggingValueKey).toFloat(); - loggingValue = String(currentValue - prevValue); - removeFile("/logs/prv" + _key + ".txt"); - addFile("/logs/prv" + _key + ".txt", String(currentValue)); - } else { - SerialPrint("E", "Logging", "This value not found on this device"); - } - } - - String filename = "/logs/" + _key + ".txt"; - - size_t cnt = countLines(filename); - size_t sz = getFileSize(filename); - - SerialPrint("I", "Logging", "http://" + WiFi.localIP().toString() + filename + " lines " + String(cnt, DEC) + ", size " + String(sz)); - - if ((cnt > _maxPoints + 1)) { - removeFile(filename); - SerialPrint("E", "Logging", "file been remooved: " + filename + " " + String(cnt) + ">" + String(_maxPoints)); - cnt = 0; - } - - if (loggingValue != "") { - if (cnt >= _maxPoints) { //удаляем старую строку и добавляем новую - String logData = readFile(filename, 20480); //10240 - SerialPrint("I", "Logging", "Free heap " + String(ESP.getFreeHeap())); - if (logData == "large") { - SerialPrint("E", "Logging", "File is very large"); - } - - logData = deleteBeforeDelimiter(logData, "\r\n"); - - if (timeNow->hasTimeSynced()) { - logData += timeNow->getTimeUnix() + " " + loggingValue + "\r\n"; - - writeFile(filename, logData); - } - } else { //просто добавляем новую строку - if (timeNow->hasTimeSynced()) { - addFileLn(filename, timeNow->getTimeUnix() + " " + loggingValue); - } - } - } - - String buf = "{}"; - jsonWriteInt(buf, "x", timeNow->getTimeUnix().toInt()); - jsonWriteFloat(buf, "y1", loggingValue.toFloat()); - buf = "{\"status\":[" + buf + "]}"; - publishChart(_key, buf); -} - -MyLoggingVector* myLogging = nullptr; - -void logging() { - myLineParsing.update(); - String loggingValueKey = myLineParsing.gval(); - String key = myLineParsing.gkey(); - String interval = myLineParsing.gint(); - String maxcnt = myLineParsing.gcnt(); - String startState = myLineParsing.gstate(); - myLineParsing.clear(); - - logging_KeyList += key + ","; - - logging_EnterCounter++; - addKey(key, logging_KeyList, logging_EnterCounter); - - static bool firstTime = true; - if (firstTime) myLogging = new MyLoggingVector(); - firstTime = false; - myLogging->push_back(LoggingClass(interval, maxcnt.toInt(), loggingValueKey, key, startState, savedFromWeb)); - - sCmd.addCommand(key.c_str(), loggingExecute); -} - -void loggingExecute() { - String key = sCmd.order(); - String value = sCmd.next(); - int number = getKeyNum(key, logging_KeyList); - if (myLogging != nullptr) { - if (number != -1) { - myLogging->at(number).execute(value); - } - } -} - -void choose_log_date_and_send() { - String all_line = logging_KeyList; - while (all_line.length() != 0) { - String tmp = selectToMarker(all_line, ","); - sendLogData("/logs/" + tmp + ".txt", tmp); - all_line = deleteBeforeDelimiter(all_line, ","); - } -} - -void sendLogData(String file, String topic) { - File configFile = FileFS.open(file, "r"); - if (!configFile) { - return; - } - configFile.seek(0, SeekSet); - int i = 0; - String buf = "{}"; - String json_array; - String unix_time; - String value; - unsigned int psn; - unsigned int sz = configFile.size(); - do { - i++; - psn = configFile.position(); - String line = configFile.readStringUntil('\n'); - unix_time = selectToMarker(line, " "); - jsonWriteInt(buf, "x", unix_time.toInt()); - value = deleteBeforeDelimiter(line, " "); - jsonWriteFloat(buf, "y1", value.toFloat()); - if (unix_time != "" || value != "") { - json_array += buf + ","; - } - int grafmax = jsonReadInt(configSetupJson, "grafmax"); - if (grafmax != 0) { - if (i >= grafmax) { - json_array = "{\"status\":[" + json_array + "]}"; - json_array.replace("},]}", "}]}"); - publishChart(topic, json_array); - json_array = ""; - i = 0; - } - } - } while (psn < sz); - - configFile.close(); - - json_array = "{\"status\":[" + json_array + "]}"; - json_array.replace("},]}", "}]}"); - publishChart(topic, json_array); -} - -void cleanLogAndData() { -#ifdef ESP8266 - auto dir = FileFS.openDir("logs"); - while (dir.next()) { - String fname = dir.fileName(); - SerialPrint("I", "System", fname); - removeFile("logs/" + fname); - } -#endif - removeFile("store.json"); - configStoreJson = ""; -} -#endif diff --git a/src/items/vOutput.cpp b/src/items/vOutput.cpp deleted file mode 100644 index cc153f2b..00000000 --- a/src/items/vOutput.cpp +++ /dev/null @@ -1,58 +0,0 @@ -#include "Consts.h" -#ifdef EnableOutput -#include - -#include "BufferExecute.h" -#include "Class/LineParsing.h" -#include "Clock.h" -#include "Global.h" -#include "items/vOutput.h" - -Output::Output(String key) { - _key = key; - String value = jsonReadStr(configLiveJson, key); - this->execute(value); -} -Output::~Output() {} - -void Output::execute(String value) { - eventGen2(_key, value); - jsonWriteStr(configLiveJson, _key, value); - publishStatus(_key, value); - //publishLastUpdateTime(_key, timeNow->getTime()); -} - -MyOutputVector* myOutput = nullptr; - -void outputValue() { - myLineParsing.update(); - String key = myLineParsing.gkey(); - myLineParsing.clear(); - - output_EnterCounter++; - addKey(key, output_KeyList, output_EnterCounter); - - static bool firstTime = true; - if (firstTime) myOutput = new MyOutputVector(); - firstTime = false; - myOutput->push_back(Output(key)); - - sCmd.addCommand(key.c_str(), outputExecute); -} - -void outputExecute() { - String key = sCmd.order(); - String value = sCmd.next(); - - value.replace("#", " "); - value.replace("%date%", timeNow->getDateTimeDotFormated()); - - int number = getKeyNum(key, output_KeyList); - - if (myOutput != nullptr) { - if (number != -1) { - myOutput->at(number).execute(value); - } - } -} -#endif diff --git a/src/items/vPwmOut.cpp b/src/items/vPwmOut.cpp deleted file mode 100644 index a6df133a..00000000 --- a/src/items/vPwmOut.cpp +++ /dev/null @@ -1,61 +0,0 @@ -#include "Consts.h" -#ifdef EnablePwmOut -#include "items/vPwmOut.h" - -#include - -#include "BufferExecute.h" -#include "Class/LineParsing.h" -#include "Consts.h" -#include "Global.h" - -//this class save data to flash -PwmOut::PwmOut(unsigned int pin, String key) { - _pin = pin; - _key = key; - pinMode(_pin, OUTPUT); - int state = jsonReadInt(configStoreJson, key); - this->execute(String(state)); -} -PwmOut::~PwmOut() {} - -void PwmOut::execute(String state) { - analogWrite(_pin, state.toInt()); - eventGen2(_key, state); - jsonWriteInt(configStoreJson, _key, state.toInt()); - saveStore(); - publishStatus(_key, state); -} - -MyPwmOutVector* myPwmOut = nullptr; - -void pwmOut() { - myLineParsing.update(); - String key = myLineParsing.gkey(); - String pin = myLineParsing.gpin(); - myLineParsing.clear(); - - pwmOut_EnterCounter++; - addKey(key, pwmOut_KeyList, pwmOut_EnterCounter); - - static bool firstTime = true; - if (firstTime) myPwmOut = new MyPwmOutVector(); - firstTime = false; - myPwmOut->push_back(PwmOut(pin.toInt(), key)); - - sCmd.addCommand(key.c_str(), pwmOutExecute); -} - -void pwmOutExecute() { - String key = sCmd.order(); - String state = sCmd.next(); - - int number = getKeyNum(key, pwmOut_KeyList); - - if (myPwmOut != nullptr) { - if (number != -1) { - myPwmOut->at(number).execute(state); - } - } -} -#endif \ No newline at end of file diff --git a/src/items/vSensorAnalog.cpp b/src/items/vSensorAnalog.cpp deleted file mode 100644 index b0df65df..00000000 --- a/src/items/vSensorAnalog.cpp +++ /dev/null @@ -1,72 +0,0 @@ -#include "Consts.h" -#ifdef EnableSensorAnalog -#include "items/vSensorAnalog.h" -#include "Class/LineParsing.h" -#include "Global.h" -#include "BufferExecute.h" -#include - -SensorAnalog::SensorAnalog(String key, unsigned long interval, unsigned int adcPin, int map1, int map2, int map3, int map4, float c) { - _interval = interval * 1000; - _key = key; - _adcPin = adcPin; - - _map1 = map1; - _map2 = map2; - _map3 = map3; - _map4 = map4; - - _c = c; -} - -SensorAnalog::~SensorAnalog() {} - -void SensorAnalog::loop() { - currentMillis = millis(); - difference = currentMillis - prevMillis; - if (difference >= _interval) { - prevMillis = millis(); - readAnalog(); - } -} - -void SensorAnalog::readAnalog() { - int value; -#ifdef ESP32 - value = analogRead(_adcPin); -#endif -#ifdef ESP8266 - value = analogRead(A0); -#endif - - value = map(value, _map1, _map2, _map3, _map4); - float valueFloat = value * _c; - - eventGen2(_key, String(valueFloat)); - jsonWriteStr(configLiveJson, _key, String(valueFloat)); - publishStatus(_key, String(valueFloat)); - SerialPrint("I", "Sensor", "'" + _key + "' data: " + String(valueFloat)); -} - -MySensorAnalogVector* mySensorAnalog = nullptr; - -void analogAdc() { - myLineParsing.update(); - String interval = myLineParsing.gint(); - String pin = myLineParsing.gpin(); - String key = myLineParsing.gkey(); - String map = myLineParsing.gmap(); - String c = myLineParsing.gc(); - myLineParsing.clear(); - - int map1 = selectFromMarkerToMarker(map, ",", 0).toInt(); - int map2 = selectFromMarkerToMarker(map, ",", 1).toInt(); - int map3 = selectFromMarkerToMarker(map, ",", 2).toInt(); - int map4 = selectFromMarkerToMarker(map, ",", 3).toInt(); - - static bool firstTime = true; - if (firstTime) mySensorAnalog = new MySensorAnalogVector(); - firstTime = false; - mySensorAnalog->push_back(SensorAnalog(key, interval.toInt(), pin.toInt(), map1, map2, map3, map4, c.toFloat())); -} -#endif diff --git a/src/items/vSensorBme280.cpp b/src/items/vSensorBme280.cpp deleted file mode 100644 index 11daf71f..00000000 --- a/src/items/vSensorBme280.cpp +++ /dev/null @@ -1,103 +0,0 @@ -#include "Consts.h" -#ifdef EnableSensorBme280 -#include "items/vSensorBme280.h" - -#include - -#include "BufferExecute.h" -#include "Class/LineParsing.h" -#include "Global.h" - -Adafruit_BME280* bme = nullptr; - -SensorBme280::SensorBme280(const paramsBme& paramsTmp, const paramsBme& paramsHum, const paramsBme& paramsPrs) { - _paramsTmp = paramsBme(paramsTmp); - _paramsHum = paramsBme(paramsHum); - _paramsPrs = paramsBme(paramsPrs); - - if (!bme) { - bme = new Adafruit_BME280; - } - - bme->getTemperatureSensor(); - bme->getPressureSensor(); - bme->getHumiditySensor(); - bme->begin(hexStringToUint8(_paramsPrs.addr)); -} - -SensorBme280::~SensorBme280() {} - -void SensorBme280::loop() { - difference = millis() - prevMillis; - if (difference >= _paramsPrs.interval) { - prevMillis = millis(); - read(); - } -} - -void SensorBme280::read() { - float tmp = bme->readTemperature(); - float hum = bme->readHumidity(); - float prs = bme->readPressure(); - prs = prs / 1.333224 / 100; - - tmp = tmp * _paramsTmp.c; - hum = hum * _paramsHum.c; - prs = prs * _paramsPrs.c; - - eventGen2(_paramsTmp.key, String(tmp)); - jsonWriteStr(configLiveJson, _paramsTmp.key, String(tmp)); - publishStatus(_paramsTmp.key, String(tmp)); - SerialPrint("I", "Sensor", "'" + _paramsTmp.key + "' data: " + String(tmp)); - - eventGen2(_paramsHum.key, String(hum)); - jsonWriteStr(configLiveJson, _paramsHum.key, String(hum)); - publishStatus(_paramsHum.key, String(hum)); - SerialPrint("I", "Sensor", "'" + _paramsHum.key + "' data: " + String(hum)); - - eventGen2(_paramsPrs.key, String(prs)); - jsonWriteStr(configLiveJson, _paramsPrs.key, String(prs)); - publishStatus(_paramsPrs.key, String(prs)); - SerialPrint("I", "Sensor", "'" + _paramsPrs.key + "' data: " + String(prs)); -} - -MySensorBme280Vector* mySensorBme280 = nullptr; - -void bme280Sensor() { - myLineParsing.update(); - String key = myLineParsing.gkey(); - String addr = myLineParsing.gaddr(); - String interval = myLineParsing.gint(); - String c = myLineParsing.gc(); - myLineParsing.clear(); - - static int enterCnt = -1; - enterCnt++; - - static paramsBme paramsTmp; - static paramsBme paramsHum; - static paramsBme paramsPrs; - - if (enterCnt == 0) { - paramsTmp.key = key; - paramsTmp.c = c.toFloat(); - } - - if (enterCnt == 1) { - paramsHum.key = key; - paramsHum.c = c.toFloat(); - } - - if (enterCnt == 2) { - paramsPrs.key = key; - paramsPrs.addr = addr; - paramsPrs.interval = interval.toInt() * 1000; - paramsPrs.c = c.toFloat(); - - static bool firstTime = true; - if (firstTime) mySensorBme280 = new MySensorBme280Vector(); - firstTime = false; - mySensorBme280->push_back(SensorBme280(paramsTmp, paramsHum, paramsPrs)); - } -} -#endif \ No newline at end of file diff --git a/src/items/vSensorBmp280.cpp b/src/items/vSensorBmp280.cpp deleted file mode 100644 index 2d9672bb..00000000 --- a/src/items/vSensorBmp280.cpp +++ /dev/null @@ -1,89 +0,0 @@ -#include "Consts.h" -#ifdef EnableSensorBmp280 -#include "items/vSensorBmp280.h" - -#include - -#include "BufferExecute.h" -#include "Class/LineParsing.h" -#include "Global.h" - -Adafruit_BMP280* bmp = nullptr; - -SensorBmp280::SensorBmp280(const paramsBmp& paramsTmp, const paramsBmp& paramsPrs) { - _paramsTmp = paramsBmp(paramsTmp); - _paramsPrs = paramsBmp(paramsPrs); - - if (!bmp) { - bmp = new Adafruit_BMP280; - } - - bmp->getTemperatureSensor(); - bmp->getPressureSensor(); - bmp->begin(hexStringToUint8(_paramsPrs.addr)); -} - -SensorBmp280::~SensorBmp280() {} - -void SensorBmp280::loop() { - difference = millis() - prevMillis; - if (difference >= _paramsPrs.interval) { - prevMillis = millis(); - read(); - } -} - -void SensorBmp280::read() { - float tmp = bmp->readTemperature(); - float prs = bmp->readPressure(); - prs = prs / 1.333224 / 100; - - tmp = tmp * _paramsTmp.c; - prs = prs * _paramsPrs.c; - - eventGen2(_paramsTmp.key, String(tmp)); - jsonWriteStr(configLiveJson, _paramsTmp.key, String(tmp)); - publishStatus(_paramsTmp.key, String(tmp)); - SerialPrint("I", "Sensor", "'" + _paramsTmp.key + "' data: " + String(tmp)); - - eventGen2(_paramsPrs.key, String(prs)); - jsonWriteStr(configLiveJson, _paramsPrs.key, String(prs)); - publishStatus(_paramsPrs.key, String(prs)); - SerialPrint("I", "Sensor", "'" + _paramsPrs.key + "' data: " + String(prs)); -} - -MySensorBmp280Vector* mySensorBmp280 = nullptr; - -void bmp280Sensor() { - myLineParsing.update(); - String key = myLineParsing.gkey(); - String addr = myLineParsing.gaddr(); - String interval = myLineParsing.gint(); - String c = myLineParsing.gc(); - myLineParsing.clear(); - - static int enterCnt = -1; - enterCnt++; - - static paramsBmp paramsTmp; - static paramsBmp paramsHum; - static paramsBmp paramsPrs; - - if (enterCnt == 0) { - paramsTmp.key = key; - paramsTmp.c = c.toFloat(); - } - - if (enterCnt == 1) { - paramsPrs.key = key; - paramsPrs.addr = addr; - paramsPrs.interval = interval.toInt() * 1000; - paramsPrs.c = c.toFloat(); - - static bool firstTime = true; - if (firstTime) mySensorBmp280 = new MySensorBmp280Vector(); - firstTime = false; - mySensorBmp280->push_back(SensorBmp280(paramsTmp, paramsPrs)); - } -} -#endif \ No newline at end of file diff --git a/src/items/vSensorCcs811.cpp b/src/items/vSensorCcs811.cpp deleted file mode 100644 index 3463ea31..00000000 --- a/src/items/vSensorCcs811.cpp +++ /dev/null @@ -1,92 +0,0 @@ -#include "Consts.h" -#ifdef EnableSensorCcs811 -#include "items/vSensorCcs811.h" - -#include - -#include "BufferExecute.h" -#include "Class/LineParsing.h" -#include "Global.h" - -SensorCcs811::SensorCcs811(const paramsCcs811& paramsPpm, const paramsCcs811& paramsPpb) { - _paramsPpm = paramsCcs811(paramsPpm); - _paramsPpb = paramsCcs811(paramsPpb); - - ccs811 = new Adafruit_CCS811(); - - if (!ccs811->begin(hexStringToUint8(_paramsPpb.addr))) SerialPrint("E", "Sensor CCS", "Wire not connected"); -} - -SensorCcs811::~SensorCcs811() {} - -void SensorCcs811::loop() { - difference = millis() - prevMillis; - if (difference >= _paramsPpb.interval) { - prevMillis = millis(); - read(); - } -} - -void SensorCcs811::read() { - float co2; - float ppm; - if (ccs811->available()) { - if (!ccs811->readData()) { - co2 = ccs811->geteCO2(); - ppm = ccs811->getTVOC(); - - co2 = co2 * _paramsPpm.c; - ppm = ppm * _paramsPpb.c; - - eventGen2(_paramsPpm.key, String(co2)); - jsonWriteStr(configLiveJson, _paramsPpm.key, String(co2)); - publishStatus(_paramsPpm.key, String(co2)); - SerialPrint("I", "Sensor", "'" + _paramsPpm.key + "' data: " + String(co2)); - - eventGen2(_paramsPpb.key, String(ppm)); - jsonWriteStr(configLiveJson, _paramsPpb.key, String(ppm)); - publishStatus(_paramsPpb.key, String(ppm)); - SerialPrint("I", "Sensor", "'" + _paramsPpb.key + "' data: " + String(ppm)); - } else { - SerialPrint("E", "Sensor CCS", "Error"); - } - } -} - -MySensorCcs811Vector* mySensorCcs811 = nullptr; - -void ccs811Sensor() { - myLineParsing.update(); - String key = myLineParsing.gkey(); - String addr = myLineParsing.gaddr(); - String interval = myLineParsing.gint(); - String c = myLineParsing.gc(); - myLineParsing.clear(); - - static int enterCnt = -1; - enterCnt++; - - static paramsCcs811 paramsPpm; - static paramsCcs811 paramsPpb; - - if (enterCnt == 0) { - paramsPpm.key = key; - paramsPpm.interval = interval.toInt() * 1000; - paramsPpm.c = c.toFloat(); - } - - if (enterCnt == 1) { - paramsPpb.key = key; - paramsPpb.addr = addr; - paramsPpb.interval = interval.toInt() * 1000; - paramsPpb.c = c.toFloat(); - - static bool firstTime = true; - if (firstTime) mySensorCcs811 = new MySensorCcs811Vector(); - firstTime = false; - mySensorCcs811->push_back(SensorCcs811(paramsPpm, paramsPpb)); - - enterCnt = -1; - } -} -#endif \ No newline at end of file diff --git a/src/items/vSensorDallas.cpp b/src/items/vSensorDallas.cpp deleted file mode 100644 index 9a2161a9..00000000 --- a/src/items/vSensorDallas.cpp +++ /dev/null @@ -1,60 +0,0 @@ -#include "Consts.h" -#ifdef EnableSensorDallas -#include "items/vSensorDallas.h" -#include "BufferExecute.h" -#include "Class/LineParsing.h" -#include "Global.h" - -#include - -OneWire* oneWire; -DallasTemperature sensors; - -SensorDallas::SensorDallas(unsigned long interval, unsigned int pin, unsigned int index, String key) { - _interval = interval * 1000; - _key = key; - _pin = pin; - _index = index; - - oneWire = new OneWire((uint8_t)_pin); - sensors.setOneWire(oneWire); - sensors.begin(); - sensors.setResolution(12); -} - -SensorDallas::~SensorDallas() {} - -void SensorDallas::loop() { - currentMillis = millis(); - difference = currentMillis - prevMillis; - if (difference >= _interval) { - prevMillis = millis(); - readDallas(); - } -} - -void SensorDallas::readDallas() { - sensors.requestTemperaturesByIndex(_index); - float value = sensors.getTempCByIndex(_index); - eventGen2(_key, String(value)); - jsonWriteStr(configLiveJson, _key, String(value)); - publishStatus(_key, String(value)); - SerialPrint("I", "Sensor", "'" + _key + "' data: " + String(value)); -} - -MySensorDallasVector* mySensorDallas2 = nullptr; - -void dallas() { - myLineParsing.update(); - String interval = myLineParsing.gint(); - String pin = myLineParsing.gpin(); - String index = myLineParsing.gindex(); - String key = myLineParsing.gkey(); - myLineParsing.clear(); - - static bool firstTime = true; - if (firstTime) mySensorDallas2 = new MySensorDallasVector(); - firstTime = false; - mySensorDallas2->push_back(SensorDallas(interval.toInt(), pin.toInt(), index.toInt(), key)); -} -#endif diff --git a/src/items/vSensorDht.cpp b/src/items/vSensorDht.cpp deleted file mode 100644 index dc605062..00000000 --- a/src/items/vSensorDht.cpp +++ /dev/null @@ -1,97 +0,0 @@ -#include "Consts.h" -#ifdef EnableSensorDht -#include "items/vSensorDht.h" - -#include - -#include "BufferExecute.h" -#include "Class/LineParsing.h" -#include "Global.h" - -SensorDht::SensorDht(const paramsDht& paramsTmp, const paramsDht& paramsHum) { - _paramsTmp = paramsDht(paramsTmp); - _paramsHum = paramsDht(paramsHum); - - dht = new DHTesp(); - - if (_paramsHum.type == "dht11") { - dht->setup(_paramsHum.pin, DHTesp::DHT11); - } else if (_paramsHum.type == "dht22") { - dht->setup(_paramsHum.pin, DHTesp::DHT22); - } - - _paramsHum.interval = _paramsHum.interval + dht->getMinimumSamplingPeriod(); -} - -SensorDht::~SensorDht() {} - -void SensorDht::loop() { - difference = millis() - prevMillis; - if (difference >= _paramsHum.interval) { - prevMillis = millis(); - readTmpHum(); - } -} - -void SensorDht::readTmpHum() { - float tmp = dht->getTemperature(); - float hum = dht->getHumidity(); - - if (String(tmp) != "nan" && String(hum) != "nan") { - tmp = tmp * _paramsTmp.c; - hum = hum * _paramsHum.c; - - eventGen2(_paramsTmp.key, String(tmp)); - jsonWriteStr(configLiveJson, _paramsTmp.key, String(tmp)); - publishStatus(_paramsTmp.key, String(tmp)); - SerialPrint("I", "Sensor", "'" + _paramsTmp.key + "' data: " + String(tmp)); - - eventGen2(_paramsHum.key, String(hum)); - jsonWriteStr(configLiveJson, _paramsHum.key, String(hum)); - publishStatus(_paramsHum.key, String(hum)); - SerialPrint("I", "Sensor", "'" + _paramsHum.key + "' data: " + String(hum)); - - } else { - SerialPrint("E", "Sensor DHT", "Error"); - } -} - -MySensorDhtVector* mySensorDht = nullptr; - -void dhtSensor() { - myLineParsing.update(); - String type = myLineParsing.gtype(); - String interval = myLineParsing.gint(); - String pin = myLineParsing.gpin(); - String key = myLineParsing.gkey(); - String c = myLineParsing.gc(); - myLineParsing.clear(); - - static int enterCnt = -1; - enterCnt++; - - static paramsDht paramsTmp; - static paramsDht paramsHum; - - if (enterCnt == 0) { - paramsTmp.key = key; - paramsTmp.interval = interval.toInt() * 1000; - paramsTmp.c = c.toFloat(); - } - - if (enterCnt == 1) { - paramsHum.type = type; - paramsHum.key = key; - paramsHum.interval = interval.toInt() * 1000; - paramsHum.pin = pin.toInt(); - paramsHum.c = c.toFloat(); - - static bool firstTime = true; - if (firstTime) mySensorDht = new MySensorDhtVector(); - firstTime = false; - mySensorDht->push_back(SensorDht(paramsTmp, paramsHum)); - - enterCnt = -1; - } -} -#endif diff --git a/src/items/vSensorImpulsIn.cpp b/src/items/vSensorImpulsIn.cpp deleted file mode 100644 index 421d6219..00000000 --- a/src/items/vSensorImpulsIn.cpp +++ /dev/null @@ -1,51 +0,0 @@ -//#include "items/vSensorImpulsIn.h" -// -//#include "BufferExecute.h" -//#include "Class/LineParsing.h" -//#include "Global.h" -//#include "SoftUART.h" -// -//SensorImpulsIn::SensorImpulsIn(const paramsImpulsIn& paramsImpuls) { -// _paramsImpuls = paramsImpulsIn(paramsImpuls); -// pinMode(14, INPUT); -// //pinMode(_paramsImpuls.pin, INPUT_PULLUP); -// //attachInterrupt(digitalPinToInterrupt(14), MYinterrupt, CHANGE); -//} -// -//SensorImpulsIn::~SensorImpulsIn() {} -// -////void SensorImpulsIn::read() { -// float voltage; //= (impulsIn->values()->voltage * _paramsV.c) + _paramsV.k; -// -// eventGen2(_paramsImpuls.key, String(voltage)); -// jsonWriteStr(configLiveJson, _paramsImpuls.key, String(voltage)); -// publishStatus(_paramsImpuls.key, String(voltage)); -// SerialPrint("I", "Sensor", "'" + _paramsImpuls.key + "' data: " + String(voltage)); -//} -// -//MySensorImpulsInVector* mySensorImpulsIn = nullptr; -// -//void impulsInSensor() { -// myLineParsing.update(); -// String key = myLineParsing.gkey(); -// String pin = myLineParsing.gpin(); -// String c = myLineParsing.gc(); -// String k = myLineParsing.gk(); -// myLineParsing.clear(); -// -// static paramsImpulsIn paramsImpuls; -// -// paramsImpuls.key = key; -// paramsImpuls.pin = pin.toInt(); -// paramsImpuls.c = c.toFloat(); -// paramsImpuls.k = k.toFloat(); -// -// static bool firstTime = true; -// if (firstTime) mySensorImpulsIn = new MySensorImpulsInVector(); -// firstTime = false; -// mySensorImpulsIn->push_back(SensorImpulsIn(paramsImpuls)); -//} -// -//void MYinterrupt() { -// Serial.println("interrupt!"); -//} diff --git a/src/items/vSensorNode.cpp b/src/items/vSensorNode.cpp deleted file mode 100644 index 00295fcd..00000000 --- a/src/items/vSensorNode.cpp +++ /dev/null @@ -1,97 +0,0 @@ -#include "Consts.h" -#ifdef EnableSensorNode -#include - -#include "BufferExecute.h" -#include "Class/LineParsing.h" -#include "Clock.h" -#include "Global.h" -#include "Utils/TimeUtils.h" -#include "items/vSensorNode.h" - -SensorNode::SensorNode(const paramsSensorNode& params) { - _params = paramsSensorNode(params); - _updateTime = ""; - _minutesPassed = 0; -} - -SensorNode::~SensorNode() {} - -void SensorNode::loop() { - difference = millis() - prevMillis; - if (difference >= 60000) { - prevMillis = millis(); - _minutesPassed++; - this->publish(); - } -} - -void SensorNode::onChange(String newValue, String incommingKey) { - if (_params.key == incommingKey) { - _minutesPassed = 0; - prevMillis = millis(); - - newValue = String(newValue.toFloat() * _params.c); - newValue = String(newValue.toFloat() + _params.k); - - eventGen2(_params.key, newValue); - jsonWriteStr(configLiveJson, _params.key, newValue); - publishStatus(_params.key, newValue); - - _updateTime = timeNow->getDateTimeDotFormated(); - - this->publish(); - //SerialPrint("I", "Sensor", "'" + _params.key + "' data: " + newValue); - } -} - -void SensorNode::publish() { - if (_minutesPassed < _params.tm1.toInt()) { - publishAnyJsonKey(_params.key, "info", String(_minutesPassed) + " min"); - publishAnyJsonKey(_params.key, "color", ""); - } else if (_minutesPassed >= _params.tm1.toInt() && _minutesPassed < _params.tm2.toInt()) { - publishAnyJsonKey(_params.key, "info", String(_minutesPassed) + " min"); - publishAnyJsonKey(_params.key, "color", "orange"); - } else if (_minutesPassed >= _params.tm2.toInt()) { - if (_updateTime == "") { - publishAnyJsonKey(_params.key, "info", "offline"); - } else { - publishAnyJsonKey(_params.key, "info", _updateTime); - } - publishAnyJsonKey(_params.key, "color", "red"); - } -} - -MySensorNodeVector* mySensorNode = nullptr; - -void nodeSensor() { - myLineParsing.update(); - String tm1 = myLineParsing.gtm1(); - String tm2 = myLineParsing.gtm2(); - String key = myLineParsing.gkey(); - String c = myLineParsing.gc(); - String k = myLineParsing.gk(); - myLineParsing.clear(); - - paramsSensorNode params; - - params.tm1 = tm1; - params.tm2 = tm2; - params.key = key; - params.c = c.toFloat(); - params.k = k.toFloat(); - - static bool firstTime = true; - if (firstTime) mySensorNode = new MySensorNodeVector(); - firstTime = false; - mySensorNode->push_back(SensorNode(params)); -} - -void publishTimes() { - if (mySensorNode != nullptr) { - for (unsigned int i = 0; i < mySensorNode->size(); i++) { - mySensorNode->at(i).publish(); - } - } -} -#endif \ No newline at end of file diff --git a/src/items/vSensorPzem.cpp b/src/items/vSensorPzem.cpp deleted file mode 100644 index 3583e444..00000000 --- a/src/items/vSensorPzem.cpp +++ /dev/null @@ -1,130 +0,0 @@ -#include "Consts.h" -#ifdef EnableSensorPzem -#include "items/vSensorPzem.h" - -#include "BufferExecute.h" -#include "Class/LineParsing.h" -#include "Global.h" -#include "SoftUART.h" - -SensorPzem::SensorPzem(const paramsPzem& paramsV, const paramsPzem& paramsA, const paramsPzem& paramsWatt, const paramsPzem& paramsWattHrs, const paramsPzem& paramsHz) { - _paramsV = paramsPzem(paramsV); - _paramsA = paramsPzem(paramsA); - _paramsWatt = paramsPzem(paramsWatt); - _paramsWattHrs = paramsPzem(paramsWattHrs); - _paramsHz = paramsPzem(paramsHz); - - pzem = new PZEMSensor(myUART, hexStringToUint8(_paramsHz.addr)); -} - -SensorPzem::~SensorPzem() {} - -void SensorPzem::loop() { - difference = millis() - prevMillis; - if (difference >= _paramsHz.interval) { - prevMillis = millis(); - read(); - } -} - -void SensorPzem::read() { - if (myUART) { - float voltage = (pzem->values()->voltage * _paramsV.c) + _paramsV.k; - float current = (pzem->values()->current * _paramsA.c) + _paramsA.k; - float power = (pzem->values()->power * _paramsWatt.c) + _paramsWatt.k; - float energy = (pzem->values()->energy * _paramsWattHrs.c) + _paramsWattHrs.k; - float freq = (pzem->values()->freq * _paramsHz.c) + _paramsHz.k; - - eventGen2(_paramsV.key, String(voltage)); - jsonWriteStr(configLiveJson, _paramsV.key, String(voltage)); - publishStatus(_paramsV.key, String(voltage)); - SerialPrint("I", "Sensor", "'" + _paramsV.key + "' data: " + String(voltage)); - - eventGen2(_paramsA.key, String(current)); - jsonWriteStr(configLiveJson, _paramsA.key, String(current)); - publishStatus(_paramsA.key, String(current)); - SerialPrint("I", "Sensor", "'" + _paramsA.key + "' data: " + String(current)); - - eventGen2(_paramsWatt.key, String(power)); - jsonWriteStr(configLiveJson, _paramsWatt.key, String(power)); - publishStatus(_paramsWatt.key, String(power)); - SerialPrint("I", "Sensor", "'" + _paramsWatt.key + "' data: " + String(power)); - - eventGen2(_paramsWattHrs.key, String(energy)); - jsonWriteStr(configLiveJson, _paramsWattHrs.key, String(energy)); - publishStatus(_paramsWattHrs.key, String(energy)); - SerialPrint("I", "Sensor", "'" + _paramsWattHrs.key + "' data: " + String(energy)); - - eventGen2(_paramsHz.key, String(freq)); - jsonWriteStr(configLiveJson, _paramsHz.key, String(freq)); - publishStatus(_paramsHz.key, String(freq)); - SerialPrint("I", "Sensor", "'" + _paramsHz.key + "' data: " + String(freq)); - } else { - SerialPrint("E", "Sensor PZEM", "Error, UART switched off"); - } -} - -MySensorPzemVector* mySensorPzem = nullptr; - -void pzemSensor() { - if (myUART) { - myLineParsing.update(); - String key = myLineParsing.gkey(); - String addr = myLineParsing.gaddr(); - String interval = myLineParsing.gint(); - String c = myLineParsing.gc(); - String k = myLineParsing.gk(); - myLineParsing.clear(); - - static int enterCnt = -1; - enterCnt++; - - static paramsPzem paramsV; - static paramsPzem paramsA; - static paramsPzem paramsWatt; - static paramsPzem paramsWattHrs; - static paramsPzem paramsHz; - - if (enterCnt == 0) { - paramsV.key = key; - paramsV.c = c.toFloat(); - paramsV.k = k.toFloat(); - } - - if (enterCnt == 1) { - paramsA.key = key; - paramsA.c = c.toFloat(); - paramsA.k = k.toFloat(); - } - - if (enterCnt == 2) { - paramsWatt.key = key; - paramsWatt.c = c.toFloat(); - paramsWatt.k = k.toFloat(); - } - - if (enterCnt == 3) { - paramsWattHrs.key = key; - paramsWattHrs.c = c.toFloat(); - paramsWattHrs.k = k.toFloat(); - } - - if (enterCnt == 4) { - paramsHz.key = key; - paramsHz.c = c.toFloat(); - paramsHz.k = k.toFloat(); - paramsHz.addr = addr; - paramsHz.interval = interval.toInt() * 1000; - - static bool firstTime = true; - if (firstTime) mySensorPzem = new MySensorPzemVector(); - firstTime = false; - mySensorPzem->push_back(SensorPzem(paramsV, paramsA, paramsWatt, paramsWattHrs, paramsHz)); - - enterCnt = -1; - } - } else { - SerialPrint("E", "Sensor PZEM", "Error, UART switched off"); - } -} -#endif \ No newline at end of file diff --git a/src/items/vSensorUltrasonic.cpp b/src/items/vSensorUltrasonic.cpp deleted file mode 100644 index 6449d4d8..00000000 --- a/src/items/vSensorUltrasonic.cpp +++ /dev/null @@ -1,92 +0,0 @@ -#include "Consts.h" -#ifdef EnableSensorUltrasonic -#include "items/vSensorUltrasonic.h" - -#include - -#include "BufferExecute.h" -#include "Class/LineParsing.h" -#include "Global.h" - -GMedian<5, int> testFilter; - -SensorUltrasonic::SensorUltrasonic(String key, unsigned long interval, unsigned int trig, unsigned int echo, int map1, int map2, int map3, int map4, float c) { - _interval = interval * 1000; - _key = key; - _trig = trig; - _echo = echo; - - _map1 = map1; - _map2 = map2; - _map3 = map3; - _map4 = map4; - - _c = c; - - pinMode(_trig, OUTPUT); - pinMode(_echo, INPUT); -} - -SensorUltrasonic::~SensorUltrasonic() {} - -void SensorUltrasonic::loop() { - currentMillis = millis(); - difference = currentMillis - prevMillis; - if (difference >= _interval) { - prevMillis = millis(); - readUltrasonic(); - } -} - -void SensorUltrasonic::readUltrasonic() { - static unsigned int counter; - counter++; - - int value; - - digitalWrite(_trig, LOW); - delayMicroseconds(2); - digitalWrite(_trig, HIGH); - delayMicroseconds(10); - digitalWrite(_trig, LOW); - long duration_ = pulseIn(_echo, HIGH, 30000); // 3000 µs = 50cm // 30000 µs = 5 m - value = duration_ / 29 / 2; - - value = testFilter.filtered(value); - - value = map(value, _map1, _map2, _map3, _map4); - float valueFloat = value * _c; - - if (counter > 10) { - eventGen2(_key, String(valueFloat)); - jsonWriteStr(configLiveJson, _key, String(valueFloat)); - publishStatus(_key, String(valueFloat)); - SerialPrint("I", "Sensor", "'" + _key + "' data: " + String(valueFloat)); - } -} - -MySensorUltrasonicVector* mySensorUltrasonic = nullptr; - -void ultrasonic() { - myLineParsing.update(); - String interval = myLineParsing.gint(); - String pin = myLineParsing.gpin(); - String key = myLineParsing.gkey(); - String map = myLineParsing.gmap(); - String c = myLineParsing.gc(); - myLineParsing.clear(); - - unsigned int trig = selectFromMarkerToMarker(pin, ",", 0).toInt(); - unsigned int echo = selectFromMarkerToMarker(pin, ",", 1).toInt(); - - int map1 = selectFromMarkerToMarker(map, ",", 0).toInt(); - int map2 = selectFromMarkerToMarker(map, ",", 1).toInt(); - int map3 = selectFromMarkerToMarker(map, ",", 2).toInt(); - int map4 = selectFromMarkerToMarker(map, ",", 3).toInt(); - - static bool firstTime = true; - if (firstTime) mySensorUltrasonic = new MySensorUltrasonicVector(); - firstTime = false; - mySensorUltrasonic->push_back(SensorUltrasonic(key, interval.toInt(), trig, echo, map1, map2, map3, map4, c.toFloat())); -} -#endif diff --git a/src/items/vSensorUptime.cpp b/src/items/vSensorUptime.cpp deleted file mode 100644 index 6d3babca..00000000 --- a/src/items/vSensorUptime.cpp +++ /dev/null @@ -1,52 +0,0 @@ -#include "Consts.h" -#ifdef EnableSensorUptime -#include "items/vSensorUptime.h" - -#include - -#include "BufferExecute.h" -#include "Class/LineParsing.h" -#include "Global.h" - -SensorUptime::SensorUptime(const paramsUptime& paramsUpt) { - _paramsUpt = paramsUptime(paramsUpt); -} - -SensorUptime::~SensorUptime() {} - -void SensorUptime::loop() { - difference = millis() - prevMillis; - if (difference >= _paramsUpt.interval) { - prevMillis = millis(); - read(); - } -} - -void SensorUptime::read() { - String upt = timeNow->getUptime(); - - eventGen2(_paramsUpt.key, upt); - jsonWriteStr(configLiveJson, _paramsUpt.key, upt); - publishStatus(_paramsUpt.key, upt); - SerialPrint("I", "Sensor", "'" + _paramsUpt.key + "' data: " + upt); -} - -MySensorUptimeVector* mySensorUptime = nullptr; - -void uptimeSensor() { - myLineParsing.update(); - String key = myLineParsing.gkey(); - String interval = myLineParsing.gint(); - myLineParsing.clear(); - - static paramsUptime paramsUpt; - - paramsUpt.key = key; - paramsUpt.interval = interval.toInt() * 1000; - - static bool firstTime = true; - if (firstTime) mySensorUptime = new MySensorUptimeVector(); - firstTime = false; - mySensorUptime->push_back(SensorUptime(paramsUpt)); -} -#endif diff --git a/src/main.cpp b/src/main.cpp deleted file mode 100644 index b3e38a21..00000000 --- a/src/main.cpp +++ /dev/null @@ -1,244 +0,0 @@ - -#include - -#include "BufferExecute.h" -#include "Bus.h" -#include "Class/CallBackTest.h" -#include "Class/NotAsync.h" -#include "Class/ScenarioClass3.h" -#include "Cmd.h" -#include "FileSystem.h" -#include "Global.h" -#include "Init.h" -#include "ItemsList.h" -#include "MySensorsDataParse.h" -#include "RemoteOrdersUdp.h" -#include "SoftUART.h" -#include "Telegram.h" -#include "Tests.h" -#include "Utils/StatUtils.h" -#include "Utils/Timings.h" -#include "Utils/WebUtils.h" -#include "WebServer.h" -#include "WebSocket.h" -#include "items/ButtonInClass.h" -#include "items/vCountDown.h" -#include "items/vImpulsOut.h" -#include "items/vLogging.h" -#include "items/vSensorAnalog.h" -#include "items/vSensorBme280.h" -#include "items/vSensorBmp280.h" -#include "items/vSensorCcs811.h" -#include "items/vSensorDallas.h" -#include "items/vSensorDht.h" -#include "items/vSensorNode.h" -#include "items/vSensorPzem.h" -#include "items/vSensorUltrasonic.h" -#include "items/vSensorUptime.h" -//========================================= -#include "SetupESP.h" -#include "WebServer.h" - -void not_async_actions(); - -Timings metric; -boolean initialized = false; - -void setup() { - Serial.begin(115200); - Serial.flush(); - Serial.println(); - Serial.println(F("--------------started----------------")); - - myNotAsyncActions = new NotAsync(do_LAST); - myScenario = new Scenario(); - - wsInit(); - - //=========================================initialisation============================================================== - setChipId(); - fileSystemInit(); - loadConfig(); -#ifdef EnableUart - uartInit(); -#endif - clockInit(); - timeInit(); - itemsListInit(); - espInit(); - routerConnect(); -#ifdef EnableTelegram - telegramInit(); -#endif - uptime_init(); - upgradeInit(); - HttpServerinit(); - HttpServerinitWS(); - web_init(); - initSt(); - busInit(); - wifiSignalInit(); -#ifdef UDP_ENABLED - asyncUdpInit(); -#endif -#ifdef SSDP_ENABLED - SsdpInit(); -#endif - - getFSInfo(); - - testsPerform(); - - just_load = false; - initialized = true; - - // const int capacity = JSON_OBJECT_SIZE(35); - // SerialPrint("I", F("Test"), String(capacity)); - - ts.add( - MYTEST, 5000, [&](void*) { - // ws.textAll("test msg from esp"); - }, - nullptr, true); - - // setupESP(); - - SerialPrint("I", F("System"), F("✔ Initialization completed")); -} - -void loop() { - if (!initialized) { - return; - } - - testLoop(); - - // if (wsSetupFlag) { - // wsSetupFlag = false; - // wsSendSetup(); - //} - - // loopWsExecute(); - -#ifdef OTA_UPDATES_ENABLED - ArduinoOTA.handle(); -#endif -#ifdef WS_enable - ws.cleanupClients(); -#endif - timeNow->loop(); - mqttLoop(); - - myScenario->loop2(); - loopCmdExecute(); - - myNotAsyncActions->loop(); - ts.update(); - -#ifdef EnableTelegram - handleTelegram(); -#endif - -#ifdef EnableUart - uartHandle(); -#endif -#ifdef MYSENSORS - loopMySensorsExecute(); -#endif - -#ifdef EnableCountDown - if (myCountDown != nullptr) { - for (unsigned int i = 0; i < myCountDown->size(); i++) { - myCountDown->at(i).loop(); - } - } -#endif -#ifdef EnableImpulsOut - if (myImpulsOut != nullptr) { - for (unsigned int i = 0; i < myImpulsOut->size(); i++) { - myImpulsOut->at(i).loop(); - } - } -#endif -#ifdef EnableLogging - if (myLogging != nullptr) { - for (unsigned int i = 0; i < myLogging->size(); i++) { - myLogging->at(i).loop(); - } - } -#endif -#ifdef EnableSensorDallas - if (mySensorDallas2 != nullptr) { - for (unsigned int i = 0; i < mySensorDallas2->size(); i++) { - mySensorDallas2->at(i).loop(); - } - } -#endif -#ifdef EnableSensorUltrasonic - if (mySensorUltrasonic != nullptr) { - for (unsigned int i = 0; i < mySensorUltrasonic->size(); i++) { - mySensorUltrasonic->at(i).loop(); - } - } -#endif - -#ifdef EnableSensorAnalog - if (mySensorAnalog != nullptr) { - for (unsigned int i = 0; i < mySensorAnalog->size(); i++) { - mySensorAnalog->at(i).loop(); - } - } -#endif -#ifdef EnableSensorDht - if (mySensorDht != nullptr) { - for (unsigned int i = 0; i < mySensorDht->size(); i++) { - mySensorDht->at(i).loop(); - } - } -#endif -#ifdef EnableSensorBme280 - if (mySensorBme280 != nullptr) { - for (unsigned int i = 0; i < mySensorBme280->size(); i++) { - mySensorBme280->at(i).loop(); - } - } -#endif -#ifdef EnableSensorBmp280 - if (mySensorBmp280 != nullptr) { - for (unsigned int i = 0; i < mySensorBmp280->size(); i++) { - mySensorBmp280->at(i).loop(); - } - } -#endif -#ifdef EnableSensorCcs811 - if (mySensorCcs811 != nullptr) { - for (unsigned int i = 0; i < mySensorCcs811->size(); i++) { - mySensorCcs811->at(i).loop(); - } - } -#endif -#ifdef EnableSensorPzem - if (mySensorPzem != nullptr) { - for (unsigned int i = 0; i < mySensorPzem->size(); i++) { - mySensorPzem->at(i).loop(); - } - } -#endif -#ifdef EnableSensorUptime - if (mySensorUptime != nullptr) { - for (unsigned int i = 0; i < mySensorUptime->size(); i++) { - mySensorUptime->at(i).loop(); - } - } -#endif -#ifdef EnableSensorNode - if (mySensorNode != nullptr) { - for (unsigned int i = 0; i < mySensorNode->size(); i++) { - mySensorNode->at(i).loop(); - } - } -#endif -#ifdef EnableButtonIn - myButtonIn.loop(); -#endif -} \ No newline at end of file diff --git a/test/README b/test/README deleted file mode 100644 index b94d0890..00000000 --- a/test/README +++ /dev/null @@ -1,11 +0,0 @@ - -This directory is intended for PlatformIO Unit Testing and project tests. - -Unit Testing is a software testing method by which individual units of -source code, sets of one or more MCU program modules together with associated -control data, usage procedures, and operating procedures, are tested to -determine whether they are fit for use. Unit testing finds problems early -in the development cycle. - -More information about PlatformIO Unit Testing: -- https://docs.platformio.org/page/plus/unit-testing.html diff --git a/tools/littlefsbuilder.py b/tools/littlefsbuilder.py deleted file mode 100644 index df1fb52d..00000000 --- a/tools/littlefsbuilder.py +++ /dev/null @@ -1,2 +0,0 @@ -Import("env") -env.Replace( MKSPIFFSTOOL=env.get("PROJECT_DIR") + '/tools/mklittlefs.exe' ) diff --git a/tools/mklittlefs.exe b/tools/mklittlefs.exe deleted file mode 100644 index 7de93ff2..00000000 Binary files a/tools/mklittlefs.exe and /dev/null differ