I’ve been trying to work out why my NSPanel ESP32 is crashing into a boot loop every so often. I realised it was happening whenever a Home Assistant MQTT sensor glitched and started reporting status ‘unavailable’, so I looked at my code and I think it’s due to me trying to convert the string value to an int, as the sensor normally reports a battery level. The code is:
- platform: homeassistant
id: lock_1_batt
entity_id: sensor.front_door_lock_battery
on_value:
then:
- wait_until:
switch.is_on: nextion_init
- lambda: |-
int symbol = 26;
int batt = stoi(id(lock_1_batt).state);
ESP_LOGD("batt_test", "The value of battery is: %i", batt);
if (batt <= 20) {
symbol=25;
} else if (batt <= 40) {
symbol=24;
} else if (batt <= 60) {
symbol=23;
} else if (batt <= 80) {
symbol=22;
} else if (batt <= 100) {
symbol=21;
} else {
symbol=26;
}
id(disp1).send_command_printf("Home.lock1batt.pic=%i", symbol);
So I think the offending line is int batt = stoi(id(lock_1_batt).state);
which would throw an error if there is no valid integer conversion. Accorinding to the CPP reference stoi
throws an error of type [std::invalid_argument]
if no conversion can be performed. How do I test for this error and gracefully handle it? I’m a CPP novice so I can only hack things together!
Thanks!