Skip to content

Commit 1a02b83

Browse files
committed
Do not change _state value in message handler to avoid race conditions
1 parent d781033 commit 1a02b83

File tree

2 files changed

+11
-2
lines changed

2 files changed

+11
-2
lines changed

src/ArduinoIoTCloudTCP.cpp

+9-2
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}
@@ -325,6 +326,12 @@ void ArduinoIoTCloudTCP::update()
325326
watchdog_reset();
326327
#endif
327328

329+
/* Check if the state has changed in message handler */
330+
if(_next_state != State::Invalid)
331+
{
332+
_state = _next_state;
333+
_next_state = State::Invalid;
334+
}
328335

329336
/* Run through the state machine. */
330337
State next_state = _state;
@@ -716,7 +723,7 @@ void ArduinoIoTCloudTCP::handleMessage(int length)
716723
CBORDecoder::decode(_device_property_container, (uint8_t*)bytes, length);
717724
_last_device_subscribe_cnt = 0;
718725
_next_device_subscribe_attempt_tick = 0;
719-
_state = State::CheckDeviceConfig;
726+
_next_state = State::CheckDeviceConfig;
720727
}
721728

722729
/* Topic for user input data */
@@ -734,7 +741,7 @@ void ArduinoIoTCloudTCP::handleMessage(int length)
734741
execCloudEventCallback(ArduinoIoTCloudEvent::SYNC);
735742
_last_sync_request_cnt = 0;
736743
_last_sync_request_tick = 0;
737-
_state = State::Connected;
744+
_next_state = State::Connected;
738745
}
739746
}
740747

src/ArduinoIoTCloudTCP.h

+2
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)