ESPHome 2026.11.0b6
Loading...
Searching...
No Matches
modem_component.h
Go to the documentation of this file.
1#pragma once
2#ifdef USE_ESP32
3
5#include "esphome/core/gpio.h"
6#ifdef USE_MODEM_URC
8#endif
12#if defined(USE_MODEM_URC) || defined(USE_MODEM_NETWORK_TYPE)
14#endif
15#ifdef USE_MODEM_SIGNAL
17#endif
18
19#include <cxx_include/esp_modem_api.hpp>
20#include <esp_modem_config.h>
21
22#include <atomic>
23#include <memory>
24#include <string>
25#include <utility>
26
27namespace esphome::modem {
28
38
39// CONNECTING runs its long commands once; the later passes only poll the attachment
45
46enum class SimResult : uint8_t {
48 SIM_RESULT_RETRY, // status not readable yet, or a PIN step is in progress
49 SIM_RESULT_LOCKED, // nothing more to try: PUK, another lock, no pin_code or the PIN is not sent again
50 SIM_RESULT_HALT, // stop this attempt; a reboot may still open the SIM, so the reboot timer stays
51};
52
53// The step that failed most recently; CONNECTED clears it
68
69#ifdef USE_MODEM_PIN_CODE
70enum class PinStep : uint8_t {
72 PIN_STEP_SAVING, // the send is counted and waits for the record to reach flash
74};
75
76// Written by loop() once it tried to save pin_record_; the task leaves the record alone while PENDING
77enum class PinSave : uint8_t {
81};
82#endif
83
84// Every esp_modem factory shares this signature, so codegen picks the one for the model
85using DceFactory = std::unique_ptr<esp_modem::DCE> (*)(const esp_modem::dce_config *, std::shared_ptr<esp_modem::DTE>,
86 esp_netif_t *);
87
88class ModemComponent : public Component {
89#ifdef USE_MODEM_URC
90 SUB_TEXT_SENSOR(urc)
91#endif
92
93 public:
94 ModemComponent(InternalGPIOPin *tx_pin, InternalGPIOPin *rx_pin, const char *model, DceFactory factory,
95 const char *apn);
96 void setup() override;
97 void loop() override;
98 void dump_config() override;
99 float get_setup_priority() const override { return setup_priority::WIFI + 1; } // Just before Wi-Fi
100
101 void set_reboot_timeout(uint32_t timeout) { this->timeout_ = timeout; }
102 void set_use_address(const char *use_address) { this->use_address_ = use_address; }
103 void set_rts_pin(InternalGPIOPin *rts_pin) { this->rts_pin_ = rts_pin; }
104 void set_cts_pin(InternalGPIOPin *cts_pin) { this->cts_pin_ = cts_pin; }
105 void set_baud_rate(int baud_rate) { this->baud_rate_ = baud_rate; }
106#ifdef USE_MODEM_PIN_CODE
107 void set_pin_code(const char *pin_code) { this->pin_code_ = pin_code; }
108#endif
109 void set_tx_buffer_size(uint16_t tx_buffer_size) { this->tx_buffer_size_ = tx_buffer_size; }
110 void set_rx_buffer_size(uint16_t rx_buffer_size) { this->rx_buffer_size_ = rx_buffer_size; }
111 void set_dte_buffer_size(uint16_t dte_buffer_size) { this->dte_buffer_size_ = dte_buffer_size; }
112 void set_init_at_commands(const char *const *cmds, uint8_t count) {
113 this->init_at_commands_ = cmds;
114 this->init_at_count_ = count;
115 }
116 template<typename F> void add_on_state_callback(F &&callback) {
117 this->on_state_callback_.add(std::forward<F>(callback));
118 }
119
120 bool is_connected() const { return this->component_state_.load() == ModemState::MODEM_STATE_CONNECTED; }
121 bool is_disabled() const {
122 return this->component_state_.load() == ModemState::MODEM_STATE_DISABLED &&
123 this->target_state_.load() == ModemState::MODEM_STATE_DISABLED;
124 }
125 bool is_enabled() const { return !this->is_disabled(); }
126 void enable();
127 void disable();
128#ifdef USE_MODEM_SEND_AT
131 bool send_at(const char *cmd, uint32_t timeout = COMMAND_TIMEOUT_MS);
132 bool send_at(const std::string &cmd, uint32_t timeout = COMMAND_TIMEOUT_MS);
133#endif
134
135 network::IPAddresses get_ip_addresses();
136 const char *get_use_address() const { return this->use_address_; }
137
138#ifdef USE_MODEM_POLL
139 void set_update_interval(uint32_t update_interval) { this->update_interval_ = update_interval; }
140#endif
141#ifdef USE_MODEM_SIGNAL
142 SUB_SENSOR(rssi)
143 SUB_SENSOR(ber)
144#endif
145#ifdef USE_MODEM_NETWORK_TYPE
146 SUB_TEXT_SENSOR(network_type)
147#endif
148
149 protected:
150 static constexpr uint32_t COMMAND_TIMEOUT_MS = 1000;
151 static constexpr uint32_t RETRY_DELAY_MS = 1000;
152 static constexpr size_t URC_LINE_SIZE = 128;
153 static constexpr size_t AT_COMMAND_SIZE = 128;
154#ifdef USE_MODEM_POLL
155 static constexpr uint8_t CSQ_UNKNOWN = 99; // AT+CSQ rssi or ber the modem cannot tell
156 static constexpr uint8_t CSQ_RSSI_MAX = 31;
157 static constexpr uint8_t NETWORK_MODE_NO_SERVICE = 0;
158 static constexpr uint8_t NETWORK_MODE_NONE = 255; // no AT+CNSMOD answer; past the name table, so Unknown
159#endif
160
161 // esp_modem's calls block until the modem answers or their own timeouts run out, up to a minute for a
162 // mode change, so the state machine runs on its own task and leaves the main loop alone
163 static void task_entry(void *arg);
164 void run_task_();
165 void wake_task_();
166 ModemState compute_next_state_();
167 ModemState handle_state_enabling_();
168 ModemState handle_state_synced_();
169 ModemState handle_state_connecting_();
170 ModemState handle_state_wait_ip_();
171 ModemState handle_state_disconnecting_();
173 uint32_t next_probe_delay_();
174 ModemState retry_(ModemState state, uint32_t delay_ms = RETRY_DELAY_MS);
175 void transition_to_(ModemState next_state);
176 // What the task left for loop() to do
177 enum Pending : uint32_t {
178 PENDING_STATUS = 1 << 0,
179 PENDING_SAVE_BAUD = 1 << 1,
180#ifdef USE_MODEM_PIN_CODE
181 PENDING_SAVE_PIN = 1 << 2,
182#endif
183 PENDING_CONNECT_TIMEOUT = 1 << 3, // arm or cancel the reboot timer for the current state
184 PENDING_ON_SYNC = 1 << 4, // loop() wakes the task once on_sync ran
185 PENDING_ON_CONNECT = 1 << 5,
186 PENDING_ON_DISCONNECT = 1 << 6,
187 };
188#ifdef USE_MODEM_POLL
189 void poll_();
190 void publish_readings_(uint8_t rssi, uint8_t ber, uint8_t mode);
191#endif
192
193 // Main loop only, so arming and cancelling cannot interleave
194 void arm_connect_timeout_();
195 void cancel_connect_timeout_();
196 void fail_setup_(const LogString *reason);
197 void set_fault_(ModemFault fault);
198 void set_teardown_fault_();
199 void clear_config_fault_(ModemFault fault);
200 void hand_over_(uint32_t pending);
202 esp_modem::command_result at_(const char *cmd, uint32_t timeout = COMMAND_TIMEOUT_MS);
203 void publish_status_();
204 void not_responding_(int baud);
205 void dump_connect_params_();
206 SimResult prepare_sim_();
207#ifdef USE_MODEM_PIN_CODE
208 SimResult send_pin_();
209 void save_pin_record_();
210#endif
211
212 InternalGPIOPin *tx_pin_;
213 InternalGPIOPin *rx_pin_;
214 InternalGPIOPin *rts_pin_{nullptr};
215 InternalGPIOPin *cts_pin_{nullptr};
216 const char *model_;
217 DceFactory dce_factory_;
218 const char *apn_;
219 const char *const *init_at_commands_{nullptr}; // static array from code generation
220#ifdef USE_MODEM_URC
221 const char *urc_line_{nullptr}; // the line urc_pending_ hands to loop(), inside urc_reader_
222#endif
223 std::unique_ptr<esp_modem::DCE> dce_;
224 std::shared_ptr<esp_modem::DTE> dte_;
225 esp_netif_t *ppp_netif_{nullptr};
227 LazyCallbackManager<void(ModemState)> on_state_callback_;
228 int baud_rate_{0}; // 0 = use the esp_modem default
229 int current_baud_rate_{0};
230 int restored_baud_{0};
231 StaticTask task_;
232 uint32_t timeout_{0};
233 uint32_t step_delay_ms_{0};
234 uint32_t state_started_ms_{0}; // when the IP wait or the PIN unlock wait began
235 std::atomic<uint32_t> pending_{0};
236#ifdef USE_MODEM_PIN_CODE
237 const char *pin_code_{nullptr};
238 ESPPreferenceObject pin_pref_;
239#endif
240 // Kept in flash so reboots cannot keep spending the SIM's attempts on a PIN it never confirmed
241 struct PinRecord {
242 uint32_t hash; // pin_code the record is about
243 uint8_t sends; // AT+CPIN= sent without the SIM reporting READY since
244 };
245#ifdef USE_MODEM_PIN_CODE
246 PinRecord pin_record_{}; // the task writes it, loop() saves it while pin_save_state_ is PENDING
247#endif
248#ifdef USE_MODEM_SEND_AT
249 uint32_t at_timeout_{COMMAND_TIMEOUT_MS};
250#endif
251#ifdef USE_MODEM_POLL
252 uint32_t update_interval_{0};
253 uint32_t next_poll_ms_{0}; // task only
254#endif
255 uint16_t tx_buffer_size_{1024};
256 uint16_t rx_buffer_size_{1024};
257 uint16_t dte_buffer_size_{1024};
258 // The task owns component_state_; the main loop sets target_state_ and reads both
259 std::atomic<ModemState> component_state_{ModemState::MODEM_STATE_DISABLED};
260 std::atomic<ModemState> target_state_{ModemState::MODEM_STATE_DISABLED};
261 // Written by the task only, read by loop()
262 std::atomic<ModemFault> fault_{ModemFault::MODEM_FAULT_NONE};
263 // A failed baud_rate or init_at step, shown once fault_ is clear until the step passes again
264 std::atomic<ModemFault> config_fault_{ModemFault::MODEM_FAULT_NONE};
265 // std::atomic<uint8_t> flags: GCC on Xtensa calls out of line for std::atomic<bool>
266 // Written by the IP event task, read by the modem task
267 std::atomic<uint8_t> got_ip_{0};
268 std::atomic<uint8_t> ppp_error_{0}; // last NETIF_PPP_STATUS error code, 0 = none
269 // Doublings of the silent-modem probe delay; enable() and an answer reset it
270 std::atomic<uint8_t> probe_backoff_{0};
271 // Set by loop() once on_sync ran; the task waits for it, not for any notification
272 std::atomic<uint8_t> sync_acked_{0};
273#ifdef USE_MODEM_SEND_AT
274 // Set by send_at() on the main loop once at_command_ is written, cleared by the task after sending it
275 std::atomic<uint8_t> at_pending_{0};
276#endif
277#ifdef USE_MODEM_URC
278 // Set by the UART task with urc_line_; until loop() has published it, new lines are dropped
279 std::atomic<uint8_t> urc_pending_{0};
280#endif
281#ifdef USE_MODEM_POLL
282 // Set by the task with the poll_ answers below; until loop() has published them, polls are skipped
283 std::atomic<uint8_t> poll_unpublished_{0};
284#endif
285#ifdef USE_MODEM_PIN_CODE
286 std::atomic<PinSave> pin_save_state_{PinSave::PIN_SAVE_DONE};
288 bool pin_record_unsaved_{false}; // loop() only; the last PIN record save failed
289#endif
291 uint8_t init_at_count_{0};
292 uint8_t uart_port_{UART_NUM_MAX};
293 uint8_t attach_polls_{0};
294#ifdef USE_MODEM_POLL
295 uint8_t poll_rssi_{CSQ_UNKNOWN}; // raw AT+CSQ answers
296 uint8_t poll_ber_{CSQ_UNKNOWN};
297 uint8_t poll_mode_{NETWORK_MODE_NONE}; // raw AT+CNSMOD answer
298#endif
299 bool connect_timeout_armed_{false};
300 bool modem_synced_{false}; // a modem that never answered has nothing to tear down
301 bool resync_{false}; // the attachment read failed, so CONNECTING syncs again first
302 bool apn_pending_{false}; // ENABLING could not set the APN at CFUN=0, so CONNECTING sets it after the SIM check
303#ifdef USE_MODEM_SEND_AT
304 char at_command_[AT_COMMAND_SIZE];
305#endif
306#ifdef USE_MODEM_URC
307 // Fed on the UART task
308 LineReader<URC_LINE_SIZE> urc_reader_;
309#endif
310
311 private:
312 // Points at a string literal from code generation, never at dynamic storage
313 const char *use_address_{""};
314};
315
316extern ModemComponent *global_modem_component; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
317
318} // namespace esphome::modem
319
320#endif
BedjetMode mode
BedJet operating mode.
Collects bytes into NUL terminated lines of up to N - 1 characters; IGNORE_CHAR bytes are skipped and...
Definition line_reader.h:15
Helper for FreeRTOS static task management.
Definition static_task.h:18
bool state
Definition fan.h:2
unsigned count
Definition gif.cpp:51
ModemComponent * global_modem_component
std::unique_ptr< esp_modem::DCE >(*)(const esp_modem::dce_config *, std::shared_ptr< esp_modem::DTE >, esp_netif_t *) DceFactory
std::array< IPAddress, 5 > IPAddresses
Definition ip_address.h:368
constexpr float WIFI
Definition component.h:50
struct esp_netif_obj esp_netif_t
static void uint32_t