Skip to content

Commit

Permalink
Add mgos_mqtt_global_disconnect()
Browse files Browse the repository at this point in the history
Disconnect from and/or stop trying to connect to MQTT server until mgos_mqtt_global_connect() is called.

CL: mqtt: Add mgos_mqtt_global_disconnect()
  • Loading branch information
rojer committed Jul 10, 2019
1 parent c180e2b commit e28a870
Show file tree
Hide file tree
Showing 3 changed files with 27 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .clang-format
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
BasedOnStyle: Google
AllowShortFunctionsOnASingleLine: false
SpaceAfterCStyleCast: true
PointerBindsToType: false
DerivePointerBinding: false
6 changes: 6 additions & 0 deletions include/mgos_mqtt.h
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,12 @@ struct mg_connection *mgos_mqtt_get_global_conn(void);
*/
bool mgos_mqtt_global_connect(void);

/*
* Disconnect from and/or stop trying to connect to MQTT server
* until mgos_mqtt_global_connect() is called.
*/
void mgos_mqtt_global_disconnect(void);

/* Returns true if MQTT connection is up, false otherwise. */
bool mgos_mqtt_global_is_connected(void);

Expand Down
18 changes: 16 additions & 2 deletions src/mgos_mqtt.c
Original file line number Diff line number Diff line change
Expand Up @@ -248,7 +248,7 @@ void mgos_mqtt_set_connect_fn(mgos_mqtt_connect_fn_t fn, void *fn_arg) {

static void mgos_mqtt_net_ev(int ev, void *evd, void *arg) {
if (ev != MGOS_NET_EV_IP_ACQUIRED) return;

if (s_reconnect_timeout_ms < 0) return; // User doesn't want us to reconnect.
mgos_mqtt_global_connect();
(void) evd;
(void) arg;
Expand Down Expand Up @@ -402,6 +402,10 @@ bool mgos_mqtt_global_connect(void) {
/* If we're already connected, do nothing */
if (s_conn != NULL) return true;

if (s_reconnect_timeout_ms < 0) {
s_reconnect_timeout_ms = 0;
}

if (!mgos_mqtt_time_ok()) {
mqtt_global_reconnect();
return false;
Expand Down Expand Up @@ -440,6 +444,14 @@ bool mgos_mqtt_global_connect(void) {
return ret;
}

void mgos_mqtt_global_disconnect(void) {
// This will prevent reconnect.
s_reconnect_timeout_ms = -1;
if (s_conn != NULL) {
s_conn->flags |= MG_F_CLOSE_IMMEDIATELY;
}
}

bool mgos_mqtt_global_is_connected(void) {
return s_connected;
}
Expand Down Expand Up @@ -471,7 +483,9 @@ static void mqtt_switch_config(void) {

static void mqtt_global_reconnect(void) {
int rt_ms;
if (s_cfg == NULL || s_cfg->server == NULL) return;
if (s_cfg == NULL || s_cfg->server == NULL || s_reconnect_timeout_ms < 0) {
return;
}

if (s_reconnect_timeout_ms >= s_cfg->reconnect_timeout_max * 1000) {
mqtt_switch_config();
Expand Down

0 comments on commit e28a870

Please sign in to comment.