Measure switchON-time

Hi,
I’m just starting with esphome, so maybe I missed some info. Im trying to measure the number of seconds a switch is in ON-state. So I store a timestamp at turning on, another one at turning off and now I’m trying to log the difference of my two timestamps:


globals:
  - id: timeON
    type: long int
    restore_value: no
  - id: timeOFF
    type: long int
    restore_value: no

i2c:
  sda: GPIO4
  scl: GPIO5
  scan: True

pcf8574:
  - id: 'pcf8574_1'
    address: 0x20
    pcf8575: False

time:
  - platform: sntp
    id: sntp_time

switch:
  - platform: gpio
    name: "test 1"
    id: t1
    pin:
      pcf8574: pcf8574_1
      number: 6
      mode: OUTPUT
      inverted: True
    on_turn_on:
      - logger.log: "turning on"
      - lambda: |-
          timeON = id(sntp_time).now().timestamp;
    on_turn_off:
      - logger.log: "turning off"
      - lambda: |-
          timeOFF = id(sntp_time).now().timestamp;
          ESP_LOGD('TEST', "Difference in seconds: %d", difftime(timeOFF, timeON) );


So I have two questions:
a) Is this the way to get my switch-ON-time? Or does a better way exist?
b) What do I have to do im my statement, because this does not compile.
Error shown:

src/main.cpp:553:14: error: invalid conversion from 'time_t {aka long int}' to 'esphome::globals::GlobalsComponent<long int>*' [-fpermissive]
       timeON = sntp_time->now().timestamp;

Thanks

2 Likes

The error is because timestamp is of type time_t which is unsigned. I would define timeON and timeOFF as type: time_t and that should fix your compile issue.

You could alternatively use the History Statistics Sensor which would do all the work for you.

1 Like

Nice feature, thanks for the link. But in my case I prefer to handle this only on my esp8266.
tomeps

No, I did try several types. But I solved it, it was a real silly mistake: instead of

timeON = sntp_time->now().timestamp;

I have to use:

id(timeON) = sntp_time->now().timestamp;

Thnaks for pointing me in the right direction!
tomesp

3 Likes