mirror of
https://github.com/esphome/esphome.git
synced 2026-11-18 02:55:59 +00:00
Compare commits
4
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c29ca6323e | ||
|
|
95ca52e270 | ||
|
|
be9ddd3243 | ||
|
|
7256cb5bb0 |
No files matched your search
@@ -489,7 +489,6 @@ esphome/components/pca9505/* @ajfriesen @ssieb
|
||||
esphome/components/pca9554/* @bdraco @clydebarrow @hwstar
|
||||
esphome/components/pcf85063/* @brogon
|
||||
esphome/components/pcf8563/* @KoenBreeman
|
||||
esphome/components/pcm1863/* @anabolyc
|
||||
esphome/components/pcm5122/* @remcom
|
||||
esphome/components/pd_pioneer_ir/* @martinsah
|
||||
esphome/components/pi4ioe5v6408/* @jesserockz
|
||||
@@ -736,7 +735,6 @@ esphome/components/veml7700/* @latonita
|
||||
esphome/components/version/* @esphome/core
|
||||
esphome/components/vevor_dtx/* @Bofr5555
|
||||
esphome/components/vl53l1x/* @will-tm
|
||||
esphome/components/vl6180x/* @NonaSuomy
|
||||
esphome/components/vnc/* @MindFreeze
|
||||
esphome/components/voice_assistant/* @jesserockz @kahrendt
|
||||
esphome/components/wake_on_lan/* @clydebarrow @willwill2will54
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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
|
||||
@@ -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
|
||||
@@ -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
|
||||
|
||||
@@ -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];
|
||||
|
||||
@@ -1,3 +0,0 @@
|
||||
"""PCM1863 audio ADC component."""
|
||||
|
||||
DOMAIN = "pcm1863"
|
||||
@@ -1,62 +0,0 @@
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import i2c
|
||||
from esphome.components.audio_adc import AudioAdc
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_BITS_PER_SAMPLE, CONF_INPUT, CONF_MIC_GAIN
|
||||
from esphome.types import ConfigType
|
||||
|
||||
CODEOWNERS = ["@anabolyc"]
|
||||
DEPENDENCIES = ["i2c"]
|
||||
|
||||
CONF_PCM1863_ID = "pcm1863_id"
|
||||
|
||||
# The PGA covers -12 dB to +40 dB in 0.5 dB steps
|
||||
PCM1863_MIC_GAIN_MIN = -12.0
|
||||
PCM1863_MIC_GAIN_MAX = 40.0
|
||||
|
||||
pcm1863_ns = cg.esphome_ns.namespace("pcm1863")
|
||||
PCM1863 = pcm1863_ns.class_("PCM1863", AudioAdc, cg.Component, i2c.I2CDevice)
|
||||
|
||||
pcm1863_input = pcm1863_ns.enum("PCM1863Input")
|
||||
# The declaration order is the select option order and the C++ enum value of each input
|
||||
PCM1863_INPUT_ENUM = pcm1863_input.options(
|
||||
"NONE", "VIN1", "VIN2", "VIN3", "VIN4", "DIFF_1", "DIFF_2", prefix="PCM1863_INPUT_"
|
||||
)
|
||||
|
||||
pcm1863_bits_per_sample = pcm1863_ns.enum("PCM1863BitsPerSample")
|
||||
PCM1863_BITS_PER_SAMPLE_ENUM = {
|
||||
16: pcm1863_bits_per_sample.PCM1863_BITS_PER_SAMPLE_16,
|
||||
20: pcm1863_bits_per_sample.PCM1863_BITS_PER_SAMPLE_20,
|
||||
24: pcm1863_bits_per_sample.PCM1863_BITS_PER_SAMPLE_24,
|
||||
32: pcm1863_bits_per_sample.PCM1863_BITS_PER_SAMPLE_32,
|
||||
}
|
||||
|
||||
_validate_bits = cv.float_with_unit("bits", "bit")
|
||||
|
||||
CONFIG_SCHEMA = (
|
||||
cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(PCM1863),
|
||||
cv.Optional(CONF_BITS_PER_SAMPLE, default="24bit"): cv.All(
|
||||
_validate_bits, cv.enum(PCM1863_BITS_PER_SAMPLE_ENUM)
|
||||
),
|
||||
cv.Optional(CONF_INPUT, default="VIN1"): cv.enum(
|
||||
PCM1863_INPUT_ENUM, upper=True
|
||||
),
|
||||
cv.Optional(CONF_MIC_GAIN, default="0db"): cv.All(
|
||||
cv.decibel,
|
||||
cv.float_range(min=PCM1863_MIC_GAIN_MIN, max=PCM1863_MIC_GAIN_MAX),
|
||||
),
|
||||
}
|
||||
)
|
||||
.extend(cv.COMPONENT_SCHEMA)
|
||||
.extend(i2c.i2c_device_schema(0x4A))
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
var = await i2c.new_i2c_component(config)
|
||||
|
||||
cg.add(var.set_bits_per_sample(config[CONF_BITS_PER_SAMPLE]))
|
||||
cg.add(var.set_input(config[CONF_INPUT]))
|
||||
cg.add(var.set_mic_gain(config[CONF_MIC_GAIN]))
|
||||
@@ -1,96 +0,0 @@
|
||||
#include "pcm1863.h"
|
||||
#include "pcm1863_const.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/progmem.h"
|
||||
#include <cmath>
|
||||
|
||||
namespace esphome::pcm1863 {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "pcm1863");
|
||||
|
||||
// Indexed by PCM1863BitsPerSample
|
||||
PROGMEM_STRING_TABLE(BitsPerSampleStrings, "32", "24", "20", "16");
|
||||
PROGMEM_STRING_TABLE(InputStrings, "NONE", "VIN1", "VIN2", "VIN3", "VIN4", "DIFF_1", "DIFF_2");
|
||||
|
||||
// Page select and power up: bits 2:0 clear is the run state, and the reserved bits 7:3
|
||||
// must be written as 0b01110 or the analog section stops
|
||||
static constexpr i2c::I2CRegValue PCM1863_INIT[] PROGMEM = {
|
||||
{PCM1863_REG_PAGE, PCM1863_PAGE_0},
|
||||
{PCM1863_REG_POWER_CTRL, PCM1863_PWR_CTRL_RSV},
|
||||
};
|
||||
|
||||
void PCM1863::dump_config() {
|
||||
ESP_LOGCONFIG(TAG,
|
||||
"PCM1863 audio ADC:\n"
|
||||
" Bits Per Sample: %s\n"
|
||||
" Input: %s\n"
|
||||
" Mic Gain: %.1f dB",
|
||||
LOG_STR_ARG(BitsPerSampleStrings::get_log_str(this->bits_per_sample_, 0)),
|
||||
LOG_STR_ARG(InputStrings::get_log_str(this->input_, 0)), this->mic_gain_);
|
||||
#ifdef USE_PCM1863_SELECT
|
||||
LOG_SELECT(" ", "Input", this->input_select_);
|
||||
#endif
|
||||
}
|
||||
|
||||
void PCM1863::setup() {
|
||||
// Writing PCM1863_RESET to the page selector restores every register to its default
|
||||
if (!this->setup_check(this->write_byte(PCM1863_REG_PAGE, PCM1863_RESET)))
|
||||
return;
|
||||
delay(2);
|
||||
// The datasheet does not say which page the reset leaves selected, so select page 0 first
|
||||
if (!this->setup_check(this->write_registers(PCM1863_INIT)))
|
||||
return;
|
||||
|
||||
if (!this->setup_check(this->configure_i2s_format_() && this->configure_input_() && this->configure_mic_gain_()))
|
||||
return;
|
||||
|
||||
this->setup_complete_ = true;
|
||||
|
||||
#ifdef USE_PCM1863_SELECT
|
||||
// Show the input the ADC booted with, so the select does not start out blank
|
||||
PUBLISH_STATE(this->input_select_, this->input_);
|
||||
#endif
|
||||
}
|
||||
|
||||
bool PCM1863::set_mic_gain(float mic_gain) {
|
||||
// Nothing reaches the chip after a failed setup, so report the change as not applied
|
||||
if (this->is_failed())
|
||||
return false;
|
||||
this->mic_gain_ = clamp<float>(mic_gain, PCM1863_MIC_GAIN_MIN, PCM1863_MIC_GAIN_MAX);
|
||||
if (!this->setup_complete_)
|
||||
return true;
|
||||
return this->status_comm_result(this->configure_mic_gain_());
|
||||
}
|
||||
|
||||
bool PCM1863::configure_mic_gain_() {
|
||||
// The PGA gain registers take a two's complement value in 0.5 dB steps
|
||||
const auto reg_val = static_cast<uint8_t>(lroundf(this->mic_gain_ / PCM1863_MIC_GAIN_STEP));
|
||||
return this->write_byte(PCM1863_REG_PGA_VAL_CH1_L, reg_val) && this->write_byte(PCM1863_REG_PGA_VAL_CH1_R, reg_val);
|
||||
}
|
||||
|
||||
bool PCM1863::set_input(PCM1863Input input) {
|
||||
if (this->is_failed())
|
||||
return false;
|
||||
this->input_ = input;
|
||||
if (!this->setup_complete_)
|
||||
return true;
|
||||
return this->status_comm_result(this->configure_input_());
|
||||
}
|
||||
|
||||
bool PCM1863::configure_input_() {
|
||||
// Bit 6 of both input select registers is reserved and must always be written as 1
|
||||
const uint8_t mux = this->input_ == PCM1863_INPUT_NONE ? 0 : 1 << (this->input_ - 1);
|
||||
const uint8_t reg_val = PCM1863_INPUT_SEL_RSV | mux;
|
||||
return this->write_byte(PCM1863_REG_ADC1_INPUT_SEL_L, reg_val) &&
|
||||
this->write_byte(PCM1863_REG_ADC1_INPUT_SEL_R, reg_val);
|
||||
}
|
||||
|
||||
bool PCM1863::configure_i2s_format_() {
|
||||
const uint8_t wlen = this->bits_per_sample_;
|
||||
const uint8_t reg_val =
|
||||
(wlen << PCM1863_PCM_CFG_RX_WLEN_SHIFT) | (wlen << PCM1863_PCM_CFG_TX_WLEN_SHIFT) | PCM1863_PCM_CFG_FMT_I2S;
|
||||
return this->write_byte(PCM1863_REG_PCM_CFG, reg_val);
|
||||
}
|
||||
|
||||
} // namespace esphome::pcm1863
|
||||
@@ -1,64 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/components/audio_adc/audio_adc.h"
|
||||
#include "esphome/components/i2c/i2c.h"
|
||||
#include "esphome/core/component.h"
|
||||
#ifdef USE_PCM1863_SELECT
|
||||
#include "esphome/components/select/select.h"
|
||||
#endif
|
||||
|
||||
#include "pcm1863_const.h"
|
||||
|
||||
namespace esphome::pcm1863 {
|
||||
|
||||
// Positions of the select options, in the order audio_adc.py declares them
|
||||
enum PCM1863Input : uint8_t {
|
||||
PCM1863_INPUT_NONE,
|
||||
PCM1863_INPUT_VIN1,
|
||||
PCM1863_INPUT_VIN2,
|
||||
PCM1863_INPUT_VIN3,
|
||||
PCM1863_INPUT_VIN4,
|
||||
PCM1863_INPUT_DIFF_1,
|
||||
PCM1863_INPUT_DIFF_2,
|
||||
};
|
||||
|
||||
// The word length code of PCM1863_REG_PCM_CFG
|
||||
enum PCM1863BitsPerSample : uint8_t {
|
||||
PCM1863_BITS_PER_SAMPLE_32,
|
||||
PCM1863_BITS_PER_SAMPLE_24,
|
||||
PCM1863_BITS_PER_SAMPLE_20,
|
||||
PCM1863_BITS_PER_SAMPLE_16,
|
||||
};
|
||||
|
||||
/// Texas Instruments PCM1863 stereo audio ADC for line and microphone input.
|
||||
/// The register map and reset sequence follow the datasheet (SLAS831D) and the Linux
|
||||
/// kernel driver in sound/soc/codecs/pcm186x.c.
|
||||
class PCM1863 final : public audio_adc::AudioAdc, public Component, public i2c::I2CDevice {
|
||||
#ifdef USE_PCM1863_SELECT
|
||||
SUB_SELECT(input)
|
||||
#endif
|
||||
|
||||
public:
|
||||
void setup() override;
|
||||
void dump_config() override;
|
||||
|
||||
void set_bits_per_sample(PCM1863BitsPerSample bits_per_sample) { this->bits_per_sample_ = bits_per_sample; }
|
||||
|
||||
/// Selects the analog input. Takes effect immediately once setup has run.
|
||||
bool set_input(PCM1863Input input);
|
||||
|
||||
bool set_mic_gain(float mic_gain) override;
|
||||
float mic_gain() override { return this->mic_gain_; }
|
||||
|
||||
protected:
|
||||
bool configure_i2s_format_();
|
||||
bool configure_mic_gain_();
|
||||
bool configure_input_();
|
||||
|
||||
float mic_gain_{0};
|
||||
bool setup_complete_{false};
|
||||
PCM1863BitsPerSample bits_per_sample_{PCM1863_BITS_PER_SAMPLE_24};
|
||||
PCM1863Input input_{PCM1863_INPUT_VIN1};
|
||||
};
|
||||
|
||||
} // namespace esphome::pcm1863
|
||||
@@ -1,50 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace esphome::pcm1863 {
|
||||
|
||||
// PCM1863 page 0 register addresses.
|
||||
// Names and layout follow the Texas Instruments PCM186x family register map (SLAS831D).
|
||||
static constexpr uint8_t PCM1863_REG_PAGE = 0x00; /* Page selector; writing 0xFE triggers a full reset */
|
||||
static constexpr uint8_t PCM1863_REG_PGA_VAL_CH1_L = 0x01; /* ADC1 left PGA gain, 0.5 dB/LSB, two's complement */
|
||||
static constexpr uint8_t PCM1863_REG_PGA_VAL_CH1_R = 0x02; /* ADC1 right PGA gain, 0.5 dB/LSB, two's complement */
|
||||
static constexpr uint8_t PCM1863_REG_ADC1_INPUT_SEL_L = 0x06;
|
||||
static constexpr uint8_t PCM1863_REG_ADC1_INPUT_SEL_R = 0x07;
|
||||
static constexpr uint8_t PCM1863_REG_PCM_CFG = 0x0B; /* Word length and serial audio format */
|
||||
static constexpr uint8_t PCM1863_REG_POWER_CTRL = 0x70; /* Power down, sleep and standby */
|
||||
|
||||
// PCM1863_REG_PAGE: the register holds the page number, and the two documented
|
||||
// commands are selecting a page and resetting every register
|
||||
static constexpr uint8_t PCM1863_PAGE_0 = 0x00;
|
||||
static constexpr uint8_t PCM1863_RESET = 0xFE;
|
||||
|
||||
// PCM1863_REG_PCM_CFG: receive word length in bits 7:6, transmit word length in bits 3:2,
|
||||
// serial audio format in bits 1:0. Bit 5 is reserved and bit 4 only applies to TDM; both
|
||||
// are zero at reset and are written as zero here.
|
||||
static constexpr uint8_t PCM1863_PCM_CFG_RX_WLEN_SHIFT = 6;
|
||||
static constexpr uint8_t PCM1863_PCM_CFG_TX_WLEN_SHIFT = 2;
|
||||
|
||||
static constexpr uint8_t PCM1863_PCM_CFG_FMT_I2S = 0x00;
|
||||
|
||||
// PCM1863_REG_ADC1_INPUT_SEL_L / _R
|
||||
// Bit 7 selects signal polarity, bit 6 is reserved and must always be written as 1,
|
||||
// and bits 5:0 pick the analog input. See the PCM186x datasheet, "MUX, MIX, and
|
||||
// Polarity Input Selection".
|
||||
static constexpr uint8_t PCM1863_INPUT_SEL_RSV = 0x40; // bit 6, always write 1
|
||||
// Bits 5:0 select one input: none, VIN1 to VIN4 single-ended (0x01 to 0x08), then the
|
||||
// differential pairs VIN1/VIN2 (0x10) and VIN4/VIN3 (0x20)
|
||||
|
||||
// PCM1863_REG_POWER_CTRL
|
||||
// Bits 2:0 are power down, sleep and standby; all three are clear in the run state.
|
||||
// Bits 7:3 are reserved and the datasheet requires them to always be written as 0b01110,
|
||||
// which is also their reset value. Writing them as zero stops the analog section.
|
||||
static constexpr uint8_t PCM1863_PWR_CTRL_RSV = 0x70;
|
||||
|
||||
// The PGA gain registers hold a two's complement value in 0.5 dB steps,
|
||||
// from -24 (-12 dB) to +80 (+40 dB)
|
||||
static constexpr float PCM1863_MIC_GAIN_MIN = -12.0f;
|
||||
static constexpr float PCM1863_MIC_GAIN_MAX = 40.0f;
|
||||
static constexpr float PCM1863_MIC_GAIN_STEP = 0.5f;
|
||||
|
||||
} // namespace esphome::pcm1863
|
||||
@@ -1,32 +0,0 @@
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import select
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import ENTITY_CATEGORY_CONFIG, ICON_CHIP
|
||||
from esphome.types import ConfigType
|
||||
|
||||
from .audio_adc import CONF_PCM1863_ID, PCM1863, PCM1863_INPUT_ENUM
|
||||
|
||||
PCM1863_INPUT_OPTIONS = list(PCM1863_INPUT_ENUM)
|
||||
|
||||
CONFIG_SCHEMA = select.select_schema(
|
||||
select.ApplySelect,
|
||||
entity_category=ENTITY_CATEGORY_CONFIG,
|
||||
icon=ICON_CHIP,
|
||||
).extend(
|
||||
{
|
||||
cv.GenerateID(CONF_PCM1863_ID): cv.use_id(PCM1863),
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
cg.add_define("USE_PCM1863_SELECT")
|
||||
hub = await cg.get_variable(config[CONF_PCM1863_ID])
|
||||
# The ADC publishes the new option only once the I2C write went through
|
||||
await select.sub_selects(config, parent=hub).create(
|
||||
config,
|
||||
hub.set_input_select,
|
||||
options=PCM1863_INPUT_OPTIONS,
|
||||
apply="set_input(static_cast<pcm1863::PCM1863Input>(index))",
|
||||
publish="on_success",
|
||||
)
|
||||
@@ -10,12 +10,10 @@ CODEOWNERS = ["@kahrendt"]
|
||||
|
||||
qwiic_pir_ns = cg.esphome_ns.namespace("qwiic_pir")
|
||||
|
||||
DebounceMode = qwiic_pir_ns.enum("DebounceMode")
|
||||
DEBOUNCE_MODE_OPTIONS = {
|
||||
"RAW": DebounceMode.RAW_DEBOUNCE_MODE,
|
||||
"NATIVE": DebounceMode.NATIVE_DEBOUNCE_MODE,
|
||||
"HYBRID": DebounceMode.HYBRID_DEBOUNCE_MODE,
|
||||
}
|
||||
DebounceMode = qwiic_pir_ns.enum("DebounceMode", is_class=True)
|
||||
DEBOUNCE_MODE_OPTIONS = DebounceMode.options(
|
||||
"RAW", "NATIVE", "HYBRID", prefix="DEBOUNCE_MODE_"
|
||||
)
|
||||
|
||||
CONF_DEBOUNCE_MODE = "debounce_mode"
|
||||
|
||||
@@ -47,12 +45,12 @@ CONFIG_SCHEMA = cv.All(
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
var = await binary_sensor.new_binary_sensor(config)
|
||||
# Without a debounce time the device is set to 1 ms; NATIVE is the only mode that takes one
|
||||
debounce = config.get(CONF_DEBOUNCE)
|
||||
var = await binary_sensor.new_binary_sensor(
|
||||
config,
|
||||
config[CONF_DEBOUNCE_MODE],
|
||||
1 if debounce is None else debounce.total_milliseconds,
|
||||
)
|
||||
await cg.register_component(var, config)
|
||||
await i2c.register_i2c_device(var, config)
|
||||
|
||||
if debounce_time_setting := config.get(CONF_DEBOUNCE):
|
||||
cg.add(var.set_debounce_time(debounce_time_setting.total_milliseconds))
|
||||
else:
|
||||
cg.add(var.set_debounce_time(1)) # default to 1 ms if not configured
|
||||
cg.add(var.set_debounce_mode(config[CONF_DEBOUNCE_MODE]))
|
||||
@@ -1,99 +1,85 @@
|
||||
#include "qwiic_pir.h"
|
||||
#include "esphome/core/log.h"
|
||||
#include "esphome/core/progmem.h"
|
||||
|
||||
namespace esphome::qwiic_pir {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "qwiic_pir");
|
||||
|
||||
static constexpr uint8_t REG_CHIP_ID = 0x00;
|
||||
static constexpr uint8_t REG_EVENT_STATUS = 0x03;
|
||||
static constexpr uint8_t REG_DEBOUNCE_TIME = 0x05; // milliseconds, 16 bits little endian
|
||||
|
||||
static constexpr uint8_t DEVICE_ID = 0x72;
|
||||
|
||||
// REG_EVENT_STATUS bits
|
||||
static constexpr uint8_t EVENT_RAW_READING = 0x01; // raw state of the PIR sensor
|
||||
static constexpr uint8_t EVENT_AVAILABLE = 0x02; // a debounced object was detected or removed
|
||||
static constexpr uint8_t EVENT_OBJECT_REMOVED = 0x04; // a debounced object is no longer detected
|
||||
static constexpr uint8_t EVENT_OBJECT_DETECTED = 0x08; // a debounced object has been detected
|
||||
|
||||
// Indexed by DebounceMode
|
||||
PROGMEM_STRING_TABLE(DebounceModeStrings, "RAW", "NATIVE", "HYBRID");
|
||||
|
||||
void QwiicPIRComponent::setup() {
|
||||
if (!this->check_chip_id(this, QWIIC_PIR_CHIP_ID, QWIIC_PIR_DEVICE_ID))
|
||||
if (!this->check_chip_id(this, REG_CHIP_ID, DEVICE_ID))
|
||||
return;
|
||||
|
||||
if (!this->setup_check(this->write_byte_16(QWIIC_PIR_DEBOUNCE_TIME, this->debounce_time_),
|
||||
if (!this->setup_check(this->write_byte_16_le(REG_DEBOUNCE_TIME, this->debounce_time_),
|
||||
LOG_STR("Failed to configure debounce time")))
|
||||
return;
|
||||
|
||||
if (this->debounce_mode_ == NATIVE_DEBOUNCE_MODE) {
|
||||
// Publish the starting raw state of the PIR sensor
|
||||
// If NATIVE mode, the binary_sensor state would be unknown until a motion event
|
||||
if (!this->setup_check(this->read_byte(QWIIC_PIR_EVENT_STATUS, &this->event_register_.reg),
|
||||
LOG_STR("Failed to read initial state")))
|
||||
if (this->debounce_mode_ == DebounceMode::DEBOUNCE_MODE_NATIVE) {
|
||||
// NATIVE only publishes on motion events, so start from the raw state
|
||||
uint8_t event;
|
||||
if (!this->setup_check(this->read_byte(REG_EVENT_STATUS, &event), LOG_STR("Failed to read initial state")))
|
||||
return;
|
||||
|
||||
this->publish_state(this->event_register_.raw_reading);
|
||||
this->publish_state((event & EVENT_RAW_READING) != 0);
|
||||
}
|
||||
}
|
||||
|
||||
void QwiicPIRComponent::loop() {
|
||||
// Read Event Register
|
||||
if (!this->read_byte(QWIIC_PIR_EVENT_STATUS, &this->event_register_.reg)) {
|
||||
ESP_LOGW(TAG, ESP_LOG_MSG_COMM_FAIL);
|
||||
uint8_t event;
|
||||
if (!this->status_comm_check(this->read_byte(REG_EVENT_STATUS, &event)))
|
||||
return;
|
||||
|
||||
switch (this->debounce_mode_) {
|
||||
case DebounceMode::DEBOUNCE_MODE_HYBRID:
|
||||
// The device debounces for 1 ms and ESPHome filters do the rest; any event means motion since the last loop
|
||||
this->publish_state((event & (EVENT_RAW_READING | EVENT_AVAILABLE)) != 0);
|
||||
break;
|
||||
case DebounceMode::DEBOUNCE_MODE_NATIVE:
|
||||
// The device's own debounce, as in SparkFun's Example2_PrintPIRStatus; it often misses objects being removed
|
||||
if (event & EVENT_AVAILABLE) {
|
||||
if (event & EVENT_OBJECT_DETECTED)
|
||||
this->publish_state(true);
|
||||
if (event & EVENT_OBJECT_REMOVED)
|
||||
this->publish_state(false);
|
||||
}
|
||||
break;
|
||||
case DebounceMode::DEBOUNCE_MODE_RAW:
|
||||
// Can miss a very short detection when the loop is slow
|
||||
this->publish_state((event & EVENT_RAW_READING) != 0);
|
||||
break;
|
||||
}
|
||||
|
||||
if (this->debounce_mode_ == HYBRID_DEBOUNCE_MODE) {
|
||||
// Use a combination of the raw sensor reading and the device's event detection to determine state
|
||||
// - The device is hardcoded to use a debounce time of 1 ms in this mode
|
||||
// - Any event, even if it is object_removed, implies motion was active since the last loop, so publish true
|
||||
// - Use ESPHome's built-in filters for debouncing
|
||||
this->publish_state(this->event_register_.raw_reading || this->event_register_.event_available);
|
||||
|
||||
if (this->event_register_.event_available) {
|
||||
this->clear_events_();
|
||||
}
|
||||
} else if (this->debounce_mode_ == NATIVE_DEBOUNCE_MODE) {
|
||||
// Uses the device's firmware to debounce the signal
|
||||
// - Follows the logic of SparkFun's example implementation:
|
||||
// https://github.com/sparkfun/SparkFun_Qwiic_PIR_Arduino_Library/blob/master/examples/Example2_PrintPIRStatus/Example2_PrintPIRStatus.ino
|
||||
// (accessed July 2023)
|
||||
// - Is unreliable at detecting an object being removed, especially at debounce rates even slightly large
|
||||
if (this->event_register_.event_available) {
|
||||
// If an object is detected, publish true
|
||||
if (this->event_register_.object_detected)
|
||||
this->publish_state(true);
|
||||
|
||||
// If an object has been removed, publish false
|
||||
if (this->event_register_.object_removed)
|
||||
this->publish_state(false);
|
||||
|
||||
this->clear_events_();
|
||||
}
|
||||
} else if (this->debounce_mode_ == RAW_DEBOUNCE_MODE) {
|
||||
// Publishes the raw PIR sensor reading with no further logic
|
||||
// - May miss a very short motion detection if the ESP's loop time is slow
|
||||
this->publish_state(this->event_register_.raw_reading);
|
||||
}
|
||||
// HYBRID and NATIVE clear a handled event; the last bus step of the poll decides the warning
|
||||
bool ok = true;
|
||||
if (this->debounce_mode_ != DebounceMode::DEBOUNCE_MODE_RAW && (event & EVENT_AVAILABLE))
|
||||
ok = this->write_byte(REG_EVENT_STATUS, 0x00);
|
||||
this->status_comm_result(ok);
|
||||
}
|
||||
|
||||
void QwiicPIRComponent::dump_config() {
|
||||
static const char *const RAW = "RAW";
|
||||
static const char *const NATIVE = "NATIVE";
|
||||
static const char *const HYBRID = "HYBRID";
|
||||
|
||||
const char *debounce_mode_str = RAW;
|
||||
if (this->debounce_mode_ == NATIVE_DEBOUNCE_MODE) {
|
||||
debounce_mode_str = NATIVE;
|
||||
} else if (this->debounce_mode_ == HYBRID_DEBOUNCE_MODE) {
|
||||
debounce_mode_str = HYBRID;
|
||||
}
|
||||
|
||||
ESP_LOGCONFIG(TAG,
|
||||
"Qwiic PIR:\n"
|
||||
" Debounce Mode: %s",
|
||||
debounce_mode_str);
|
||||
if (this->debounce_mode_ == NATIVE_DEBOUNCE_MODE) {
|
||||
LOG_STR_ARG(DebounceModeStrings::get_log_str(static_cast<uint8_t>(this->debounce_mode_), 0)));
|
||||
if (this->debounce_mode_ == DebounceMode::DEBOUNCE_MODE_NATIVE) {
|
||||
ESP_LOGCONFIG(TAG, " Debounce Time: %ums", this->debounce_time_);
|
||||
}
|
||||
|
||||
LOG_I2C_DEVICE(this);
|
||||
LOG_BINARY_SENSOR(" ", "Binary Sensor", this);
|
||||
}
|
||||
|
||||
void QwiicPIRComponent::clear_events_() {
|
||||
// Clear event status register
|
||||
if (!this->write_byte(QWIIC_PIR_EVENT_STATUS, 0x00)) {
|
||||
ESP_LOGW(TAG, "Failed to clear events");
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace esphome::qwiic_pir
|
||||
@@ -2,8 +2,8 @@
|
||||
* Adds support for Qwiic PIR motion sensors that communicate over an I2C bus.
|
||||
* These sensors use Sharp PIR motion sensors to detect motion. A firmware running on an ATTiny84 translates the digital
|
||||
* output to I2C communications.
|
||||
* ATTiny84 firmware: https://github.com/sparkfun/Qwiic_PIR (accessed July 2023)
|
||||
* SparkFun's Arduino library: https://github.com/sparkfun/SparkFun_Qwiic_PIR_Arduino_Library (accessed July 2023)
|
||||
* ATTiny84 firmware: https://github.com/sparkfun/Qwiic_PIR
|
||||
* SparkFun's Arduino library: https://github.com/sparkfun/SparkFun_Qwiic_PIR_Arduino_Library
|
||||
*/
|
||||
|
||||
#pragma once
|
||||
@@ -14,48 +14,24 @@
|
||||
|
||||
namespace esphome::qwiic_pir {
|
||||
|
||||
// Qwiic PIR I2C Register Addresses
|
||||
enum {
|
||||
QWIIC_PIR_CHIP_ID = 0x00,
|
||||
QWIIC_PIR_EVENT_STATUS = 0x03,
|
||||
QWIIC_PIR_DEBOUNCE_TIME = 0x05, // uint16_t debounce time in milliseconds
|
||||
enum class DebounceMode : uint8_t {
|
||||
DEBOUNCE_MODE_RAW,
|
||||
DEBOUNCE_MODE_NATIVE,
|
||||
DEBOUNCE_MODE_HYBRID,
|
||||
};
|
||||
|
||||
enum DebounceMode {
|
||||
RAW_DEBOUNCE_MODE,
|
||||
NATIVE_DEBOUNCE_MODE,
|
||||
HYBRID_DEBOUNCE_MODE,
|
||||
};
|
||||
|
||||
static const uint8_t QWIIC_PIR_DEVICE_ID = 0x72;
|
||||
|
||||
class QwiicPIRComponent final : public Component, public i2c::I2CDevice, public binary_sensor::BinarySensor {
|
||||
public:
|
||||
QwiicPIRComponent(DebounceMode debounce_mode, uint16_t debounce_time)
|
||||
: debounce_time_(debounce_time), debounce_mode_(debounce_mode) {}
|
||||
|
||||
void setup() override;
|
||||
void loop() override;
|
||||
|
||||
void dump_config() override;
|
||||
|
||||
void set_debounce_time(uint16_t debounce_time) { this->debounce_time_ = debounce_time; }
|
||||
void set_debounce_mode(DebounceMode mode) { this->debounce_mode_ = mode; }
|
||||
|
||||
protected:
|
||||
uint16_t debounce_time_{};
|
||||
|
||||
DebounceMode debounce_mode_{};
|
||||
|
||||
union {
|
||||
struct {
|
||||
bool raw_reading : 1; // raw state of PIR sensor
|
||||
bool event_available : 1; // a debounced object has been detected or removed
|
||||
bool object_removed : 1; // a debounced object is no longer detected
|
||||
bool object_detected : 1; // a debounced object has been detected
|
||||
bool : 4;
|
||||
};
|
||||
uint8_t reg;
|
||||
} event_register_ = {.reg = 0};
|
||||
|
||||
void clear_events_();
|
||||
uint16_t debounce_time_;
|
||||
DebounceMode debounce_mode_;
|
||||
};
|
||||
|
||||
} // namespace esphome::qwiic_pir
|
||||
@@ -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),
|
||||
|
||||
@@ -1,88 +0,0 @@
|
||||
from esphome import pins
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import i2c
|
||||
from esphome.components.i2c import CONF_I2C_ID
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import CONF_ADDRESS, CONF_ENABLE_PIN
|
||||
import esphome.final_validate as fv
|
||||
from esphome.types import ConfigType
|
||||
|
||||
AUTO_LOAD = ["sensor"]
|
||||
CODEOWNERS = ["@NonaSuomy"]
|
||||
DEPENDENCIES = ["i2c"]
|
||||
DOMAIN = "vl6180x"
|
||||
MULTI_CONF = True
|
||||
|
||||
CONF_VL6180X_ID = "vl6180x_id"
|
||||
|
||||
vl6180x_ns = cg.esphome_ns.namespace("vl6180x")
|
||||
VL6180XComponent = vl6180x_ns.class_(
|
||||
"VL6180XComponent", cg.PollingComponent, i2c.I2CDevice
|
||||
)
|
||||
|
||||
_request_enable_pin_slot = cg.slot_counter("VL6180X_ENABLE_PIN_COUNT")
|
||||
|
||||
DEFAULT_ADDRESS = 0x29
|
||||
|
||||
|
||||
def _validate_address(config: ConfigType) -> ConfigType:
|
||||
# The sensor always boots at 0x29; only an enable pin lets it move elsewhere
|
||||
if config[CONF_ADDRESS] != DEFAULT_ADDRESS and CONF_ENABLE_PIN not in config:
|
||||
raise cv.Invalid(
|
||||
f"An address other than 0x{DEFAULT_ADDRESS:02X} needs an enable_pin"
|
||||
)
|
||||
return config
|
||||
|
||||
|
||||
CONFIG_SCHEMA = cv.All(
|
||||
cv.Schema(
|
||||
{
|
||||
cv.GenerateID(): cv.declare_id(VL6180XComponent),
|
||||
cv.Optional(CONF_ENABLE_PIN): pins.gpio_output_pin_schema,
|
||||
}
|
||||
)
|
||||
.extend(cv.polling_component_schema("60s"))
|
||||
.extend(i2c.i2c_device_schema(DEFAULT_ADDRESS)),
|
||||
_validate_address,
|
||||
)
|
||||
|
||||
|
||||
def _final_validate(config: ConfigType) -> ConfigType:
|
||||
# With several sensors on one bus each needs its own enable_pin so it can be held in reset
|
||||
# while the others are re-addressed, and none may stay at 0x29, or a later sibling boots at
|
||||
# the same address and the re-address write reaches both chips.
|
||||
addresses = [
|
||||
conf[CONF_ADDRESS]
|
||||
for conf in fv.full_config.get()[DOMAIN]
|
||||
if conf[CONF_I2C_ID] == config[CONF_I2C_ID]
|
||||
]
|
||||
if len(addresses) < 2:
|
||||
return config
|
||||
if CONF_ENABLE_PIN not in config:
|
||||
raise cv.Invalid(
|
||||
"Every VL6180X on a shared I2C bus needs an enable_pin",
|
||||
path=[CONF_ENABLE_PIN],
|
||||
)
|
||||
address = config[CONF_ADDRESS]
|
||||
if address == DEFAULT_ADDRESS:
|
||||
raise cv.Invalid(
|
||||
f"VL6180X sensors sharing an I2C bus must all be re-addressed away "
|
||||
f"from 0x{DEFAULT_ADDRESS:02X}",
|
||||
path=[CONF_ADDRESS],
|
||||
)
|
||||
if addresses.count(address) > 1:
|
||||
raise cv.Invalid(
|
||||
f"Address 0x{address:02X} is used by more than one VL6180X on this bus",
|
||||
path=[CONF_ADDRESS],
|
||||
)
|
||||
return config
|
||||
|
||||
|
||||
FINAL_VALIDATE_SCHEMA = _final_validate
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
var = await i2c.new_i2c_component(config)
|
||||
if pin := await cg.add_pin(var.set_enable_pin, config.get(CONF_ENABLE_PIN)):
|
||||
_request_enable_pin_slot()
|
||||
cg.add(var.register_enable_pin(pin))
|
||||
@@ -1,80 +0,0 @@
|
||||
import esphome.codegen as cg
|
||||
from esphome.components import sensor
|
||||
import esphome.config_validation as cv
|
||||
from esphome.const import (
|
||||
CONF_DISTANCE,
|
||||
CONF_GAIN,
|
||||
CONF_ILLUMINANCE,
|
||||
CONF_INTEGRATION_TIME,
|
||||
DEVICE_CLASS_DISTANCE,
|
||||
DEVICE_CLASS_ILLUMINANCE,
|
||||
STATE_CLASS_MEASUREMENT,
|
||||
UNIT_LUX,
|
||||
UNIT_MILLIMETER,
|
||||
)
|
||||
import esphome.final_validate as fv
|
||||
from esphome.types import ConfigType
|
||||
|
||||
from . import CONF_VL6180X_ID, DOMAIN, VL6180XComponent
|
||||
|
||||
DEPENDENCIES = ["vl6180x"]
|
||||
|
||||
CONF_SCALER = "scaler"
|
||||
|
||||
# Gain factor to the SYSALS_ANALOGUE_GAIN code
|
||||
ALS_GAINS = {1: 6, 1.25: 5, 1.67: 4, 2.5: 3, 5: 2, 10: 1, 20: 0, 40: 7}
|
||||
|
||||
CONFIG_SCHEMA = cv.All(
|
||||
cv.Schema(
|
||||
{
|
||||
cv.GenerateID(CONF_VL6180X_ID): cv.use_id(VL6180XComponent),
|
||||
cv.Optional(CONF_DISTANCE): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_MILLIMETER,
|
||||
accuracy_decimals=0,
|
||||
device_class=DEVICE_CLASS_DISTANCE,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
).extend(
|
||||
{cv.Optional(CONF_SCALER, default=1): cv.one_of(1, 2, 3, int=True)}
|
||||
),
|
||||
cv.Optional(CONF_ILLUMINANCE): sensor.sensor_schema(
|
||||
unit_of_measurement=UNIT_LUX,
|
||||
accuracy_decimals=1,
|
||||
device_class=DEVICE_CLASS_ILLUMINANCE,
|
||||
state_class=STATE_CLASS_MEASUREMENT,
|
||||
).extend(
|
||||
{
|
||||
cv.Optional(CONF_GAIN, default=1): cv.enum(ALS_GAINS),
|
||||
cv.Optional(CONF_INTEGRATION_TIME, default="100ms"): cv.All(
|
||||
cv.positive_time_period_milliseconds,
|
||||
cv.Range(
|
||||
min=cv.TimePeriod(milliseconds=1),
|
||||
max=cv.TimePeriod(milliseconds=512),
|
||||
),
|
||||
),
|
||||
}
|
||||
),
|
||||
}
|
||||
),
|
||||
cv.has_at_least_one_key(CONF_DISTANCE, CONF_ILLUMINANCE),
|
||||
)
|
||||
|
||||
FINAL_VALIDATE_SCHEMA = fv.unique_platform_key(
|
||||
domain=sensor.DOMAIN,
|
||||
platform=DOMAIN,
|
||||
keys=(CONF_VL6180X_ID,),
|
||||
message="Only one VL6180X sensor platform entry is allowed per hub",
|
||||
)
|
||||
|
||||
|
||||
async def to_code(config: ConfigType) -> None:
|
||||
hub = await cg.get_variable(config[CONF_VL6180X_ID])
|
||||
sensors = sensor.sub_sensors(config)
|
||||
if (distance_config := config.get(CONF_DISTANCE)) is not None:
|
||||
await sensors(CONF_DISTANCE, hub.set_distance_sensor)
|
||||
cg.add(hub.set_scaler(distance_config[CONF_SCALER]))
|
||||
if (illuminance_config := config.get(CONF_ILLUMINANCE)) is not None:
|
||||
await sensors(CONF_ILLUMINANCE, hub.set_illuminance_sensor)
|
||||
gain = illuminance_config[CONF_GAIN]
|
||||
time_ms = illuminance_config[CONF_INTEGRATION_TIME].total_milliseconds
|
||||
# The datasheet scale is 0.32 lux per count at 1x gain and 100 ms
|
||||
cg.add(hub.set_als(gain.enum_value, time_ms, 32.0 / (float(gain) * time_ms)))
|
||||
@@ -1,267 +0,0 @@
|
||||
#include "vl6180x.h"
|
||||
#include "esphome/core/hal.h"
|
||||
#include "esphome/core/log.h"
|
||||
|
||||
namespace esphome::vl6180x {
|
||||
|
||||
ESPHOME_LOG_TAG(TAG, "vl6180x");
|
||||
|
||||
static constexpr uint32_t MEASUREMENT_ID = 0;
|
||||
|
||||
static constexpr uint8_t DEFAULT_ADDRESS = 0x29;
|
||||
static constexpr uint8_t MODEL_ID = 0xB4;
|
||||
|
||||
static constexpr uint16_t REG_IDENTIFICATION_MODEL_ID = 0x000;
|
||||
static constexpr uint16_t REG_SYSTEM_INTERRUPT_CLEAR = 0x015;
|
||||
static constexpr uint16_t REG_SYSTEM_FRESH_OUT_OF_RESET = 0x016;
|
||||
static constexpr uint16_t REG_SYSRANGE_START = 0x018;
|
||||
static constexpr uint16_t REG_SYSRANGE_CROSSTALK_VALID_HEIGHT = 0x021;
|
||||
static constexpr uint16_t REG_SYSRANGE_PART_TO_PART_OFFSET = 0x024;
|
||||
static constexpr uint16_t REG_SYSRANGE_RANGE_CHECK_ENABLES = 0x02D;
|
||||
static constexpr uint16_t REG_SYSALS_START = 0x038;
|
||||
static constexpr uint16_t REG_SYSALS_ANALOGUE_GAIN = 0x03F;
|
||||
static constexpr uint16_t REG_SYSALS_INTEGRATION_PERIOD = 0x040;
|
||||
static constexpr uint16_t REG_RESULT_RANGE_STATUS = 0x04D;
|
||||
static constexpr uint16_t REG_RESULT_ALS_STATUS = 0x04E;
|
||||
static constexpr uint16_t REG_RESULT_RANGE_VAL = 0x062;
|
||||
static constexpr uint16_t REG_RANGE_SCALING = 0x096;
|
||||
static constexpr uint16_t REG_I2C_DEVICE_ADDRESS = 0x212;
|
||||
|
||||
// RESULT_INTERRUPT_STATUS_GPIO: a new range sample in bits 2:0, a new ALS sample in bits 5:3
|
||||
static constexpr uint8_t RANGE_SAMPLE_READY = 0x04;
|
||||
static constexpr uint8_t ALS_SAMPLE_READY = 0x04 << 3;
|
||||
|
||||
// Range conversion is at most the 50 ms convergence time set below plus readout
|
||||
static constexpr uint32_t RANGE_TIME_MS = 70;
|
||||
static constexpr uint32_t ALS_READOUT_MARGIN_MS = 400;
|
||||
|
||||
// Indexed by the range scaler, 1x to 3x (AN4545)
|
||||
static constexpr uint16_t RANGE_SCALING_VALUES[] PROGMEM = {0, 253, 127, 84};
|
||||
|
||||
struct RegValue {
|
||||
uint16_t reg;
|
||||
uint8_t value;
|
||||
};
|
||||
|
||||
// Private settings written once after a power-on reset (AN4545 table 7)
|
||||
static constexpr RegValue MANDATORY_SETTINGS[] PROGMEM = {
|
||||
{0x0207, 0x01},
|
||||
{0x0208, 0x01},
|
||||
{0x0096, 0x00},
|
||||
{0x0097, 0xFD},
|
||||
{0x00E3, 0x00},
|
||||
{0x00E4, 0x04},
|
||||
{0x00E5, 0x02},
|
||||
{0x00E6, 0x01},
|
||||
{0x00E7, 0x03},
|
||||
{0x00F5, 0x02},
|
||||
{0x00D9, 0x05},
|
||||
{0x00DB, 0xCE},
|
||||
{0x00DC, 0x03},
|
||||
{0x00DD, 0xF8},
|
||||
{0x009F, 0x00},
|
||||
{0x00A3, 0x3C},
|
||||
{0x00B7, 0x00},
|
||||
{0x00BB, 0x3C},
|
||||
{0x00B2, 0x09},
|
||||
{0x00CA, 0x09},
|
||||
{0x0198, 0x01},
|
||||
{0x01B0, 0x17},
|
||||
{0x01AD, 0x00},
|
||||
{0x00FF, 0x05},
|
||||
{0x0100, 0x05},
|
||||
{0x0199, 0x05},
|
||||
{0x01A6, 0x1B},
|
||||
{0x01AC, 0x3E},
|
||||
{0x01A7, 0x1F},
|
||||
{0x0030, 0x00},
|
||||
{REG_SYSTEM_FRESH_OUT_OF_RESET, 0x00},
|
||||
};
|
||||
|
||||
// Recommended settings (AN4545 section 9), with GPIO1 left floating and new-sample interrupts flagged
|
||||
static constexpr RegValue DEFAULT_SETTINGS[] PROGMEM = {
|
||||
{0x010A, 0x30}, // averaging sample period
|
||||
{0x0031, 0xFF}, // repeat temperature calibration every 255 range measurements
|
||||
{0x002E, 0x01}, // run the first temperature calibration now
|
||||
{0x001C, 0x32}, // 50 ms maximum convergence time
|
||||
{0x0011, 0x20}, // GPIO1 off
|
||||
{0x0014, RANGE_SAMPLE_READY | ALS_SAMPLE_READY},
|
||||
{REG_SYSTEM_INTERRUPT_CLEAR, 0x07},
|
||||
};
|
||||
|
||||
template<size_t N> static bool write_settings(i2c::I2CDevice *device, const RegValue (&table)[N]) {
|
||||
for (const auto &entry : table) {
|
||||
RegValue setting;
|
||||
progmem_memcpy(&setting, &entry, sizeof(setting));
|
||||
if (!device->write_byte_reg16(setting.reg, setting.value))
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
#ifdef VL6180X_ENABLE_PIN_COUNT
|
||||
SlotList<GPIOPin *, VL6180X_ENABLE_PIN_COUNT> VL6180XComponent::enable_pins; // NOLINT
|
||||
#endif
|
||||
|
||||
void VL6180XComponent::setup() {
|
||||
#ifdef VL6180X_ENABLE_PIN_COUNT
|
||||
// Every sensor boots at 0x29, so all are held in reset and then released one at a time
|
||||
for (auto *pin : enable_pins) {
|
||||
pin->setup();
|
||||
pin->digital_write(false);
|
||||
}
|
||||
enable_pins.clear();
|
||||
if (this->enable_pin_ != nullptr) {
|
||||
this->enable_pin_->digital_write(true);
|
||||
delay(10);
|
||||
}
|
||||
#endif
|
||||
const uint8_t address = this->address_;
|
||||
this->set_i2c_address(DEFAULT_ADDRESS);
|
||||
uint8_t model_id = 0;
|
||||
const bool read_ok = this->read_byte_reg16(REG_IDENTIFICATION_MODEL_ID, &model_id);
|
||||
const bool ok = read_ok && model_id == MODEL_ID && this->init_() &&
|
||||
(address == DEFAULT_ADDRESS || this->write_byte_reg16(REG_I2C_DEVICE_ADDRESS, address));
|
||||
this->set_i2c_address(address);
|
||||
if (ok)
|
||||
return;
|
||||
#ifdef VL6180X_ENABLE_PIN_COUNT
|
||||
// A sensor left at 0x29 would answer for the next one released
|
||||
if (this->enable_pin_ != nullptr)
|
||||
this->enable_pin_->digital_write(false);
|
||||
#endif
|
||||
if (read_ok && model_id != MODEL_ID) {
|
||||
ESP_LOGE(TAG, "Wrong model ID 0x%02X", model_id);
|
||||
this->mark_failed(LOG_STR("Wrong model ID"));
|
||||
return;
|
||||
}
|
||||
this->mark_failed(LOG_STR(ESP_LOG_MSG_COMM_FAIL));
|
||||
}
|
||||
|
||||
bool VL6180XComponent::init_() {
|
||||
uint8_t fresh;
|
||||
uint8_t offset;
|
||||
if (!this->read_byte_reg16(REG_SYSTEM_FRESH_OUT_OF_RESET, &fresh) ||
|
||||
!this->read_byte_reg16(REG_SYSRANGE_PART_TO_PART_OFFSET, &offset))
|
||||
return false;
|
||||
// The factory offset is for 1x; a sensor that kept power through an MCU reboot already holds it divided by the
|
||||
// scaler from the last setup
|
||||
int16_t part_offset = static_cast<int8_t>(offset);
|
||||
if (fresh & 0x01) {
|
||||
if (!write_settings(this, MANDATORY_SETTINGS))
|
||||
return false;
|
||||
} else {
|
||||
uint8_t scaling[2];
|
||||
if (this->read_register16(REG_RANGE_SCALING, scaling, 2) != i2c::ERROR_OK)
|
||||
return false;
|
||||
const uint16_t value = encode_uint16(scaling[0], scaling[1]);
|
||||
for (uint8_t scaler = 2; scaler <= 3; scaler++) {
|
||||
if (value == progmem_read_uint16(&RANGE_SCALING_VALUES[scaler]))
|
||||
part_offset *= scaler;
|
||||
}
|
||||
}
|
||||
|
||||
uint8_t period[2];
|
||||
put_be16(period, this->als_integration_time_ms_ - 1);
|
||||
uint8_t scaling[2];
|
||||
put_be16(scaling, progmem_read_uint16(&RANGE_SCALING_VALUES[this->scaler_]));
|
||||
return write_settings(this, DEFAULT_SETTINGS) &&
|
||||
this->write_byte_reg16(REG_SYSALS_ANALOGUE_GAIN, 0x40 | this->als_gain_code_) &&
|
||||
this->write_register16(REG_SYSALS_INTEGRATION_PERIOD, period, 2) == i2c::ERROR_OK &&
|
||||
this->write_register16(REG_RANGE_SCALING, scaling, 2) == i2c::ERROR_OK &&
|
||||
this->write_byte_reg16(REG_SYSRANGE_PART_TO_PART_OFFSET, static_cast<uint8_t>(part_offset / this->scaler_)) &&
|
||||
this->write_byte_reg16(REG_SYSRANGE_CROSSTALK_VALID_HEIGHT, 20 / this->scaler_) &&
|
||||
// SNR check, plus the early convergence estimate only at 1x, as in ST's API
|
||||
this->write_byte_reg16(REG_SYSRANGE_RANGE_CHECK_ENABLES, 0x10 | (this->scaler_ == 1 ? 0x01 : 0x00));
|
||||
}
|
||||
|
||||
void VL6180XComponent::update() {
|
||||
// A measurement still running means the update interval is shorter than one cycle
|
||||
if (this->measuring_)
|
||||
return;
|
||||
this->measuring_ = true;
|
||||
if (this->distance_sensor_ != nullptr) {
|
||||
this->start_range_();
|
||||
} else {
|
||||
this->start_als_();
|
||||
}
|
||||
}
|
||||
|
||||
void VL6180XComponent::start_range_() {
|
||||
if (!this->status_comm_check(this->write_byte_reg16(REG_SYSRANGE_START, 0x01))) {
|
||||
this->measuring_ = false;
|
||||
return;
|
||||
}
|
||||
this->set_timeout(MEASUREMENT_ID, RANGE_TIME_MS, [this]() { this->read_range_(); });
|
||||
}
|
||||
|
||||
void VL6180XComponent::read_range_() {
|
||||
uint8_t status[3]; // range status, ALS status, interrupt status
|
||||
uint8_t raw;
|
||||
if (!this->status_comm_check(this->read_register16(REG_RESULT_RANGE_STATUS, status, 3) == i2c::ERROR_OK) ||
|
||||
!this->status_comm_check((status[2] & 0x07) == RANGE_SAMPLE_READY) ||
|
||||
!this->status_comm_check(this->read_byte_reg16(REG_RESULT_RANGE_VAL, &raw) &&
|
||||
this->write_byte_reg16(REG_SYSTEM_INTERRUPT_CLEAR, 0x07))) {
|
||||
this->measuring_ = false;
|
||||
return;
|
||||
}
|
||||
const uint8_t error = status[0] >> 4;
|
||||
// Codes 1 to 5 are self-test faults (VCSEL or PLL); a fault keeps the warning until a whole cycle works
|
||||
if (error >= 1 && error <= 5) {
|
||||
ESP_LOGW(TAG, "Range self-test fault %u", error);
|
||||
PUBLISH_STATE(this->distance_sensor_, NAN);
|
||||
this->status_set_warning();
|
||||
this->measuring_ = false;
|
||||
return;
|
||||
}
|
||||
// Other codes mean no target or out of range
|
||||
if (error != 0) {
|
||||
ESP_LOGV(TAG, "Range error code %u", error);
|
||||
PUBLISH_STATE(this->distance_sensor_, NAN);
|
||||
} else {
|
||||
PUBLISH_STATE(this->distance_sensor_, static_cast<float>(raw * this->scaler_));
|
||||
}
|
||||
// With illuminance configured, read_als_() clears the warning once the whole cycle has worked
|
||||
if (this->illuminance_sensor_ != nullptr) {
|
||||
this->start_als_();
|
||||
} else {
|
||||
this->measuring_ = false;
|
||||
this->status_clear_warning();
|
||||
}
|
||||
}
|
||||
|
||||
void VL6180XComponent::start_als_() {
|
||||
if (!this->status_comm_check(this->write_byte_reg16(REG_SYSALS_START, 0x01))) {
|
||||
this->measuring_ = false;
|
||||
return;
|
||||
}
|
||||
this->set_timeout(MEASUREMENT_ID, this->als_integration_time_ms_ + ALS_READOUT_MARGIN_MS,
|
||||
[this]() { this->read_als_(); });
|
||||
}
|
||||
|
||||
void VL6180XComponent::read_als_() {
|
||||
this->measuring_ = false;
|
||||
uint8_t result[4]; // ALS status, interrupt status, ALS value
|
||||
if (!this->status_comm_check(this->read_register16(REG_RESULT_ALS_STATUS, result, 4) == i2c::ERROR_OK) ||
|
||||
!this->status_comm_check((result[1] & 0x38) == ALS_SAMPLE_READY) ||
|
||||
!this->status_comm_result(this->write_byte_reg16(REG_SYSTEM_INTERRUPT_CLEAR, 0x07)))
|
||||
return;
|
||||
// An overflow in bright light is a reading, not a fault
|
||||
if (result[0] >> 4) {
|
||||
ESP_LOGV(TAG, "ALS error code %u", result[0] >> 4);
|
||||
PUBLISH_STATE(this->illuminance_sensor_, NAN);
|
||||
return;
|
||||
}
|
||||
PUBLISH_STATE(this->illuminance_sensor_, encode_uint16(result[2], result[3]) * this->lux_per_count_);
|
||||
}
|
||||
|
||||
void VL6180XComponent::dump_config() {
|
||||
ESP_LOGCONFIG(TAG, "VL6180X:");
|
||||
LOG_I2C_DEVICE(this);
|
||||
LOG_PIN(" Enable Pin: ", this->enable_pin_);
|
||||
LOG_UPDATE_INTERVAL(this);
|
||||
LOG_SENSOR(" ", "Distance", this->distance_sensor_);
|
||||
LOG_SENSOR(" ", "Illuminance", this->illuminance_sensor_);
|
||||
}
|
||||
|
||||
} // namespace esphome::vl6180x
|
||||
@@ -1,55 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include "esphome/components/i2c/i2c.h"
|
||||
#include "esphome/components/sensor/sensor.h"
|
||||
#include "esphome/core/component.h"
|
||||
#include "esphome/core/gpio.h"
|
||||
#include "esphome/core/helpers.h"
|
||||
|
||||
namespace esphome::vl6180x {
|
||||
|
||||
class VL6180XComponent final : public PollingComponent, public i2c::I2CDevice {
|
||||
SUB_SENSOR(distance)
|
||||
SUB_SENSOR(illuminance)
|
||||
|
||||
public:
|
||||
void setup() override;
|
||||
void update() override;
|
||||
void dump_config() override;
|
||||
|
||||
void set_enable_pin(GPIOPin *pin) { this->enable_pin_ = pin; }
|
||||
void set_scaler(uint8_t scaler) { this->scaler_ = scaler; }
|
||||
/// @param gain_code SYSALS_ANALOGUE_GAIN code of the gain
|
||||
/// @param integration_time_ms 1 to 512 ms
|
||||
/// @param lux_per_count lux of one ALS count at this gain and integration time
|
||||
void set_als(uint8_t gain_code, uint16_t integration_time_ms, float lux_per_count) {
|
||||
this->als_gain_code_ = gain_code;
|
||||
this->als_integration_time_ms_ = integration_time_ms;
|
||||
this->lux_per_count_ = lux_per_count;
|
||||
}
|
||||
|
||||
#ifdef VL6180X_ENABLE_PIN_COUNT
|
||||
/// The first setup() holds every registered sensor in reset, so each can be moved off 0x29 alone.
|
||||
static void register_enable_pin(GPIOPin *pin) { enable_pins.push_back(pin); }
|
||||
#endif
|
||||
|
||||
protected:
|
||||
bool init_();
|
||||
void start_range_();
|
||||
void read_range_();
|
||||
void start_als_();
|
||||
void read_als_();
|
||||
|
||||
#ifdef VL6180X_ENABLE_PIN_COUNT
|
||||
static SlotList<GPIOPin *, VL6180X_ENABLE_PIN_COUNT> enable_pins; // NOLINT
|
||||
#endif
|
||||
|
||||
GPIOPin *enable_pin_{nullptr};
|
||||
float lux_per_count_{0.0f};
|
||||
uint16_t als_integration_time_ms_{100};
|
||||
uint8_t als_gain_code_{6};
|
||||
uint8_t scaler_{1};
|
||||
bool measuring_{false};
|
||||
};
|
||||
|
||||
} // namespace esphome::vl6180x
|
||||
@@ -241,7 +241,6 @@
|
||||
#define REMOTE_BASE_DUMPER_COUNT 1
|
||||
#define REMOTE_BASE_LISTENER_COUNT 1
|
||||
#define SX1509_ON_KEY_COUNT 1
|
||||
#define VL6180X_ENABLE_PIN_COUNT 2
|
||||
#define WIEGAND_ON_KEY_COUNT 1
|
||||
#define WIEGAND_ON_RAW_COUNT 1
|
||||
#define WIEGAND_ON_TAG_COUNT 1
|
||||
@@ -335,7 +334,6 @@
|
||||
#define USE_PACKET_INTERFACE_HDLC
|
||||
#define USE_PACKET_INTERFACE_XXTEA
|
||||
#define USE_PCA9554_PCAL
|
||||
#define USE_PCM1863_SELECT
|
||||
#define USE_POWER_SUPPLY
|
||||
// Only defined by key-lookup preference backends; the slot-based platforms
|
||||
// (esp8266, rp2040) never set it in generated builds, and their preferences
|
||||
|
||||
+1
-1
@@ -28,7 +28,7 @@ bleak==3.1.0
|
||||
smpclient==7.4.0
|
||||
# smp 4.2+ needs cbor2 6+, which ships no Intel macOS wheels (arm64 only).
|
||||
smp==4.3.0; platform_system != "Darwin" or platform_machine != "x86_64"
|
||||
smp==4.3.0; platform_system == "Darwin" and platform_machine == "x86_64"
|
||||
smp==4.2.0; platform_system == "Darwin" and platform_machine == "x86_64"
|
||||
requests==2.34.2
|
||||
py7zr==1.1.4
|
||||
platformdirs==4.14.5 # native esp-idf toolchain global cache dir
|
||||
|
||||
@@ -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}
|
||||
)
|
||||
@@ -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
|
||||
@@ -1,6 +0,0 @@
|
||||
from tests.testing_helpers import ComponentManifestOverride
|
||||
|
||||
|
||||
def override_manifest(manifest: ComponentManifestOverride) -> None:
|
||||
# The ADC is an audio_adc platform on I2C; the tests drive its input select.
|
||||
manifest.dependencies = manifest.dependencies + ["audio_adc", "i2c", "select"]
|
||||
@@ -1,24 +0,0 @@
|
||||
esphome:
|
||||
on_boot:
|
||||
then:
|
||||
- audio_adc.set_mic_gain:
|
||||
id: pcm1863_adc
|
||||
mic_gain: 0db
|
||||
- audio_adc.set_mic_gain:
|
||||
id: pcm1863_adc
|
||||
mic_gain: !lambda 'return 4;'
|
||||
- audio_adc.set_mic_gain:
|
||||
id: pcm1863_adc
|
||||
mic_gain: 6db
|
||||
|
||||
audio_adc:
|
||||
- platform: pcm1863
|
||||
i2c_id: i2c_bus
|
||||
id: pcm1863_adc
|
||||
input: VIN2
|
||||
|
||||
select:
|
||||
# Switches the analog input mux at runtime
|
||||
- platform: pcm1863
|
||||
pcm1863_id: pcm1863_adc
|
||||
name: Line Input
|
||||
@@ -1,98 +0,0 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <array>
|
||||
|
||||
#include "esphome/components/pcm1863/pcm1863.h"
|
||||
#include "esphome/components/select/select.h"
|
||||
|
||||
namespace esphome::pcm1863::testing {
|
||||
|
||||
static constexpr uint8_t ADDRESS = 0x4A;
|
||||
|
||||
// The body codegen emits for the input select with publish="on_success".
|
||||
static PCM1863 *adc = nullptr; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
|
||||
static void apply_input(select::Select *entity, size_t index) {
|
||||
if (adc->set_input(static_cast<PCM1863Input>(index)))
|
||||
entity->publish_state(index);
|
||||
}
|
||||
|
||||
// Page 0 registers written as register/value pairs; failing writes are not acknowledged.
|
||||
class RegisterBus final : public i2c::I2CBus {
|
||||
public:
|
||||
i2c::ErrorCode write_readv(uint8_t address, const uint8_t *data, size_t size, uint8_t * /*out*/,
|
||||
size_t /*out_size*/) override {
|
||||
EXPECT_EQ(address, ADDRESS);
|
||||
if (this->fail)
|
||||
return i2c::ERROR_NOT_ACKNOWLEDGED;
|
||||
if (size == 2)
|
||||
this->registers[data[0]] = data[1];
|
||||
return i2c::ERROR_OK;
|
||||
}
|
||||
|
||||
std::array<uint8_t, 256> registers{};
|
||||
bool fail{false};
|
||||
};
|
||||
|
||||
class PCM1863InputSelectTest : public ::testing::Test {
|
||||
protected:
|
||||
void SetUp() override {
|
||||
this->adc_.set_i2c_bus(&this->bus_);
|
||||
this->adc_.set_i2c_address(ADDRESS);
|
||||
adc = &this->adc_;
|
||||
this->select_.traits.set_options({"NONE", "VIN1", "VIN2", "VIN3", "VIN4", "DIFF_1", "DIFF_2"});
|
||||
this->select_.add_on_state_callback([this](size_t) { ++this->publishes_; });
|
||||
}
|
||||
|
||||
void choose_(size_t index) { this->select_.make_call().set_index(index).perform(); }
|
||||
|
||||
RegisterBus bus_;
|
||||
PCM1863 adc_;
|
||||
select::ApplySelect<apply_input> select_;
|
||||
unsigned publishes_{0};
|
||||
};
|
||||
|
||||
TEST_F(PCM1863InputSelectTest, EveryOptionWritesItsMuxBitsToBothChannels) {
|
||||
this->adc_.setup();
|
||||
ASSERT_FALSE(this->adc_.is_failed());
|
||||
static constexpr std::array<uint8_t, 7> MUX = {0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20};
|
||||
for (size_t index = 0; index < MUX.size(); index++) {
|
||||
this->choose_(index);
|
||||
// Bit 6 is reserved and always written as 1
|
||||
EXPECT_EQ(this->bus_.registers[PCM1863_REG_ADC1_INPUT_SEL_L], PCM1863_INPUT_SEL_RSV | MUX[index]);
|
||||
EXPECT_EQ(this->bus_.registers[PCM1863_REG_ADC1_INPUT_SEL_R], PCM1863_INPUT_SEL_RSV | MUX[index]);
|
||||
EXPECT_EQ(this->select_.active_index(), index);
|
||||
}
|
||||
EXPECT_EQ(this->publishes_, MUX.size());
|
||||
}
|
||||
|
||||
TEST_F(PCM1863InputSelectTest, FailedWriteLeavesTheSelectUnpublished) {
|
||||
this->adc_.setup();
|
||||
this->bus_.fail = true;
|
||||
this->choose_(2);
|
||||
EXPECT_EQ(this->publishes_, 0u);
|
||||
EXPECT_FALSE(this->select_.has_state());
|
||||
}
|
||||
|
||||
TEST_F(PCM1863InputSelectTest, FailedWriteDoesNotLeakIntoTheNextRequest) {
|
||||
this->adc_.setup();
|
||||
this->bus_.fail = true;
|
||||
this->choose_(2);
|
||||
this->bus_.fail = false;
|
||||
this->choose_(5);
|
||||
EXPECT_EQ(this->publishes_, 1u);
|
||||
EXPECT_EQ(this->select_.active_index(), 5u);
|
||||
EXPECT_EQ(this->bus_.registers[PCM1863_REG_ADC1_INPUT_SEL_L], PCM1863_INPUT_SEL_RSV | 0x10);
|
||||
}
|
||||
|
||||
TEST_F(PCM1863InputSelectTest, FailedSetupRejectsTheSelect) {
|
||||
this->bus_.fail = true;
|
||||
this->adc_.setup();
|
||||
ASSERT_TRUE(this->adc_.is_failed());
|
||||
this->bus_.fail = false;
|
||||
this->choose_(3);
|
||||
EXPECT_EQ(this->publishes_, 0u);
|
||||
EXPECT_FALSE(this->select_.has_state());
|
||||
EXPECT_EQ(this->bus_.registers[PCM1863_REG_ADC1_INPUT_SEL_L], 0);
|
||||
}
|
||||
|
||||
} // namespace esphome::pcm1863::testing
|
||||
@@ -1,3 +0,0 @@
|
||||
packages:
|
||||
i2c: !include ../../test_build_components/common/i2c/esp32-idf.yaml
|
||||
pcm1863: !include common.yaml
|
||||
@@ -1,46 +0,0 @@
|
||||
# Every analog input the PCM1863 mux can select, and every supported word length
|
||||
packages:
|
||||
i2c: !include ../../test_build_components/common/i2c/esp32-idf.yaml
|
||||
|
||||
audio_adc:
|
||||
- platform: pcm1863
|
||||
i2c_id: i2c_bus
|
||||
id: pcm1863_vin1
|
||||
address: 0x4A
|
||||
input: VIN1
|
||||
bits_per_sample: 16bit
|
||||
- platform: pcm1863
|
||||
i2c_id: i2c_bus
|
||||
id: pcm1863_vin2
|
||||
address: 0x4B
|
||||
input: VIN2
|
||||
bits_per_sample: 20bit
|
||||
- platform: pcm1863
|
||||
i2c_id: i2c_bus
|
||||
id: pcm1863_vin3
|
||||
address: 0x4C
|
||||
input: VIN3
|
||||
bits_per_sample: 32bit
|
||||
- platform: pcm1863
|
||||
i2c_id: i2c_bus
|
||||
id: pcm1863_vin4
|
||||
address: 0x4D
|
||||
input: vin4
|
||||
mic_gain: -12db
|
||||
- platform: pcm1863
|
||||
i2c_id: i2c_bus
|
||||
id: pcm1863_diff1
|
||||
address: 0x4E
|
||||
input: DIFF_1
|
||||
mic_gain: 40db
|
||||
- platform: pcm1863
|
||||
i2c_id: i2c_bus
|
||||
id: pcm1863_diff2
|
||||
address: 0x4F
|
||||
input: DIFF_2
|
||||
mic_gain: 20db
|
||||
- platform: pcm1863
|
||||
i2c_id: i2c_bus
|
||||
id: pcm1863_none
|
||||
address: 0x50
|
||||
input: none
|
||||
@@ -2,3 +2,14 @@ binary_sensor:
|
||||
- platform: qwiic_pir
|
||||
i2c_id: i2c_bus
|
||||
name: Qwiic PIR Motion Sensor
|
||||
- platform: qwiic_pir
|
||||
i2c_id: i2c_bus
|
||||
address: 0x13
|
||||
name: Qwiic PIR Native
|
||||
debounce_mode: NATIVE
|
||||
debounce: 10ms
|
||||
- platform: qwiic_pir
|
||||
i2c_id: i2c_bus
|
||||
address: 0x14
|
||||
name: Qwiic PIR Raw
|
||||
debounce_mode: RAW
|
||||
@@ -1,4 +1,3 @@
|
||||
packages:
|
||||
i2c: !include ../../test_build_components/common/i2c/esp32-idf.yaml
|
||||
|
||||
<<: !include common.yaml
|
||||
qwiic_pir: !include common.yaml
|
||||
@@ -1,4 +1,3 @@
|
||||
packages:
|
||||
i2c: !include ../../test_build_components/common/i2c/esp8266-ard.yaml
|
||||
|
||||
<<: !include common.yaml
|
||||
qwiic_pir: !include common.yaml
|
||||
@@ -1,4 +1,3 @@
|
||||
packages:
|
||||
i2c: !include ../../test_build_components/common/i2c/rp2040-ard.yaml
|
||||
|
||||
<<: !include common.yaml
|
||||
qwiic_pir: !include common.yaml
|
||||
@@ -1,14 +0,0 @@
|
||||
import esphome.codegen as cg
|
||||
from esphome.types import ConfigType
|
||||
from tests.testing_helpers import ComponentManifestOverride
|
||||
|
||||
|
||||
def override_manifest(manifest: ComponentManifestOverride) -> None:
|
||||
# The C++ tests build the hubs directly and register two enable pins
|
||||
manifest.dependencies = manifest.dependencies + ["sensor"]
|
||||
manifest.multi_conf = False
|
||||
|
||||
async def to_code_testing(config: ConfigType) -> None:
|
||||
cg.add_define("VL6180X_ENABLE_PIN_COUNT", 2)
|
||||
|
||||
manifest.to_code = to_code_testing
|
||||
@@ -1,14 +0,0 @@
|
||||
vl6180x:
|
||||
- id: vl6180x_sensor
|
||||
i2c_id: i2c_bus
|
||||
|
||||
sensor:
|
||||
- platform: vl6180x
|
||||
vl6180x_id: vl6180x_sensor
|
||||
distance:
|
||||
name: VL6180X Distance
|
||||
scaler: 2
|
||||
illuminance:
|
||||
name: VL6180X Illuminance
|
||||
gain: 2.5
|
||||
integration_time: 50ms
|
||||
@@ -1,24 +0,0 @@
|
||||
packages:
|
||||
i2c: !include ../../test_build_components/common/i2c/esp32-idf.yaml
|
||||
|
||||
vl6180x:
|
||||
- id: vl6180x_near
|
||||
i2c_id: i2c_bus
|
||||
address: 0x30
|
||||
enable_pin: GPIO4
|
||||
- id: vl6180x_far
|
||||
i2c_id: i2c_bus
|
||||
address: 0x31
|
||||
enable_pin: GPIO13
|
||||
|
||||
sensor:
|
||||
- platform: vl6180x
|
||||
vl6180x_id: vl6180x_near
|
||||
distance:
|
||||
name: Near Distance
|
||||
scaler: 3
|
||||
- platform: vl6180x
|
||||
vl6180x_id: vl6180x_far
|
||||
illuminance:
|
||||
name: Far Illuminance
|
||||
gain: 40
|
||||
@@ -1,3 +0,0 @@
|
||||
packages:
|
||||
i2c: !include ../../test_build_components/common/i2c/esp32-idf.yaml
|
||||
vl6180x: !include common.yaml
|
||||
@@ -1,3 +0,0 @@
|
||||
packages:
|
||||
i2c: !include ../../test_build_components/common/i2c/esp8266-ard.yaml
|
||||
vl6180x: !include common.yaml
|
||||
@@ -1,3 +0,0 @@
|
||||
packages:
|
||||
i2c: !include ../../test_build_components/common/i2c/rp2040-ard.yaml
|
||||
vl6180x: !include common.yaml
|
||||
@@ -1,232 +0,0 @@
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
|
||||
#include "esphome/components/vl6180x/vl6180x.h"
|
||||
#include "esphome/core/application.h"
|
||||
#include "esphome/core/hal.h"
|
||||
|
||||
namespace esphome::vl6180x::testing {
|
||||
|
||||
// The sensor's 16-bit register map; writes and reads advance the register pointer.
|
||||
class RegisterBus final : public i2c::I2CBus {
|
||||
public:
|
||||
i2c::ErrorCode write_readv(uint8_t /*address*/, const uint8_t *data, size_t size, uint8_t *out,
|
||||
size_t out_size) override {
|
||||
uint16_t pointer = encode_uint16(data[0], data[1]);
|
||||
for (size_t i = 2; i < size; i++)
|
||||
this->registers[pointer++] = data[i];
|
||||
for (size_t i = 0; i < out_size; i++)
|
||||
out[i] = this->registers[pointer++];
|
||||
return i2c::ERROR_OK;
|
||||
}
|
||||
|
||||
std::array<uint8_t, 0x213> registers{};
|
||||
};
|
||||
|
||||
class VL6180XTest : public ::testing::Test {
|
||||
protected:
|
||||
void SetUp() override {
|
||||
this->hub_.set_i2c_bus(&this->bus_);
|
||||
this->hub_.set_i2c_address(0x29);
|
||||
this->hub_.set_distance_sensor(&this->range_);
|
||||
this->hub_.set_illuminance_sensor(&this->lux_);
|
||||
// 1x gain over 1 ms: 32 lux per count
|
||||
this->hub_.set_als(6, 1, 32.0f);
|
||||
this->bus_.registers[0x000] = 0xB4; // model ID
|
||||
this->bus_.registers[0x016] = 0x01; // fresh out of reset
|
||||
}
|
||||
|
||||
// One update: range, then the ALS once its integration time and readout margin have passed.
|
||||
void measure_() {
|
||||
this->hub_.update();
|
||||
delay(80); // NOLINT
|
||||
App.scheduler.call(millis());
|
||||
delay(420); // NOLINT
|
||||
App.scheduler.call(millis());
|
||||
}
|
||||
|
||||
RegisterBus bus_;
|
||||
VL6180XComponent hub_;
|
||||
sensor::Sensor range_;
|
||||
sensor::Sensor lux_;
|
||||
};
|
||||
|
||||
TEST_F(VL6180XTest, FreshSensorGetsTheMandatorySettingsAndTheScaler) {
|
||||
this->bus_.registers[0x024] = 0xFA; // factory part-to-part offset, -6 mm
|
||||
this->hub_.set_scaler(2);
|
||||
this->hub_.setup();
|
||||
ASSERT_FALSE(this->hub_.is_failed());
|
||||
EXPECT_EQ(this->bus_.registers[0x0207], 0x01);
|
||||
EXPECT_EQ(this->bus_.registers[0x016], 0x00);
|
||||
EXPECT_EQ(encode_uint16(this->bus_.registers[0x096], this->bus_.registers[0x097]), 127);
|
||||
EXPECT_EQ(this->bus_.registers[0x024], 0xFD); // -3 mm at 2x
|
||||
EXPECT_EQ(this->bus_.registers[0x02D], 0x10);
|
||||
}
|
||||
|
||||
TEST_F(VL6180XTest, SensorThatKeptPowerRestoresTheOffsetBeforeRescaling) {
|
||||
this->bus_.registers[0x016] = 0x00;
|
||||
this->bus_.registers[0x024] = 0xFE; // -2 mm, written at 3x by the last setup
|
||||
this->bus_.registers[0x096] = 0x00;
|
||||
this->bus_.registers[0x097] = 84;
|
||||
this->hub_.set_scaler(2);
|
||||
this->hub_.setup();
|
||||
EXPECT_EQ(this->bus_.registers[0x0207], 0x00); // the one-time settings are not written again
|
||||
EXPECT_EQ(this->bus_.registers[0x024], 0xFD); // -6 mm / 2
|
||||
}
|
||||
|
||||
TEST_F(VL6180XTest, WrongModelIdFailsSetup) {
|
||||
this->bus_.registers[0x000] = 0x00;
|
||||
this->hub_.setup();
|
||||
EXPECT_TRUE(this->hub_.is_failed());
|
||||
}
|
||||
|
||||
TEST_F(VL6180XTest, PublishesScaledRangeAndLux) {
|
||||
this->hub_.set_scaler(2);
|
||||
this->hub_.setup();
|
||||
this->bus_.registers[0x04D] = 0x01; // no range error
|
||||
this->bus_.registers[0x04F] = 0x24; // range and ALS samples ready
|
||||
this->bus_.registers[0x062] = 100;
|
||||
this->bus_.registers[0x050] = 0x00;
|
||||
this->bus_.registers[0x051] = 10;
|
||||
this->measure_();
|
||||
EXPECT_FLOAT_EQ(this->range_.state, 200.0f);
|
||||
EXPECT_FLOAT_EQ(this->lux_.state, 320.0f);
|
||||
EXPECT_FALSE(this->hub_.status_has_warning());
|
||||
}
|
||||
|
||||
TEST_F(VL6180XTest, NoTargetAndAlsOverflowPublishNanWithoutAWarning) {
|
||||
this->hub_.setup();
|
||||
this->bus_.registers[0x04D] = 0xB1; // range error 11, no target
|
||||
this->bus_.registers[0x04E] = 0x31; // ALS error 3, overflow in bright light
|
||||
this->bus_.registers[0x04F] = 0x24;
|
||||
this->measure_();
|
||||
EXPECT_TRUE(std::isnan(this->range_.state));
|
||||
EXPECT_TRUE(std::isnan(this->lux_.state));
|
||||
EXPECT_FALSE(this->hub_.status_has_warning());
|
||||
}
|
||||
|
||||
TEST_F(VL6180XTest, SelfTestFaultSetsAWarningThatTheLightReadDoesNotClear) {
|
||||
this->hub_.setup();
|
||||
this->bus_.registers[0x04D] = 0x31; // range error 3, VCSEL watchdog test
|
||||
this->bus_.registers[0x04F] = 0x24;
|
||||
this->measure_();
|
||||
EXPECT_TRUE(std::isnan(this->range_.state));
|
||||
EXPECT_FALSE(this->lux_.has_state()); // the light reading is skipped for that cycle
|
||||
EXPECT_TRUE(this->hub_.status_has_warning());
|
||||
}
|
||||
|
||||
TEST_F(VL6180XTest, SampleNotReadySetsAWarning) {
|
||||
this->hub_.setup();
|
||||
this->bus_.registers[0x04F] = 0x00;
|
||||
this->hub_.update();
|
||||
delay(80); // NOLINT
|
||||
App.scheduler.call(millis());
|
||||
EXPECT_TRUE(this->hub_.status_has_warning());
|
||||
EXPECT_FALSE(this->range_.has_state());
|
||||
}
|
||||
|
||||
TEST_F(VL6180XTest, FailedLightReadKeepsTheWarningUntilAWholeCycleWorks) {
|
||||
this->hub_.setup();
|
||||
this->bus_.registers[0x04D] = 0x01;
|
||||
this->bus_.registers[0x062] = 50;
|
||||
this->bus_.registers[0x04F] = 0x04; // range sample ready, ALS sample not
|
||||
this->measure_();
|
||||
EXPECT_FLOAT_EQ(this->range_.state, 50.0f);
|
||||
EXPECT_FALSE(this->lux_.has_state());
|
||||
EXPECT_TRUE(this->hub_.status_has_warning());
|
||||
|
||||
this->bus_.registers[0x04F] = 0x24;
|
||||
this->bus_.registers[0x051] = 1;
|
||||
this->hub_.update();
|
||||
delay(80); // NOLINT
|
||||
App.scheduler.call(millis());
|
||||
EXPECT_TRUE(this->hub_.status_has_warning()); // a good distance alone does not clear it
|
||||
delay(420); // NOLINT
|
||||
App.scheduler.call(millis());
|
||||
EXPECT_FLOAT_EQ(this->lux_.state, 32.0f);
|
||||
EXPECT_FALSE(this->hub_.status_has_warning());
|
||||
}
|
||||
|
||||
class FakePin final : public GPIOPin {
|
||||
public:
|
||||
void setup() override {}
|
||||
void pin_mode(gpio::Flags /*flags*/) override {}
|
||||
gpio::Flags get_flags() const override { return gpio::FLAG_OUTPUT; }
|
||||
bool digital_read() override { return this->level; }
|
||||
void digital_write(bool value) override { this->level = value; }
|
||||
bool level{true};
|
||||
};
|
||||
|
||||
// Two chips that answer at their own address only while their enable pin is high.
|
||||
class TwoChipBus final : public i2c::I2CBus {
|
||||
public:
|
||||
struct Chip {
|
||||
FakePin *pin;
|
||||
uint8_t address{0x29};
|
||||
uint8_t model_id{0xB4};
|
||||
};
|
||||
|
||||
i2c::ErrorCode write_readv(uint8_t address, const uint8_t *data, size_t size, uint8_t *out,
|
||||
size_t out_size) override {
|
||||
bool acked = false;
|
||||
for (auto &chip : this->chips) {
|
||||
if (!chip.pin->level || chip.address != address)
|
||||
continue;
|
||||
const uint16_t reg = encode_uint16(data[0], data[1]);
|
||||
if (out_size > 0)
|
||||
out[0] = reg == 0x000 ? chip.model_id : 0x01; // the fresh-out-of-reset flag reads 1
|
||||
if (reg == 0x212 && size == 3)
|
||||
chip.address = data[2];
|
||||
acked = true;
|
||||
}
|
||||
return acked ? i2c::ERROR_OK : i2c::ERROR_NOT_ACKNOWLEDGED;
|
||||
}
|
||||
|
||||
FakePin pin_a;
|
||||
FakePin pin_b;
|
||||
std::array<Chip, 2> chips{Chip{&pin_a}, Chip{&pin_b}};
|
||||
};
|
||||
|
||||
class VL6180XEnablePinTest : public ::testing::Test {
|
||||
protected:
|
||||
void SetUp() override {
|
||||
uint8_t address = 0x30;
|
||||
for (auto *hub : {&this->hub_a_, &this->hub_b_}) {
|
||||
hub->set_i2c_bus(&this->bus_);
|
||||
hub->set_i2c_address(address++);
|
||||
}
|
||||
this->hub_a_.set_enable_pin(&this->bus_.pin_a);
|
||||
this->hub_b_.set_enable_pin(&this->bus_.pin_b);
|
||||
VL6180XComponent::register_enable_pin(&this->bus_.pin_a);
|
||||
VL6180XComponent::register_enable_pin(&this->bus_.pin_b);
|
||||
}
|
||||
|
||||
TwoChipBus bus_;
|
||||
VL6180XComponent hub_a_;
|
||||
VL6180XComponent hub_b_;
|
||||
};
|
||||
|
||||
TEST_F(VL6180XEnablePinTest, SensorsAreMovedOffTheDefaultAddressOneAtATime) {
|
||||
this->hub_a_.setup();
|
||||
EXPECT_FALSE(this->bus_.pin_b.level); // still held in reset while the first one moves
|
||||
this->hub_b_.setup();
|
||||
EXPECT_FALSE(this->hub_a_.is_failed());
|
||||
EXPECT_FALSE(this->hub_b_.is_failed());
|
||||
EXPECT_EQ(this->bus_.chips[0].address, 0x30);
|
||||
EXPECT_EQ(this->bus_.chips[1].address, 0x31);
|
||||
}
|
||||
|
||||
TEST_F(VL6180XEnablePinTest, FailedSensorIsHeldInResetSoTheNextOneIsAlone) {
|
||||
this->bus_.chips[0].model_id = 0x00;
|
||||
this->hub_a_.setup();
|
||||
EXPECT_TRUE(this->hub_a_.is_failed());
|
||||
EXPECT_FALSE(this->bus_.pin_a.level);
|
||||
this->hub_b_.setup();
|
||||
EXPECT_FALSE(this->hub_b_.is_failed());
|
||||
EXPECT_EQ(this->bus_.chips[0].address, 0x29);
|
||||
EXPECT_EQ(this->bus_.chips[1].address, 0x31);
|
||||
}
|
||||
|
||||
} // namespace esphome::vl6180x::testing
|
||||
Reference in new issue
Block a user