I’ve been playing with creating a parking sensor with a simple RGB led as an indicator for proximity to the “ideal” parking distance.
I’m storing the distance as a global variable in the ESPHome code upon a long button press, which is great, except for when the device would restart. I don’t want to hard code the right distance in, though that would be a lot simpler.
I want to retain that custom distance between reboots, which is the main goal here.
If there’s a way to do that within the ESPHome code without hardcoding it, that’d be awesome and you don’t need to read any farther.
However, the only way I’ve imagined having a source of that retained info, is to pull the number from an input_boolean within Home Assistant–and having the button press on the device set a new input_boolean value within Home Assistant. That way, Home Assistant will have an active value for the parking sensor if the parking sensor reboots… obviously the failing here is if both devices restart.
My question is how to convert the platform: homeassistant sensor value, which comes in as a string (shown as nan in the console), to a float value. I’ve tried a few solutions and Googled a bunch–even going so far as looking into how I’d write a C++ custom component, which is way over my head.
Here’s the code for the sensors that I’m trying to play with–a “${device_name}_hass_target” sensor that is the imported string and a “${device_name}_target” that is a float value–either being set by the global value or in the case of the global value being the initial value (0), then relying on the “${device_name}_hass_target” to provide that value.
- platform: homeassistant
# https://esphome.io/components/sensor/homeassistant.html
id: ${device_name}_hass_target
entity_id: input_number.${device_name}_target
- platform: template
# https://esphome.io/components/sensor/template.html
name: ${device_name}_target
id: ${device_name}_target
unit_of_measurement: "in"
icon: "mdi:target"
lambda: |-
if (id(${device_name}_target_global) == 0) {
float hassTarget = std::stof(id(${device_name}_hass_target).state); # also tried "std::stof" here too...
id(${device_name}_target_global) = hassTarget;
return hassTarget;
} else {
return id(${device_name}_target_global);
}
When I try using this method of C++ code to convert the string to a float, I get this error:
src/main.cpp: In lambda function:
src/main.cpp:913:44: error: 'stof' is not a member of 'std'
garage_01_target_global->value() = std::stof(garage_01_hass_target->state);
^
*** [.pioenvs/garage_01/src/main.cpp.o] Error 1
And this error if I just use “float hassTarget = stof(id(${device_name}_hass_target).state);”
src/main.cpp: In lambda function:
src/main.cpp:913:77: error: 'stof' was not declared in this scope
garage_01_target_global->value() = stof(garage_01_hass_target->state);
^
*** [.pioenvs/garage_01/src/main.cpp.o] Error 1