Compare commits

..
3 Commits
Author SHA1 Message Date
J. Nick Koston 4e82d88efe [cse7766] Name the error-frame warning, test it, and use ESP_LOGVV_HEX
Restores the direct helpers.h include, gives the warning for an error frame its own
message, adds tests that error frames keep the warning until a valid frame and that an
out-of-range power cycle does not set it, and logs the raw frame with ESP_LOGVV_HEX.
2026-11-17 15:56:06 -06:00
J. Nick Koston a7e64f4e88 [cse7766] Append the fixed log prefix with buf_append_str 2026-11-17 15:52:48 -06:00
J. Nick Koston 2dcd6128c0 [cse7766] Keep the warning for frames that report an error and tidy the parser
A frame that reports a calibration or circuit error now keeps the component warning instead
of clearing it. The idle loop returns before the receive timeout check, the per-byte modulo
and the read-back of the stored byte are gone, the energy and current paths drop two float
divisions per frame, and the 24-bit wrapper gives way to encode_uint24 and the nibble
helpers. The tests build all seven sensors with dict-style packages.
2026-11-17 15:49:28 -06:00
16 changed files with 241 additions and 937 deletions

No files matched your search

+83 -93
View File
@@ -10,121 +10,119 @@ ESPHOME_LOG_TAG(TAG, "cse7766");
// The chip only sends the time since the last pulse once a cycle is longer than 1 s (in us)
static constexpr uint32_t MIN_HELD_POWER_CYCLE = 1000000;
// A gap this long between bytes starts a new frame
static constexpr uint32_t RX_RESET_TIMEOUT_MS = 500;
// Datasheet: the smallest current the chip measures
static constexpr float MIN_CURRENT_A = 0.05f;
// Energy per CF pulse is the power coefficient in uW·s; this turns pulses × coefficient into Wh
static constexpr float PULSE_COEFF_TO_WH = 1.0f / (1000000.0f * 3600.0f);
static constexpr uint8_t HEADER_OK = 0x55;
static constexpr uint8_t HEADER_NOT_CALIBRATED = 0xAA;
static constexpr uint8_t HEADER_VOLTAGE_CYCLE_EXCEEDS = 1 << 3;
static constexpr uint8_t HEADER_CURRENT_CYCLE_EXCEEDS = 1 << 2;
static constexpr uint8_t HEADER_POWER_CYCLE_EXCEEDS = 1 << 1;
static constexpr uint8_t HEADER_COEFF_STORAGE_ABNORMAL = 1 << 0;
static constexpr uint8_t HEADER2 = 0x5A;
// Adjustment byte: which registers hold a new measurement
static constexpr uint8_t ADJ_POWER = 0x10;
static constexpr uint8_t ADJ_CURRENT = 0x20;
static constexpr uint8_t ADJ_VOLTAGE = 0x40;
void CSE7766Component::loop() {
const uint32_t now = App.get_loop_component_start_time();
if (now - this->last_transmission_ >= 500) {
// last transmission too long ago. Reset RX index.
this->raw_data_index_ = 0;
}
// Early return prevents updating last_transmission_ when no data is available.
size_t avail = this->available();
if (avail == 0) {
if (avail == 0)
return;
}
const uint32_t now = App.get_loop_component_start_time();
if (now - this->last_transmission_ >= RX_RESET_TIMEOUT_MS)
this->raw_data_index_ = 0;
this->last_transmission_ = now;
// Read all available bytes in batches to reduce UART call overhead.
// At 4800 baud (~480 bytes/sec) with ~122 Hz loop rate, typically ~4 bytes per call.
this->read_available<CSE7766_RAW_DATA_SIZE>(
// At 4800 baud (~480 bytes/sec) with ~122 Hz loop rate, typically ~4 bytes per call
this->read_available<RAW_DATA_SIZE>(
[this](uint8_t byte) {
this->raw_data_[this->raw_data_index_] = byte;
if (!this->check_byte_()) {
const uint8_t index = this->raw_data_index_;
this->raw_data_[index] = byte;
if (!this->check_byte_(index, byte)) {
this->raw_data_index_ = 0;
this->status_set_warning();
return;
}
if (this->raw_data_index_ == CSE7766_RAW_DATA_SIZE - 1) {
this->parse_data_();
this->status_clear_warning();
if (index == RAW_DATA_SIZE - 1) {
this->raw_data_index_ = 0;
this->status_comm_result(this->parse_data_(), LOG_STR("Chip reports an error"));
return;
}
this->raw_data_index_ = (this->raw_data_index_ + 1) % CSE7766_RAW_DATA_SIZE;
this->raw_data_index_ = index + 1;
},
avail);
}
bool CSE7766Component::check_byte_() {
uint8_t index = this->raw_data_index_;
uint8_t byte = this->raw_data_[index];
if (index == 0) {
return (byte == 0x55) || ((byte & 0xF0) == 0xF0) || (byte == 0xAA);
}
bool CSE7766Component::check_byte_(uint8_t index, uint8_t byte) const {
if (index == 0)
return byte == HEADER_OK || high_nibble(byte) == 0xF || byte == HEADER_NOT_CALIBRATED;
if (index == 1) {
if (byte != 0x5A) {
ESP_LOGV(TAG, "Invalid Header 2 Start: 0x%02X!", byte);
return false;
}
return true;
if (byte == HEADER2)
return true;
ESP_LOGV(TAG, "Invalid Header 2 Start: 0x%02X!", byte);
return false;
}
if (index == CSE7766_RAW_DATA_SIZE - 1) {
const uint8_t checksum = sum_bytes(this->raw_data_ + 2, CSE7766_RAW_DATA_SIZE - 3);
if (checksum != this->raw_data_[CSE7766_RAW_DATA_SIZE - 1]) {
ESP_LOGW(TAG, "Invalid checksum from CSE7766: 0x%02X != 0x%02X", checksum,
this->raw_data_[CSE7766_RAW_DATA_SIZE - 1]);
if (index == RAW_DATA_SIZE - 1) {
const uint8_t checksum = sum_bytes(this->raw_data_ + 2, RAW_DATA_SIZE - 3);
if (checksum != byte) {
ESP_LOGW(TAG, "Invalid checksum from CSE7766: 0x%02X != 0x%02X", checksum, byte);
return false;
}
return true;
}
return true;
}
void CSE7766Component::parse_data_() {
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
{
char hex_buf[format_hex_pretty_size(CSE7766_RAW_DATA_SIZE)];
ESP_LOGVV(TAG, "Raw data: %s", format_hex_pretty_to(hex_buf, this->raw_data_, sizeof(this->raw_data_)));
}
#endif
// Parse header
uint8_t header1 = this->raw_data_[0];
bool CSE7766Component::parse_data_() {
ESP_LOGVV_HEX(TAG, this->raw_data_, RAW_DATA_SIZE, RAW_DATA_SIZE, "Raw data: %s");
if (header1 == 0xAA) {
const uint8_t header1 = this->raw_data_[0];
if (header1 == HEADER_NOT_CALIBRATED) {
ESP_LOGE(TAG, "CSE7766 not calibrated!");
return;
return false;
}
bool power_cycle_exceeds_range = false;
if ((header1 & 0xF0) == 0xF0) {
if (header1 & 0xD) {
// 0xFx: the low nibble holds error bits
if (high_nibble(header1) == 0xF) {
if (header1 & (HEADER_VOLTAGE_CYCLE_EXCEEDS | HEADER_CURRENT_CYCLE_EXCEEDS | HEADER_COEFF_STORAGE_ABNORMAL)) {
ESP_LOGE(TAG, "CSE7766 reports abnormal external circuit or chip damage: (0x%02X)", header1);
if (header1 & (1 << 3)) {
if (header1 & HEADER_VOLTAGE_CYCLE_EXCEEDS) {
ESP_LOGE(TAG, " Voltage cycle exceeds range.");
}
if (header1 & (1 << 2)) {
if (header1 & HEADER_CURRENT_CYCLE_EXCEEDS) {
ESP_LOGE(TAG, " Current cycle exceeds range.");
}
if (header1 & (1 << 0)) {
if (header1 & HEADER_COEFF_STORAGE_ABNORMAL) {
ESP_LOGE(TAG, " Coefficient storage area is abnormal.");
}
// Datasheet: voltage or current cycle exceeding range means invalid values
return;
return false;
}
power_cycle_exceeds_range = header1 & (1 << 1);
power_cycle_exceeds_range = header1 & HEADER_POWER_CYCLE_EXCEEDS;
}
// Parse data frame
uint32_t voltage_coeff = this->get_24_bit_uint_(2);
uint32_t voltage_cycle = this->get_24_bit_uint_(5);
uint32_t current_coeff = this->get_24_bit_uint_(8);
uint32_t current_cycle = this->get_24_bit_uint_(11);
uint32_t power_coeff = this->get_24_bit_uint_(14);
uint32_t power_cycle = this->get_24_bit_uint_(17);
uint8_t adj = this->raw_data_[20];
uint16_t cf_pulses = (this->raw_data_[21] << 8) + this->raw_data_[22];
const uint8_t *d = this->raw_data_;
uint32_t voltage_coeff = encode_uint24(d[2], d[3], d[4]);
uint32_t voltage_cycle = encode_uint24(d[5], d[6], d[7]);
uint32_t current_coeff = encode_uint24(d[8], d[9], d[10]);
uint32_t current_cycle = encode_uint24(d[11], d[12], d[13]);
uint32_t power_coeff = encode_uint24(d[14], d[15], d[16]);
uint32_t power_cycle = encode_uint24(d[17], d[18], d[19]);
uint8_t adj = d[20];
uint16_t cf_pulses = encode_uint16(d[21], d[22]);
bool have_power = adj & 0x10;
bool have_current = adj & 0x20;
bool have_voltage = adj & 0x40;
bool have_power = adj & ADJ_POWER;
bool have_current = adj & ADJ_CURRENT;
bool have_voltage = adj & ADJ_VOLTAGE;
float voltage = 0.0f;
if (have_voltage) {
@@ -132,7 +130,7 @@ void CSE7766Component::parse_data_() {
PUBLISH_STATE(this->voltage_sensor_, voltage);
}
float energy = 0.0;
float energy = 0.0f;
if (this->energy_sensor_ != nullptr) {
if (this->cf_pulses_last_ == 0 && !this->energy_sensor_->has_state()) {
this->cf_pulses_last_ = cf_pulses;
@@ -140,7 +138,7 @@ void CSE7766Component::parse_data_() {
uint16_t cf_diff = cf_pulses - this->cf_pulses_last_;
this->cf_pulses_total_ += cf_diff;
this->cf_pulses_last_ = cf_pulses;
energy = this->cf_pulses_total_ * float(power_coeff) / 1000000.0f / 3600.0f;
energy = this->cf_pulses_total_ * float(power_coeff) * PULSE_COEFF_TO_WH;
this->energy_sensor_->publish_state(energy);
}
@@ -149,37 +147,30 @@ void CSE7766Component::parse_data_() {
// Datasheet: power cycle exceeding range means active power is 0
have_power = true;
this->last_power_cycle_ = 0;
PUBLISH_STATE(this->power_sensor_, 0.0f);
} else if (have_power) {
power = power_coeff / float(power_cycle);
this->last_power_cycle_ = power_cycle;
PUBLISH_STATE(this->power_sensor_, power);
} else if (this->last_power_cycle_ > MIN_HELD_POWER_CYCLE && power_cycle <= 2 * this->last_power_cycle_) {
// No new measurement in this frame. With cycles over 1 s the register holds the last
// cycle or the time elapsed since the last pulse. While that time is within twice the
// last cycle, the next pulse is not overdue, so the last measurement still applies.
// Shorter cycles never get here in normal operation and keep the previous behaviour.
// Shorter cycles never get here in normal operation.
have_power = true;
power = power_coeff / float(this->last_power_cycle_);
PUBLISH_STATE(this->power_sensor_, power);
} else {
// The next pulse is overdue: the load has dropped, report 0 W. A load that drops to less
// than half also reads 0 W here until its first new pulse arrives.
this->last_power_cycle_ = 0;
PUBLISH_STATE(this->power_sensor_, 0.0f);
}
PUBLISH_STATE(this->power_sensor_, power);
// Without a power measurement the current is likely below the 50 mA the chip can measure;
// P > I_min·U is P/U > I_min without the division
const bool current_measurable = have_power && voltage > 1.0f && power > MIN_CURRENT_A * voltage;
float current = 0.0f;
float calculated_current = 0.0f;
if (have_current) {
// Assumption: if we don't have power measurement, then current is likely below 50mA
if (have_power && voltage > 1.0f) {
calculated_current = power / voltage;
}
// Datasheet: minimum measured current is 50mA
if (calculated_current > 0.05f) {
if (current_measurable)
current = current_coeff / float(current_cycle);
}
PUBLISH_STATE(this->current_sensor_, current);
}
@@ -196,7 +187,7 @@ void CSE7766Component::parse_data_() {
this->reactive_power_sensor_->publish_state(std::sqrt(q_squared));
}
}
if (this->power_factor_sensor_ != nullptr && (have_power || power_cycle_exceeds_range)) {
if (this->power_factor_sensor_ != nullptr && have_power) {
float pf = NAN;
if (apparent_power > 0) {
pf = power / apparent_power;
@@ -209,8 +200,7 @@ void CSE7766Component::parse_data_() {
} else if (apparent_power == 0 && power == 0) {
// No load, report ideal power factor
pf = 1.0f;
} else if (current == 0 && calculated_current <= 0.05f) {
// Datasheet: minimum measured current is 50mA
} else if (current == 0 && !current_measurable) {
ESP_LOGV(TAG, "Can't calculate power factor (current below minimum for CSE7766)");
} else {
ESP_LOGW(TAG, "Can't calculate power factor from P = %.4f W, S = %.4f VA", power, apparent_power);
@@ -221,10 +211,9 @@ void CSE7766Component::parse_data_() {
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERY_VERBOSE
{
// Buffer: 7 + 15 + 33 + 15 + 25 = 95 chars max + null, rounded to 128 for safety margin.
// Float sizes with %.4f can be up to 11 chars for large values (e.g., 999999.9999).
char buf[128];
size_t pos = buf_append_printf(buf, sizeof(buf), 0, "Parsed:");
const float calculated_current = have_power && voltage > 1.0f ? power / voltage : 0.0f;
char buf[128]; // five fields at %.4f fit with room to spare
size_t pos = buf_append_str(buf, sizeof(buf), 0, "Parsed:");
if (have_voltage) {
pos = buf_append_printf(buf, sizeof(buf), pos, " V=%.4fV", voltage);
}
@@ -241,6 +230,7 @@ void CSE7766Component::parse_data_() {
ESP_LOGVV(TAG, "%s", buf);
}
#endif
return true;
}
void CSE7766Component::dump_config() {
+6 -9
View File
@@ -7,8 +7,6 @@
namespace esphome::cse7766 {
static constexpr size_t CSE7766_RAW_DATA_SIZE = 24;
class CSE7766Component final : public Component, public uart::UARTDevice {
SUB_SENSOR(voltage)
SUB_SENSOR(current)
@@ -23,14 +21,13 @@ class CSE7766Component final : public Component, public uart::UARTDevice {
void dump_config() override;
protected:
bool check_byte_();
void parse_data_();
uint32_t get_24_bit_uint_(uint8_t start_index) const {
return encode_uint24(this->raw_data_[start_index], this->raw_data_[start_index + 1],
this->raw_data_[start_index + 2]);
}
static constexpr size_t RAW_DATA_SIZE = 24;
uint8_t raw_data_[CSE7766_RAW_DATA_SIZE];
bool check_byte_(uint8_t index, uint8_t byte) const;
/// Returns false when the frame reports an error instead of measurements.
bool parse_data_();
uint8_t raw_data_[RAW_DATA_SIZE];
uint8_t raw_data_index_{0};
uint16_t cf_pulses_last_{0};
uint32_t last_transmission_{0};
+29 -15
View File
@@ -180,18 +180,23 @@ void ArduinoI2CBus::recover_() {
return;
}
// Activate input and pull up resistor for the SDA pin, so it can be read during the pulses.
pinMode(this->sda_pin_, INPUT_PULLUP); // NOLINT
// From the specification:
// "If the data line (SDA) is stuck LOW, send nine clock pulses. The
// device that held the bus LOW should release it sometime within
// those nine clocks."
// We don't really have to detect if SDA is stuck low. We'll simply send
// nine clock pulses here, just in case SDA is stuck. Actual checks on
// the SDA line status will be done after the clock pulses.
// Make sure that switching to output mode will make SCL low, just in
// case other code has setup the pin for a HIGH signal.
digitalWrite(this->scl_pin_, LOW); // NOLINT
delayMicroseconds(half_period_usec);
// Spec: "If the data line (SDA) is stuck LOW, send nine clock pulses."
// Pulse only while SDA is low: a device receiving a write ACKs every ninth pulse.
for (auto i = 0; i < 9 && digitalRead(this->sda_pin_) == LOW; i++) { // NOLINT
// Drive LOW. Set the level while the pin is a plain input: on RP2040 a write to an
// INPUT_PULLUP pin drives it, which would leave SCL low if the loop never runs.
pinMode(this->scl_pin_, INPUT); // NOLINT
digitalWrite(this->scl_pin_, LOW); // NOLINT
pinMode(this->scl_pin_, OUTPUT); // NOLINT
for (auto i = 0; i < 9; i++) {
// Release pull up resistor and switch to output to make the signal LOW.
pinMode(this->scl_pin_, INPUT); // NOLINT
pinMode(this->scl_pin_, OUTPUT); // NOLINT
delayMicroseconds(half_period_usec);
// Release output and activate pull up resistor to make the signal HIGH.
@@ -218,7 +223,14 @@ void ArduinoI2CBus::recover_() {
}
}
// A device still holding SDA after nine pulses cannot be freed here.
// Activate input and pull resistor for the SDA pin, so we can verify
// that SDA is pulled HIGH in the following step.
pinMode(this->sda_pin_, INPUT_PULLUP); // NOLINT
digitalWrite(this->sda_pin_, LOW); // NOLINT
// By now, any stuck device ought to have sent all remaining bits of its
// transaction, meaning that it should have freed up the SDA line, resulting
// in SDA being pulled up.
if (digitalRead(this->sda_pin_) == LOW) { // NOLINT
ESP_LOGE(TAG, "Recovery failed: SDA is held LOW after clock pulse cycle");
this->recovery_result_ = RECOVERY_FAILED_SDA_LOW;
@@ -230,13 +242,15 @@ void ArduinoI2CBus::recover_() {
// a START or repeated START condition such that they all anticipate
// the sending of a target address, even if these START conditions are
// not positioned according to the proper format."
// SDA high does not mean the device is idle (it may be mid-byte); the START resets it.
// While the 9 clock pulses from above might have drained all bits of a
// single byte within a transaction, a device might have more bytes to
// transmit. So here we'll generate a START condition to snap the device
// out of this state.
// SCL and SDA are already high at this point, so we can generate a START
// condition by making the SDA signal LOW.
delayMicroseconds(half_period_usec);
pinMode(this->sda_pin_, INPUT); // NOLINT
digitalWrite(this->sda_pin_, LOW); // NOLINT
pinMode(this->sda_pin_, OUTPUT); // NOLINT
pinMode(this->sda_pin_, INPUT); // NOLINT
pinMode(this->sda_pin_, OUTPUT); // NOLINT
// From the specification:
// "A START condition immediately followed by a STOP condition (void
+15 -5
View File
@@ -346,9 +346,14 @@ void IDFI2CBus::recover_() {
return;
}
// Spec: "If the data line (SDA) is stuck LOW, send nine clock pulses."
// Pulse only while SDA is low: a device receiving a write ACKs every ninth pulse.
for (auto i = 0; i < 9 && gpio_get_level(sda_pin) == 0; i++) {
// From the specification:
// "If the data line (SDA) is stuck LOW, send nine clock pulses. The
// device that held the bus LOW should release it sometime within
// those nine clocks."
// We don't really have to detect if SDA is stuck low. We'll simply send
// nine clock pulses here, just in case SDA is stuck. Actual checks on
// the SDA line status will be done after the clock pulses.
for (auto i = 0; i < 9; i++) {
gpio_set_level(scl_pin, 0);
delayMicroseconds(half_period_usec);
gpio_set_level(scl_pin, 1);
@@ -373,7 +378,9 @@ void IDFI2CBus::recover_() {
}
}
// A device still holding SDA after nine pulses cannot be freed here.
// By now, any stuck device ought to have sent all remaining bits of its
// transaction, meaning that it should have freed up the SDA line, resulting
// in SDA being pulled up.
if (gpio_get_level(sda_pin) == 0) {
ESP_LOGE(TAG, "Recovery failed: SDA is held LOW after clock pulse cycle");
this->recovery_result_ = RECOVERY_FAILED_SDA_LOW;
@@ -385,7 +392,10 @@ void IDFI2CBus::recover_() {
// a START or repeated START condition such that they all anticipate
// the sending of a target address, even if these START conditions are
// not positioned according to the proper format."
// SDA high does not mean the device is idle (it may be mid-byte); the START resets it.
// While the 9 clock pulses from above might have drained all bits of a
// single byte within a transaction, a device might have more bytes to
// transmit. So here we'll generate a START condition to snap the device
// out of this state.
// SCL and SDA are already high at this point, so we can generate a START
// condition by making the SDA signal LOW.
delayMicroseconds(half_period_usec);
-165
View File
@@ -1,165 +0,0 @@
#include "at_reply.h"
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <strings.h>
namespace esphome::modem {
bool collect_reply(char *buf, size_t size, size_t &len, const char *data, size_t data_len, bool whole) {
const size_t capacity = size - 1;
if (whole) {
len = 0;
}
bool dropped = false;
if (data_len > capacity) {
memcpy(buf, data + data_len - capacity, capacity);
len = capacity;
dropped = true;
} else {
if (len + data_len > capacity) {
const size_t drop = len + data_len - capacity;
memmove(buf, buf + drop, len - drop);
len -= drop;
dropped = true;
}
memcpy(buf + len, data, data_len);
len += data_len;
}
buf[len] = '\0';
return dropped;
}
ReplyEnd reply_end(const char *data, size_t len, bool skip_first) {
const char *end = data + len;
const char *line = data;
if (skip_first) {
const auto *newline = static_cast<const char *>(memchr(data, '\n', len));
line = newline != nullptr ? newline + 1 : end;
}
while (line < end) {
const auto *newline = static_cast<const char *>(memchr(line, '\n', end - line));
if (newline == nullptr) {
break; // the line has not ended yet
}
size_t size = newline - line;
if (size != 0 && line[size - 1] == '\r') {
size--;
}
if (size == 2 && memcmp(line, "OK", 2) == 0) {
return ReplyEnd::REPLY_END_OK;
}
// esp_modem drops a CMUX frame without a line end, so the ": <reason>" part may be missing
if ((size == 5 && memcmp(line, "ERROR", 5) == 0) || (size >= 10 && memcmp(line, "+CME ERROR", 10) == 0) ||
(size >= 10 && memcmp(line, "+CMS ERROR", 10) == 0)) {
return ReplyEnd::REPLY_END_ERROR;
}
line = newline + 1;
}
return ReplyEnd::REPLY_END_NONE;
}
size_t flatten_reply(char *reply, size_t len) {
for (size_t i = 0; i < len; i++) {
if (reply[i] == '\r' || reply[i] == '\n') {
reply[i] = ' ';
}
}
while (len != 0 && reply[len - 1] == ' ') {
len--;
}
if (len >= 2 && memcmp(reply + len - 2, "OK", 2) == 0 && (len == 2 || reply[len - 3] == ' ')) {
len -= 2;
while (len != 0 && reply[len - 1] == ' ') {
len--;
}
}
size_t start = 0;
while (start < len && reply[start] == ' ') {
start++;
}
len -= start;
memmove(reply, reply + start, len);
reply[len] = '\0';
return len;
}
int registration_from_reply(const char *reply, const char *prefix) {
const size_t prefix_len = strlen(prefix);
for (const char *line = strstr(reply, prefix); line != nullptr; line = strstr(line + 1, prefix)) {
const char *start = line + prefix_len;
char *end = nullptr;
strtol(start, &end, 10);
if (end == start || *end != ',') {
continue;
}
start = end + 1;
const auto stat = static_cast<int32_t>(strtol(start, &end, 10));
if (end != start) {
return stat;
}
}
return REGISTRATION_UNKNOWN;
}
int merge_registration(int lte, int legacy) {
// A multimode modem can be registered or still searching on one network type while the other refuses it
if (is_registered(lte)) {
return lte;
}
if (is_registered(legacy)) {
return legacy;
}
// A definite answer from one query outweighs a timeout of the other
if (lte == REGISTRATION_SEARCHING || legacy == REGISTRATION_SEARCHING) {
return REGISTRATION_SEARCHING;
}
if (lte == REGISTRATION_DENIED || legacy == REGISTRATION_DENIED) {
return REGISTRATION_DENIED;
}
if (lte >= 0 || legacy >= 0) {
return lte >= 0 ? lte : legacy;
}
if (lte == REGISTRATION_NO_ANSWER || legacy == REGISTRATION_NO_ANSWER) {
return REGISTRATION_NO_ANSWER;
}
if (lte == REGISTRATION_UNSUPPORTED && legacy == REGISTRATION_UNSUPPORTED) {
return REGISTRATION_UNSUPPORTED;
}
return REGISTRATION_UNKNOWN;
}
bool reply_names_unsupported(const char *reply) {
static constexpr char PREFIX[] = "+CME ERROR:";
static constexpr char TEXT[] = "operation not supported";
const char *code = strstr(reply, PREFIX);
if (code == nullptr) {
return false;
}
code += sizeof(PREFIX) - 1;
while (*code == ' ') {
code++;
}
return strncasecmp(code, TEXT, sizeof(TEXT) - 1) == 0 || (code[0] == '4' && !isdigit(code[1]));
}
const char *sim_status(char *reply) {
static constexpr char PREFIX[] = "+CPIN:";
char *status = strstr(reply, PREFIX);
if (status == nullptr) {
return nullptr;
}
status += sizeof(PREFIX) - 1;
while (*status == ' ') {
status++;
}
// A URC in the same reply follows on its own line, which flatten_reply() turned into two spaces
char *end = strstr(status, " ");
if (end != nullptr) {
*end = '\0';
}
return status;
}
} // namespace esphome::modem
-67
View File
@@ -1,67 +0,0 @@
#pragma once
#include <cstddef>
#include <cstdint>
// Parsers for raw AT replies; free of esp_modem so they build and run in host unit tests
namespace esphome::modem {
enum class ReplyEnd : uint8_t {
REPLY_END_NONE, // no complete final result line yet
REPLY_END_OK, // an OK line
REPLY_END_ERROR, // an ERROR, +CME ERROR: or +CMS ERROR: line
};
// AT+CEREG? and AT+CREG? <stat> values (3GPP TS 27.007)
static constexpr int REGISTRATION_NOT_SEARCHING = 0;
static constexpr int REGISTRATION_HOME = 1;
static constexpr int REGISTRATION_SEARCHING = 2;
static constexpr int REGISTRATION_DENIED = 3;
static constexpr int REGISTRATION_REPORTED_UNKNOWN = 4;
static constexpr int REGISTRATION_ROAMING = 5;
static constexpr int REGISTRATION_SMS_ONLY_HOME = 6;
static constexpr int REGISTRATION_SMS_ONLY_ROAMING = 7;
static constexpr int REGISTRATION_EMERGENCY_ONLY = 8;
static constexpr int REGISTRATION_CSFB_NOT_PREFERRED_HOME = 9;
static constexpr int REGISTRATION_CSFB_NOT_PREFERRED_ROAMING = 10;
// Results beyond the 3GPP values
static constexpr int REGISTRATION_UNKNOWN = -1; // no readable answer
static constexpr int REGISTRATION_UNSUPPORTED = -2; // the query is not supported
static constexpr int REGISTRATION_NO_ANSWER = -3; // the query timed out
/// Registered on a network, so the data attach can be requested. SMS only and "CSFB not preferred" limit the
/// circuit switched side, not the packet data attach; emergency only (8) is not a registration.
inline bool is_registered(int registration) {
return registration == REGISTRATION_HOME || registration == REGISTRATION_ROAMING ||
(registration >= REGISTRATION_SMS_ONLY_HOME && registration <= REGISTRATION_SMS_ONLY_ROAMING) ||
(registration >= REGISTRATION_CSFB_NOT_PREFERRED_HOME &&
registration <= REGISTRATION_CSFB_NOT_PREFERRED_ROAMING);
}
/// Add data to the reply in buf (size includes the terminator, len is the current length). With whole, data is
/// everything received so far (UART) and replaces the reply; otherwise it is one new CMUX frame and is appended. A
/// reply longer than the buffer keeps its newest bytes, where the final line is. Returns true when bytes were dropped.
bool collect_reply(char *buf, size_t size, size_t &len, const char *data, size_t data_len, bool whole);
/// How the reply ends. Only a complete final result line counts, so ERROR inside a payload line does not; a +CME ERROR
/// line counts even without its reason, which a dropped CMUX frame can take away. With
/// skip_first, the first line is a cut-off fragment and is ignored.
ReplyEnd reply_end(const char *data, size_t len, bool skip_first);
/// Puts a raw reply on one line for the log and drops the final OK; returns the new length
size_t flatten_reply(char *reply, size_t len);
/// The <stat> after the first comma of the "<n>,<stat>" line starting with prefix (+CREG: and friends), or
/// REGISTRATION_UNKNOWN; a one-field line is an unsolicited notification and is skipped
int registration_from_reply(const char *reply, const char *prefix);
/// The state that tells most from the AT+CEREG? (LTE) and AT+CREG? (2G and 3G) results
int merge_registration(int lte, int legacy);
/// Whether an error reply says the command is not supported (+CME ERROR: 4 or its verbose text)
bool reply_names_unsupported(const char *reply);
/// The SIM status in a flattened AT+CPIN? reply, cut before any following line, or nullptr
const char *sim_status(char *reply);
} // namespace esphome::modem
+47 -296
View File
@@ -1,6 +1,5 @@
#ifdef USE_ESP32
#include "modem_component.h"
#include "at_reply.h"
#include "soc/soc_caps.h"
#include <driver/uart.h>
@@ -43,14 +42,6 @@ static constexpr uint32_t PROBE_TIMEOUT_MS = 100;
// A silent modem is not going to answer the next second, so its probes are spaced out, doubling up to a minute
static constexpr uint32_t PROBE_RETRY_DELAY_MS = 5000;
static constexpr uint32_t PROBE_RETRY_MAX_MS = 60000;
// A modem in command mode answers the ATE0 sent before the mode detection within this time
static constexpr uint32_t ECHO_OFF_TIMEOUT_MS = 100;
// The +++ escape needs a second of silence before it; esp_modem waits for the answer after it
static constexpr uint32_t ESCAPE_GUARD_MS = 1100;
// A SIM7670 left in CMUX by an ESP reset ignores every frame until this many flag bytes overflow its receive buffer;
// it then reinitialises its AT channel within about 2 s
static constexpr size_t CMUX_FLUSH_BYTES = 4096;
static constexpr uint32_t CMUX_FLUSH_SETTLE_MS = 3000;
// How long the task waits for the main loop to run on_sync before attaching
static constexpr uint32_t SYNC_ACK_TIMEOUT_MS = 5000;
// esp_modem's command strings and the log lines are built on this stack
@@ -65,12 +56,6 @@ static constexpr uint8_t PIN_MAX_UNCONFIRMED_SENDS = 2;
// The attachment is polled every 4 s; the signal and operator queries only every 4th poll
static constexpr uint32_t ATTACH_POLL_MS = 4000;
static constexpr uint8_t ATTACH_DIAG_EVERY = 4;
static constexpr uint8_t ATTACH_UNKNOWN_POLLS = 15; // about a minute of polls
// AT+CGATT=1: SIMCom documents up to 75 s, but a SIM7080G that is not registered yet held it for 141 s
static constexpr uint32_t ATTACH_TIMEOUT_MS = 150000;
// SIM status polls that fail before a warning, and between repeats of it
static constexpr uint8_t SIM_WARN_AFTER = 10;
static constexpr uint8_t SIM_WARN_EVERY = 60;
static constexpr int RADIO_STATE_MINIMUM = 0; // CFUN=0: radio off and the SIM powered down
static constexpr int RADIO_STATE_RF_OFF = 4; // CFUN=4: transmit and receive off, SIM still powered
static constexpr uint8_t UART_EVENT_QUEUE_SIZE = 10;
@@ -88,22 +73,8 @@ static const LogString *state_to_str(ModemState state) {
// Indexed by ModemFault
PROGMEM_STRING_TABLE(ModemFaultStrings, "", "Modem not responding", "Configured baud rate failed",
"init_at command failed", "SIM not ready", "SIM locked", "SIM PIN not sent; check pin_code",
"PIN record not saved", "APN or radio setup failed", "No network attachment",
"Network registration denied", "PPP link failed", "Modem teardown failed");
// Indexed by the AT+CEREG? <stat> value
PROGMEM_STRING_TABLE(RegistrationStrings, "not searching", "registered", "searching", "denied", "unknown", "roaming",
"registered for SMS only", "roaming for SMS only", "emergency only",
"registered, CSFB not preferred", "roaming, CSFB not preferred", "other");
static const LogString *registration_to_str(int registration) {
if (registration == REGISTRATION_UNSUPPORTED) {
return LOG_STR("not supported");
}
if (registration < 0) {
return LOG_STR("not reported");
}
return RegistrationStrings::get_log_str(static_cast<uint8_t>(registration), RegistrationStrings::LAST_INDEX);
}
"PIN record not saved", "APN or radio setup failed", "No network attachment", "PPP link failed",
"Modem teardown failed");
// Indexed by esp_modem::command_result
PROGMEM_STRING_TABLE(CommandResultStrings, "OK", "FAIL", "TIMEOUT");
@@ -615,9 +586,6 @@ ModemState ModemComponent::compute_next_state_() {
}
ModemState ModemComponent::handle_state_enabling_() {
// With echo on (SIM7670G after power-up), the modem sends esp_modem's PPP probe back and the detection takes it for
// a PPP reply; in PPP or CMUX these bytes are dropped as a bad frame
this->at_reply_("ATE0", ECHO_OFF_TIMEOUT_MS);
// Find the baud rate the modem answers at and leave it in command mode, synced
if (!this->dce_->set_mode(modem_mode::AUTODETECT)) {
// A failed detection keeps the previous mode, which would skip the baud rate search below
@@ -643,18 +611,21 @@ ModemState ModemComponent::handle_state_enabling_() {
exited = false;
const int bauds[] = {this->restored_baud_, this->baud_rate_, FALLBACK_BAUD_RATE};
bool found = false;
bool probed = false;
bool rejected = false;
for (size_t i = 0; i != std::size(bauds) && !found; i++) {
const int baud = bauds[i];
if (baud == 0 || baud == detected || std::find(bauds, bauds + i, baud) != bauds + i) {
continue;
}
if (this->set_uart_baud_(baud) != ESP_OK) {
if (uart_set_baudrate(static_cast<uart_port_t>(this->uart_port_), baud) != ESP_OK) {
ESP_LOGW(TAG, "UART rejected baud rate %d", baud);
this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
rejected = true;
continue;
}
this->current_baud_rate_ = baud;
probed = true;
std::string output;
found = this->dce_->at("AT", output, PROBE_TIMEOUT_MS) == command_result::OK;
if (!found) {
@@ -662,31 +633,11 @@ ModemState ModemComponent::handle_state_enabling_() {
}
}
if (!found) {
// A modem left in data mode before PPP started, or stuck in CMUX, answers none of the probes; both recoveries
// go out at the rate the detection used
if (this->current_baud_rate_ != detected) {
const esp_err_t err = this->set_uart_baud_(detected);
if (err != ESP_OK) {
ESP_LOGW(TAG, "UART rejected baud rate %d (%s); data mode and CMUX recovery skipped", detected,
esp_err_to_name(err));
this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
rejected = true;
}
}
// The escape before the flush is what a stuck SIM7670G responds to; the order is measured, not arbitrary
if (this->current_baud_rate_ == detected && (this->escape_data_mode_() || this->flush_cmux_())) {
exited = true;
break;
}
// A UART that refused a rate set BAUD
if (!rejected) {
// The detection at the current rate already failed; a UART that refused every other rate set BAUD
if (!probed && !rejected) {
this->not_responding_(detected);
}
const uint32_t delay_ms = this->next_probe_delay_();
if (delay_ms == PROBE_RETRY_MAX_MS) {
this->answered_ = false; // silent for minutes, so the wiring hint applies again
}
return this->retry_(ModemState::MODEM_STATE_ENABLING, delay_ms);
return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
}
ESP_LOGD(TAG, "Modem responded at baud %d", this->current_baud_rate_);
break;
@@ -720,19 +671,10 @@ ModemState ModemComponent::handle_state_enabling_() {
this->set_fault_(ModemFault::MODEM_FAULT_TEARDOWN);
return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
}
// The modem answers AT, so it is in command mode. A failed data mode exit leaves esp_modem's UART side in data mode,
// from where its later switch to CMUX fails at once, so its mode is set to match; this sends nothing to the modem.
if (!this->dce_->set_mode(modem_mode::RESUME_COMMAND_MODE)) {
ESP_LOGW(TAG, "esp_modem refused command mode; the switch to PPP may fail");
}
// esp_modem keeps the last line before OK as the reply, which can be the echoed command
if (this->dce_->set_echo(false) != command_result::OK) {
ESP_LOGW(TAG, "Failed to disable command echo");
}
// Verbose +CME ERROR text, so a failed command or a missing SIM says why; a modem without it keeps plain ERROR
if (this->dce_->config_mobile_termination_error(2) != command_result::OK) {
ESP_LOGW(TAG, "Modem refused verbose errors (AT+CMEE=2)");
}
// The SIM7670G only uses an APN written at CFUN=0 (else the attach fails with an ESM failure); CFUN=0 also drops a
// session left by a warm reboot. A modem that refuses gets the APN after the SIM check instead, as before.
@@ -748,7 +690,6 @@ ModemState ModemComponent::handle_state_enabling_() {
ESP_LOGW(TAG, "Failed to power the SIM up");
this->set_fault_(ModemFault::MODEM_FAULT_SETUP);
this->modem_synced_ = true; // it answers, so a disable() still tears it down
this->answered_ = true;
return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
}
this->probe_backoff_.store(0, std::memory_order_relaxed);
@@ -757,11 +698,12 @@ ModemState ModemComponent::handle_state_enabling_() {
ESP_LOGD(TAG, "Setting baud rate: %d -> %d", this->current_baud_rate_, this->baud_rate_);
if (this->dce_->set_baud(this->baud_rate_) == command_result::OK) {
delay(200); // NOLINT
if (this->set_uart_baud_(this->baud_rate_) != ESP_OK) {
if (uart_set_baudrate(static_cast<uart_port_t>(this->uart_port_), this->baud_rate_) != ESP_OK) {
ESP_LOGE(TAG, "UART rejected baud rate %d", this->baud_rate_);
this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
return ModemState::MODEM_STATE_DISCONNECTING;
}
this->current_baud_rate_ = this->baud_rate_;
if (this->dce_->sync() != command_result::OK) {
ESP_LOGE(TAG, "Failed to sync modem at baud rate %d.", this->baud_rate_);
this->set_fault_(ModemFault::MODEM_FAULT_BAUD);
@@ -789,7 +731,6 @@ ModemState ModemComponent::handle_state_enabling_() {
ESP_LOGW(TAG, "Modem refused hardware flow control; UART overruns are possible");
}
this->modem_synced_ = true;
this->answered_ = true;
return ModemState::MODEM_STATE_SYNCED;
}
@@ -805,13 +746,12 @@ ModemState ModemComponent::handle_state_synced_() {
this->clear_config_fault_(ModemFault::MODEM_FAULT_INIT_AT);
}
this->connect_step_ = ConnectStep::CONNECT_STEP_START;
this->sim_polls_ = 0;
return ModemState::MODEM_STATE_CONNECTING;
}
ModemState ModemComponent::handle_state_connecting_() {
if (this->connect_step_ == ConnectStep::CONNECT_STEP_START) {
// ENABLING just synced; a command that timed out comes back here unsure of the modem
// ENABLING just synced; only a failed attachment read comes back here unsure of the modem
if (this->resync_) {
this->resync_ = false;
if (this->dce_->sync() != command_result::OK) {
@@ -852,78 +792,35 @@ ModemState ModemComponent::handle_state_connecting_() {
}
this->connect_step_ = ConnectStep::CONNECT_STEP_RADIO_ON;
this->attach_polls_ = 0;
this->idle_polls_ = 0;
this->unknown_polls_ = 0;
}
if (this->connect_step_ == ConnectStep::CONNECT_STEP_RADIO_ON) {
// A modem still searching for a network refuses this; the attachment poll asks again
if (this->dce_->set_network_attachment_state(1) != command_result::OK) {
ESP_LOGD(TAG, "Network attachment request refused");
}
this->connect_step_ = ConnectStep::CONNECT_STEP_ATTACH_REQUESTED;
}
int attached = 0;
if (this->dce_->get_network_attachment_state(attached) != command_result::OK) {
ESP_LOGW(TAG, "Failed to read the network attachment state");
this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
this->request_resync_();
this->connect_step_ = ConnectStep::CONNECT_STEP_START; // start over with a sync on the next pass
this->resync_ = true;
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
}
if (!attached) {
const int registration = this->read_registration_();
if (registration == REGISTRATION_NO_ANSWER) {
// The state is open, so the modem is checked with a sync instead
ESP_LOGW(TAG, "No answer to a registration query");
this->request_resync_();
this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
}
// "Not searching" for a few polls in a row means the attachment is off; right after CFUN=1 it is only brief
this->idle_polls_ = registration == REGISTRATION_NOT_SEARCHING ? static_cast<uint8_t>(this->idle_polls_ + 1) : 0;
const bool idle = this->idle_polls_ >= ATTACH_DIAG_EVERY;
// A state that cannot be read or means nothing here holds the request back only for a while
const bool unknown = registration == REGISTRATION_UNKNOWN || registration == REGISTRATION_REPORTED_UNKNOWN ||
(registration > REGISTRATION_ROAMING && !is_registered(registration));
this->unknown_polls_ = unknown ? static_cast<uint8_t>(this->unknown_polls_ + 1) : 0;
const bool unknown_too_long = this->unknown_polls_ >= ATTACH_UNKNOWN_POLLS;
if (this->connect_step_ == ConnectStep::CONNECT_STEP_RADIO_ON &&
(is_registered(registration) || registration == REGISTRATION_UNSUPPORTED || idle || unknown_too_long)) {
if (unknown_too_long) {
ESP_LOGI(TAG, "Registration state %d (%s) for %u polls; requesting the network attachment anyway", registration,
LOG_STR_ARG(registration_to_str(registration)), this->unknown_polls_);
this->unknown_polls_ = 0;
}
// Before registration a modem can hold the AT channel on this for minutes and drop every command meanwhile,
// so it waits for one; the fallbacks above send it anyway, and ATTACH_TIMEOUT_MS covers that hold
const command_result attach = this->at_reply_("AT+CGATT=1", ATTACH_TIMEOUT_MS);
if (attach == command_result::TIMEOUT) {
ESP_LOGW(TAG, "No answer to the network attachment request");
this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
this->request_resync_();
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
}
if (attach != command_result::OK) {
ESP_LOGW(TAG, "Network attachment request refused: %s", this->reply_);
}
this->connect_step_ = ConnectStep::CONNECT_STEP_ATTACH_REQUESTED;
return this->retry_(ModemState::MODEM_STATE_CONNECTING);
}
if (this->attach_polls_++ % ATTACH_DIAG_EVERY == 0) {
int rssi = 99, ber = 99, mode = -1; // -1 stays when the query fails
int rssi = 99, ber = 99, registration = -1, mode = -1; // -1 stays when the query fails
this->dce_->get_network_registration_state(registration);
this->dce_->get_signal_quality(rssi, ber);
this->dce_->get_network_system_mode(mode);
ESP_LOGW(TAG, "Modem not attached yet: registration %d (%s), network type %d, CSQ %d, BER %d", registration,
LOG_STR_ARG(registration_to_str(registration)), mode, rssi, ber);
if (unknown) {
ESP_LOGW(TAG, "Network attachment request held back while the registration state is unknown (%u of %u polls)",
this->unknown_polls_, ATTACH_UNKNOWN_POLLS);
}
if (registration == REGISTRATION_DENIED) {
// The modem's reason tells a rejected APN (ESM failure) from a SIM the network does not serve
const command_result reason_read = this->at_reply_("AT+CEER");
ESP_LOGW(TAG,
"The network refused registration (AT+CEER %s: %s); check the APN and that the SIM's plan covers "
"this modem's network types",
LOG_STR_ARG(result_to_str(reason_read)), this->reply_);
}
ESP_LOGW(TAG, "Modem not attached yet: registration %d, network type %d, CSQ %d, BER %d", registration, mode,
rssi, ber);
this->connect_step_ = ConnectStep::CONNECT_STEP_RADIO_ON; // request the attachment again
}
this->set_fault_(registration == REGISTRATION_DENIED ? ModemFault::MODEM_FAULT_REGISTRATION_DENIED
: ModemFault::MODEM_FAULT_NOT_ATTACHED);
this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
return this->retry_(ModemState::MODEM_STATE_CONNECTING, ATTACH_POLL_MS);
}
@@ -1026,114 +923,11 @@ void ModemComponent::transition_to_(ModemState next_state) {
}
}
esp_err_t ModemComponent::set_uart_baud_(int baud) {
const esp_err_t err = uart_set_baudrate(static_cast<uart_port_t>(this->uart_port_), baud);
if (err == ESP_OK) {
this->current_baud_rate_ = baud;
}
return err;
}
bool ModemComponent::escape_data_mode_() {
delay(ESCAPE_GUARD_MS); // NOLINT
if (this->dce_->set_command_mode() != command_result::OK) {
ESP_LOGD(TAG, "No answer after the data mode escape");
return false;
}
ESP_LOGW(TAG, "Modem was left in data mode; escaped to command mode");
return true;
}
bool ModemComponent::flush_cmux_() {
// With RTS/CTS a silent modem can hold CTS off; the flag bytes would then stay queued and block every later write
if (this->rts_pin_ != nullptr) {
ESP_LOGW(TAG, "CMUX recovery is not available with RTS/CTS flow control");
return false;
}
static constexpr uint8_t CMUX_FLAG = 0xF9;
uint8_t flags[64];
memset(flags, CMUX_FLAG, sizeof(flags));
const auto port = static_cast<uart_port_t>(this->uart_port_);
for (size_t sent = 0; sent < CMUX_FLUSH_BYTES; sent += sizeof(flags)) {
if (this->dte_->write(flags, sizeof(flags)) != static_cast<int>(sizeof(flags))) {
ESP_LOGW(TAG, "CMUX flush: short write after %u bytes", static_cast<unsigned>(sent));
return false;
}
}
// 10 bits per byte, plus a margin
const uint32_t send_ms = CMUX_FLUSH_BYTES * 10 * 1000 / this->current_baud_rate_ + 100;
if (uart_wait_tx_done(port, pdMS_TO_TICKS(send_ms)) != ESP_OK) {
ESP_LOGW(TAG, "CMUX flush: transmit not finished after %u ms", static_cast<unsigned>(send_ms));
return false;
}
delay(CMUX_FLUSH_SETTLE_MS); // NOLINT
if (this->dce_->sync() != command_result::OK) {
ESP_LOGD(TAG, "No answer after the CMUX flush");
return false;
}
ESP_LOGW(TAG, "Modem was stuck in CMUX; reset it to command mode");
return true;
}
// A command timed out: the next pass checks with a sync that the modem still answers
void ModemComponent::request_resync_() {
this->connect_step_ = ConnectStep::CONNECT_STEP_START;
this->resync_ = true;
}
// One registration query: the <stat>, REGISTRATION_UNSUPPORTED, REGISTRATION_NO_ANSWER or REGISTRATION_UNKNOWN
int ModemComponent::read_stat_(const char *cmd, const char *prefix) {
const command_result result = this->at_reply_(cmd);
if (result == command_result::TIMEOUT) {
return REGISTRATION_NO_ANSWER;
}
if (result == command_result::FAIL && reply_names_unsupported(this->reply_)) {
return REGISTRATION_UNSUPPORTED;
}
const int stat = result == command_result::OK ? registration_from_reply(this->reply_, prefix) : REGISTRATION_UNKNOWN;
if (stat == REGISTRATION_UNKNOWN) {
// An error such as a SIM failure is a warning on the diagnostic polls, so it shows at the default log level
if (result == command_result::FAIL && this->attach_polls_ % ATTACH_DIAG_EVERY == 0) {
ESP_LOGW(TAG, "%s failed: %s", cmd, this->reply_);
} else {
ESP_LOGD(TAG, "%s gave no state: %s", cmd, this->reply_);
}
}
return stat;
}
// AT+CEREG covers LTE; on 2G and 3G the network registration is in AT+CREG, and AT+CGATT=1 is answered quickly once
// it is set. Returns the <stat> that tells most, or one of the negative REGISTRATION_ values.
int ModemComponent::read_registration_() {
const int lte = this->read_stat_("AT+CEREG?", "+CEREG:");
if (is_registered(lte)) {
return lte;
}
return merge_registration(lte, this->read_stat_("AT+CREG?", "+CREG:"));
}
void ModemComponent::not_responding_(int baud) {
if (this->answered_) {
// It answered before, so the wiring is fine; a long command or a modem restart keeps it silent for minutes
ESP_LOGW(TAG, "Modem not responding at %d baud; it may be busy or restarting", baud);
} else {
ESP_LOGW(TAG, "Modem not responding at %d baud. Check power, PWRKEY and TX/RX wiring.", baud);
}
ESP_LOGW(TAG, "Modem not responding at %d baud. Check power, PWRKEY and TX/RX wiring.", baud);
this->set_fault_(ModemFault::MODEM_FAULT_NO_RESPONSE);
}
void ModemComponent::sim_not_ready_(const char *reason) {
// A missing or broken SIM never gets ready; the status is polled every second, so only some polls warn
if (++this->sim_polls_ == SIM_WARN_AFTER + SIM_WARN_EVERY) {
this->sim_polls_ = SIM_WARN_AFTER;
}
if (this->sim_polls_ == SIM_WARN_AFTER) {
ESP_LOGW(TAG, "SIM not ready: %s. Check that a working SIM is inserted",
reason[0] != '\0' ? reason : LOG_STR_LITERAL("no reply"));
}
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
}
#ifdef USE_MODEM_SEND_AT
bool ModemComponent::send_at(const std::string &cmd, uint32_t timeout) { return this->send_at(cmd.c_str(), timeout); }
@@ -1160,54 +954,13 @@ bool ModemComponent::send_at(const char *cmd, uint32_t timeout) {
#endif
// at() keeps no text from a failed command, so the raw reply is collected into reply_ to show the +CME ERROR
command_result ModemComponent::at_reply_(const char *cmd, uint32_t timeout) {
std::string line = cmd; // poll commands fit the short string buffer
line += '\r';
this->reply_len_ = 0;
this->reply_[0] = '\0';
#ifdef CONFIG_ESP_MODEM_USE_INFLATABLE_BUFFER_IF_NEEDED
// The inflatable buffer gathers CMUX frames too, so every reply comes over whole each time
const bool whole = true;
#else
// esp_modem hands a UART reply over whole each time, and a CMUX reply one frame at a time
const modem_mode mode = this->dce_->get_mode();
const bool whole = mode != modem_mode::CMUX_MODE && mode != modem_mode::CMUX_MANUAL_MODE &&
mode != modem_mode::CMUX_MANUAL_DATA && mode != modem_mode::CMUX_MANUAL_COMMAND;
#endif
struct {
bool whole;
bool cut;
} state{whole, false};
const command_result result = this->dce_->command(
line,
[this, &state](const uint8_t *data, size_t len) {
// OK, or FAIL once an ERROR line has ended (the +CME ERROR reason may still be on its way), else TIMEOUT
state.cut |= collect_reply(this->reply_, sizeof(this->reply_), this->reply_len_,
reinterpret_cast<const char *>(data), len, state.whole);
switch (reply_end(this->reply_, this->reply_len_, state.cut)) {
case ReplyEnd::REPLY_END_OK:
return command_result::OK;
case ReplyEnd::REPLY_END_ERROR:
return command_result::FAIL;
default:
return command_result::TIMEOUT;
}
},
timeout);
this->reply_len_ = flatten_reply(this->reply_, this->reply_len_);
this->reply_cut_ = state.cut;
return result;
}
command_result ModemComponent::at_(const char *cmd, uint32_t timeout) {
const command_result result = this->at_reply_(cmd, timeout);
// A reply longer than the buffer kept only its end
const char *cut = this->reply_cut_ ? LOG_STR_LITERAL("...") : "";
std::string output;
const command_result result = this->dce_->at(cmd, output, timeout);
if (result == command_result::OK) {
ESP_LOGI(TAG, "AT '%s' -> OK: %s%s", cmd, cut, this->reply_);
ESP_LOGI(TAG, "AT '%s' -> OK: %s", cmd, output.c_str());
} else {
ESP_LOGW(TAG, "AT '%s' -> %s: %s%s", cmd, LOG_STR_ARG(result_to_str(result)), cut, this->reply_);
ESP_LOGW(TAG, "AT '%s' -> %s: %s", cmd, LOG_STR_ARG(result_to_str(result)), output.c_str());
}
return result;
}
@@ -1220,27 +973,25 @@ SimResult ModemComponent::prepare_sim_() {
return SimResult::SIM_RESULT_RETRY; // the save wakes the task
}
#endif
// The raw reply keeps the +CME ERROR text a missing SIM gives; status below points into it
const command_result result = this->at_reply_("AT+CPIN?");
if (result == command_result::TIMEOUT) {
// The next pass checks with a sync whether the modem or only the SIM interface is silent
ESP_LOGD(TAG, "No answer to the SIM status request");
this->sim_not_ready_(LOG_STR_LITERAL("no answer to AT+CPIN?"));
this->request_resync_();
return SimResult::SIM_RESULT_RETRY;
}
if (result != command_result::OK) {
std::string output;
if (this->dce_->at("AT+CPIN?", output, COMMAND_TIMEOUT_MS) != command_result::OK) {
// A SIM that is still starting answers with an error for a second or so
ESP_LOGD(TAG, "SIM status not readable yet: %s", this->reply_);
this->sim_not_ready_(this->reply_);
ESP_LOGD(TAG, "SIM status not readable yet: %s", output.c_str());
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
return SimResult::SIM_RESULT_RETRY;
}
// Anything else, such as an echoed command, is not a status and must not reach the lock checks below
const char *found = sim_status(this->reply_);
const char *found = strstr(output.c_str(), "+CPIN:");
if (found != nullptr) {
found += sizeof("+CPIN:") - 1;
while (*found == ' ') {
found++;
}
}
const StringRef status = found != nullptr ? StringRef(found) : StringRef();
if (status.empty()) {
ESP_LOGD(TAG, "SIM status not reported yet: %s", this->reply_);
this->sim_not_ready_(this->reply_);
ESP_LOGD(TAG, "SIM status not reported yet: %s", output.c_str());
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
return SimResult::SIM_RESULT_RETRY;
}
ESP_LOGD(TAG, "SIM: %s", status.c_str());
@@ -1268,8 +1019,8 @@ SimResult ModemComponent::prepare_sim_() {
this->set_fault_(ModemFault::MODEM_FAULT_SIM_LOCKED);
return SimResult::SIM_RESULT_LOCKED;
}
ESP_LOGD(TAG, "SIM not ready: %s", status.c_str()); // e.g. NOT READY or NOT INSERTED
this->sim_not_ready_(status.c_str());
ESP_LOGW(TAG, "SIM not ready: %s", status.c_str()); // e.g. NOT READY or NOT INSERTED
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
return SimResult::SIM_RESULT_RETRY;
}
#ifdef USE_MODEM_PIN_CODE
+1 -22
View File
@@ -62,7 +62,6 @@ enum class ModemFault : uint8_t {
MODEM_FAULT_PIN_RECORD,
MODEM_FAULT_SETUP,
MODEM_FAULT_NOT_ATTACHED,
MODEM_FAULT_REGISTRATION_DENIED,
MODEM_FAULT_PPP,
MODEM_FAULT_TEARDOWN,
};
@@ -152,7 +151,6 @@ class ModemComponent : public Component {
static constexpr uint32_t RETRY_DELAY_MS = 1000;
static constexpr size_t URC_LINE_SIZE = 128;
static constexpr size_t AT_COMMAND_SIZE = 128;
static constexpr size_t REPLY_SIZE = 256; // a longer reply keeps its newest bytes, so its final line counts
#ifdef USE_MODEM_POLL
static constexpr uint8_t CSQ_UNKNOWN = 99; // AT+CSQ rssi or ber the modem cannot tell
static constexpr uint8_t CSQ_RSSI_MAX = 31;
@@ -202,20 +200,8 @@ class ModemComponent : public Component {
void hand_over_(uint32_t pending);
/// Send an AT command from the task and log the result; blocks for up to the timeout
esp_modem::command_result at_(const char *cmd, uint32_t timeout = COMMAND_TIMEOUT_MS);
/// Send an AT command; reply_ gets the whole reply on one line, including any +CME ERROR text
esp_modem::command_result at_reply_(const char *cmd, uint32_t timeout = COMMAND_TIMEOUT_MS);
void publish_status_();
/// Send the +++ escape with its guard times; true when the modem answered
bool escape_data_mode_();
/// Overflow a stuck CMUX receiver with flag bytes; true when the modem answers AT afterwards
bool flush_cmux_();
void request_resync_();
int read_stat_(const char *cmd, const char *prefix);
int read_registration_();
/// Set the UART rate; current_baud_rate_ follows when the UART takes it
esp_err_t set_uart_baud_(int baud);
void not_responding_(int baud);
void sim_not_ready_(const char *reason);
void dump_connect_params_();
SimResult prepare_sim_();
#ifdef USE_MODEM_PIN_CODE
@@ -235,9 +221,6 @@ class ModemComponent : public Component {
const char *urc_line_{nullptr}; // the line urc_pending_ hands to loop(), inside urc_reader_
#endif
std::unique_ptr<esp_modem::DCE> dce_;
char reply_[REPLY_SIZE + 1]{}; // task only; the last reply, null-terminated
size_t reply_len_{0};
bool reply_cut_{false}; // the last reply was longer than reply_ and kept only its end
std::shared_ptr<esp_modem::DTE> dte_;
esp_netif_t *ppp_netif_{nullptr};
ESPPreferenceObject pref_;
@@ -308,9 +291,6 @@ class ModemComponent : public Component {
uint8_t init_at_count_{0};
uint8_t uart_port_{UART_NUM_MAX};
uint8_t attach_polls_{0};
uint8_t idle_polls_{0}; // polls in a row that reported "not searching"
uint8_t unknown_polls_{0}; // polls in a row with no usable registration state
uint8_t sim_polls_{0}; // failed SIM status reads in this attempt
#ifdef USE_MODEM_POLL
uint8_t poll_rssi_{CSQ_UNKNOWN}; // raw AT+CSQ answers
uint8_t poll_ber_{CSQ_UNKNOWN};
@@ -318,8 +298,7 @@ class ModemComponent : public Component {
#endif
bool connect_timeout_armed_{false};
bool modem_synced_{false}; // a modem that never answered has nothing to tear down
bool answered_{false}; // the modem synced since boot, so its wiring and power are fine
bool resync_{false}; // a command timed out, so CONNECTING syncs again first
bool resync_{false}; // the attachment read failed, so CONNECTING syncs again first
bool apn_pending_{false}; // ENABLING could not set the APN at CFUN=0, so CONNECTING sets it after the SIM check
#ifdef USE_MODEM_SEND_AT
char at_command_[AT_COMMAND_SIZE];
+8
View File
@@ -2,6 +2,10 @@
#include "esphome/core/log.h"
#include "esphome/core/hal.h"
#ifdef USE_ESP8266
#include <Wire.h>
#endif
namespace esphome::scd30 {
ESPHOME_LOG_TAG(TAG, "scd30");
@@ -23,6 +27,10 @@ static const uint16_t SCD30_CMD_TEMPERATURE_OFFSET = 0x5403;
static const uint16_t SCD30_CMD_SOFT_RESET = 0xD304;
void SCD30Component::setup() {
#ifdef USE_ESP8266
Wire.setClockStretchLimit(150000);
#endif
/// Firmware version identification
uint16_t raw_firmware_version[3];
if (!this->setup_check(this->get_register(SCD30_CMD_GET_FIRMWARE_VERSION, raw_firmware_version, 3),
+9 -1
View File
@@ -5,4 +5,12 @@ sensor:
current:
name: CSE7766 Current
power:
name: CSE776 Power
name: CSE7766 Power
energy:
name: CSE7766 Energy
apparent_power:
name: CSE7766 Apparent Power
reactive_power:
name: CSE7766 Reactive Power
power_factor:
name: CSE7766 Power Factor
@@ -1,10 +1,11 @@
#include <gtest/gtest.h>
#include <array>
#include <cstdint>
#include <vector>
#include "esphome/components/cse7766/cse7766.h"
#include "esphome/components/sensor/sensor.h"
#include "esphome/core/helpers.h"
#include "../common.h"
namespace esphome::cse7766::testing {
@@ -21,34 +22,23 @@ constexpr uint32_t POWER_COEFF = 5425000;
constexpr uint32_t LOW_LOAD_CYCLE = 2507613;
constexpr uint32_t SHORT_CYCLE = 900000; // about 6 W, just under 1 s
constexpr uint32_t HIGH_LOAD_CYCLE = 2000;
constexpr uint32_t ONE_SECOND_WAIT = 1078140; // about one second since the last pulse
constexpr uint16_t CF_PULSES = 0x0B81;
constexpr uint8_t HEADER_OK = 0x55;
constexpr uint8_t HEADER_POWER_CYCLE_EXCEEDS_RANGE = 0xF2;
constexpr uint8_t HEADER_NOT_CALIBRATED = 0xAA;
constexpr uint8_t ADJ_NEW_POWER = 0x71;
constexpr uint8_t ADJ_NO_NEW_POWER = 0x61;
void put24(std::vector<uint8_t> &frame, uint32_t value) {
frame.push_back(value >> 16);
frame.push_back(value >> 8);
frame.push_back(value);
}
std::vector<uint8_t> make_frame(uint8_t header, uint32_t power_cycle, uint8_t adj) {
std::vector<uint8_t> frame{header, 0x5A};
put24(frame, VOLTAGE_COEFF);
put24(frame, VOLTAGE_CYCLE);
put24(frame, CURRENT_COEFF);
put24(frame, CURRENT_CYCLE);
put24(frame, POWER_COEFF);
put24(frame, power_cycle);
frame.push_back(adj);
frame.push_back(0x0B);
frame.push_back(0x81);
uint8_t checksum = 0;
for (size_t i = 2; i < frame.size(); i++) {
checksum += frame[i];
}
frame.push_back(checksum);
std::array<uint8_t, 24> make_frame(uint8_t header, uint32_t power_cycle, uint8_t adj) {
std::array<uint8_t, 24> frame{header, 0x5A};
uint8_t *p = frame.data() + 2;
for (uint32_t value : {VOLTAGE_COEFF, VOLTAGE_CYCLE, CURRENT_COEFF, CURRENT_CYCLE, POWER_COEFF, power_cycle})
p = put_be24(p, value);
*p++ = adj;
p = put_be16(p, CF_PULSES);
*p = sum_bytes(frame.data() + 2, 21);
return frame;
}
@@ -60,7 +50,8 @@ class CSE7766Test : public ::testing::Test {
}
float feed_(uint8_t header, uint32_t power_cycle, uint8_t adj) {
this->uart_.push_rx(make_frame(header, power_cycle, adj));
const auto frame = make_frame(header, power_cycle, adj);
this->uart_.push_rx({frame.begin(), frame.end()});
this->sut_.loop();
return this->power_.state;
}
@@ -81,12 +72,12 @@ TEST_F(CSE7766Test, NewMeasurementIsReported) {
TEST_F(CSE7766Test, LowLoadKeepsLastMeasurementBetweenPulses) {
this->feed_(HEADER_OK, LOW_LOAD_CYCLE, ADJ_NEW_POWER);
EXPECT_NEAR(this->feed_(HEADER_OK, LOW_LOAD_CYCLE, ADJ_NO_NEW_POWER), 2.163f, 0.001f);
EXPECT_NEAR(this->feed_(HEADER_OK, 1078140, ADJ_NO_NEW_POWER), 2.163f, 0.001f);
EXPECT_NEAR(this->feed_(HEADER_OK, ONE_SECOND_WAIT, ADJ_NO_NEW_POWER), 2.163f, 0.001f);
EXPECT_NEAR(this->feed_(HEADER_OK, 4900000, ADJ_NO_NEW_POWER), 2.163f, 0.001f);
}
// Below 1 s the chip does not send waiting times in normal operation, so such a frame
// means the pulse is overdue and 0 W is reported at once, as before
// means the pulse is overdue and 0 W is reported at once
TEST_F(CSE7766Test, ShortCycleReportsZeroWithoutNewMeasurement) {
this->feed_(HEADER_OK, SHORT_CYCLE, ADJ_NEW_POWER);
EXPECT_EQ(this->feed_(HEADER_OK, 1050000, ADJ_NO_NEW_POWER), 0.0f);
@@ -106,12 +97,33 @@ TEST_F(CSE7766Test, HighLoadSwitchingOffReportsZeroAtOnce) {
EXPECT_EQ(this->feed_(HEADER_OK, 1072601, ADJ_NO_NEW_POWER), 0.0f);
}
TEST_F(CSE7766Test, NoMeasurementYetReportsZero) { EXPECT_EQ(this->feed_(HEADER_OK, 1078140, ADJ_NO_NEW_POWER), 0.0f); }
TEST_F(CSE7766Test, NoMeasurementYetReportsZero) {
EXPECT_EQ(this->feed_(HEADER_OK, ONE_SECOND_WAIT, ADJ_NO_NEW_POWER), 0.0f);
}
TEST_F(CSE7766Test, PowerCycleExceedsRangeReportsZero) {
this->feed_(HEADER_OK, LOW_LOAD_CYCLE, ADJ_NEW_POWER);
EXPECT_EQ(this->feed_(HEADER_POWER_CYCLE_EXCEEDS_RANGE, 9000000, ADJ_NO_NEW_POWER), 0.0f);
EXPECT_EQ(this->feed_(HEADER_OK, 1078140, ADJ_NO_NEW_POWER), 0.0f);
EXPECT_EQ(this->feed_(HEADER_OK, ONE_SECOND_WAIT, ADJ_NO_NEW_POWER), 0.0f);
}
// Frames that report an error carry no measurements, so the warning stays set until a valid frame
TEST_F(CSE7766Test, ErrorFramesKeepTheWarningUntilAValidFrame) {
this->feed_(HEADER_NOT_CALIBRATED, LOW_LOAD_CYCLE, ADJ_NEW_POWER);
EXPECT_TRUE(this->sut_.status_has_warning());
// Voltage cycle, current cycle and coefficient storage faults
for (uint8_t header : {0xF8, 0xF4, 0xF1}) {
this->feed_(header, LOW_LOAD_CYCLE, ADJ_NEW_POWER);
EXPECT_TRUE(this->sut_.status_has_warning());
}
this->feed_(HEADER_OK, LOW_LOAD_CYCLE, ADJ_NEW_POWER);
EXPECT_FALSE(this->sut_.status_has_warning());
}
// A power cycle out of range is a valid frame meaning 0 W, not an error
TEST_F(CSE7766Test, PowerCycleExceedsRangeIsNotAWarning) {
this->feed_(HEADER_POWER_CYCLE_EXCEEDS_RANGE, 9000000, ADJ_NO_NEW_POWER);
EXPECT_FALSE(this->sut_.status_has_warning());
}
} // namespace esphome::cse7766::testing
+1 -2
View File
@@ -1,4 +1,3 @@
packages:
uart_4800_even: !include ../../test_build_components/common/uart_4800_even/esp32-idf.yaml
<<: !include common.yaml
cse7766: !include common.yaml
@@ -1,8 +1,3 @@
substitutions:
tx_pin: GPIO1
rx_pin: GPIO3
packages:
uart_4800_even: !include ../../test_build_components/common/uart_4800_even/esp8266-ard.yaml
<<: !include common.yaml
cse7766: !include common.yaml
@@ -1,8 +1,3 @@
substitutions:
tx_pin: GPIO4
rx_pin: GPIO5
packages:
uart_4800_even: !include ../../test_build_components/common/uart_4800_even/rp2040-ard.yaml
<<: !include common.yaml
cse7766: !include common.yaml
-11
View File
@@ -1,11 +0,0 @@
import esphome.config_validation as cv
from esphome.const import CONF_USE_ADDRESS
from tests.testing_helpers import ComponentManifestOverride
def override_manifest(manifest: ComponentManifestOverride) -> None:
# Only the reply parsers are tested; the build still needs the address a modem config provides.
manifest.dependencies = []
manifest.config_schema = cv.Schema(
{cv.Optional(CONF_USE_ADDRESS, default="test.local"): cv.string_strict}
)
-211
View File
@@ -1,211 +0,0 @@
#include <gtest/gtest.h>
#include <cstring>
#include <string>
#include "esphome/components/modem/at_reply.h"
namespace esphome::modem::testing {
// Runs a raw reply through flatten_reply() as at_reply_() does
static std::string flat(const char *raw) {
char buf[256];
const size_t len = strlen(raw);
memcpy(buf, raw, len + 1);
return std::string(buf, flatten_reply(buf, len));
}
static ReplyEnd end_of(const char *reply, bool skip_first = false) {
return reply_end(reply, strlen(reply), skip_first);
}
TEST(ModemReplyEnd, OnlyCompleteFinalLinesCount) {
EXPECT_EQ(end_of("\r\n+CSQ: 20,99\r\n\r\nOK\r\n"), ReplyEnd::REPLY_END_OK);
EXPECT_EQ(end_of("\r\nERROR\r\n"), ReplyEnd::REPLY_END_ERROR);
EXPECT_EQ(end_of("\r\n+CME ERROR: SIM not inserted\r\n"), ReplyEnd::REPLY_END_ERROR);
EXPECT_EQ(end_of("\r\n+CMS ERROR: 500\r\n"), ReplyEnd::REPLY_END_ERROR);
// ERROR inside a payload line is not a result
EXPECT_EQ(end_of("\r\n+CEER: PROTOCOL_ERROR\r\n"), ReplyEnd::REPLY_END_NONE);
EXPECT_EQ(end_of("\r\n+CEER: PROTOCOL_ERROR\r\n\r\nOK\r\n"), ReplyEnd::REPLY_END_OK);
// A line that has not ended yet
EXPECT_EQ(end_of("\r\nOK"), ReplyEnd::REPLY_END_NONE);
EXPECT_EQ(end_of("\r\n+CME ERROR: 10"), ReplyEnd::REPLY_END_NONE);
}
TEST(ModemReplyEnd, ErrorWithoutItsReason) {
// esp_modem drops the CMUX frame ": SIM not inserted" because it holds no line end
char buf[64];
size_t len = 0;
collect_reply(buf, sizeof(buf), len, "\r\n+CME ERROR", 12, false);
EXPECT_EQ(reply_end(buf, len, false), ReplyEnd::REPLY_END_NONE);
collect_reply(buf, sizeof(buf), len, "\r\n", 2, false);
EXPECT_EQ(reply_end(buf, len, false), ReplyEnd::REPLY_END_ERROR);
EXPECT_EQ(end_of("\r\n+CMS ERROR\r\n"), ReplyEnd::REPLY_END_ERROR);
}
TEST(ModemReplyEnd, CutFirstLineIsSkipped) {
// The tail of "...OK" from a longer line must not count as a result
EXPECT_EQ(end_of("OK\r\nmore text\r\n", true), ReplyEnd::REPLY_END_NONE);
EXPECT_EQ(end_of("OK\r\nmore text\r\n", false), ReplyEnd::REPLY_END_OK);
EXPECT_EQ(end_of("tail\r\nOK\r\n", true), ReplyEnd::REPLY_END_OK);
}
TEST(ModemCollectReply, UartReplyComesBackWhole) {
char buf[9];
size_t len = 0;
EXPECT_FALSE(collect_reply(buf, sizeof(buf), len, "abc", 3, true));
EXPECT_STREQ(buf, "abc");
EXPECT_FALSE(collect_reply(buf, sizeof(buf), len, "abcdef", 6, true));
EXPECT_STREQ(buf, "abcdef");
// Data longer than the buffer keeps its tail
EXPECT_TRUE(collect_reply(buf, sizeof(buf), len, "0123456789", 10, true));
EXPECT_STREQ(buf, "23456789");
}
TEST(ModemCollectReply, GatheredCmuxFramesAreNotRepeated) {
// With esp_modem's inflatable buffer, each CMUX frame comes with the ones before it
char buf[64];
size_t len = 0;
const char *first = "\r\n+CSQ: 20,99\r\n";
const char *both = "\r\n+CSQ: 20,99\r\n\r\nOK\r\n";
collect_reply(buf, sizeof(buf), len, first, strlen(first), true);
collect_reply(buf, sizeof(buf), len, both, strlen(both), true);
EXPECT_STREQ(buf, both);
EXPECT_EQ(reply_end(buf, len, false), ReplyEnd::REPLY_END_OK);
}
TEST(ModemCollectReply, ExactlyFullIsNotCut) {
char buf[9];
size_t len = 0;
EXPECT_FALSE(collect_reply(buf, sizeof(buf), len, "OK\r\nabcd", 8, true));
EXPECT_STREQ(buf, "OK\r\nabcd");
len = 0;
EXPECT_FALSE(collect_reply(buf, sizeof(buf), len, "OK\r\nabcd", 8, false));
EXPECT_EQ(reply_end(buf, len, false), ReplyEnd::REPLY_END_OK);
// Filling up by appending is not a cut either, one more byte is
len = 0;
EXPECT_FALSE(collect_reply(buf, sizeof(buf), len, "OK\r\n", 4, false));
EXPECT_FALSE(collect_reply(buf, sizeof(buf), len, "abcd", 4, false));
EXPECT_TRUE(collect_reply(buf, sizeof(buf), len, "e", 1, false));
EXPECT_STREQ(buf, "K\r\nabcde");
}
TEST(ModemCollectReply, CmuxFramesAreAppended) {
char buf[9];
size_t len = 0;
EXPECT_FALSE(collect_reply(buf, sizeof(buf), len, "abc", 3, false));
// A frame that starts like the text so far is still new data
EXPECT_FALSE(collect_reply(buf, sizeof(buf), len, "abcd", 4, false));
EXPECT_STREQ(buf, "abcabcd");
// The oldest bytes go once the buffer is full
EXPECT_TRUE(collect_reply(buf, sizeof(buf), len, "XY", 2, false));
EXPECT_STREQ(buf, "bcabcdXY");
EXPECT_EQ(len, 8u);
EXPECT_TRUE(collect_reply(buf, sizeof(buf), len, "0123456789", 10, false));
EXPECT_STREQ(buf, "23456789");
}
TEST(ModemFlattenReply, OneLineWithoutFinalOk) {
EXPECT_EQ(flat("\r\n+CSQ: 20,99\r\n\r\nOK\r\n"), "+CSQ: 20,99");
EXPECT_EQ(flat("\r\nOK\r\n"), "");
EXPECT_EQ(flat("\r\n+CME ERROR: SIM not inserted\r\n"), "+CME ERROR: SIM not inserted");
EXPECT_EQ(flat("\r\n+COPS: 0,0,\"NOK\"\r\n"), "+COPS: 0,0,\"NOK\"");
// A line ending in OK is not the final result
EXPECT_EQ(flat("\r\n+CSPN: NOK\r\n"), "+CSPN: NOK");
EXPECT_EQ(flat(""), "");
}
TEST(ModemRegistration, QueryAnswerNotNotification) {
// A one-field URC before the query answer is skipped
EXPECT_EQ(registration_from_reply("+CEREG: 2 +CEREG: 0,1", "+CEREG:"), 1);
EXPECT_EQ(registration_from_reply("+CEREG: 2,5,\"1A2B\",\"01A2B3C4\",7", "+CEREG:"), 5);
EXPECT_EQ(registration_from_reply("+CREG: 0,3", "+CREG:"), 3);
EXPECT_EQ(registration_from_reply("+CEREG: 1", "+CEREG:"), REGISTRATION_UNKNOWN);
EXPECT_EQ(registration_from_reply("+CREG: 0,1", "+CEREG:"), REGISTRATION_UNKNOWN);
EXPECT_EQ(registration_from_reply("", "+CEREG:"), REGISTRATION_UNKNOWN);
}
TEST(ModemRegistration, OtherRegisteredStates) {
EXPECT_TRUE(is_registered(REGISTRATION_HOME));
EXPECT_TRUE(is_registered(REGISTRATION_ROAMING));
EXPECT_TRUE(is_registered(REGISTRATION_SMS_ONLY_HOME));
EXPECT_TRUE(is_registered(REGISTRATION_SMS_ONLY_ROAMING));
EXPECT_TRUE(is_registered(REGISTRATION_CSFB_NOT_PREFERRED_HOME));
EXPECT_TRUE(is_registered(REGISTRATION_CSFB_NOT_PREFERRED_ROAMING));
EXPECT_FALSE(is_registered(REGISTRATION_NOT_SEARCHING));
EXPECT_FALSE(is_registered(REGISTRATION_SEARCHING));
EXPECT_FALSE(is_registered(REGISTRATION_DENIED));
EXPECT_FALSE(is_registered(REGISTRATION_REPORTED_UNKNOWN));
EXPECT_FALSE(is_registered(REGISTRATION_EMERGENCY_ONLY));
EXPECT_FALSE(is_registered(11));
EXPECT_FALSE(is_registered(REGISTRATION_UNKNOWN));
}
TEST(ModemMergeRegistration, RegisteredOnEitherSideWins) {
EXPECT_EQ(merge_registration(REGISTRATION_HOME, REGISTRATION_DENIED), REGISTRATION_HOME);
EXPECT_EQ(merge_registration(REGISTRATION_DENIED, REGISTRATION_ROAMING), REGISTRATION_ROAMING);
EXPECT_EQ(merge_registration(REGISTRATION_NO_ANSWER, REGISTRATION_HOME), REGISTRATION_HOME);
EXPECT_EQ(merge_registration(REGISTRATION_UNSUPPORTED, REGISTRATION_ROAMING), REGISTRATION_ROAMING);
EXPECT_EQ(merge_registration(REGISTRATION_UNSUPPORTED, REGISTRATION_CSFB_NOT_PREFERRED_ROAMING),
REGISTRATION_CSFB_NOT_PREFERRED_ROAMING);
EXPECT_EQ(merge_registration(REGISTRATION_SEARCHING, REGISTRATION_CSFB_NOT_PREFERRED_HOME),
REGISTRATION_CSFB_NOT_PREFERRED_HOME);
EXPECT_EQ(merge_registration(REGISTRATION_SMS_ONLY_HOME, REGISTRATION_DENIED), REGISTRATION_SMS_ONLY_HOME);
// Emergency only is no registration, so a searching query still decides
EXPECT_EQ(merge_registration(REGISTRATION_EMERGENCY_ONLY, REGISTRATION_SEARCHING), REGISTRATION_SEARCHING);
}
TEST(ModemMergeRegistration, SearchingBeatsDenied) {
EXPECT_EQ(merge_registration(REGISTRATION_SEARCHING, REGISTRATION_DENIED), REGISTRATION_SEARCHING);
EXPECT_EQ(merge_registration(REGISTRATION_DENIED, REGISTRATION_SEARCHING), REGISTRATION_SEARCHING);
}
TEST(ModemMergeRegistration, DefiniteAnswerBeatsTimeout) {
EXPECT_EQ(merge_registration(REGISTRATION_DENIED, REGISTRATION_NO_ANSWER), REGISTRATION_DENIED);
EXPECT_EQ(merge_registration(REGISTRATION_NO_ANSWER, REGISTRATION_SEARCHING), REGISTRATION_SEARCHING);
EXPECT_EQ(merge_registration(REGISTRATION_NO_ANSWER, REGISTRATION_NO_ANSWER), REGISTRATION_NO_ANSWER);
// Any reported <stat> outweighs a timeout, so the fallbacks still count it
EXPECT_EQ(merge_registration(REGISTRATION_NOT_SEARCHING, REGISTRATION_NO_ANSWER), REGISTRATION_NOT_SEARCHING);
EXPECT_EQ(merge_registration(REGISTRATION_NO_ANSWER, REGISTRATION_NOT_SEARCHING), REGISTRATION_NOT_SEARCHING);
EXPECT_EQ(merge_registration(REGISTRATION_REPORTED_UNKNOWN, REGISTRATION_NO_ANSWER), REGISTRATION_REPORTED_UNKNOWN);
EXPECT_EQ(merge_registration(REGISTRATION_NO_ANSWER, REGISTRATION_REPORTED_UNKNOWN), REGISTRATION_REPORTED_UNKNOWN);
// Only a timeout and no <stat> at all leave the state open
EXPECT_EQ(merge_registration(REGISTRATION_UNSUPPORTED, REGISTRATION_NO_ANSWER), REGISTRATION_NO_ANSWER);
EXPECT_EQ(merge_registration(REGISTRATION_NO_ANSWER, REGISTRATION_UNKNOWN), REGISTRATION_NO_ANSWER);
}
TEST(ModemMergeRegistration, UnsupportedOnlyWhenBothAre) {
EXPECT_EQ(merge_registration(REGISTRATION_UNSUPPORTED, REGISTRATION_UNSUPPORTED), REGISTRATION_UNSUPPORTED);
EXPECT_EQ(merge_registration(REGISTRATION_UNSUPPORTED, REGISTRATION_NOT_SEARCHING), REGISTRATION_NOT_SEARCHING);
EXPECT_EQ(merge_registration(REGISTRATION_UNKNOWN, REGISTRATION_UNSUPPORTED), REGISTRATION_UNKNOWN);
}
TEST(ModemMergeRegistration, UnknownFallback) {
// The LTE value goes first, then the 2G and 3G one, then unknown
EXPECT_EQ(merge_registration(REGISTRATION_NOT_SEARCHING, REGISTRATION_REPORTED_UNKNOWN), REGISTRATION_NOT_SEARCHING);
EXPECT_EQ(merge_registration(REGISTRATION_UNKNOWN, REGISTRATION_REPORTED_UNKNOWN), REGISTRATION_REPORTED_UNKNOWN);
EXPECT_EQ(merge_registration(REGISTRATION_UNKNOWN, REGISTRATION_UNKNOWN), REGISTRATION_UNKNOWN);
}
TEST(ModemUnsupported, OnlyWhenTheErrorSaysSo) {
EXPECT_TRUE(reply_names_unsupported("+CME ERROR: operation not supported"));
EXPECT_TRUE(reply_names_unsupported("+CME ERROR: Operation Not Supported"));
EXPECT_TRUE(reply_names_unsupported("+CME ERROR: 4"));
EXPECT_FALSE(reply_names_unsupported("+CME ERROR: 40"));
EXPECT_FALSE(reply_names_unsupported("+CME ERROR: SIM busy"));
EXPECT_FALSE(reply_names_unsupported("ERROR"));
EXPECT_FALSE(reply_names_unsupported(""));
}
TEST(ModemSimStatus, CutBeforeTheNextLine) {
char ready[] = "+CPIN: READY";
EXPECT_STREQ(sim_status(ready), "READY");
char with_urc[] = "+CPIN: SIM PIN +CGEV: ME PDN DEACT 1";
EXPECT_STREQ(sim_status(with_urc), "SIM PIN");
char echoed[] = "AT+CPIN?";
EXPECT_EQ(sim_status(echoed), nullptr);
char empty[] = "+CPIN:";
EXPECT_STREQ(sim_status(empty), "");
}
} // namespace esphome::modem::testing