I have a modbus sensor that returns time in 24H format as an integer [0000 2359]. So 09:00 will be returned as 900, 23:45 would be returned as 2345, 01:30 returned as 130. You get the idea. I want to write a lambda function to return the time in the format hh:mm. This is as far as I’ve got but I dont know how to output the string value.
- platform: modbus_controller
modbus_controller_id: inverter
name: "Setting Timezone2"
id: setting_timezone2
register_type: holding
skip_updates: ${settings_skipped_updates}
address: 251
filters:
- lambda: |-
int minutes, hours;
minutes = static_cast<int>(x) % 100;
hours = static_cast<int>(x) / 100;
return <what next>;
icon: "mdi:clock"
I’ve created a template sensor in home assistant which does what I want but how to do this in ESPHome?
time_zone2:
friendly_name: Program2
value_template: >
{% set time = {
"hour": (states('sensor.setting_timezone2') |float(0) /100 ) | round(0),
"minute": (states('sensor.setting_timezone2') |float(0) % 100 ) | round(0) }
%}
{{'{:02d}'.format(time.hour)}}:{{'{:02d}'.format(time.minute)}}
Update
I’ve manged to create a text sensor, that does this. Is there a better way?
text_sensor:
- platform: template
name: "Program2_test"
lambda: |-
int minutes, hours;
minutes = static_cast<int>(id(setting_timezone2).state) % 100;
hours = static_cast<int>(id(setting_timezone2).state) / 100;
char formatted_time[6];
snprintf(formatted_time, sizeof(formatted_time), "%02d:%02d", hours, minutes);
return esphome::optional<std::string>(formatted_time);