Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Door sensor deep sleep for bk7231n board #2467

Open
yaminahacs opened this issue Nov 8, 2023 · 35 comments
Open

Door sensor deep sleep for bk7231n board #2467

yaminahacs opened this issue Nov 8, 2023 · 35 comments

Comments

@yaminahacs
Copy link

Door sensor deep sleep for bk7231n board

Describe the problem you have/What new integration you would like

Add door sensor deep sleep for bk7231n board

Please describe your use case for this integration and alternatives you've tried:

ESPHOME deep sleep not working for bk72xx platform

Additional context

@imorlxs
Copy link

imorlxs commented Dec 12, 2023

I didn't know how to enable deep sleep too

@Mostalk
Copy link

Mostalk commented Dec 24, 2023

My temporary solution

script:
    - id: scr
      then:
        - wifi.enable:
        - delay: 30s
        - wifi.disable:
      mode: restart
      
binary_sensor:
  - platform: gpio
    device_class: door
    name: Door
    pin: P22
    on_state:
      then:
        - script.execute: scr

@yaminahacs
Copy link
Author

yaminahacs commented Dec 27, 2023 via email

@YuraBogdan
Copy link

Having functional deep sleep will help in a long run.

in mean time, I've been trying to get up to speed with the project

@grego1981
Copy link

grego1981 commented Jan 24, 2024

I've implemented your solution as I'm trying to find the deep sleep code for the exact same type of sensor... Below my running ESPHome config as it works now, quite well. Please comments are needed as I'm not really sure it is efficent enough!

esphome:
  name: basement-door-sensor
  friendly_name: basement_door_sensor
  on_boot:
    priority: 10
    then:
      - switch.turn_on: batt_dv
      - script.execute: scr
bk72xx:
  board: cb3s
  framework:
    version: dev

# Enable logging
logger:

# Enable Home Assistant API
api:
  encryption:
    key: ""

ota:

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password

  # Enable fallback hotspot in case wifi connection fails
  ap:
    ssid: "Basement-Door-Sensor"
    password: "1234567890"

web_server:
  port: 80
  version: 2
  include_internal: true
  ota: true

captive_portal:

script:
    - id: scr
      then:
        - wifi.enable:
        - delay: 30s
        - wifi.disable:
      mode: restart    
binary_sensor:
  - platform: gpio
    device_class: door
    name: Door
    pin: P8
    on_state:
      then:
        - output.turn_on: light_output
        - delay: 500ms
        - output.turn_off: light_output 
        - script.execute: scr    
switch:
  - platform: gpio
    id: batt_dv
    pin: P14
sensor:
  - platform: adc
    pin: ADC3
    id: "VCC"
    name: "Battery Level"
    filters:
      - multiply: 2.4
  - platform: template
    name: "Battery Level (%)"
    unit_of_measurement: '%'
    update_interval: 240s
    lambda: |-
      return ((id(VCC).state /3.0) * 100.00);
light:
  - platform: binary
    name: "Activity LED"
    output: light_output

output:
  - id: light_output
    platform: gpio
    pin: P26

@Mostalk
Copy link

Mostalk commented Feb 22, 2024

Any updates?

@0x3333
Copy link

0x3333 commented Feb 22, 2024

There is some work going on the LibreTiny to support it in ESPHome, but I believe it will take some time until we have Deep Sleep for these chips.

@jon-daemon
Copy link

Does the above script work? What is the power consumption? I have two water sensors operating with 2xAAA batteries and I'd really like to replace the tuya firmware with something else.

@AlenHodnik
Copy link

grego1981's code works great.
The only thing I can't figure out is why it doesn't show me battery level correctly. Just states 0V.

@afarago
Copy link

afarago commented Jun 1, 2024

I have found a nice deep_sleep component for bk72xx / cb3s processor.

Additionally added code for delayed deep sleep and forced manual mode as well.
I would love to see the deep_sleep code from @Xmister merged if someone has the right knowledge.

It took 2-3 days for me to fine tune this, pasting it here to share the info and love of bkn :D hope it helps someone.

# PINOUT: CB3S Module Datasheet - https://developer.tuya.com/en/docs/iot/cb3s?id=Kai94mec0s076
# UART flash with: https://github.com/libretiny-eu/ltchiptool
# UART flashing: GND(pin9),VCC3V(pin8),TX(pin16),RX(pin15) / connect CEN(pin3) to GND(pin9)
# CB3S / tuya chip - https://community.home-assistant.io/t/tuya-door-sensor-configuration/673484
# MORE INFO on the board: https://www.elektroda.com/rtvforum/topic3960149.html
# MORE INFO on the board: https://www.elektroda.com/rtvforum/topic3914412-30.html#gallery-2

### TODO & FURTHER IDEAS
# - additional pins?
# - explore manual "stored" server side update switch
# - switch off w restore LED on activate
# - support Bluetooth LE.

bk72xx:
  # board: generic-bk7231n-qfn32-tuya
  board: cb3s # FAMILY_BK7231N
  framework:
    version: dev

esphome:
  name: z-test-door
  friendly_name: z-test-door
  on_boot:
    # https://esphome.io/components/esphome.html#on-boot
    - priority: 600.0 # 600.0: This is where most sensors are set up.
      then:
        - component.update: VCC
        - switch.turn_on: batt_dv # start measuring voltage
    - priority: 100.0
      then:
        - output.turn_on: activity_led_output
    - priority: -100 # 200.0: Network connections like MQTT/native API are set up at this priority.
      then:
        - component.update: VCC
        - component.update: homeassistant_time
        - component.update: update_time
        - script.execute: scr

logger:
  # level: info

api:

globals:
  - id: first_connect_ms_int
    type: uint32_t
    initial_value: "0"

ota:
  on_begin:
    - output.turn_on: activity_led_output
  # on_progress:
  #   - output.toggle: light_output

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password
  # fast_connect: True
  # manual_ip:
  #   gateway: 192.168.0.1
  #   static_ip: 192.168.0.212
  #   subnet: 255.255.255.0
  on_connect:
    - lambda: |-
        if (id(first_connect_ms_int) == 0) id(first_connect_ms_int) = esphome::millis();
    - component.update: first_connect_ms

web_server:
  version: 3

### we need this reset as there is no reset action with deep_sleep
### see: https://github.com/esphome/feature-requests/issues/2467 - original idea for workaround
### see: https://github.com/esphome/feature-requests/issues/1653 - feature request
script:
  - id: scr
    then:
      - deep_sleep.prevent
      # - wifi.enable:
      - delay: 10s
      # - wifi.disable:
      - script.execute: check_deep_sleep
    mode: restart
  - id: check_deep_sleep
    then:
      - deep_sleep.prevent
      - if:
          condition:
            - switch.is_off: manual_mode
          then:
            - output.turn_off: activity_led_output
            - deep_sleep.allow
    mode: restart

binary_sensor:
  - platform: gpio
    device_class: door
    name: Door
    pin:
      number: P8 # pin-13 hall sensor, GPIOP_8, which corresponds to P8 of the IC, PWM 2
      allow_other_uses: true
    on_state:
      - if:
          condition:
            - switch.is_off: manual_mode
          then:
            - output.turn_on: activity_led_output
            - delay: 1000ms
            - output.turn_off: activity_led_output
          else:
            - light.turn_on:
                id: activity_led
                effect: pulse
      - script.execute: scr
    icon: mdi:door

  - platform: gpio
    id: bottom_button
    pin:
      number: P7 # pin-14 bottom button, GPIOP_7, which corresponds to P7 of the IC, PWM 1
      inverted: true
      allow_other_uses: true
    name: "Bottom button"
    icon: mdi:button-pointer
    on_state:
      - script.execute: check_deep_sleep
    on_multi_click:
      - timing:
          - on for at least 1s
        then:
          - switch.toggle: manual_mode

switch:
  - platform: gpio
    # enables measuring voltage - see https://www.elektroda.com/rtvforum/topic3914412-30.html#gallery-2
    id: batt_dv
    pin: P14

  - platform: template
    # manual mode for OTA
    optimistic: True
    name: Manual mode
    id: manual_mode
    on_turn_off:
      - script.execute: check_deep_sleep
    on_turn_on:
      - script.execute: check_deep_sleep
      - light.turn_on:
          id: activity_led
          effect: pulse
    entity_category: config
    icon: mdi:sleep-off

light:
  # - platform: binary
  #   name: "Activity LED"
  #   output: light_output
  #   id: activity_led_output
  #   icon: mdi:lamp
  #   effects:
  #     - strobe:
  - platform: monochromatic
    name: "Activity LED"
    output: activity_led_output
    id: activity_led
    icon: mdi:lamp
    effects:
      - strobe:
      - pulse:
          transition_length:
            on_length: 1s
            off_length: 2s
          update_interval: 3s

output:
  # - id: light_output
  #   platform: gpio
  #   pin:
  #     number: P26 # P26=pin-5
  #     inverted: true
  - id: activity_led_output
    platform: libretiny_pwm
    frequency: 1000 Hz
    pin:
      number: P26 # P26=pin-5
      inverted: true

time:
  - platform: homeassistant
    id: homeassistant_time
    on_time_sync:
      then:
        - component.update: update_time

sensor:
  - platform: adc
    pin: ADC3 # ADC3 = pin-2 (internally connnected), gives valid only if "batt_dv" is enabled (see more info there)
    id: "VCC"
    name: "Battery Level"
    filters:
      - multiply: 2.4
      - clamp:
          min_value: 0.0
          max_value: 3.0
          ignore_out_of_range: true
    on_value:
      then:
        - component.update: battery_level
    icon: mdi:battery

  - platform: template
    name: "Battery Level (%)"
    unit_of_measurement: "%"
    update_interval: 86400s
    id: battery_level
    lambda: |-
      return ((id(VCC).state /3.0) * 100.00);
    icon: mdi:battery

  - platform: template
    # temporary solution to measure startup time
    name: first_connect_ms
    id: first_connect_ms
    lambda: |-
      return id(first_connect_ms_int);

  - platform: internal_temperature
    name: Internal Temperature
    icon: mdi:thermometer

text_sensor:
  - platform: template
    id: update_time
    name: "Current time"
    lambda: |-
      char str[17];
      time_t currTime = id(homeassistant_time).now().timestamp;
      strftime(str, sizeof(str), "%Y-%m-%d %H:%M", localtime(&currTime));
      return  { str };
    icon: "mdi:clock"

external_components:
  - source: github://Xmister/libretuya-esphome@deep-sleep
    components: [deep_sleep]
  # - source: github://libretiny-eu/libretiny-esphome@dev
  #   components: [ deep_sleep ]
  # - source:
  #     type: git
  #     url: https://github.com/bkaufx/esphome
  #   components: [ web_server_base ]

deep_sleep:
  id: deep_sleep_control
  sleep_duration: 24h
  run_duration: 10s
  wakeup_pins:
    - pin:
        number: P7 # pin-14 bottom button
        allow_other_uses: true
      wakeup_pin_mode: IGNORE
    - pin:
        number: P8 # pin-13 hall sensor
        allow_other_uses: true
      wakeup_pin_mode: INVERT_WAKEUP

@Xmister
Copy link

Xmister commented Jun 1, 2024

@afarago Welcome to the club 🥲 This was my initial PR to prepare the deep sleep for BKN: esphome/esphome#5739

@afarago
Copy link

afarago commented Jun 2, 2024

@afarago Welcome to the club 🥲 This was my initial PR to prepare the deep sleep for BKN: esphome/esphome#5739

Thanks for your awesome work! Is there anything missing for the PR to be merged?
I love it and it seems to work flawlessly on my device after testing it for a few days.

@AlenHodnik
Copy link

AlenHodnik commented Jun 2, 2024

How fast does it use batteries with this code?
All seem to work good, showing battery, deep_sleep checking, manual override, ... but it doesn't change state of the binary_sensor. Wrong pin maybe?
If I use generic tuya board (generic-bk7231n-qfn32-tuya), it's P16.
In board: cb3s, pin P8 doesn't work.

@afarago
Copy link

afarago commented Jun 2, 2024

I have not measured the deep_sleep current, yet it should be the same as the original tuya firmware.
Power consumption seems to be almost zero after a few days.

PIN depends on your board, mine is as above in the links. You could check the integrated circuit by eyes or by a manual multimeter.

@AlenHodnik
Copy link

Found right pin. But seems smth wrong in my case. Doesnt change to open at all, battery -30% over night.

Screenshot_20240603_072924_Home Assistant.jpg

@0x3333
Copy link

0x3333 commented Jun 6, 2024

...battery -30% over night.

It seems that deep sleep is not working.

@starbrights
Copy link

Maybe my measurement is to bad, but I don't see much of an effect for disabling wifi for some time 1..2min.
Any experience how much energy is needed when Wifi is enabled again? I mean is there a certain period to be off required that it is worth (in case reconnect takes more energy than keep connection).
What else can be done to reduce consumption?
I am already using this:
(About the measurements results in comment: Not sure this is serious, I do see mixed results).

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password
  manual_ip:
    static_ip: 192.168.3.250
    gateway: 192.168.3.1
    subnet: 255.255.255.0
  ap:  
    password: !secret wifi_ap_password
  fast_connect: 'true'
  power_save_mode: 'high'    # Optionen: none 1.5W, light 1.43W, high 1.28W
  output_power: 10dB         # reduce power (default is 20db)  10/15 ->  0,92W
  reboot_timeout: '0s'

@AlenHodnik
Copy link

...battery -30% over night.

It seems that deep sleep is not working.

Deep sleep is working, measured current consumption. The problem is that device keeps getting out of deep sleep for no reason (see led light). It should only wake every 24h and on pin change, but it isnt. Any ideas?

V.

@afarago
Copy link

afarago commented Jun 23, 2024

We might spot the error seeing the complete yaml file. Would you add it to this discussion?

Changing Wifi power save and transmit power does not make a sense imo, as ideally the device is like 10s awake every now and then, so if deep_sleep is operational you practically have zero wake time.

@afarago
Copy link

afarago commented Jun 26, 2024

I have perfomed two test scenarios with the deep_sleep component above.

  1. wake up every 6 hours (or on hall sensor / bottom button press)
    battery performance: started with two rechargeable IKEA batteries (worst choice) at 2.64V
    after cc two days and 9 wake cycles => 2.62V

  2. wake up every minute (endurance test)
    after cc 1.5 days and 1843 wake cycles battery is depleted
    (I checked with a multimeter and change the multiplier factor afterwards -> 2.64V->2.00V)

IMG_0046
IMG_0028

Hope this helps, certainly impressive data for me that predicts >1y runtime.
I am not sure that an I-am-alive is neccessary every 6h, could easily be every day or so.

@starbrights
Copy link

starbrights commented Jul 2, 2024

Want use by Rollerblind switch in energy saving way. So I used @afarago setup to adapt it.
It has 3 buttons-each with a LED. Lets see what happens when pressing one of it:

I could see status LED starts blinking (is it to get Wifi connection?). Usually it does it 13 times, than a little break, starting again. Than after few blinks the 3LEDs for the keys blink 2 times. This is from "on_boot" section to indicates a reboot (I did it because I have no serial connection and Wifi is off for logging). After few seconds the LEDs for the 3 keys are off. Guess this is the enery saving mode. I measure around 0.5W (but maybe that is the smalles number I can get with this device - it is a 220V device).
But the problem: I can hear any action on the relays/switches! Maybe there is a misunderstanding what happens in deep_sleep and what happens when wake up?

What am I doing wrong?

  name: moes
  on_boot:
    - priority: -10
      then:
      - logger.log: "run on_boot"
      - output.turn_on: gpio_backlight
      - delay: 500ms
      - output.turn_off: gpio_backlight
      - delay: 500ms
      - output.turn_on: gpio_backlight
      - delay: 500ms
      - output.turn_off: gpio_backlight
      - delay: 500ms
      - output.turn_on: gpio_backlight
    - priority: -100
      then:   
      - script.execute: scr

bk72xx:
  board: cb3s # FAMILY_BK7231N
  framework:
    version: dev

logger:

web_server:

captive_portal:

mdns:

#api:
#  password: ""

ota:
  password: ""

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password
  manual_ip:
    static_ip: 192.168.3.250
    gateway: 192.168.3.1
    subnet: 255.255.255.0
  ap:  
    password: !secret wifi_ap_password
  fast_connect: 'true'
  power_save_mode: 'high'    # Optionen: none 1.5W, light 1.43W, high 1.28W
  output_power: 10dB         # Reduziert die Sendeleistung 10/15 0,92W
  reboot_timeout: '0s'

script:
  - id: scr
    then:
      - deep_sleep.prevent
      - delay: 10s
      - script.execute: check_deep_sleep
    mode: restart
  - id: check_deep_sleep
    then:
      - deep_sleep.prevent
      - if:
          condition:
             and:
                - switch.is_off: switch_up
                - switch.is_off: switch_down
          then:
            - output.turn_off: gpio_backlight
            - deep_sleep.allow
    mode: restart


button:
  - platform: restart
    name: Restart

debug:
  update_interval: 30s

text_sensor:
  - platform: debug
    reset_reason:
      name: Reset Reason
  - platform: libretiny
    version:
      name: LibreTiny Version

sensor:
  - platform: uptime
    name: Uptime
    accuracy_decimals: 0

globals:
  - id: pref_pos
    type: int
    initial_value: '55'
  - id: timer_active
    type: bool
    initial_value: 'true'
  - id: backlight_active
    type: bool
    initial_value: 'true'

cover:
  - platform: time_based
    name: moes1
    id: my_cover
    open_action:
      - switch.turn_on: switch_up
      - output.turn_on: output_led_up
    open_duration: 26000ms
    close_action:
      - switch.turn_on: switch_down
      - output.turn_on: output_led_down
    close_duration: 25000ms
    stop_action:
      - switch.turn_off: switch_up
      - switch.turn_off: switch_down
      - output.turn_off: output_led_up
      - output.turn_off: output_led_down
    on_open:
      - logger.log: "Cover is/should fully open!"
      - switch.turn_on: switch_up
    on_closed:
      - logger.log: "Cover is/should fully closed!"
      - switch.turn_on: switch_down

output:
  - platform: gpio
    id: output_led_up
    pin: P14
  - platform: gpio
    id: output_led_down
    pin: P23
  - platform: gpio
    id: output_led_stop
    pin: P8
  - platform: gpio
    id: gpio_backlight
    pin: P11

binary_sensor:
  - platform: gpio
    id: binary_switch_up
    pin:
      number: P24
      inverted: true
      mode: INPUT_PULLUP
      allow_other_uses: true
    on_multi_click:
      - timing:
          - ON for at most 1s
          - OFF for at least 0.1s
        then:
        - logger.log: "press up detected"
        - lambda: |-
            ESP_LOGD("main", "cover.current_operation %i", id(my_cover).current_operation);
            if (id(my_cover).current_operation == CoverOperation::COVER_OPERATION_IDLE) {
              // Cover is idle
              auto call = id(my_cover).make_call();
              call.set_command_open();
              call.perform();
              ESP_LOGD("main", "cover.open");
            } else if (id(my_cover).current_operation == CoverOperation::COVER_OPERATION_OPENING) {
              // Cover is currently opening
              auto call = id(my_cover).make_call();
              call.set_command_stop();
              call.perform();
              ESP_LOGD("main", "already opening: cover.stop");
            } else if (id(my_cover).current_operation == CoverOperation::COVER_OPERATION_CLOSING) {
              // Cover is currently closing
              auto call = id(my_cover).make_call();
              call.set_command_stop();
              call.perform();
              ESP_LOGD("main", "cover.stop");
            }
 
  - platform: gpio
    id: binary_switch_down
    pin:
      number: P7
      inverted: true
      mode: INPUT_PULLUP
      allow_other_uses: true
    on_multi_click:
      - timing:
          - ON for at most 1s
          - OFF for at least 0.1s
        then:
        - logger.log: "press down detected"
        - lambda: |-
            ESP_LOGD("main", "cover.current_operation %i", id(my_cover).current_operation);
            if (id(my_cover).current_operation == CoverOperation::COVER_OPERATION_IDLE) {
              // Cover is idle
              auto call = id(my_cover).make_call();
              call.set_command_close();
              call.perform();
              ESP_LOGD("main", "idle - cover.close");
            } else if (id(my_cover).current_operation == CoverOperation::COVER_OPERATION_OPENING) {
              // Cover is currently opening
              auto call = id(my_cover).make_call();
              call.set_command_stop();
              call.perform();
              ESP_LOGD("main", "already opening - cover.stop");
            } else if (id(my_cover).current_operation == CoverOperation::COVER_OPERATION_CLOSING) {
              // Cover is currently closing
              auto call = id(my_cover).make_call();
              call.set_command_stop();
              call.perform();
              ESP_LOGD("main", "closing - cover.stop");
            }


  - platform: gpio
    id: binary_switch_stop
    pin:
      number: P10
      inverted: true
      mode: INPUT_PULLUP
      allow_other_uses: true
    on_multi_click:
      - timing:
          - ON for at most 1s
          - OFF for at least 0.1s
        then:
          - logger.log: "press stop detected"
          - lambda: |-
                ESP_LOGD("main", "stop: cover.current_operation %i", id(my_cover).current_operation);
                if (id(my_cover).current_operation == CoverOperation::COVER_OPERATION_IDLE) {
                  ESP_LOGD("main", "act pos %i -> pref pos %i", int(id(my_cover).position*100), id(pref_pos));
                    if (abs(int(id(my_cover).position*100) - id(pref_pos))>1) {
                      auto call = id(my_cover).make_call();
                      call.set_position(id(pref_pos)/100.0);
                      call.perform();                  
                    } else {
                      ESP_LOGD("main", "no action needed, already at right pos");
                    }
                } else {
                  auto call = id(my_cover).make_call();
                  call.set_command_stop();
                  call.perform();
                  ESP_LOGD("main", "pressed stop while running - cover.stop");
                }


switch:
  - platform: gpio
    id: switch_up
    name: Relay up
    pin: P6
    interlock: [switch_down]
  - platform: gpio
    id: switch_down
    name: Relay down
    pin: P9
    interlock: [switch_up]

status_led:
  pin: P26

external_components:
  - source: github://Xmister/libretuya-esphome@deep-sleep
    components: [deep_sleep]
  # - source: github://libretiny-eu/libretiny-esphome@dev
  #   components: [ deep_sleep ]
  # - source:
  #     type: git
  #     url: https://github.com/bkaufx/esphome
  #   components: [ web_server_base ]

deep_sleep:
  id: deep_sleep_control
  sleep_duration: 24h
  run_duration: 10s
  wakeup_pins:
    - pin:
        number: P24 # Up
        allow_other_uses: true
      wakeup_pin_mode: INVERT_WAKEUP
    - pin:
        number: P7 # Down
        allow_other_uses: true
      wakeup_pin_mode: INVERT_WAKEUP
    - pin:
        number: P10 # Stop
        allow_other_uses: true
      wakeup_pin_mode: INVERT_WAKEUP```

@starbrights
Copy link

starbrights commented Jul 7, 2024

@afarago @Xmister :
Can you explain how to use deep sleep properly, or what I am doing wrong?
Intention of the above is to sleep until it wakes up by pressing up/down/stop key and than perform the action.

It seems not doing anything but wake up and reboot. It is difficult to follow with no (serial log) attached.
Below the more simpler example for my rollerblind - without cover component and no deep sleep at all. How to make it able to sleep?

  name: moes
  on_boot:
    - priority: -10
      then:
      - logger.log: "run on_boot"
      - output.turn_on: gpio_backlight
      - delay: 500ms
      - output.turn_off: gpio_backlight
      - delay: 500ms
      - output.turn_on: gpio_backlight
      - delay: 500ms
      - output.turn_off: gpio_backlight
      - delay: 500ms
      - output.turn_on: gpio_backlight

bk72xx:
  board: cb3s # FAMILY_BK7231N
  framework:
    version: dev

logger:

web_server:

captive_portal:

mdns:

#api:
#  password: ""

ota:
  password: ""

wifi:
  ssid: !secret wifi_ssid
  password: !secret wifi_password
  manual_ip:
    static_ip: 192.168.3.250
    gateway: 192.168.3.1
    subnet: 255.255.255.0
  ap:  
    password: !secret wifi_ap_password
  reboot_timeout: '0s'



button:
  - platform: restart
    name: Restart

globals:
  - id: backlight_active
    type: bool
    initial_value: 'true'

output:
  - platform: gpio
    id: output_led_up
    pin: P14
  - platform: gpio
    id: output_led_down
    pin: P23
  - platform: gpio
    id: output_led_stop
    pin: P8
  - platform: gpio
    id: gpio_backlight
    pin: P11

binary_sensor:
  - platform: gpio
    id: binary_switch_up
    pin:
      number: P24
      inverted: true
      mode: INPUT_PULLUP
#      allow_other_uses: true
    on_press:
        - lambda: |-
            if ( !id(switch_down).state && !id(switch_up).state) {
              // Cover is idle
              id(switch_up).turn_on();
            } else if (id(switch_up)) {
              // Cover is currently opening
              id(switch_up).turn_off();
            } else if (id(switch_down)) {
              // Cover is currently closing
              id(switch_up).turn_off();
            }
 
  - platform: gpio
    id: binary_switch_down
    pin:
      number: P7
      inverted: true
      mode: INPUT_PULLUP
#      allow_other_uses: true
    on_press:
        - lambda: |-
            if ( !id(switch_down).state && !id(switch_up).state) {
              // Cover is idle
              id(switch_up).turn_on();
            } else if (id(switch_up)) {
              // Cover is currently opening
              id(switch_up).turn_off();
            } else if (id(switch_down)) {
              // Cover is currently closing
              id(switch_up).turn_off();
            }

  - platform: gpio
    id: binary_switch_stop
    pin:
      number: P10
      inverted: true
      mode: INPUT_PULLUP
#      allow_other_uses: true
    on_press:
        - lambda: |-
              id(switch_up).turn_off();
              id(switch_down).turn_off();


switch:
  - platform: gpio
    id: switch_up
    name: Relay up
    pin: P6
    interlock: [switch_down]
  - platform: gpio
    id: switch_down
    name: Relay down
    pin: P9
    interlock: [switch_up]

status_led:
  pin: P26

@starbrights
Copy link

No updates here?

@toughvj
Copy link

toughvj commented Aug 9, 2024

it looks like there is an never ending deep_sleep loop.

this is my yaml:
`substitutions:
device_name: pokoj_helenki_czujnik_okna
upper_devicename: Pokój Helenki czujnik okna

esphome:
name: ${device_name}
friendly_name: ${upper_devicename}

bk72xx:
board: cbu

logger:

api:
encryption:
key: ""
reboot_timeout: 0s

ota:

  • platform: esphome
    password: ""

wifi:
ssid: !secret wifi_ssid
password: !secret wifi_password
manual_ip:
static_ip: 10.0.40.219
gateway: 10.0.40.1
subnet: 255.255.255.0
ap:
ssid: ${upper_devicename}
password: ""

captive_portal:

web_server:
port: 80

light:

  • platform: status_led
    id: activity_led
    pin:
    number: P15
    inverted: True

text_sensor:

  • platform: wifi_info
    ip_address:
    name: Adres IP

button:
platform: restart
name: Restart
id: button_restart

binary_sensor:

  • platform: gpio
    pin:
    number: P22
    allow_other_uses: true
    device_class: window
    name: Okno
    on_state:
    then:
    - light.turn_on: activity_led
    - delay: 250ms
    - light.turn_off: activity_led
  • platform: gpio
    pin:
    number: P14
    allow_other_uses: true
    id: btn_rst
  • platform: gpio
    id: voltage_relay
    internal: true
    pin:
    number: P20
    inverted: False
    mode: INPUT_PULLUP

sensor:

  • platform: adc
    pin: ADC3
    id: VCC
    filters:
    • multiply: 2.4
    • clamp:
      min_value: 0.0
      max_value: 3.0
      ignore_out_of_range: true
  • platform: template
    id: battery_level
    name: "Bateria"
    unit_of_measurement: '%'
    update_interval: 240s
    lambda: |-
    return ((id(VCC).state /3.0) * 100.00);

external_components:

  • source: github://Xmister/libretuya-esphome@deep-sleep
    components: [deep_sleep]

deep_sleep:
id: deep_sleep_control
sleep_duration: 24h
run_duration: 10s
wakeup_pins:
- pin:
number: P14
allow_other_uses: true
wakeup_pin_mode: IGNORE
- pin:
number: P22
allow_other_uses: true
wakeup_pin_mode: INVERT_WAKEUP`

and log:
logs_pokoj-helenki-czujnik-okna_logs.txt

@szupi-ipuzs
Copy link

Hi, if anyone is interested I have a somewhat working external component that implements deep sleep for bk7231 boards.
I do plan to create a PR out of it, but seeing how @Xmister 's PR for deep sleep is treated by the maintainers, I don't get my hopes up...

@szupi-ipuzs
Copy link

@Xmister , I can now see that you were the original poster of the PR I based my external component on. So, the cycle loops again :)

@toughvj
Copy link

toughvj commented Aug 15, 2024

Hi, if anyone is interested I have a somewhat working external component that implements deep sleep for bk7231 boards. I do plan to create a PR out of it, but seeing how @Xmister 's PR for deep sleep is treated by the maintainers, I don't get my hopes up...

Sorry for my begginers question but how to use it?

@szupi-ipuzs
Copy link

Hi, if anyone is interested I have a somewhat working external component that implements deep sleep for bk7231 boards. I do plan to create a PR out of it, but seeing how @Xmister 's PR for deep sleep is treated by the maintainers, I don't get my hopes up...

Sorry for my begginers question but how to use it?

Just follow the official guide for using external components.
You need to specify the whole set of my external components, which is here, and then tell esphome which of them you import.

external_components:
  - source:
      type: git
      url: https://github.com/szupi-ipuzs/esphome-external-components
      ref: main
    components: [ deep_sleep_libretiny ]

And then follow the description.

@toughvj
Copy link

toughvj commented Aug 16, 2024

I did as you wrote, but in the esphome editor I get a message like in the screenshot. I added the component locally, then everything works, the device goes into deep sleep, but now I have a problem with the unavailable state. I edited the file you indicated in the esphome container, compiled, added the device again, but after going into sleep mode, it still appears as unavailable. Am I doing something wrong?

Are you sure this part of the code is correct?

#ifdef USE_DEEP_SLEEP
namespace esphome::deep_sleep {
extern bool global_has_deep_sleep; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
#endif
}

Shouldn't it be:

#ifdef USE_DEEP_SLEEP namespace esphome::deep_sleep { extern bool global_has_deep_sleep; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
}
#endif

Zrzut ekranu 2024-08-16 o 08 52 57

@szupi-ipuzs
Copy link

Are you sure this part of the code is correct?

Yes, I'm sure. This should work.
How long is the sleep time you have setup in the yaml? I had the same problem when I set it to 24h. When I changed it to 1h, HA started to show the correct state. I haven't yet investigated why.
Also, what are your esphome and Home Assistant versions?

@szupi-ipuzs
Copy link

szupi-ipuzs commented Aug 18, 2024

Yes, I'm sure. This should work.

Ok, I can now see that you're right, the last curly brace is out of place. But your code snippet is also not correct (maybe due to white chars?).
The correct code is:

#ifdef USE_DEEP_SLEEP
namespace esphome::deep_sleep {
extern bool global_has_deep_sleep;  // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
}
#endif

I will change it in the readme of my external component.

@szupi-ipuzs
Copy link

@toughvj I've also noticed I haven't checked in all the needed changes before. I've just fixed it. Please download the external component locally again. It should work fine now.
Also, for any future problems with my external component, please open an issue in my repository, It will be easier to track the problems there.

@AlenHodnik
Copy link

AlenHodnik commented Aug 21, 2024

I must say everything works somewhat good, except it takes ~35s after open/close sensor for it to change status. Any ideas what could be wrong? Takes really long time to wake...

@szupi-ipuzs
Copy link

I also use this with a door sensor and sadly I observe similar behavior. The device actually wakes up immediately, but it takes veery long time to connect to wifi. I know this because I told it to start blinking at boot and then turn on the light completely on HA connection.
I will fiddle with my wifi settings, maybe something will help, but I think that to really improve the connection time - some changes need to be done in libretiny itself. Eg, this PR might help.

@dskw
Copy link

dskw commented Dec 4, 2024

So what is the current state of deep sleep support on BK7231N ?
To this day I am still using the deepsleep component from @Xmister:
github://Xmister/libretuya-esphome@deep-sleep
which works well for my window/door sensors.

Yes, they do take much longer to connect to wifi compared to the stock firmware, but with the 2 aaa batteries in there it lasts me for 6-12 months, so I'm not complaining.
I would really like to see this getting integrated though, to make use of the pure esphome repository.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests