1+ #include " lte.h"
2+
13#include " led_ctrl.h"
24#include " log.h"
3- #include " lte.h"
45#include " mqtt_client.h"
56#include " sequans_controller.h"
67
@@ -97,14 +98,22 @@ static void timezoneCallback(__attribute__((unused)) char* buffer) {
9798 got_timezone = true ;
9899}
99100
100- bool LteClass::begin (const bool print_messages) {
101+ bool LteClass::begin (const uint32_t timeout_ms, const bool print_messages) {
102+
103+ const uint32_t start = millis ();
101104
102105 // If low power is utilized, sequans controller will already been
103106 // initialized, so don't reset it by calling begin again
104107 if (!SequansController.isInitialized ()) {
105108 SequansController.begin ();
106109 }
107110
111+ // Disconnect before configuration if already connected
112+ SequansController.writeCommand (AT_DISCONNECT);
113+
114+ delay (100 );
115+ SequansController.clearReceiveBuffer ();
116+
108117 SequansController.registerCallback (TIMEZONE_CALLBACK, timezoneCallback);
109118
110119 SequansController.writeCommand (AT_ENABLE_TIME_ZONE_UPDATE);
@@ -154,7 +163,7 @@ bool LteClass::begin(const bool print_messages) {
154163 Log.infof (" Connecting to operator" );
155164 }
156165
157- while (!isConnected ()) {
166+ while (!isConnected () && millis () - start < timeout_ms ) {
158167 LedCtrl.toggle (Led::CELL, true );
159168 delay (500 );
160169
@@ -163,6 +172,20 @@ bool LteClass::begin(const bool print_messages) {
163172 }
164173 }
165174
175+ if (millis () - start >= timeout_ms) {
176+
177+ Log.rawf (" Was not able to connect to the network within the timeout "
178+ " of %d ms. Consider increasing the timeout or checking your "
179+ " cellular coverage.\r\n " ,
180+ timeout_ms);
181+
182+ SequansController.unregisterCallback (CEREG_CALLBACK);
183+ SequansController.unregisterCallback (TIMEZONE_CALLBACK);
184+ SequansController.writeCommand (AT_DISCONNECT);
185+
186+ return false ;
187+ }
188+
166189 if (print_messages) {
167190 Log.rawf (" OK!\r\n " );
168191 }
@@ -264,6 +287,7 @@ void LteClass::end(void) {
264287 while (isConnected () && millis () - start < 2000 ) {}
265288 SequansController.unregisterCallback (CEREG_CALLBACK);
266289
290+ SequansController.clearReceiveBuffer ();
267291 SequansController.end ();
268292 }
269293
0 commit comments