mirror of
https://github.com/esphome/esphome.git
synced 2026-11-18 11:06:02 +00:00
Compare commits
59
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fdf7ebb3bf | ||
|
|
cda4d0fab7 | ||
|
|
b3474a1ed5 | ||
|
|
69037820fa | ||
|
|
6c28ef21d9 | ||
|
|
ab6e3d9bf0 | ||
|
|
10ef6e371b | ||
|
|
c84cd04cf7 | ||
|
|
fb6d7bf265 | ||
|
|
3ad8e35be8 | ||
|
|
11f9f20b61 | ||
|
|
b6d0961f25 | ||
|
|
6046d067aa | ||
|
|
690c5f2fb6 | ||
|
|
654954f684 | ||
|
|
e5728407db | ||
|
|
0cf5af743e | ||
|
|
7ffead44fe | ||
|
|
3dc121a199 | ||
|
|
f245927b49 | ||
|
|
058a5b0358 | ||
|
|
deb8ff7747 | ||
|
|
1cc5593038 | ||
|
|
be7ebd4502 | ||
|
|
2b6abf538b | ||
|
|
8441f30da4 | ||
|
|
d5622826f6 | ||
|
|
a1ede4e5c6 | ||
|
|
5208ddc5f7 | ||
|
|
93efaca879 | ||
|
|
b7d59ccf7d | ||
|
|
ae79c13c8a | ||
|
|
f55557f581 | ||
|
|
6eac98162d | ||
|
|
b78f3df6c1 | ||
|
|
ced25b128b | ||
|
|
9cde6881c9 | ||
|
|
507f754c78 | ||
|
|
3b7e4a9970 | ||
|
|
e465f754c6 | ||
|
|
2c67c6726c | ||
|
|
4e09edb59a | ||
|
|
2009d19ad6 | ||
|
|
4e6f994b7c | ||
|
|
61fcee3320 | ||
|
|
195d16eb27 | ||
|
|
c60e5d9c54 | ||
|
|
fab9d004cc | ||
|
|
215f65fcd5 | ||
|
|
d4ffa31c4a | ||
|
|
0df4082d36 | ||
|
|
1296f3bc63 | ||
|
|
b1af3e65d2 | ||
|
|
e40165dd84 | ||
|
|
fbbab7178a | ||
|
|
ae81f6bd47 | ||
|
|
9579244ef3 | ||
|
|
a80c24842f | ||
|
|
60812d8055 |
No files matched your search
@@ -20,6 +20,9 @@ flagging in a review; read the matching skill for the detail behind any item.
|
||||
Only raise findings that the diff actually introduces or changes. Do not ask for
|
||||
drive-by cleanup of pre-existing code the PR did not touch.
|
||||
|
||||
For error paths that fail without telling the user (early returns, swallowed
|
||||
errors, ignored results), the `silent-failure-review` skill has its own checklist.
|
||||
|
||||
## Scope: shared code does not ride a component PR
|
||||
|
||||
Check the file list first. A PR titled for one component (`[ld2450] ...`) must
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
---
|
||||
name: silent-failure-review
|
||||
description: Find code paths in a branch's diff that fail without telling the user - early returns, swallowed errors, ignored return values, half-done cleanup, and checks that are only safe under an unstated assumption. Use when asked for a silent failure review or before pushing a PR for review.
|
||||
---
|
||||
|
||||
# Silent failure review
|
||||
|
||||
Report only. Do not edit files.
|
||||
|
||||
## Scope
|
||||
|
||||
The diff of the checked-out branch against its base. Fetch the base first (`git fetch upstream dev`, or
|
||||
`git fetch origin dev` when there is no `upstream` remote); a stale base pulls in commits the branch only merged.
|
||||
Then run `git merge-base upstream/dev HEAD` (or `origin/dev`) on its own. If it fails or prints nothing (often a
|
||||
shallow clone; `git fetch --unshallow` fixes that), say the review could not run and stop; never report "no
|
||||
findings" then. Diff against that commit with `git diff <base>`. The diff includes uncommitted changes but not
|
||||
untracked files, so also read in full every file `git status --porcelain --untracked-files=all` lists as `??`.
|
||||
Use another branch only if the user names one. If neither remote exists, say so and stop. Read each changed
|
||||
function in full, and its callers, not just the hunks. When a failure depends on how a library call behaves,
|
||||
read that library's code too.
|
||||
|
||||
## What to look for
|
||||
|
||||
1. **Early returns and skips:** a `return` or `continue` taken before a check or a fetch. Name the assumption
|
||||
it relies on and the case that breaks it (a later release, a lost file, an older install).
|
||||
2. **Swallowed errors:** `except` that logs, passes or returns a default; `OSError` tolerated where the next
|
||||
step needs the file. In C++: an error code mapped to a default, or a status flag that is never set.
|
||||
3. **Ignored results:** a `False`, `None`, exit code, `bool` or `ErrorCode` that the caller does not check.
|
||||
4. **Half-done state:** a failure between two writes that leaves a marker, stamp, lock or filter saying
|
||||
something is done when it is not; cleanup missing on an error path.
|
||||
5. **Stale stored state:** markers, stamps or saved preferences (NVS, flash) written by an older version that
|
||||
the new code trusts.
|
||||
6. **Unclear late failure:** an error that surfaces later (CMake, compile, boot) instead of where it starts,
|
||||
with a message that does not point back to the cause.
|
||||
7. **Defaults standing in for errors:** `x or default`, `.get(key, default)` or an empty object takes the
|
||||
place of a value that is missing or could not be read, and the code carries on as if it were real.
|
||||
8. **Unwatched work:** a thread, task or subprocess is started and nothing ever looks at how it ended.
|
||||
9. **Wrong value on an error branch:** the error is detected, but the branch returns success, `None` or the
|
||||
wrong code instead of passing it on.
|
||||
10. **State reset or skipped:** for each counter, flag, retry or timeout the diff adds or changes, find every
|
||||
place that writes it, and check that no path resets or skips it before it can do its job.
|
||||
11. **Boundaries:** length and buffer comparisons (`>=` against `>`, `len` against `len + 1`), the exact-fit
|
||||
case and the empty case.
|
||||
12. **Unjudged results:** a test or script that prints a result but never fails on it.
|
||||
|
||||
Moved code counts too: if the original had the same flaw, say so, but still report it. Report only flaws in
|
||||
changed or moved lines; unchanged callers are context. If the branch has an open PR (`gh pr view --json number`
|
||||
finds it), read its reviews (`gh pr view <n> --comments` and
|
||||
`gh api --paginate repos/esphome/esphome/pulls/<n>/comments`) and skip what they already raised.
|
||||
|
||||
Before reporting a candidate, follow it to the line that proves it and quote that line. If you cannot
|
||||
confirm it, drop it or mark it as likely.
|
||||
|
||||
## Skip
|
||||
|
||||
- Code that ignores a failure and has a comment explaining why.
|
||||
- Tests that provoke an error and check for it.
|
||||
- Optional tidy-up steps (removing a temp file, say) that may fail with only a log line.
|
||||
|
||||
## Report
|
||||
|
||||
One entry per finding, most severe first:
|
||||
|
||||
- **HIGH / MEDIUM / LOW** - one-line title, `file:line`. HIGH: wrong result or lost data. MEDIUM: a
|
||||
misleading or delayed failure. LOW: affects only logs or diagnostics.
|
||||
- **Confidence:** confirmed, or likely and why it could not be confirmed.
|
||||
- **Risk:** the concrete input or state, and what the user sees.
|
||||
- **Fix:** the smallest change.
|
||||
- **Test:** the test that fails before the fix, or for on-device code, the steps to reproduce it on a board.
|
||||
|
||||
No findings: say so in one line. Keep the report short; no summary of what the PR does.
|
||||
@@ -66,6 +66,8 @@ file does, and it is the authority when they disagree. The most useful starting
|
||||
* `breaking-changes`: what is public API, deprecation patterns and migration notes.
|
||||
* `pr-workflow`, `code-review`, `hardware-test`, `display-test`: creating PRs, reviewing them, and testing
|
||||
on real boards and panels.
|
||||
* `silent-failure-review`: code paths in a branch's diff that fail without telling the user, checked
|
||||
before a PR goes up for review.
|
||||
|
||||
* **Formatting:**
|
||||
* **Python:** Uses `ruff` for linting and formatting. Configuration is in `pyproject.toml`.
|
||||
|
||||
@@ -41,7 +41,7 @@ from esphome.const import (
|
||||
__version__ as ESPHOME_VERSION,
|
||||
)
|
||||
from esphome.core import CORE, ID, MACAddress
|
||||
from esphome.cpp_generator import MockObj, StaticCastExpression
|
||||
from esphome.cpp_generator import MockObj, StaticCastExpression, UnaryOpExpression
|
||||
import esphome.final_validate as fv
|
||||
from esphome.schema_extractors import SCHEMA_EXTRACT
|
||||
from esphome.types import ConfigType, TemplateArgsType
|
||||
@@ -704,21 +704,21 @@ async def to_code_descriptor(descriptor_conf, char_conf, char_var):
|
||||
descriptor_conf[CONF_MAX_LENGTH],
|
||||
descriptor_permissions(descriptor_conf, char_conf),
|
||||
)
|
||||
cg.add(char_var.add_descriptor(desc_var))
|
||||
# Static storage, so the characteristic must not free it
|
||||
cg.add(char_var.add_descriptor(UnaryOpExpression("*", desc_var)))
|
||||
cg.add(desc_var.set_value(value))
|
||||
if (on_write_conf := descriptor_conf.get(CONF_ON_WRITE)) is not None:
|
||||
await _build_on_write_automation(desc_var, on_write_conf)
|
||||
|
||||
|
||||
async def to_code_characteristic(service_var, char_conf):
|
||||
char_var = cg.Pvariable(
|
||||
char_var = cg.new_Pvariable(
|
||||
char_conf[CONF_ID],
|
||||
service_var.create_characteristic(
|
||||
parse_uuid(char_conf[CONF_UUID]),
|
||||
parse_properties(char_conf),
|
||||
characteristic_permissions(char_conf),
|
||||
),
|
||||
parse_uuid(char_conf[CONF_UUID]),
|
||||
parse_properties(char_conf),
|
||||
characteristic_permissions(char_conf),
|
||||
)
|
||||
cg.add(service_var.add_characteristic(UnaryOpExpression("*", char_var)))
|
||||
if (on_write_conf := char_conf.get(CONF_ON_WRITE)) is not None:
|
||||
await _build_on_write_automation(char_var, on_write_conf)
|
||||
if CONF_VALUE in char_conf:
|
||||
@@ -823,14 +823,13 @@ async def to_code(config):
|
||||
for service_config in config[CONF_SERVICES]:
|
||||
# Calculate the optimal number of handles based on the number of characteristics and descriptors
|
||||
num_handles = calculate_num_handles(service_config)
|
||||
service_var = cg.Pvariable(
|
||||
service_var = cg.new_Pvariable(
|
||||
service_config[CONF_ID],
|
||||
var.create_service(
|
||||
parse_uuid(service_config[CONF_UUID]),
|
||||
service_config[CONF_ADVERTISE],
|
||||
num_handles,
|
||||
),
|
||||
parse_uuid(service_config[CONF_UUID]),
|
||||
num_handles,
|
||||
service_config[CONF_ADVERTISE],
|
||||
)
|
||||
cg.add(var.add_service(UnaryOpExpression("*", service_var)))
|
||||
for char_conf in service_config[CONF_CHARACTERISTICS]:
|
||||
await to_code_characteristic(service_var, char_conf)
|
||||
if uuid_is(service_config[CONF_UUID], DEVICE_INFORMATION_SERVICE_UUID):
|
||||
|
||||
@@ -2,6 +2,8 @@
|
||||
#include "ble_server.h"
|
||||
#include "ble_service.h"
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include "esphome/core/helpers.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
@@ -13,7 +15,12 @@ ESPHOME_LOG_TAG(TAG, "esp32_ble_server.characteristic");
|
||||
|
||||
BLECharacteristic::~BLECharacteristic() {
|
||||
for (auto *descriptor : this->descriptors_) {
|
||||
delete descriptor; // NOLINT(cppcoreguidelines-owning-memory)
|
||||
if (descriptor->owned_) {
|
||||
delete descriptor; // NOLINT(cppcoreguidelines-owning-memory)
|
||||
} else if (descriptor->characteristic_ == this) {
|
||||
// A caller-owned descriptor outlives this characteristic, and may already belong to another one
|
||||
descriptor->characteristic_ = nullptr;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -79,10 +86,27 @@ void BLECharacteristic::notify() {
|
||||
}
|
||||
}
|
||||
|
||||
void BLECharacteristic::add_descriptor(BLEDescriptor *descriptor) {
|
||||
void BLECharacteristic::do_delete() {
|
||||
this->clients_to_notify_.clear();
|
||||
// The stack may reuse the handles, so a deleted characteristic must not match events until it is created again
|
||||
this->handle_ = 0xFFFF;
|
||||
this->state_ = INIT;
|
||||
for (auto *descriptor : this->descriptors_) {
|
||||
descriptor->handle_ = 0xFFFF;
|
||||
descriptor->state_ = BLEDescriptor::INIT;
|
||||
}
|
||||
}
|
||||
|
||||
bool BLECharacteristic::add_descriptor(BLEDescriptor &descriptor) {
|
||||
// Bound until removed or the parent is destroyed
|
||||
if (descriptor.characteristic_ != nullptr) {
|
||||
ESP_LOGE(TAG, "Already added");
|
||||
return false;
|
||||
}
|
||||
descriptor.characteristic_ = this;
|
||||
// If the descriptor is the CCCD descriptor, listen to its write event to know if the client wants to be notified
|
||||
if (descriptor->get_uuid() == ESPBTUUID::from_uint16(ESP_GATT_UUID_CHAR_CLIENT_CONFIG)) {
|
||||
descriptor->on_write([this](std::span<const uint8_t> value, uint16_t conn_id) {
|
||||
if (descriptor.get_uuid() == ESPBTUUID::from_uint16(ESP_GATT_UUID_CHAR_CLIENT_CONFIG)) {
|
||||
descriptor.on_write([this](std::span<const uint8_t> value, uint16_t conn_id) {
|
||||
if (value.size() != 2)
|
||||
return;
|
||||
uint16_t cccd = encode_uint16(value[1], value[0]);
|
||||
@@ -96,16 +120,18 @@ void BLECharacteristic::add_descriptor(BLEDescriptor *descriptor) {
|
||||
}
|
||||
});
|
||||
}
|
||||
this->descriptors_.push_back(descriptor);
|
||||
this->descriptors_.push_back(&descriptor);
|
||||
return true;
|
||||
}
|
||||
|
||||
void BLECharacteristic::remove_descriptor(BLEDescriptor *descriptor) {
|
||||
this->descriptors_.erase(std::remove(this->descriptors_.begin(), this->descriptors_.end(), descriptor),
|
||||
this->descriptors_.end());
|
||||
if (std::erase(this->descriptors_, descriptor) == 0)
|
||||
return;
|
||||
descriptor->owned_ = false; // the caller owns it again
|
||||
descriptor->characteristic_ = nullptr;
|
||||
}
|
||||
|
||||
void BLECharacteristic::do_create(BLEService *service) {
|
||||
this->service_ = service;
|
||||
void BLECharacteristic::do_create() {
|
||||
esp_attr_control_t control;
|
||||
control.auto_rsp = ESP_GATT_RSP_BY_APP;
|
||||
|
||||
@@ -116,8 +142,9 @@ void BLECharacteristic::do_create(BLEService *service) {
|
||||
#endif
|
||||
|
||||
esp_bt_uuid_t uuid = this->uuid_.get_uuid();
|
||||
esp_err_t err = esp_ble_gatts_add_char(service->get_handle(), &uuid, static_cast<esp_gatt_perm_t>(this->permissions_),
|
||||
this->properties_, nullptr, &control);
|
||||
esp_err_t err =
|
||||
esp_ble_gatts_add_char(this->service_->get_handle(), &uuid, static_cast<esp_gatt_perm_t>(this->permissions_),
|
||||
this->properties_, nullptr, &control);
|
||||
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGE(TAG, "esp_ble_gatts_add_char failed: %d", err);
|
||||
@@ -188,11 +215,15 @@ void BLECharacteristic::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt
|
||||
break;
|
||||
}
|
||||
case ESP_GATTS_ADD_CHAR_EVT: {
|
||||
if (this->uuid_ == ESPBTUUID::from_uuid(param->add_char.char_uuid)) {
|
||||
// Only while creating, in its own service: a late event for a removed service or a same-UUID
|
||||
// characteristic elsewhere must not set the handle or start the descriptors
|
||||
if (this->state_ == CREATING && this->service_ != nullptr &&
|
||||
this->service_->get_handle() == param->add_char.service_handle &&
|
||||
this->uuid_ == ESPBTUUID::from_uuid(param->add_char.char_uuid)) {
|
||||
this->handle_ = param->add_char.attr_handle;
|
||||
|
||||
for (auto *descriptor : this->descriptors_) {
|
||||
descriptor->do_create(this);
|
||||
descriptor->do_create();
|
||||
}
|
||||
|
||||
this->state_ = CREATING_DEPENDENTS;
|
||||
|
||||
@@ -25,6 +25,8 @@ using namespace bytebuffer;
|
||||
class BLEService;
|
||||
|
||||
class BLECharacteristic final {
|
||||
friend class BLEService;
|
||||
|
||||
public:
|
||||
BLECharacteristic(ESPBTUUID uuid, uint32_t properties, esp_gatt_perm_t permissions);
|
||||
~BLECharacteristic();
|
||||
@@ -44,11 +46,18 @@ class BLECharacteristic final {
|
||||
|
||||
void notify();
|
||||
|
||||
void do_create(BLEService *service);
|
||||
void do_delete() { this->clients_to_notify_.clear(); }
|
||||
void do_create();
|
||||
void do_delete();
|
||||
void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);
|
||||
|
||||
void add_descriptor(BLEDescriptor *descriptor);
|
||||
/// Takes ownership of a heap-allocated descriptor and frees it with this characteristic.
|
||||
void add_descriptor(BLEDescriptor *descriptor) {
|
||||
if (this->add_descriptor(*descriptor))
|
||||
descriptor->owned_ = true;
|
||||
}
|
||||
/// Adds a descriptor the caller keeps alive (such as a component member); it is never freed here.
|
||||
/// False when it already belongs to a characteristic.
|
||||
bool add_descriptor(BLEDescriptor &descriptor);
|
||||
void remove_descriptor(BLEDescriptor *descriptor);
|
||||
|
||||
BLEService *get_service() { return this->service_; }
|
||||
@@ -106,6 +115,8 @@ class BLECharacteristic final {
|
||||
CREATING_DEPENDENTS,
|
||||
CREATED,
|
||||
} state_{INIT};
|
||||
// Set by BLEService::create_characteristic(), which allocates it; the service frees it
|
||||
bool owned_{false};
|
||||
};
|
||||
|
||||
} // namespace esphome::esp32_ble_server
|
||||
|
||||
@@ -27,8 +27,7 @@ BLEDescriptor::BLEDescriptor(ESPBTUUID uuid, uint16_t max_len, esp_gatt_perm_t p
|
||||
|
||||
BLEDescriptor::~BLEDescriptor() { free(this->value_.attr_value); } // NOLINT
|
||||
|
||||
void BLEDescriptor::do_create(BLECharacteristic *characteristic) {
|
||||
this->characteristic_ = characteristic;
|
||||
void BLEDescriptor::do_create() {
|
||||
esp_attr_control_t control;
|
||||
control.auto_rsp = ESP_GATT_AUTO_RSP;
|
||||
|
||||
@@ -66,7 +65,8 @@ void BLEDescriptor::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_
|
||||
esp_ble_gatts_cb_param_t *param) {
|
||||
switch (event) {
|
||||
case ESP_GATTS_ADD_CHAR_DESCR_EVT: {
|
||||
if (this->characteristic_ != nullptr && this->uuid_ == ESPBTUUID::from_uuid(param->add_char_descr.descr_uuid) &&
|
||||
// Bound by add_descriptor(), so only a descriptor do_create() is creating may claim the event
|
||||
if (this->state_ == CREATING && this->uuid_ == ESPBTUUID::from_uuid(param->add_char_descr.descr_uuid) &&
|
||||
this->characteristic_->get_service()->get_handle() == param->add_char_descr.service_handle &&
|
||||
this->characteristic_ == this->characteristic_->get_service()->get_last_created_characteristic()) {
|
||||
this->handle_ = param->add_char_descr.attr_handle;
|
||||
|
||||
@@ -20,11 +20,13 @@ class BLECharacteristic;
|
||||
|
||||
// Base class for BLE descriptors
|
||||
class BLEDescriptor {
|
||||
friend class BLECharacteristic;
|
||||
|
||||
public:
|
||||
BLEDescriptor(ESPBTUUID uuid, uint16_t max_len = 100, bool read = true, bool write = true);
|
||||
BLEDescriptor(ESPBTUUID uuid, uint16_t max_len, esp_gatt_perm_t permissions);
|
||||
virtual ~BLEDescriptor();
|
||||
void do_create(BLECharacteristic *characteristic);
|
||||
void do_create();
|
||||
ESPBTUUID get_uuid() const { return this->uuid_; }
|
||||
|
||||
void set_value(const uint8_t *data, size_t length);
|
||||
@@ -60,6 +62,8 @@ class BLEDescriptor {
|
||||
CREATING,
|
||||
CREATED,
|
||||
} state_{INIT};
|
||||
// Set when the characteristic took ownership through add_descriptor(BLEDescriptor *) and frees it
|
||||
bool owned_{false};
|
||||
};
|
||||
|
||||
} // namespace esphome::esp32_ble_server
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
#include "ble_server.h"
|
||||
|
||||
#include <vector>
|
||||
|
||||
#include "esphome/components/ble_device_base/ble_device.h"
|
||||
#include "esphome/components/esp32_ble/ble.h"
|
||||
#include "esphome/core/log.h"
|
||||
@@ -123,31 +125,52 @@ void BLEServer::release_advertising_() {
|
||||
}
|
||||
|
||||
BLEService *BLEServer::create_service(ESPBTUUID uuid, bool advertise, uint16_t num_handles) {
|
||||
// Checked before allocating, so a failure never deletes a service and pulls in its destructor
|
||||
const uint8_t inst_id = this->free_inst_id_(uuid);
|
||||
if (inst_id == INVALID_INST_ID)
|
||||
return nullptr;
|
||||
auto *service = new BLEService(uuid, num_handles, advertise); // NOLINT(cppcoreguidelines-owning-memory)
|
||||
this->register_service_(*service, inst_id, true);
|
||||
return service;
|
||||
}
|
||||
|
||||
bool BLEServer::add_service(BLEService &service) {
|
||||
// Adding it twice would free or start it twice
|
||||
for (auto &entry : this->services_) {
|
||||
if (entry.service == &service) {
|
||||
ESP_LOGE(TAG, "Already added");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const uint8_t inst_id = this->free_inst_id_(service.get_uuid());
|
||||
if (inst_id == INVALID_INST_ID)
|
||||
return false;
|
||||
this->register_service_(service, inst_id, false);
|
||||
return true;
|
||||
}
|
||||
|
||||
uint8_t BLEServer::free_inst_id_(const ESPBTUUID &uuid) {
|
||||
#if ESPHOME_LOG_LEVEL >= ESPHOME_LOG_LEVEL_VERBOSE
|
||||
char uuid_buf[esp32_ble::UUID_STR_LEN];
|
||||
uuid.to_str(uuid_buf);
|
||||
ESP_LOGV(TAG, "Creating BLE service - %s", uuid_buf);
|
||||
ESP_LOGV(TAG, "Adding BLE service - %s", uuid_buf);
|
||||
#endif
|
||||
// Calculate the inst_id for the service
|
||||
uint8_t inst_id = 0;
|
||||
for (; inst_id < 0xFF; inst_id++) {
|
||||
if (this->get_service(uuid, inst_id) == nullptr) {
|
||||
break;
|
||||
}
|
||||
for (uint8_t inst_id = 0; inst_id < INVALID_INST_ID; inst_id++) {
|
||||
if (this->get_service(uuid, inst_id) == nullptr)
|
||||
return inst_id;
|
||||
}
|
||||
if (inst_id == 0xFF) {
|
||||
char warn_uuid_buf[esp32_ble::UUID_STR_LEN];
|
||||
uuid.to_str(warn_uuid_buf);
|
||||
ESP_LOGW(TAG, "Could not create BLE service %s, too many instances", warn_uuid_buf);
|
||||
return nullptr;
|
||||
}
|
||||
BLEService *service = // NOLINT(cppcoreguidelines-owning-memory)
|
||||
new BLEService(uuid, num_handles, inst_id, advertise);
|
||||
this->services_.push_back({uuid, inst_id, service});
|
||||
char warn_uuid_buf[esp32_ble::UUID_STR_LEN];
|
||||
uuid.to_str(warn_uuid_buf);
|
||||
ESP_LOGW(TAG, "Could not create BLE service %s, too many instances", warn_uuid_buf);
|
||||
return INVALID_INST_ID;
|
||||
}
|
||||
|
||||
void BLEServer::register_service_(BLEService &service, uint8_t inst_id, bool owned) {
|
||||
service.inst_id_ = inst_id;
|
||||
this->services_.push_back({service.get_uuid(), inst_id, owned, &service});
|
||||
if (this->parent_->is_active() && this->registered_) {
|
||||
service->do_create(this);
|
||||
service.do_create(this);
|
||||
}
|
||||
return service;
|
||||
}
|
||||
|
||||
void BLEServer::remove_service(ESPBTUUID uuid, uint8_t inst_id) {
|
||||
@@ -159,7 +182,10 @@ void BLEServer::remove_service(ESPBTUUID uuid, uint8_t inst_id) {
|
||||
for (auto it = this->services_.begin(); it != this->services_.end(); ++it) {
|
||||
if (it->uuid == uuid && it->inst_id == inst_id) {
|
||||
it->service->do_delete();
|
||||
delete it->service; // NOLINT(cppcoreguidelines-owning-memory)
|
||||
// A service still waiting to start must not stay queued once it is unregistered or freed
|
||||
std::erase(this->services_to_start_, it->service);
|
||||
if (it->owned)
|
||||
delete it->service; // NOLINT(cppcoreguidelines-owning-memory)
|
||||
this->services_.erase(it);
|
||||
return;
|
||||
}
|
||||
@@ -218,6 +244,15 @@ void BLEServer::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t ga
|
||||
for (auto &entry : this->services_) {
|
||||
entry.service->gatts_event_handler(event, gatts_if, param);
|
||||
}
|
||||
// A service this server asked for but removed while the stack was still creating it is deleted once its handle
|
||||
// arrives; services of other GATT applications are left alone
|
||||
if (event == ESP_GATTS_CREATE_EVT && gatts_if == this->gatts_if_ && param->create.status == ESP_GATT_OK) {
|
||||
for (auto &entry : this->services_) {
|
||||
if (entry.service->get_handle() == param->create.service_handle)
|
||||
return;
|
||||
}
|
||||
esp_ble_gatts_delete_service(param->create.service_handle);
|
||||
}
|
||||
}
|
||||
|
||||
int8_t BLEServer::find_client_index_(uint16_t conn_id) const {
|
||||
|
||||
@@ -49,6 +49,10 @@ class BLEServer final : public Component, public Parented<ESP32BLE> {
|
||||
uint8_t get_max_clients() const { return this->max_clients_; }
|
||||
|
||||
BLEService *create_service(ESPBTUUID uuid, bool advertise = false, uint16_t num_handles = 15);
|
||||
/// Adds a service the caller keeps alive (such as a component member); remove_service() never frees it.
|
||||
/// Do not add it again after remove_service(). Returns false when it is already added or the UUID already has
|
||||
/// 255 instances.
|
||||
bool add_service(BLEService &service);
|
||||
void remove_service(ESPBTUUID uuid, uint8_t inst_id = 0);
|
||||
BLEService *get_service(ESPBTUUID uuid, uint8_t inst_id = 0);
|
||||
void enqueue_start_service(BLEService *service) { this->services_to_start_.push_back(service); }
|
||||
@@ -114,9 +118,13 @@ class BLEServer final : public Component, public Parented<ESP32BLE> {
|
||||
struct ServiceEntry {
|
||||
ESPBTUUID uuid;
|
||||
uint8_t inst_id;
|
||||
bool owned; // allocated by create_service(), freed by remove_service()
|
||||
BLEService *service;
|
||||
};
|
||||
|
||||
static constexpr uint8_t INVALID_INST_ID = 0xFF;
|
||||
uint8_t free_inst_id_(const ESPBTUUID &uuid);
|
||||
void register_service_(BLEService &service, uint8_t inst_id, bool owned);
|
||||
void restart_advertising_();
|
||||
void request_advertising_();
|
||||
void release_advertising_();
|
||||
|
||||
@@ -12,8 +12,25 @@ BLEService::BLEService(ESPBTUUID uuid, uint16_t num_handles, uint8_t inst_id, bo
|
||||
: uuid_(uuid), num_handles_(num_handles), inst_id_(inst_id), advertise_(advertise) {}
|
||||
|
||||
BLEService::~BLEService() {
|
||||
for (auto &chr : this->characteristics_)
|
||||
delete chr; // NOLINT(cppcoreguidelines-owning-memory)
|
||||
for (auto *chr : this->characteristics_) {
|
||||
if (chr->owned_) {
|
||||
delete chr; // NOLINT(cppcoreguidelines-owning-memory)
|
||||
} else if (chr->service_ == this) {
|
||||
// A caller-owned characteristic outlives this service, and may already belong to another one
|
||||
chr->service_ = nullptr;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool BLEService::add_characteristic(BLECharacteristic &characteristic) {
|
||||
// Bound until the parent is destroyed
|
||||
if (characteristic.service_ != nullptr) {
|
||||
ESP_LOGE(TAG, "Already added");
|
||||
return false;
|
||||
}
|
||||
characteristic.service_ = this;
|
||||
this->characteristics_.push_back(&characteristic);
|
||||
return true;
|
||||
}
|
||||
|
||||
BLECharacteristic *BLEService::get_characteristic(ESPBTUUID uuid) {
|
||||
@@ -39,7 +56,8 @@ BLECharacteristic *BLEService::create_characteristic(ESPBTUUID uuid, esp_gatt_ch
|
||||
esp_gatt_perm_t permissions) {
|
||||
// NOLINTNEXTLINE(cppcoreguidelines-owning-memory)
|
||||
BLECharacteristic *characteristic = new BLECharacteristic(uuid, properties, permissions);
|
||||
this->characteristics_.push_back(characteristic);
|
||||
characteristic->owned_ = true;
|
||||
this->add_characteristic(*characteristic);
|
||||
return characteristic;
|
||||
}
|
||||
|
||||
@@ -69,8 +87,14 @@ void BLEService::do_delete() {
|
||||
// Call all characteristics to delete
|
||||
for (auto *characteristic : this->characteristics_)
|
||||
characteristic->do_delete();
|
||||
// Not created on the stack yet; if a create is in flight, the server deletes it when its handle arrives
|
||||
if (this->handle_ == 0xFFFF) {
|
||||
this->state_ = DELETED;
|
||||
return;
|
||||
}
|
||||
this->stop_();
|
||||
esp_err_t err = esp_ble_gatts_delete_service(this->handle_);
|
||||
this->handle_ = 0xFFFF; // a later add creates it again with a new handle
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGE(TAG, "esp_ble_gatts_delete_service failed: %d", err);
|
||||
return;
|
||||
@@ -87,7 +111,7 @@ bool BLEService::do_create_characteristics_() {
|
||||
|
||||
auto *characteristic = this->characteristics_[this->created_characteristic_count_++];
|
||||
this->last_created_characteristic_ = characteristic;
|
||||
characteristic->do_create(this);
|
||||
characteristic->do_create();
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -140,7 +164,7 @@ void BLEService::gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t g
|
||||
esp_ble_gatts_cb_param_t *param) {
|
||||
switch (event) {
|
||||
case ESP_GATTS_CREATE_EVT: {
|
||||
if (this->uuid_ == ESPBTUUID::from_uuid(param->create.service_id.id.uuid) &&
|
||||
if (this->state_ == CREATING && this->uuid_ == ESPBTUUID::from_uuid(param->create.service_id.id.uuid) &&
|
||||
this->inst_id_ == param->create.service_id.id.inst_id) {
|
||||
this->handle_ = param->create.service_handle;
|
||||
this->state_ = CREATED;
|
||||
|
||||
@@ -20,8 +20,12 @@ class BLEServer;
|
||||
using namespace esp32_ble;
|
||||
|
||||
class BLEService final {
|
||||
friend class BLEServer;
|
||||
|
||||
public:
|
||||
BLEService(ESPBTUUID uuid, uint16_t num_handles, uint8_t inst_id, bool advertise);
|
||||
/// The server picks the instance id when the service is added.
|
||||
BLEService(ESPBTUUID uuid, uint16_t num_handles, bool advertise) : BLEService(uuid, num_handles, 0, advertise) {}
|
||||
~BLEService();
|
||||
BLECharacteristic *get_characteristic(ESPBTUUID uuid);
|
||||
BLECharacteristic *get_characteristic(uint16_t uuid);
|
||||
@@ -32,6 +36,8 @@ class BLEService final {
|
||||
esp_gatt_perm_t permissions = ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE);
|
||||
BLECharacteristic *create_characteristic(ESPBTUUID uuid, esp_gatt_char_prop_t properties,
|
||||
esp_gatt_perm_t permissions = ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE);
|
||||
/// Adds a characteristic the caller keeps alive; it is never freed here. False when it already belongs to a service.
|
||||
bool add_characteristic(BLECharacteristic &characteristic);
|
||||
|
||||
ESPBTUUID get_uuid() { return this->uuid_; }
|
||||
uint8_t get_inst_id() { return this->inst_id_; }
|
||||
|
||||
@@ -180,23 +180,18 @@ void ArduinoI2CBus::recover_() {
|
||||
return;
|
||||
}
|
||||
|
||||
// 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
|
||||
// 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
|
||||
|
||||
delayMicroseconds(half_period_usec);
|
||||
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
|
||||
// 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
|
||||
delayMicroseconds(half_period_usec);
|
||||
|
||||
// Release output and activate pull up resistor to make the signal HIGH.
|
||||
@@ -223,14 +218,7 @@ void ArduinoI2CBus::recover_() {
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
// A device still holding SDA after nine pulses cannot be freed here.
|
||||
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;
|
||||
@@ -242,15 +230,13 @@ 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."
|
||||
// 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.
|
||||
// SDA high does not mean the device is idle (it may be mid-byte); the START resets it.
|
||||
// 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
|
||||
pinMode(this->sda_pin_, OUTPUT); // NOLINT
|
||||
pinMode(this->sda_pin_, INPUT); // NOLINT
|
||||
digitalWrite(this->sda_pin_, LOW); // NOLINT
|
||||
pinMode(this->sda_pin_, OUTPUT); // NOLINT
|
||||
|
||||
// From the specification:
|
||||
// "A START condition immediately followed by a STOP condition (void
|
||||
|
||||
@@ -346,14 +346,9 @@ void IDFI2CBus::recover_() {
|
||||
return;
|
||||
}
|
||||
|
||||
// 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++) {
|
||||
// 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++) {
|
||||
gpio_set_level(scl_pin, 0);
|
||||
delayMicroseconds(half_period_usec);
|
||||
gpio_set_level(scl_pin, 1);
|
||||
@@ -378,9 +373,7 @@ void IDFI2CBus::recover_() {
|
||||
}
|
||||
}
|
||||
|
||||
// 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.
|
||||
// A device still holding SDA after nine pulses cannot be freed here.
|
||||
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;
|
||||
@@ -392,10 +385,7 @@ 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."
|
||||
// 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.
|
||||
// SDA high does not mean the device is idle (it may be mid-byte); the START resets it.
|
||||
// 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);
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
#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
|
||||
@@ -0,0 +1,67 @@
|
||||
#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
|
||||
@@ -1,5 +1,6 @@
|
||||
#ifdef USE_ESP32
|
||||
#include "modem_component.h"
|
||||
#include "at_reply.h"
|
||||
#include "soc/soc_caps.h"
|
||||
#include <driver/uart.h>
|
||||
|
||||
@@ -42,6 +43,14 @@ 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
|
||||
@@ -56,6 +65,12 @@ 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;
|
||||
@@ -73,8 +88,22 @@ 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", "PPP link failed",
|
||||
"Modem teardown failed");
|
||||
"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);
|
||||
}
|
||||
|
||||
// Indexed by esp_modem::command_result
|
||||
PROGMEM_STRING_TABLE(CommandResultStrings, "OK", "FAIL", "TIMEOUT");
|
||||
@@ -586,6 +615,9 @@ 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
|
||||
@@ -611,21 +643,18 @@ 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 (uart_set_baudrate(static_cast<uart_port_t>(this->uart_port_), baud) != ESP_OK) {
|
||||
if (this->set_uart_baud_(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) {
|
||||
@@ -633,11 +662,31 @@ ModemState ModemComponent::handle_state_enabling_() {
|
||||
}
|
||||
}
|
||||
if (!found) {
|
||||
// The detection at the current rate already failed; a UART that refused every other rate set BAUD
|
||||
if (!probed && !rejected) {
|
||||
// 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) {
|
||||
this->not_responding_(detected);
|
||||
}
|
||||
return this->retry_(ModemState::MODEM_STATE_ENABLING, this->next_probe_delay_());
|
||||
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);
|
||||
}
|
||||
ESP_LOGD(TAG, "Modem responded at baud %d", this->current_baud_rate_);
|
||||
break;
|
||||
@@ -671,10 +720,19 @@ 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.
|
||||
@@ -690,6 +748,7 @@ 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);
|
||||
@@ -698,12 +757,11 @@ 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 (uart_set_baudrate(static_cast<uart_port_t>(this->uart_port_), this->baud_rate_) != ESP_OK) {
|
||||
if (this->set_uart_baud_(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);
|
||||
@@ -731,6 +789,7 @@ 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;
|
||||
}
|
||||
|
||||
@@ -746,12 +805,13 @@ 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; only a failed attachment read comes back here unsure of the modem
|
||||
// ENABLING just synced; a command that timed out comes back here unsure of the modem
|
||||
if (this->resync_) {
|
||||
this->resync_ = false;
|
||||
if (this->dce_->sync() != command_result::OK) {
|
||||
@@ -792,35 +852,78 @@ ModemState ModemComponent::handle_state_connecting_() {
|
||||
}
|
||||
this->connect_step_ = ConnectStep::CONNECT_STEP_RADIO_ON;
|
||||
this->attach_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;
|
||||
this->idle_polls_ = 0;
|
||||
this->unknown_polls_ = 0;
|
||||
}
|
||||
|
||||
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->connect_step_ = ConnectStep::CONNECT_STEP_START; // start over with a sync on the next pass
|
||||
this->resync_ = true;
|
||||
this->request_resync_();
|
||||
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, registration = -1, mode = -1; // -1 stays when the query fails
|
||||
this->dce_->get_network_registration_state(registration);
|
||||
int rssi = 99, ber = 99, mode = -1; // -1 stays when the query fails
|
||||
this->dce_->get_signal_quality(rssi, ber);
|
||||
this->dce_->get_network_system_mode(mode);
|
||||
ESP_LOGW(TAG, "Modem not attached yet: registration %d, network type %d, CSQ %d, BER %d", registration, mode,
|
||||
rssi, ber);
|
||||
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_);
|
||||
}
|
||||
this->connect_step_ = ConnectStep::CONNECT_STEP_RADIO_ON; // request the attachment again
|
||||
}
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_NOT_ATTACHED);
|
||||
this->set_fault_(registration == REGISTRATION_DENIED ? ModemFault::MODEM_FAULT_REGISTRATION_DENIED
|
||||
: ModemFault::MODEM_FAULT_NOT_ATTACHED);
|
||||
return this->retry_(ModemState::MODEM_STATE_CONNECTING, ATTACH_POLL_MS);
|
||||
}
|
||||
|
||||
@@ -923,11 +1026,114 @@ 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) {
|
||||
ESP_LOGW(TAG, "Modem not responding at %d baud. Check power, PWRKEY and TX/RX wiring.", 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);
|
||||
}
|
||||
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); }
|
||||
|
||||
@@ -954,13 +1160,54 @@ 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) {
|
||||
std::string output;
|
||||
const command_result result = this->dce_->at(cmd, output, 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("...") : "";
|
||||
if (result == command_result::OK) {
|
||||
ESP_LOGI(TAG, "AT '%s' -> OK: %s", cmd, output.c_str());
|
||||
ESP_LOGI(TAG, "AT '%s' -> OK: %s%s", cmd, cut, this->reply_);
|
||||
} else {
|
||||
ESP_LOGW(TAG, "AT '%s' -> %s: %s", cmd, LOG_STR_ARG(result_to_str(result)), output.c_str());
|
||||
ESP_LOGW(TAG, "AT '%s' -> %s: %s%s", cmd, LOG_STR_ARG(result_to_str(result)), cut, this->reply_);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -973,25 +1220,27 @@ SimResult ModemComponent::prepare_sim_() {
|
||||
return SimResult::SIM_RESULT_RETRY; // the save wakes the task
|
||||
}
|
||||
#endif
|
||||
std::string output;
|
||||
if (this->dce_->at("AT+CPIN?", output, COMMAND_TIMEOUT_MS) != command_result::OK) {
|
||||
// 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) {
|
||||
// A SIM that is still starting answers with an error for a second or so
|
||||
ESP_LOGD(TAG, "SIM status not readable yet: %s", output.c_str());
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
|
||||
ESP_LOGD(TAG, "SIM status not readable yet: %s", this->reply_);
|
||||
this->sim_not_ready_(this->reply_);
|
||||
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 = strstr(output.c_str(), "+CPIN:");
|
||||
if (found != nullptr) {
|
||||
found += sizeof("+CPIN:") - 1;
|
||||
while (*found == ' ') {
|
||||
found++;
|
||||
}
|
||||
}
|
||||
const char *found = sim_status(this->reply_);
|
||||
const StringRef status = found != nullptr ? StringRef(found) : StringRef();
|
||||
if (status.empty()) {
|
||||
ESP_LOGD(TAG, "SIM status not reported yet: %s", output.c_str());
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_SIM_NOT_READY);
|
||||
ESP_LOGD(TAG, "SIM status not reported yet: %s", this->reply_);
|
||||
this->sim_not_ready_(this->reply_);
|
||||
return SimResult::SIM_RESULT_RETRY;
|
||||
}
|
||||
ESP_LOGD(TAG, "SIM: %s", status.c_str());
|
||||
@@ -1019,8 +1268,8 @@ SimResult ModemComponent::prepare_sim_() {
|
||||
this->set_fault_(ModemFault::MODEM_FAULT_SIM_LOCKED);
|
||||
return SimResult::SIM_RESULT_LOCKED;
|
||||
}
|
||||
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);
|
||||
ESP_LOGD(TAG, "SIM not ready: %s", status.c_str()); // e.g. NOT READY or NOT INSERTED
|
||||
this->sim_not_ready_(status.c_str());
|
||||
return SimResult::SIM_RESULT_RETRY;
|
||||
}
|
||||
#ifdef USE_MODEM_PIN_CODE
|
||||
|
||||
@@ -62,6 +62,7 @@ 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,
|
||||
};
|
||||
@@ -151,6 +152,7 @@ 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;
|
||||
@@ -200,8 +202,20 @@ 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
|
||||
@@ -221,6 +235,9 @@ 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_;
|
||||
@@ -291,6 +308,9 @@ 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};
|
||||
@@ -298,7 +318,8 @@ 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 resync_{false}; // the attachment read failed, so CONNECTING syncs again first
|
||||
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 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];
|
||||
|
||||
@@ -2,10 +2,6 @@
|
||||
#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");
|
||||
@@ -27,10 +23,6 @@ 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),
|
||||
|
||||
@@ -4,6 +4,7 @@ from __future__ import annotations
|
||||
|
||||
from collections.abc import Callable
|
||||
from pathlib import Path
|
||||
import re
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -147,6 +148,42 @@ def test_set_value_constants_share_a_flash_table(
|
||||
assert "ByteBuffer::wrap" not in main_cpp
|
||||
|
||||
|
||||
def test_yaml_services_and_characteristics_are_static(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
component_config_path: Callable[[str], Path],
|
||||
) -> None:
|
||||
main_cpp = generate_main(component_config_path("own_service.yaml"))
|
||||
|
||||
# Placement new into static storage, with handle count then advertise
|
||||
service = re.search(
|
||||
r"new\((\w+)\) esp32_ble_server::BLEService\("
|
||||
r'esp32_ble::ESPBTUUID::from_raw\("2A24B789-7AAB-4535-AF3E-EE76A35CC12D"\), \d+, (?:true|false)\);',
|
||||
main_cpp,
|
||||
)
|
||||
assert service is not None
|
||||
assert f"ble_server->add_service((*{service[1]}));" in main_cpp
|
||||
characteristic = re.search(
|
||||
r"new\((\w+)\) esp32_ble_server::BLECharacteristic\("
|
||||
r'esp32_ble::ESPBTUUID::from_raw\("CAD48E28-7FBE-41CF-BAE9-D77A6C233423"\)',
|
||||
main_cpp,
|
||||
)
|
||||
assert characteristic is not None
|
||||
assert f"{service[1]}->add_characteristic((*{characteristic[1]}));" in main_cpp
|
||||
assert "create_service(" not in main_cpp
|
||||
assert "create_characteristic(" not in main_cpp
|
||||
|
||||
|
||||
def test_yaml_descriptors_are_added_by_reference(
|
||||
generate_main: Callable[[str | Path], str],
|
||||
component_config_path: Callable[[str], Path],
|
||||
) -> None:
|
||||
main_cpp = generate_main(component_config_path("set_value.yaml"))
|
||||
|
||||
# Descriptors live in static storage, so the characteristic must not take ownership
|
||||
assert "->add_descriptor((*test_descriptor));" in main_cpp
|
||||
assert "->add_descriptor(test_descriptor);" not in main_cpp
|
||||
|
||||
|
||||
def test_float32_rejects_out_of_range() -> None:
|
||||
for value in (1e40, -1e40):
|
||||
with pytest.raises(cv.Invalid, match="out of range for a float"):
|
||||
|
||||
@@ -1,3 +1,18 @@
|
||||
esphome:
|
||||
on_boot:
|
||||
- lambda: |-
|
||||
// Objects the caller keeps alive, registered without heap allocation
|
||||
static esp32_ble_server::BLEService battery(esp32_ble::ESPBTUUID::from_uint16(0x180F), 6, false);
|
||||
static esp32_ble_server::BLECharacteristic level(
|
||||
esp32_ble::ESPBTUUID::from_uint16(0x2A19),
|
||||
esp32_ble_server::BLECharacteristic::PROPERTY_READ | esp32_ble_server::BLECharacteristic::PROPERTY_NOTIFY,
|
||||
ESP_GATT_PERM_READ);
|
||||
static esp32_ble_server::BLE2902 level_cccd;
|
||||
level.add_descriptor(level_cccd);
|
||||
battery.add_characteristic(level);
|
||||
if (id(ble_server).add_service(battery))
|
||||
id(ble_server).enqueue_start_service(&battery);
|
||||
|
||||
esp32_ble_server:
|
||||
id: ble_server
|
||||
manufacturer_data: [0x72, 0x4, 0x00, 0x23]
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
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}
|
||||
)
|
||||
@@ -0,0 +1,211 @@
|
||||
#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
|
||||
Reference in new issue
Block a user