Skip to content

Commit 5b87b2b

Browse files
committed
Do not change _state value in message handler to avoid race conditions
1 parent 804dbab commit 5b87b2b

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

src/ArduinoIoTCloudTCP.cpp

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -80,6 +80,7 @@ extern "C" void setThingIdOutdated()
8080

8181
ArduinoIoTCloudTCP::ArduinoIoTCloudTCP()
8282
: _state{State::ConnectPhy}
83+
, _next_state{State::Invalid}
8384
, _next_connection_attempt_tick{0}
8485
, _last_connection_attempt_cnt{0}
8586
, _next_device_subscribe_attempt_tick{0}
@@ -323,6 +324,13 @@ void ArduinoIoTCloudTCP::update()
323324
watchdog_reset();
324325
#endif
325326

327+
/* Check if the state has changed in message handler */
328+
if(_next_state != State::Invalid)
329+
{
330+
DEBUG_VERBOSE("ArduinoIoTCloudTCP::%s state changed in message handler", __FUNCTION__);
331+
_state = _next_state;
332+
_next_state = State::Invalid;
333+
}
326334

327335
/* Run through the state machine. */
328336
State next_state = _state;
@@ -694,7 +702,7 @@ void ArduinoIoTCloudTCP::handleMessage(int length)
694702
CBORDecoder::decode(_device_property_container, (uint8_t*)bytes, length);
695703
_last_device_subscribe_cnt = 0;
696704
_next_device_subscribe_attempt_tick = 0;
697-
_state = State::CheckDeviceConfig;
705+
_next_state = State::CheckDeviceConfig;
698706
}
699707

700708
/* Topic for user input data */
@@ -712,7 +720,7 @@ void ArduinoIoTCloudTCP::handleMessage(int length)
712720
execCloudEventCallback(ArduinoIoTCloudEvent::SYNC);
713721
_last_sync_request_cnt = 0;
714722
_last_sync_request_tick = 0;
715-
_state = State::Connected;
723+
_next_state = State::Connected;
716724
}
717725
}
718726

src/ArduinoIoTCloudTCP.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -112,9 +112,11 @@ class ArduinoIoTCloudTCP: public ArduinoIoTCloudClass
112112
SubscribeThingTopics,
113113
RequestLastValues,
114114
Connected,
115+
Invalid
115116
};
116117

117118
State _state;
119+
State _next_state;
118120

119121
unsigned long _next_connection_attempt_tick;
120122
unsigned int _last_connection_attempt_cnt;

0 commit comments

Comments
 (0)