Skip to content

Instantly share code, notes, and snippets.

@jnimmo
Forked from jacobw/dev4.yaml
Last active April 27, 2024 07:59
Show Gist options
  • Save jnimmo/58263362deac2c98470278edaa5570c4 to your computer and use it in GitHub Desktop.
Save jnimmo/58263362deac2c98470278edaa5570c4 to your computer and use it in GitHub Desktop.
ESPHome BTHome Pulse Meter Example
esphome:
name: power-meter
on_boot:
priority: -100
then:
- if:
condition:
switch.is_on: disable_wifi
then:
script.execute: schedule_disable_wifi
esp32:
board: m5stack-atom
# Enable logging
logger:
# Enable Home Assistant API
api:
reboot_timeout: 0s
wifi:
reboot_timeout: 0s
networks:
- ssid: !secret wifi_ssid
password: !secret wifi_password
esp32_ble_server:
id: ble
manufacturer: "Orange"
manufacturer_data: [0x4C, 0, 0x23, 77, 0xF0]
time:
- platform: homeassistant
id: hatime
script:
- id: schedule_disable_wifi
mode: restart
then:
- delay: 5min
- if:
condition:
- switch.is_on: disable_wifi
then:
- wifi.disable
- id: update_bthome_broadcast
mode: single
then:
- lambda: |-
// Get current power consumption in watts and total energy in kWh
if (!id(energy_sensor).has_state()) {
return;
}
int watts = ((int)roundf(id(power_sensor).state * 100000));
int energy = ((int)roundf(id(energy_sensor).state * 1000));
// Create points to enable little endian conversion
uint8_t *pEnergy = (uint8_t*)&energy;
uint8_t *pPower = (uint8_t*)&watts;
// Create and send BTHome payload
std::vector<uint8_t> service_data = {
0xD2, 0xFC, // BTHome UUID
0x40, // BTHome Device Information
0x0A, // 3 byte energy type (kWh)
pEnergy[0], pEnergy[1], pEnergy[2], // Total energy consumption (little endian)
0x0B, // 3 byte power type (W)
pPower[0], pPower[1], pPower[2] // Instantaneous watts (little endian)
};
esphome::esp32_ble::global_ble->advertising_set_service_data(service_data);
ESP_LOGD("BThome", "Sent Energy: %i, Power: %i", energy, watts);
ESP_LOGD("BTHome", "Hex Energy: 0x%02X%02X%02X, Power: 0x%02X%02X%02X", pEnergy[0], pEnergy[1], pEnergy[2], pPower[0], pPower[1], pPower[2]);
switch:
- platform: template
id: disable_wifi
name: "Disable WiFi after boot"
optimistic: True
restore_mode: RESTORE_DEFAULT_OFF
on_turn_on:
then:
- script.execute: schedule_disable_wifi
sensor:
- platform: pulse_meter
id: power_sensor
pin: GPIO26
unit_of_measurement: 'kW'
name: 'Electricity Usage'
internal_filter: 100ms
accuracy_decimals: 2
filters:
- multiply: 0.06
- delta: 0.01
on_value:
then:
- script.execute: update_bthome_broadcast
total:
name: "Electricity Total"
id: energy_sensor
unit_of_measurement: "kWh"
device_class: "energy"
state_class: "total_increasing"
accuracy_decimals: 3
filters:
- multiply: 0.001
- delta: 0.01
on_value:
then:
- script.execute: update_bthome_broadcast
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment