From e38f3f4865b0c1a7de240f3c11c2f169a765f9e2 Mon Sep 17 00:00:00 2001 From: Tifaifai Maupiti Date: Thu, 4 Apr 2024 14:18:02 +0200 Subject: [PATCH] =?UTF-8?q?D=C3=A9but=20clean=20+=20spdlog?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- examples/Raspberry_cJSON/.gitignore | 3 + examples/Raspberry_cJSON/README.md | 32 ++++- examples/Raspberry_cJSON/makefile | 17 ++- examples/Raspberry_cJSON/raspjson_stand.cpp | 123 ++++++-------------- examples/Raspberry_cJSON/raspjson_stand.h | 36 +----- src/LibTeleinfo.cpp | 8 +- 6 files changed, 86 insertions(+), 133 deletions(-) create mode 100644 examples/Raspberry_cJSON/.gitignore diff --git a/examples/Raspberry_cJSON/.gitignore b/examples/Raspberry_cJSON/.gitignore new file mode 100644 index 0000000..bb1ec4c --- /dev/null +++ b/examples/Raspberry_cJSON/.gitignore @@ -0,0 +1,3 @@ +*.o +*.bak +raspjson_standard diff --git a/examples/Raspberry_cJSON/README.md b/examples/Raspberry_cJSON/README.md index 5f7ee65..c723d34 100644 --- a/examples/Raspberry_cJSON/README.md +++ b/examples/Raspberry_cJSON/README.md @@ -12,6 +12,26 @@ Se connecter en ssh sur votre Pi, il doit y avoir les environnements de dévelop `apt-get install build-essential git-core libcjson-dev libcurl4-openssl-dev` +Nous utilisons la version récente de développement de la librairie spdlog (Ne pas utiliser le packge): +Version Static (.a) +``` +$ cd /home/pi/GIT (Adapter en fonction de votre système / voir aussi dans Makefile ensuite) +$ git clone https://github.com/gabime/spdlog.git +$ cd spdlog && mkdir build && cd build +$ cmake .. && make -j +``` + +Version Dynamic (.so) +``` +$ cd /home/pi/GIT (Adapter en fonction de votre système / voir aussi dans Makefile ensuite) +$ git clone https://github.com/gabime/spdlog.git +$ cd spdlog && mkdir build && cd build +$ cmake .. -DSPDLOG_BUILD_BENCH=OFF -DSPDLOG_BUILD_EXAMPLES=OFF -DSPDLOG_BUILD_TESTS=ON -DCMAKE_BUILD_TYPE=Release -DCMAKE_INSTALL_PREFIX=/usr/local -DCMAKE_INSTALL_LIBDIR=lib -DSPDLOG_BUILD_SHARED=ON +$ cd ../include & sudo cp -Rf spglog /usr/local/include/spdlog +$ sudo cp -a build/libspdlog.* /usr/local/lib/ +$ sudo ldconfig +``` + Ensuite : ``` git clone https://github.com/Tifaifai/LibTeleinfo @@ -20,6 +40,9 @@ make ./raspjson ``` +Exemple avec un alias de lancement : +alias linky='/usr/local/bin/raspjson_standard -m s -y /dev/ttyACM0 -e -k aa38f67...... -r http://....fr/input/post -n linky -d' + ### Installation MQTT : Publication MQTT Lire le README_MQTT.md pour installer MQTT (mosquitto 2.0.15 avec support de Websockets 4.3.2) @@ -31,7 +54,7 @@ make raspjson_mqtt ./raspjson_mqtt ``` -Et voilà ce que ça donne avec un dongle MicroTeleinfo +Et voilà ce que ça donne avec un dongle MicroTeleinfo en mode Historique sur le Linky ``` root@pi01(rw):~# git clone https://github.com/Tifaifai/LibTeleinfo @@ -42,9 +65,9 @@ remote: Total 23 (delta 5), reused 21 (delta 3), pack-reused 0 Unpacking objects: 100% (23/23), done. root@pi01(rw):~# cd LibTeleinfo/examples/Raspberry_cJSON/ root@pi01(rw):~/LibTeleinfo/examples/Raspberry_cJSON# make -cc -DRASPBERRY_PI -c raspjson.cpp -cc -DRASPBERRY_PI -c ../../LibTeleinfo.cpp -cc -DRASPBERRY_PI -o raspjson raspjson.o LibTeleinfo.o + +.... + root@pi01(rw):~/LibTeleinfo/examples/Raspberry_JSON# ./raspjson -d /dev/ttyUSB0 {"_UPTIME":34957, "ADCO":2147483647, "OPTARIF":"HC..", "ISOUSC":15, "HCHC":247418, "HCHP":0, "PTEC":"HC..", "IINST":1, "IMAX":1, "PAPP":150, "HHPHC":"A", "MOTDETAT":0} {"PAPP":140} @@ -94,4 +117,3 @@ Vous pouvez aller voir les nouveautés et autres projets sur [blog][7] [8]: https://community.hallard.me/category/7 [9]: https://community.hallard.me [10]: https://hallard.me/libteleinfo - diff --git a/examples/Raspberry_cJSON/makefile b/examples/Raspberry_cJSON/makefile index 348fc43..6128074 100644 --- a/examples/Raspberry_cJSON/makefile +++ b/examples/Raspberry_cJSON/makefile @@ -11,21 +11,30 @@ CXXFLAGS += -lcjson # cURL CXXFLAGS += -lcurl +# spdlog +#INCLUDES += -I/home/pi/GIT/spdlog/include +#CXXFLAGS += -pthread -lspdlog -DSPDLOG_COMPILED_LIB +#LDFLAGS += -L/home/pi/GIT/spdlog/build -lspdlog +INCLUDES += -I/usr/local/include/spdlog/ +CXXFLAGS += -pthread -lspdlog -DSPDLOG_COMPILED_LIB +LDFLAGS += -L/usr/local/lib/ -lspdlog + + # raspjson all: raspjson_standard # ===== Compile LibTeleinfo.o: ../../src/LibTeleinfo.cpp - $(CC) $(CFLAGS) -c ../../src/LibTeleinfo.cpp + $(CC) $(CFLAGS) -c ../../src/LibTeleinfo.cpp raspjson.o: raspjson.cpp - $(CC) $(CFLAGS) -c raspjson.cpp $(CXXFLAGS) $(INCLUDES) + $(CC) $(CFLAGS) -c raspjson.cpp $(INCLUDES) $(CXXFLAGS) raspjson_stand.o: raspjson_stand.cpp - $(CC) $(CFLAGS) -c raspjson_stand.cpp $(CXXFLAGS) $(INCLUDES) + $(CC) $(CFLAGS) -c raspjson_stand.cpp $(INCLUDES) $(CXXFLAGS) raspjson_mqtt.o: raspjson_mqtt.cpp - $(CC) $(CFLAGS) -g -c raspjson_mqtt.cpp $(CXXFLAGS) $(INCLUDES) -lmosquitto + $(CC) $(CFLAGS) -g -c raspjson_mqtt.cpp $(INCLUDES) $(CXXFLAGS) -lmosquitto # ===== Link raspjson: raspjson.o LibTeleinfo.o diff --git a/examples/Raspberry_cJSON/raspjson_stand.cpp b/examples/Raspberry_cJSON/raspjson_stand.cpp index b4b0969..5851d32 100644 --- a/examples/Raspberry_cJSON/raspjson_stand.cpp +++ b/examples/Raspberry_cJSON/raspjson_stand.cpp @@ -39,6 +39,8 @@ #include "cJSON.h" #include +#include "spdlog/spdlog.h" +#include "spdlog/sinks/rotating_file_sink.h" // support for rotating file logging // ---------------- // Constants @@ -81,10 +83,8 @@ static struct // Configuration structure defaults values } opts; -void log_syslog( FILE * stream, const char *format, ...); void sendJSON(ValueList * me, bool all); - // ====================================================================== // Global vars // ====================================================================== @@ -100,35 +100,6 @@ char http_buffer[HTTP_BUFFER_SIZE]; // Where http returned data will be filled // Used to indicate if we need to send all date or just modified ones bool fulldata = true; -/* ====================================================================== -Function: getValueFromLabelIndex -Purpose : return label value from label index -Input : label index to search for -Output : value filled -Comments: - -====================================================================== */ -char * getValueFromLabelIndex(int labelIndex, char * value) -{ - fprintf(stdout, "I:%d, V%s\n", labelIndex, &value); - if (!value) { - return nullptr; - } - char labelName[17]; - *value = '\0'; - - // Get the label name - GetTextIndexed(labelName, sizeof(labelName), labelIndex, kLabel); - // Get value of label name - tinfo.valueGet(labelName, value) ; - - // Standard mode has values with space before/after - if (opts.mode ==TINFO_MODE_STANDARD) { - Trim(value); - } - - return *value ? value : nullptr; -} - /* ====================================================================== Function: ADPSCallback Purpose : called by library when we detected a ADPS on any phased @@ -316,19 +287,19 @@ int http_post( char * str_url ) // Set curl URL if ( curl_easy_setopt(g_pcurl, CURLOPT_URL, str_url) != CURLE_OK ) - log_syslog(stderr, "Error while setting curl url %s : %s", str_url, curl_easy_strerror(res)); + spdlog::error("Error while setting curl url {} : {}", str_url, curl_easy_strerror(res)); else { // Perform the request, res will get the return code if( (res = curl_easy_perform(g_pcurl)) != CURLE_OK) { - log_syslog(stderr, "Error on http request %s : %s", str_url, curl_easy_strerror(res)); + spdlog::error("Error on http request {} : {}", str_url, curl_easy_strerror(res)); } else { // return data received if (opts.verbose) - log_syslog(stdout, "http_post %s ==> '%s'\n", str_url, http_buffer); + spdlog::info("http_post {} ==> '{}'", str_url, http_buffer); // emoncms returned string "ok", all went fine if (strcmp(http_buffer, "ok") == 0 ) @@ -351,18 +322,21 @@ Comments: - bool isBlacklistedLabel(char * name, char * value) { bool bl = false; - if ( strstr(kLabelBlacklist, name) ) { + char rname[32] = ""; + sprintf(rname, "|%s|", name); + + if ( strstr(kLabelBlacklist, rname) ) { bl = true; if(opts.verbose) { fprintf(stdout, "TIC: %s is blacklisted\n", name); } } - if ( !strstr(kLabel, name) ) { + if ( !strstr(kLabel, rname) ) { bl = true; if(opts.verbose) { fprintf(stdout, "TIC: Label %s:%s no exist in datasheet\n", name, value); } - log_syslog(stderr, "TIC: Label [%s:%s] no exist\n",name, value); + spdlog::error("TIC: Label [{}:{}] no exist",name, value); } return bl; } @@ -408,8 +382,6 @@ void sendJSON(ValueList * me, bool all) if (!isBlacklistedLabel(me->name, me->value)) { if (opts.mode == TINFO_MODE_STANDARD) { - //getValueFromLabelIndex(LABEL_LTARF, me->value); - //getValueFromLabelIndex(LABEL_NGTF, me->value); tlf_treat_label_standard(me->name, me->value); } @@ -474,7 +446,7 @@ void sendJSON(ValueList * me, bool all) // Send data to emoncms if (!http_post(emoncms_url)) { - log_syslog(stderr, "emoncms post error\n"); + spdlog::error("emoncms post error [{}]", emoncms_url); } } else @@ -486,41 +458,6 @@ void sendJSON(ValueList * me, bool all) // ====================================================================== void tlf_close_serial(int); -/* ====================================================================== -Function: log_syslog -Purpose : write event to syslog -Input : stream to write if needed - string to write in printf format - printf other arguments -Output : - -Comments: -====================================================================== */ -void log_syslog( FILE * stream, const char *format, ...) -{ - static char tmpbuff[512]=""; - va_list args; - int len; - - // do a style printf style in ou buffer - va_start (args, format); - len = vsnprintf (tmpbuff, sizeof(tmpbuff), format, args); - tmpbuff[sizeof(tmpbuff) - 1] = '\0'; - va_end (args); - - // Write to logfile - openlog( PRG_NAME, LOG_PID|LOG_CONS, LOG_USER); - syslog(LOG_INFO, "%s", tmpbuff); - closelog(); - - // stream passed ? write also to it - if (stream && opts.verbose && !opts.daemon) - { - fprintf(stream, "%s", tmpbuff); - //fprintf(stream, "\n"); - fflush(stream); - } -} - /* ====================================================================== Function: clean_exit Purpose : exit program @@ -540,7 +477,7 @@ void clean_exit (int exit_code) { // Restore Old parameters. if ( (r = tcsetattr(g_fd_teleinfo, TCSAFLUSH, &g_oldtermios)) < 0 ) - log_syslog(stderr, "cannot restore old parameters %s: %s", opts.port, strerror(errno)); + spdlog::error("cannot restore old parameters {}: {}", opts.port, strerror(errno)); // then close tlf_close_serial(g_fd_teleinfo); @@ -645,13 +582,13 @@ void signal_handler (int signum) { // Indicate we want to quit g_exit_pgm = true; - log_syslog(stdout, "\nReceived SIGINT\n"); + spdlog::info("Received SIGINT"); } else if ( signum==SIGTERM ) { // Indicate we want to quit g_exit_pgm = true; - log_syslog(stdout, "\nReceived SIGTERM\n"); + spdlog::info("Received SIGTERM"); } } @@ -671,14 +608,14 @@ int tlf_init_serial(void) if ( (tty_fd = open(opts.port, O_RDWR | O_NOCTTY | O_NDELAY | O_NONBLOCK)) < 0 ) fatal( "tlf_init_serial %s: %s", opts.port, strerror(errno)); else - log_syslog( stdout, "'%s' opened.\n",opts.port); + spdlog::info("'{}' opened.",opts.port); // Set descriptor status flags fcntl (tty_fd, F_SETFL, O_RDWR ) ; // Get current parameters for saving if ( (r = tcgetattr(tty_fd, &g_oldtermios)) < 0 ) - log_syslog(stderr, "cannot get current parameters %s: %s", opts.port, strerror(errno)); + spdlog::error("cannot get current parameters {}: {}", opts.port, strerror(errno)); // copy current parameters and change for our own memcpy( &termios, &g_oldtermios, sizeof(termios)); @@ -689,11 +626,11 @@ int tlf_init_serial(void) if(opts.mode == TINFO_MODE_HISTORIQUE) { // Set serial speed to 1200 bps if (cfsetospeed(&termios, B1200) < 0 || cfsetispeed(&termios, B1200) < 0 ) - log_syslog(stderr, "cannot set serial speed to 1200 bps (mode historique): %s", strerror(errno)); + spdlog::error("cannot set serial speed to 1200 bps (mode historique): {}", strerror(errno)); } else { // Set serial speed to 9600 bps if (cfsetospeed(&termios, B9600) < 0 || cfsetispeed(&termios, B9600) < 0 ) - log_syslog(stderr, "cannot set serial speed to 9600 bps (mode standard): %s", strerror(errno)); + spdlog::error("cannot set serial speed to 9600 bps (mode standard): {}", strerror(errno)); } // Parity Even @@ -716,7 +653,7 @@ int tlf_init_serial(void) // now setup the whole parameters if ( tcsetattr (tty_fd, TCSANOW | TCSAFLUSH, &termios) <0) - log_syslog(stderr, "cannot set current parameters %s: %s", opts.port, strerror(errno)); + spdlog::error("cannot set current parameters {}: {}", opts.port, strerror(errno)); // Sleep 50ms // trust me don't forget this one, it will remove you some @@ -973,6 +910,15 @@ int main(int argc, char **argv) g_fd_teleinfo = 0; g_exit_pgm = false; + bool m_gen_log = true; + if(m_gen_log) { + spdlog::set_level(spdlog::level::debug); + auto file_logger = spdlog::rotating_logger_mt("file_logger", "/home/pi/linky.log", 1024 * 1024 * 5, 3); + spdlog::set_default_logger(file_logger); + spdlog::flush_on(spdlog::level::debug); + spdlog::info("{} - LINKY Téléinfo", __FUNCTION__); + } + // get configuration read_config(argc, argv); @@ -1010,7 +956,7 @@ int main(int argc, char **argv) else { if (opts.verbose) - log_syslog(stderr, "Curl Initialized\n"); + spdlog::info("Curl Initialized"); } } } @@ -1031,11 +977,11 @@ int main(int argc, char **argv) tinfo.attachUpdatedFrame(UpdatedFrame); tinfo.attachNewFrame(NewFrame); - log_syslog(stdout, "Inits succeded, entering Main loop\n"); + spdlog::info("Inits succeded, entering Main loop"); if (opts.daemon) { - log_syslog(stdout, "Starting as a daemon\n"); + spdlog::info("Starting as a daemon"); daemonize(); } @@ -1058,8 +1004,9 @@ int main(int argc, char **argv) usleep(10000); } - log_syslog(stderr, "Program terminated\n"); - + spdlog::info("Program terminated"); + spdlog::shutdown(); + clean_exit(EXIT_SUCCESS); // avoid compiler warning diff --git a/examples/Raspberry_cJSON/raspjson_stand.h b/examples/Raspberry_cJSON/raspjson_stand.h index 028d5a0..5c763ca 100644 --- a/examples/Raspberry_cJSON/raspjson_stand.h +++ b/examples/Raspberry_cJSON/raspjson_stand.h @@ -83,13 +83,15 @@ const char kLabel[] = "|SINSTI|SMAXIN|SMAXIN-1|CCASN|CCASN-1|CCAIN|CCAIN-1" "|TENSION|UMOY1|UMOY2|UMOY3" "|DPM1|FPM1|DPM2|FPM2|DPM3|FPM3" - "|IMAX|IMAX1|IMAX2|IMAX3|PMAX|SMAXSN" + "|IMAX|IMAX1|IMAX2|IMAX3|PMAX" "|DEMAIN|MSG1|MSG2|STGE|PRM|RELAIS|NJOURF|NJOURF+1|PJOURF+1|PPOINTE" + "|" ; // Blacklisted label from telemetry // Each label shoud be enclosed by pipe const char kLabelBlacklist[] = + "|DATE" "|PJOURF+1" "|MSG1" "|PPOINTE" @@ -141,34 +143,4 @@ char* TrimSpace(char *p) { return p; } -char* GetTextIndexed(char* destination, size_t destination_size, uint16_t index, const char* haystack) -{ - // Returns empty string if not found - // Returns text of found - char* write = destination; - const char* read = haystack; - - index++; - while (index--) { - size_t size = destination_size -1; - write = destination; - char ch = '.'; - while ((ch != '\0') && (ch != '|')) { - ch = pgm_read_byte(read++); - if (size && (ch != '|')) { - *write++ = ch; - size--; - } - } - if (0 == ch) { - if (index) { - write = destination; - } - break; - } - } - *write = '\0'; - return destination; -} - -#endif \ No newline at end of file +#endif diff --git a/src/LibTeleinfo.cpp b/src/LibTeleinfo.cpp index 8e1e9e3..161f224 100644 --- a/src/LibTeleinfo.cpp +++ b/src/LibTeleinfo.cpp @@ -698,8 +698,8 @@ unsigned char TInfo::calcChecksum(char *etiquette, char *valeur, char * horodate if (strlen(etiquette) && strlen(valeur)) { while (*etiquette) { c =*etiquette++; - // Add another validity check since checksum may not be sufficient - if ( (c>='A' && c<='Z') || (c>='0' && c<='9') || c=='-' || c=='+') { + // Add basic validity check + if (c>=0x20 && c<=0x7E) { sum += c ; } else { return 0; @@ -708,8 +708,8 @@ unsigned char TInfo::calcChecksum(char *etiquette, char *valeur, char * horodate while(*valeur) { c = *valeur++ ; - // Add another validity check since checksum may not be sufficient (space authorized in Standard mode) - if ( (c>='A' && c<='Z') || (c>='0' && c<='9') || c==' ' || c=='.' || c=='-' || c=='+' || c=='/') { + // AAdd basic validity check + if (c>=0x20 && c<=0x7E) { sum += c ; } else { return 0;