ESPHome 2026.11.0
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
69
70#ifdef USE_MODEM_PIN_CODE
71enum class PinStep : uint8_t {
73 PIN_STEP_SAVING, // the send is counted and waits for the record to reach flash
75};
76
77// Written by loop() once it tried to save pin_record_; the task leaves the record alone while PENDING
78enum class PinSave : uint8_t {
82};
83#endif
84
85// Every esp_modem factory shares this signature, so codegen picks the one for the model
86using DceFactory = std::unique_ptr<esp_modem::DCE> (*)(const esp_modem::dce_config *, std::shared_ptr<esp_modem::DTE>,
87 esp_netif_t *);
88
89class ModemComponent : public Component {
90#ifdef USE_MODEM_URC
91 SUB_TEXT_SENSOR(urc)
92#endif
93
94 public:
95 ModemComponent(InternalGPIOPin *tx_pin, InternalGPIOPin *rx_pin, const char *model, DceFactory factory,
96 const char *apn);
97 void setup() override;
98 void loop() override;
99 void dump_config() override;
100 float get_setup_priority() const override { return setup_priority::WIFI + 1; } // Just before Wi-Fi
101
102 void set_reboot_timeout(uint32_t timeout) { this->timeout_ = timeout; }
103 void set_use_address(const char *use_address) { this->use_address_ = use_address; }
104 void set_rts_pin(InternalGPIOPin *rts_pin) { this->rts_pin_ = rts_pin; }
105 void set_cts_pin(InternalGPIOPin *cts_pin) { this->cts_pin_ = cts_pin; }
106 void set_baud_rate(int baud_rate) { this->baud_rate_ = baud_rate; }
107#ifdef USE_MODEM_PIN_CODE
108 void set_pin_code(const char *pin_code) { this->pin_code_ = pin_code; }
109#endif
110 void set_tx_buffer_size(uint16_t tx_buffer_size) { this->tx_buffer_size_ = tx_buffer_size; }
111 void set_rx_buffer_size(uint16_t rx_buffer_size) { this->rx_buffer_size_ = rx_buffer_size; }
112 void set_dte_buffer_size(uint16_t dte_buffer_size) { this->dte_buffer_size_ = dte_buffer_size; }
113 void set_init_at_commands(const char *const *cmds, uint8_t count) {
114 this->init_at_commands_ = cmds;
115 this->init_at_count_ = count;
116 }
117 template<typename F> void add_on_state_callback(F &&callback) {
118 this->on_state_callback_.add(std::forward<F>(callback));
119 }
120
121 bool is_connected() const { return this->component_state_.load() == ModemState::MODEM_STATE_CONNECTED; }
122 bool is_disabled() const {
123 return this->component_state_.load() == ModemState::MODEM_STATE_DISABLED &&
124 this->target_state_.load() == ModemState::MODEM_STATE_DISABLED;
125 }
126 bool is_enabled() const { return !this->is_disabled(); }
127 void enable();
128 void disable();
129#ifdef USE_MODEM_SEND_AT
132 bool send_at(const char *cmd, uint32_t timeout = COMMAND_TIMEOUT_MS);
133 bool send_at(const std::string &cmd, uint32_t timeout = COMMAND_TIMEOUT_MS);
134#endif
135
136 network::IPAddresses get_ip_addresses();
137 const char *get_use_address() const { return this->use_address_; }
138
139#ifdef USE_MODEM_POLL
140 void set_update_interval(uint32_t update_interval) { this->update_interval_ = update_interval; }
141#endif
142#ifdef USE_MODEM_SIGNAL
143 SUB_SENSOR(rssi)
144 SUB_SENSOR(ber)
145#endif
146#ifdef USE_MODEM_NETWORK_TYPE
147 SUB_TEXT_SENSOR(network_type)
148#endif
149
150 protected:
151 static constexpr uint32_t COMMAND_TIMEOUT_MS = 1000;
152 static constexpr uint32_t RETRY_DELAY_MS = 1000;
153 static constexpr size_t URC_LINE_SIZE = 128;
154 static constexpr size_t AT_COMMAND_SIZE = 128;
155 static constexpr size_t REPLY_SIZE = 256; // a longer reply keeps its newest bytes, so its final line counts
156#ifdef USE_MODEM_POLL
157 static constexpr uint8_t CSQ_UNKNOWN = 99; // AT+CSQ rssi or ber the modem cannot tell
158 static constexpr uint8_t CSQ_RSSI_MAX = 31;
159 static constexpr uint8_t NETWORK_MODE_NO_SERVICE = 0;
160 static constexpr uint8_t NETWORK_MODE_NONE = 255; // no AT+CNSMOD answer; past the name table, so Unknown
161#endif
162
163 // esp_modem's calls block until the modem answers or their own timeouts run out, up to a minute for a
164 // mode change, so the state machine runs on its own task and leaves the main loop alone
165 static void task_entry(void *arg);
166 void run_task_();
167 void wake_task_();
168 ModemState compute_next_state_();
169 ModemState handle_state_enabling_();
170 ModemState handle_state_synced_();
171 ModemState handle_state_connecting_();
172 ModemState handle_state_wait_ip_();
173 ModemState handle_state_disconnecting_();
175 uint32_t next_probe_delay_();
176 ModemState retry_(ModemState state, uint32_t delay_ms = RETRY_DELAY_MS);
177 void transition_to_(ModemState next_state);
178 // What the task left for loop() to do
179 enum Pending : uint32_t {
180 PENDING_STATUS = 1 << 0,
181 PENDING_SAVE_BAUD = 1 << 1,
182#ifdef USE_MODEM_PIN_CODE
183 PENDING_SAVE_PIN = 1 << 2,
184#endif
185 PENDING_CONNECT_TIMEOUT = 1 << 3, // arm or cancel the reboot timer for the current state
186 PENDING_ON_SYNC = 1 << 4, // loop() wakes the task once on_sync ran
187 PENDING_ON_CONNECT = 1 << 5,
188 PENDING_ON_DISCONNECT = 1 << 6,
189 };
190#ifdef USE_MODEM_POLL
191 void poll_();
192 void publish_readings_(uint8_t rssi, uint8_t ber, uint8_t mode);
193#endif
194
195 // Main loop only, so arming and cancelling cannot interleave
196 void arm_connect_timeout_();
197 void cancel_connect_timeout_();
198 void fail_setup_(const LogString *reason);
199 void set_fault_(ModemFault fault);
200 void set_teardown_fault_();
201 void clear_config_fault_(ModemFault fault);
202 void hand_over_(uint32_t pending);
204 esp_modem::command_result at_(const char *cmd, uint32_t timeout = COMMAND_TIMEOUT_MS);
206 esp_modem::command_result at_reply_(const char *cmd, uint32_t timeout = COMMAND_TIMEOUT_MS);
207 void publish_status_();
209 bool escape_data_mode_();
211 bool flush_cmux_();
212 void request_resync_();
213 int read_stat_(const char *cmd, const char *prefix);
214 int read_registration_();
216 esp_err_t set_uart_baud_(int baud);
217 void not_responding_(int baud);
218 void sim_not_ready_(const char *reason);
219 void dump_connect_params_();
220 SimResult prepare_sim_();
221#ifdef USE_MODEM_PIN_CODE
222 SimResult send_pin_();
223 void save_pin_record_();
224#endif
225
226 InternalGPIOPin *tx_pin_;
227 InternalGPIOPin *rx_pin_;
228 InternalGPIOPin *rts_pin_{nullptr};
229 InternalGPIOPin *cts_pin_{nullptr};
230 const char *model_;
231 DceFactory dce_factory_;
232 const char *apn_;
233 const char *const *init_at_commands_{nullptr}; // static array from code generation
234#ifdef USE_MODEM_URC
235 const char *urc_line_{nullptr}; // the line urc_pending_ hands to loop(), inside urc_reader_
236#endif
237 std::unique_ptr<esp_modem::DCE> dce_;
238 char reply_[REPLY_SIZE + 1]{}; // task only; the last reply, null-terminated
239 size_t reply_len_{0};
240 bool reply_cut_{false}; // the last reply was longer than reply_ and kept only its end
241 std::shared_ptr<esp_modem::DTE> dte_;
242 esp_netif_t *ppp_netif_{nullptr};
244 LazyCallbackManager<void(ModemState)> on_state_callback_;
245 int baud_rate_{0}; // 0 = use the esp_modem default
246 int current_baud_rate_{0};
247 int restored_baud_{0};
248 StaticTask task_;
249 uint32_t timeout_{0};
250 uint32_t step_delay_ms_{0};
251 uint32_t state_started_ms_{0}; // when the IP wait or the PIN unlock wait began
252 std::atomic<uint32_t> pending_{0};
253#ifdef USE_MODEM_PIN_CODE
254 const char *pin_code_{nullptr};
255 ESPPreferenceObject pin_pref_;
256#endif
257 // Kept in flash so reboots cannot keep spending the SIM's attempts on a PIN it never confirmed
258 struct PinRecord {
259 uint32_t hash; // pin_code the record is about
260 uint8_t sends; // AT+CPIN= sent without the SIM reporting READY since
261 };
262#ifdef USE_MODEM_PIN_CODE
263 PinRecord pin_record_{}; // the task writes it, loop() saves it while pin_save_state_ is PENDING
264#endif
265#ifdef USE_MODEM_SEND_AT
266 uint32_t at_timeout_{COMMAND_TIMEOUT_MS};
267#endif
268#ifdef USE_MODEM_POLL
269 uint32_t update_interval_{0};
270 uint32_t next_poll_ms_{0}; // task only
271#endif
272 uint16_t tx_buffer_size_{1024};
273 uint16_t rx_buffer_size_{1024};
274 uint16_t dte_buffer_size_{1024};
275 // The task owns component_state_; the main loop sets target_state_ and reads both
276 std::atomic<ModemState> component_state_{ModemState::MODEM_STATE_DISABLED};
277 std::atomic<ModemState> target_state_{ModemState::MODEM_STATE_DISABLED};
278 // Written by the task only, read by loop()
279 std::atomic<ModemFault> fault_{ModemFault::MODEM_FAULT_NONE};
280 // A failed baud_rate or init_at step, shown once fault_ is clear until the step passes again
281 std::atomic<ModemFault> config_fault_{ModemFault::MODEM_FAULT_NONE};
282 // std::atomic<uint8_t> flags: GCC on Xtensa calls out of line for std::atomic<bool>
283 // Written by the IP event task, read by the modem task
284 std::atomic<uint8_t> got_ip_{0};
285 std::atomic<uint8_t> ppp_error_{0}; // last NETIF_PPP_STATUS error code, 0 = none
286 // Doublings of the silent-modem probe delay; enable() and an answer reset it
287 std::atomic<uint8_t> probe_backoff_{0};
288 // Set by loop() once on_sync ran; the task waits for it, not for any notification
289 std::atomic<uint8_t> sync_acked_{0};
290#ifdef USE_MODEM_SEND_AT
291 // Set by send_at() on the main loop once at_command_ is written, cleared by the task after sending it
292 std::atomic<uint8_t> at_pending_{0};
293#endif
294#ifdef USE_MODEM_URC
295 // Set by the UART task with urc_line_; until loop() has published it, new lines are dropped
296 std::atomic<uint8_t> urc_pending_{0};
297#endif
298#ifdef USE_MODEM_POLL
299 // Set by the task with the poll_ answers below; until loop() has published them, polls are skipped
300 std::atomic<uint8_t> poll_unpublished_{0};
301#endif
302#ifdef USE_MODEM_PIN_CODE
303 std::atomic<PinSave> pin_save_state_{PinSave::PIN_SAVE_DONE};
305 bool pin_record_unsaved_{false}; // loop() only; the last PIN record save failed
306#endif
308 uint8_t init_at_count_{0};
309 uint8_t uart_port_{UART_NUM_MAX};
310 uint8_t attach_polls_{0};
311 uint8_t idle_polls_{0}; // polls in a row that reported "not searching"
312 uint8_t unknown_polls_{0}; // polls in a row with no usable registration state
313 uint8_t sim_polls_{0}; // failed SIM status reads in this attempt
314#ifdef USE_MODEM_POLL
315 uint8_t poll_rssi_{CSQ_UNKNOWN}; // raw AT+CSQ answers
316 uint8_t poll_ber_{CSQ_UNKNOWN};
317 uint8_t poll_mode_{NETWORK_MODE_NONE}; // raw AT+CNSMOD answer
318#endif
319 bool connect_timeout_armed_{false};
320 bool modem_synced_{false}; // a modem that never answered has nothing to tear down
321 bool answered_{false}; // the modem synced since boot, so its wiring and power are fine
322 bool resync_{false}; // a command timed out, so CONNECTING syncs again first
323 bool apn_pending_{false}; // ENABLING could not set the APN at CFUN=0, so CONNECTING sets it after the SIM check
324#ifdef USE_MODEM_SEND_AT
325 char at_command_[AT_COMMAND_SIZE];
326#endif
327#ifdef USE_MODEM_URC
328 // Fed on the UART task
329 LineReader<URC_LINE_SIZE> urc_reader_;
330#endif
331
332 private:
333 // Points at a string literal from code generation, never at dynamic storage
334 const char *use_address_{""};
335};
336
337extern ModemComponent *global_modem_component; // NOLINT(cppcoreguidelines-avoid-non-const-global-variables)
338
339} // namespace esphome::modem
340
341#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