From 7c2631800a57c195fd1744f61f5bdd07d18c4c55 Mon Sep 17 00:00:00 2001 From: Mit4el Date: Tue, 20 Jun 2023 23:22:58 +0300 Subject: [PATCH] update GoogleSheet --- src/modules/exec/HttpGet/modinfo.json | 1 + .../virtual/GoogleSheet/GoogleSheet.cpp | 142 ++++++++++++++---- src/modules/virtual/GoogleSheet/goggleapp.gs | 52 +++++++ src/modules/virtual/GoogleSheet/modinfo.json | 23 ++- 4 files changed, 184 insertions(+), 34 deletions(-) create mode 100644 src/modules/virtual/GoogleSheet/goggleapp.gs diff --git a/src/modules/exec/HttpGet/modinfo.json b/src/modules/exec/HttpGet/modinfo.json index 56c4d57b..0c97357e 100644 --- a/src/modules/exec/HttpGet/modinfo.json +++ b/src/modules/exec/HttpGet/modinfo.json @@ -49,6 +49,7 @@ "defActive": false, "usedLibs": { "esp32_4mb": [], + "esp32s2_4mb": [], "esp8266_4mb": [], "esp8266_1mb": [], "esp8266_1mb_ota": [], diff --git a/src/modules/virtual/GoogleSheet/GoogleSheet.cpp b/src/modules/virtual/GoogleSheet/GoogleSheet.cpp index 39b9d74a..d192e10f 100644 --- a/src/modules/virtual/GoogleSheet/GoogleSheet.cpp +++ b/src/modules/virtual/GoogleSheet/GoogleSheet.cpp @@ -2,8 +2,7 @@ #include "Global.h" #include "classes/IoTItem.h" -String URL = "https://script.google.com/macros/s/"; - +String URL = F("https://script.google.com/macros/s/"); class GoogleSheet : public IoTItem { @@ -12,9 +11,11 @@ private: String logid; String scid = ""; String shname = ""; - bool init = false; + // bool init = false; int interval = 1; - // long interval; + // long interval; + String urlFinal; + public: GoogleSheet(String parameters) : IoTItem(parameters) { @@ -24,6 +25,7 @@ public: jsonRead(parameters, F("shname"), shname); jsonRead(parameters, F("int"), interval); interval = interval * 1000 * 60; // так как у нас в минутах + urlFinal = URL + scid + F("/exec?") + F("sheet=") + shname; } void doByInterval() @@ -31,34 +33,8 @@ public: if (WiFi.status() == WL_CONNECTED) { String value = getItemValue(logid); - String urlFinal = URL + scid + "/exec?"+"sheet=" + shname + "&id=" + logid + "&value=" + value; - if (!init){ init=true; urlFinal = urlFinal + "&init=1";} - - HTTPClient http; -#if defined ESP8266 - WiFiClientSecure client; - client.setInsecure(); - if (!http.begin(client, urlFinal)) - { -#elif defined ESP32 - WiFiClient client; - if (!http.begin(urlFinal)) - { -#endif - SerialPrint("I", F("GoogleSheet"), "connection failed "); - } - http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS); // HTTPC_STRICT_FOLLOW_REDIRECTS HTTPC_FORCE_FOLLOW_REDIRECTS - http.addHeader("Content-Type", "application/x-www-form-urlencoded"); - int httpCode = http.GET(); -// String payload = http.getString(); - SerialPrint("<-", F("GoogleSheet"), "URL: " + urlFinal); - SerialPrint("->", F("GoogleSheet"), "server: " + (String)httpCode); /*"URL: " + urlFinal + */ -/* if (httpCode > 0) - { - SerialPrint("->", F("GoogleSheet"), "msg from server: " + (String)payload.c_str()); - } -*/ - http.end(); + if (value != "") + send2Google(logid, value, true); } } @@ -75,6 +51,108 @@ public: } } } + + IoTValue execute(String command, std::vector ¶m) + { + if (WiFi.status() == WL_CONNECTED) + { + if (command == F("logGoogle")) + { // Логирование определенного элемента по его идентификатору в GoogleSheet + /* if (param.size() == 1) + { + String id = param[0].valS; + String value = getItemValue(id); + send2Google(id, value, true); + return {}; + } + */ + if (param.size() >= 1) + { + int sizeOfParam = param.size(); + for (unsigned int i = 0; i < sizeOfParam; i++) + { + IoTItem *itm = findIoTItemOnValue(param[i].valS); + if (itm != nullptr) + { + if (i == sizeOfParam - 1) + send2Google(itm->getID(), param[i].valS, true); + else + send2Google(itm->getID(), param[i].valS, false); + } + } + } + } + else if (command == F("logGoogleAny")) + { // Запись произвольных данных в GoogleSheet + if (param.size() == 2) + { + send2Google(param[0].valS, param[1].valS, true); + return {}; + } + } + } + return {}; + } + + void send2Google(String logid, String value, bool send) + { + urlFinal = urlFinal + ("&id=") + logid + ("&value=") + value; + + if (!send) + return; // Не отправляем просто накапливаем данные + + /* if (!init) + { + init = true; + urlFinal = urlFinal + "&init=1"; + } + */ + HTTPClient http; +#if defined ESP8266 + WiFiClientSecure client; + client.setInsecure(); + if (!http.begin(client, urlFinal)) + { +#elif defined ESP32 + WiFiClient client; + if (!http.begin(urlFinal)) + { +#endif + SerialPrint("I", F("GoogleSheet"), F("connection failed")); + } + http.setFollowRedirects(HTTPC_STRICT_FOLLOW_REDIRECTS); // HTTPC_STRICT_FOLLOW_REDIRECTS HTTPC_FORCE_FOLLOW_REDIRECTS + http.addHeader(F("Content-Type"), F("application/x-www-form-urlencoded")); + int httpCode = http.GET(); + + // String payload = http.getString(); + SerialPrint("<-", F("GoogleSheet"), "URL: " + urlFinal); + SerialPrint("->", F("GoogleSheet"), "server: " + (String)httpCode); /*"URL: " + urlFinal + */ + + /* if (httpCode > 0) + { + SerialPrint("->", F("GoogleSheet"), "msg from server: " + (String)payload.c_str()); + } + */ + http.end(); + // Обнуляем данные в запросе, так как все отправили + urlFinal = URL + scid + F("/exec?") + F("sheet=") + shname; + }; + + // поиск элемента модуля в существующей конфигурации по его значению + // По хорошему ЭТО наверное надо в ЯДРО пернести + IoTItem *findIoTItemOnValue(const String &value) + { + if (value == "") + return nullptr; + for (std::list::iterator it = IoTItems.begin(); it != IoTItems.end(); ++it) + { + if ((*it)->getValue() == value) + return *it; + } + + return nullptr; + }; + ~GoogleSheet(){}; }; diff --git a/src/modules/virtual/GoogleSheet/goggleapp.gs b/src/modules/virtual/GoogleSheet/goggleapp.gs new file mode 100644 index 00000000..2fc24a21 --- /dev/null +++ b/src/modules/virtual/GoogleSheet/goggleapp.gs @@ -0,0 +1,52 @@ + +var SS = SpreadsheetApp.openById('GOOGLE_SHEET_ID'); + +function doGet(e){ + + var value = e.parameters.value; + var id = e.parameters.id; + var sheet = e.parameter.sheet; + var init = e.parameter.init; + + if (sheet == undefined) { + sheet = SS.getActiveSheet(); + } else{ + sheet = SS.getSheetByName(sheet); + } + + if (sheet == null) { + return ContentService.createTextOutput("Error sheet name"); + } + +// if (init !== undefined){ + sheet.getRange('A1').setValue("ID"); + sheet.getRange('B1').setValue("VALUE"); + sheet.getRange('C1').setValue("DATE"); +// } + + var nextFreeRow = sheet.getLastRow() + 1; + + if (id == undefined) id = "nan"; + if (value !== undefined){ + try { + var now = Utilities.formatDate(new Date(), "GMT+03:00", "dd.MM.yyyy HH:mm:ss"); + for (let i = 0; i < id.length; i++) { + sheet.getRange("A"+nextFreeRow).setValue(id[i]); + value[i] = value[i].replace(/\./, ","); + sheet.getRange("B"+nextFreeRow).setValue(value[i]); + sheet.getRange("C"+nextFreeRow).setValue(now); + nextFreeRow++; + } + return ContentService.createTextOutput("Successfully wrote: " + + e.parameter.value + "\ninto spreadsheet."); + //Logger.log(str); + } + catch(f){ + return ContentService.createTextOutput("Error in parsing appendRow"); + } + } else { + return ContentService.createTextOutput("Error wrote: value = " + + e.parameter.value + " , id = "+e.parameter.id); + } +} + diff --git a/src/modules/virtual/GoogleSheet/modinfo.json b/src/modules/virtual/GoogleSheet/modinfo.json index efcb94dc..a81e3a6c 100644 --- a/src/modules/virtual/GoogleSheet/modinfo.json +++ b/src/modules/virtual/GoogleSheet/modinfo.json @@ -11,7 +11,7 @@ "page": "", "descr": "", "int": 5, - "logid": "id", + "logid": "", "scid": "Script_ID", "shname": "Logger" } @@ -35,7 +35,26 @@ "logid": "ID величины которую будем логировать", "scid": "Идентификатор развертывания Google Apps (script id)", "shname": "Наименование листа в таблице (sheet name)" - } + }, + "retInfo": "", + "funcInfo": [ + { + "name": "logGoogle", + "descr": "Использовать не чаще раз в минуту! Логирование элементов по их идентификатору в GoogleSheet, указывать через запятую, от одного до N (проверено на 16шт)", + "params": [ + "id Идентификатор 1-го элеменета", + "id Идентификатор N-го элеменета" + ] + }, + { + "name": "logGoogleAny", + "descr": "Использовать не чаще раз в минуту! Запись произвольных данных в GoogleSheet", + "params": [ + "Наименование данных", + "Значение для записи" + ] + } + ] }, "defActive": false, "usedLibs": {