diff --git a/main.cpp b/main.cpp index 7f64326..1cd636c 100644 --- a/main.cpp +++ b/main.cpp @@ -570,28 +570,11 @@ int main(int argc, char *argv[]) set_boot_loader(b, bootloader); } else { - FILE *fh = fopen(deserialize.c_str(), "r"); - if (!fh) + auto rc = deserialize_file(deserialize); + if (rc.has_value() == false) error_exit(true, "Failed to open %s", deserialize.c_str()); - std::string j_in; - char buffer[4096]; - for(;;) { - char *rc = fgets(buffer, sizeof buffer, fh); - if (!rc) - break; - - j_in += buffer; - } - - fclose(fh); - - JsonDocument j; - DeserializationError error = deserializeJson(j, j_in); - if (error) - error_exit(true, "State file %s is corrupt: %s", deserialize.c_str(), error.c_str()); - - b = bus::deserialize(j, cnsl, &event); + b = bus::deserialize(rc.value(), cnsl, &event); myusleep(251000); } diff --git a/utils.cpp b/utils.cpp index 9d21de7..11f7b0e 100644 --- a/utils.cpp +++ b/utils.cpp @@ -17,7 +17,9 @@ #include #endif +#include #include +#include #include #include #include @@ -269,3 +271,33 @@ std::string get_endpoint_name(const int fd) return std::string(inet_ntoa(addr.sin_addr)) + "." + format("%d", ntohs(addr.sin_port)); } + +std::optional deserialize_file(const std::string & filename) +{ + FILE *fh = fopen(filename.c_str(), "r"); + if (!fh) { + DOLOG(warning, false, "Failed to open %s", filename.c_str()); + return { }; + } + + std::string j_in; + char buffer[4096]; + for(;;) { + char *rc = fgets(buffer, sizeof buffer, fh); + if (!rc) + break; + + j_in += buffer; + } + + fclose(fh); + + JsonDocument j; + DeserializationError error = deserializeJson(j, j_in); + if (error) { + DOLOG(warning, false, "Failed to de-serialize %s", filename.c_str()); + return { }; + } + + return j; +} diff --git a/utils.h b/utils.h index 8fd97a0..95f9e5c 100644 --- a/utils.h +++ b/utils.h @@ -1,6 +1,8 @@ // (C) 2018-2024 by Folkert van Heusden // Released under MIT license +#include +#include #include #include #include @@ -28,3 +30,5 @@ void update_word(uint16_t *const w, const bool msb, const uint8_t v); void set_nodelay(const int fd); std::string get_endpoint_name(const int fd); + +std::optional deserialize_file(const std::string & filename);