Storing time_t to flash

Hi,

I have tried to use global variable which can be stored to flash using restore_value: yes.

But I want to use that value in text sensor lambda as time_t type. But I am not able to get the casting working so that it would compile. The casting should happen both way, int to time_t and then back to int so that it can be flashed. If you have this kind of example, please advice.

Thanks

You’ll need to post both code and exception you’re getting.

I have tried quite many things, I just never get this casting thing to compile.

This is the code:

globals:
  - id: g_last_minor_maintenance
    type: int
    restore_value: yes
    initial_value: '1577811600'

text_sensor:
  - platform: template
    name: $devicename last minor maintenance
    icon: mdi:calendar-clock
    lambda: |-
      char str[17];
      time_t last_minor_maintenance;
      last_minor_maintenance = static_cast<time_t> (g_last_minor_maintenance);
      strftime(str, sizeof(str), "%d.%m.%Y %H:%M", localtime(&last_minor_maintenance));
      g_last_minor_maintenance = static_cast<int> (last_minor_maintenance);
      return  {str};

This is the error:

/config/esphome/ac-base.yaml: In lambda function:
/config/esphome/ac-base.yaml:349:77: error: invalid static_cast from type 'esphome::globals::RestoringGlobalsComponent<int>*' to type 'time_t' {aka 'long int'}
       last_minor_maintenance = static_cast<time_t> (g_last_minor_maintenance);
                                                                             ^
/config/esphome/ac-base.yaml:351:34: error: invalid conversion from 'int' to 'esphome::globals::RestoringGlobalsComponent<int>*' [-fpermissive]
       g_last_minor_maintenance = static_cast<int> (last_minor_maintenance);
                                  ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
*** [/data/living-room-ac/.pioenvs/living-room-ac/src/main.cpp.o] Error 1
========================= [FAILED] Took 85.85 seconds =========================

I got it working. I can now store time to esphome own flash and also use it in text sensor. See below an example.

 switch:
  - platform: template
    name: $devicename minor maintenance timer reset
    id: minor_maintenance_reset
    optimistic: true
    turn_on_action:
      - lambda: |-
          id(g_last_minor_maintenance) = id(my_time).now().timestamp;
      - switch.turn_off: minor_maintenance_reset

globals:
  - id: g_last_minor_maintenance
    type: long int
    restore_value: yes
    initial_value: '1681182000'

time:
  - platform: sntp
    id: my_time
    timezone: UTC-7

text_sensor:
  - platform: template
    name: $devicename last minor maintenance
    icon: mdi:calendar-clock
    lambda: |-
      char str[17];
      strftime(str, sizeof(str), "%d.%m.%Y %H:%M", localtime(&id(g_last_minor_maintenance)));
      return  {str};