8 static const char *
const TAG =
"bl0940";
10 static const uint8_t BL0940_READ_COMMAND = 0x50;
11 static const uint8_t BL0940_FULL_PACKET = 0xAA;
12 static const uint8_t BL0940_PACKET_HEADER = 0x55;
14 static const uint8_t BL0940_WRITE_COMMAND = 0xA0;
15 static const uint8_t BL0940_REG_I_FAST_RMS_CTRL = 0x10;
16 static const uint8_t BL0940_REG_MODE = 0x18;
17 static const uint8_t BL0940_REG_SOFT_RESET = 0x19;
18 static const uint8_t BL0940_REG_USR_WRPROT = 0x1A;
19 static const uint8_t BL0940_REG_TPS_CTRL = 0x1B;
23 {BL0940_WRITE_COMMAND, BL0940_REG_SOFT_RESET, 0x5A, 0x5A, 0x5A, 0x38},
25 {BL0940_WRITE_COMMAND, BL0940_REG_USR_WRPROT, 0x55, 0x00, 0x00, 0xF0},
27 {BL0940_WRITE_COMMAND, BL0940_REG_MODE, 0x00, 0x10, 0x00, 0x37},
29 {BL0940_WRITE_COMMAND, BL0940_REG_TPS_CTRL, 0xFF, 0x47, 0x00, 0xFE},
31 {BL0940_WRITE_COMMAND, BL0940_REG_I_FAST_RMS_CTRL, 0x1C, 0x18, 0x00, 0x1B}};
38 if (
read_array((uint8_t *) &buffer,
sizeof(buffer))) {
43 ESP_LOGW(TAG,
"Junk on wire. Throwing away partial message");
50 uint8_t
checksum = BL0940_READ_COMMAND;
52 for (uint32_t i = 0; i <
sizeof(data->
raw) - 1; i++) {
53 checksum += data->
raw[i];
57 ESP_LOGW(TAG,
"BL0940 invalid checksum! 0x%02X != 0x%02X", checksum, data->
checksum);
69 for (
auto *i : BL0940_INIT) {
77 auto tb = (float) (temperature.
h << 8 | temperature.
l);
78 float converted_temp = ((float) 170 / 448) * (tb / 2 - 32) - 45;
79 if (sensor !=
nullptr) {
81 ESP_LOGD(TAG,
"Invalid temperature change. Sensor: '%s', Old temperature: %f, New temperature: %f",
87 return converted_temp;
93 ESP_LOGI(TAG,
"Invalid data. Header mismatch: %d", data->
frame_header);
119 ESP_LOGV(TAG,
"BL0940: U %fV, I %fA, P %fW, Cnt %" PRId32
", ∫P %fkWh, T1 %f°C, T2 %f°C", v_rms, i_rms, watt, cf_cnt,
120 total_energy_consumption, tps1, tps2);
124 ESP_LOGCONFIG(TAG,
"BL0940:");
optional< std::array< uint8_t, N > > read_array()
void write_array(const uint8_t *data, size_t len)
static bool validate_checksum(const DataPacket *data)
void write_byte(uint8_t data)
sensor::Sensor * current_sensor_
float update_temp_(sensor::Sensor *sensor, ube16_t packed_temperature) const
static int32_t to_int32_t(sbe24_t input)
void dump_config() override
void received_package_(const DataPacket *data) const
void publish_state(float state)
Publish a new state to the front-end.
sensor::Sensor * internal_temperature_sensor_
const uint8_t BL0940_INIT[5][6]
sensor::Sensor * energy_sensor_
static uint32_t to_uint32_t(ube24_t input)
constexpr const char * c_str() const
float get_state() const
Getter-syntax for .state.
Implementation of SPI Controller mode.
bool has_state() const
Return whether this sensor has gotten a full state (that passed through all filters) yet...
sensor::Sensor * voltage_sensor_
Base-class for all sensors.
float max_temperature_diff_
sensor::Sensor * power_sensor_
esphome::sensor::Sensor * sensor
const StringRef & get_name() const
sensor::Sensor * external_temperature_sensor_
void IRAM_ATTR HOT delay(uint32_t ms)