diff --git a/Chapter07/error_handling/app/src/main_expected.cpp b/Chapter07/error_handling/app/src/main_expected.cpp index 3d8dd34..f1fa6a9 100644 --- a/Chapter07/error_handling/app/src/main_expected.cpp +++ b/Chapter07/error_handling/app/src/main_expected.cpp @@ -1,7 +1,7 @@ #include #include #include - +#include #include @@ -10,6 +10,29 @@ #include +struct ble_light_bulb { + enum class error { + disconnected, + timeout + }; + struct config { + int r; + int g; + int b; + }; + + bool ret_val; + std::expected get_config() { + ret_val = !ret_val; + if(ret_val) { + return config {10, 20, 30}; + } + else { + return std::unexpected(error::timeout); + } + } +}; + int main() { hal::init(); @@ -21,6 +44,27 @@ int main() printf("std::expected example\r\n"); + ble_light_bulb bulb; + + const auto get_config_from_main = [&bulb]() { + auto result = bulb.get_config(); + if(result.has_value()) { + auto conf = result.value(); + printf("Config r %d, g %d, b %d\r\n", conf.r, conf.g, conf.b); + } else { + auto err = result.error(); + if(err == ble_light_bulb::error::disconnected) { + printf("The bulb is disconnected! \r\n"); + } + else if(err == ble_light_bulb::error::timeout) { + printf("Timeout!\r\n"); + } + } + }; + + get_config_from_main(); + get_config_from_main(); + while(true) { } diff --git a/Chapter07/error_handling/app/src/main_optional.cpp b/Chapter07/error_handling/app/src/main_optional.cpp index 7d228ba..6d4fdf1 100644 --- a/Chapter07/error_handling/app/src/main_optional.cpp +++ b/Chapter07/error_handling/app/src/main_optional.cpp @@ -38,7 +38,7 @@ int main() printf("std::optional example\r\n"); - auto get_data_from_main = [] () { + const auto get_data_from_main = [] () { auto result = sensor::get_data(); if(result) { printf("x = %d, y = %d\r\n", (*result).x, (*result).y);