Skip to content

Commit e55c803

Browse files
committed
net: lib: mqtt_client: Don't initialize MQTT client struct on connect
Part of the MQTT client struct initialization is memset() on the structure and mutex initialization. Having this as a part of the client connect doesn't work well in multi-threaded environment (as in MQTT sample), where client reconnect can be triggered from a different thread than regular client processing. In such case, the mutex structure could be reinitialized while already being in use by the MQTT helper thread, leading to asserts. Fix this by initializing the MQTT client structure once, on MQTT helper library init. Align the mqtt_helper testsuite with the change. Jira: NCSIDB-1569 Signed-off-by: Robert Lubos <[email protected]>
1 parent 2b21d5a commit e55c803

File tree

2 files changed

+4
-6
lines changed

2 files changed

+4
-6
lines changed

subsys/net/lib/mqtt_helper/mqtt_helper.c

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -452,8 +452,6 @@ static int client_connect(struct mqtt_helper_conn_params *conn_params)
452452
.size = conn_params->password.size,
453453
};
454454

455-
mqtt_client_init(&mqtt_client);
456-
457455
err = broker_init(&broker, conn_params);
458456
if (err) {
459457
return err;
@@ -576,6 +574,8 @@ int mqtt_helper_init(struct mqtt_helper_cfg *cfg)
576574

577575
current_cfg = *cfg;
578576

577+
mqtt_client_init(&mqtt_client);
578+
579579
mqtt_state_set(MQTT_STATE_DISCONNECTED);
580580

581581
return 0;

tests/subsys/net/lib/mqtt_helper/src/mqtt_helper_test.c

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -242,6 +242,8 @@ void test_mqtt_helper_init_when_unitialized(void)
242242
},
243243
};
244244

245+
__cmock_mqtt_client_init_Expect(&mqtt_client);
246+
245247
TEST_ASSERT_EQUAL(0, mqtt_helper_init(&cfg));
246248
TEST_ASSERT_EQUAL(mqtt_state_get(), MQTT_STATE_DISCONNECTED);
247249
}
@@ -272,8 +274,6 @@ void test_mqtt_helper_connect_when_disconnected(void)
272274
},
273275
};
274276

275-
__cmock_mqtt_client_init_Expect(&mqtt_client);
276-
277277
/* Make getddrinfo return a pointer that points to NULL. Otherwise the unit under test
278278
* would be dereferencing uninitialized memory location. The behavior of the unit
279279
* under test for when non-NULL values are returned is out of scope of this test.
@@ -299,8 +299,6 @@ void test_mqtt_helper_connect_when_disconnected_mqtt_api_error(void)
299299
{
300300
struct mqtt_helper_conn_params conn_params_dummy;
301301

302-
__cmock_mqtt_client_init_Expect(&mqtt_client);
303-
304302
__cmock_zsock_freeaddrinfo_ExpectAnyArgs();
305303
__cmock_mqtt_connect_ExpectAndReturn(&mqtt_client, -2);
306304

0 commit comments

Comments
 (0)