int keepalive(MQTTClient *c) { int rc = SUCCESS; if (c->keepAliveInterval == 0) { goto exit; } if (TimerIsExpired(&c->last_sent) || TimerIsExpired(&c->last_received)) { if (c->ping_outstanding && TimerIsExpired(&c->ping_wait)) { rc = FAILURE; /* PINGRESP not received in keepalive interval */ } else { Timer timer; TimerInit(&timer); TimerCountdownMS(&timer, 1000); int len = MQTTSerialize_pingreq(c->buf, c->buf_size); if (len > 0 && (rc = sendPacket(c, len, &timer)) == SUCCESS) { // send the ping packet c->ping_outstanding = 1; TimerCountdownMS(&c->ping_wait, CONFIG_MQTT_PING_TIMEOUT); } } } exit: return rc; }
int waitfor(MQTTClient* c, int packet_type, Timer* timer) { int rc = FAILURE; do { if (TimerIsExpired(timer)) break; // we timed out } while ((rc = cycle(c, timer)) != packet_type); return rc; }
int MQTTYield(MQTTClient *c, int timeout_ms) { int rc = SUCCESS; Timer timer; TimerInit(&timer); TimerCountdownMS(&timer, timeout_ms); do { if (cycle(c, &timer) < 0) { rc = FAILURE; break; } } while (!TimerIsExpired(&timer)); return rc; }
static int sendPacket(MQTTClient* c, int length, Timer* timer) { int rc = FAILURE, sent = 0; while ((sent < length) && !TimerIsExpired(timer)) { rc = c->ipstack->mqttwrite(c->ipstack, &c->buf[sent], length, TimerLeftMS(timer)); if (rc < 0) break; sent += rc; } /* The send progress only send the packet to the socket buffer we dont know if it successeds, default it is SUCCESS */ if (sent == length) { rc = SUCCESS; } else { rc = FAILURE; } return rc; }
static int sendPacket(MQTTClient *c, int length, Timer *timer) { int rc = FAILURE, sent = 0; while (sent < length && !TimerIsExpired(timer)) { rc = c->ipstack->mqttwrite(c->ipstack, &c->buf[sent], length, TimerLeftMS(timer)); if (rc < 0) { // there was an error writing the data break; } sent += rc; } if (sent == length) { TimerCountdown(&c->last_sent, c->keepAliveInterval); // record the fact that we have successfully sent the packet rc = SUCCESS; } else { rc = FAILURE; } return rc; }
int keepalive(MQTTClient* c) { int rc = SUCCESS; if (c->keepAliveInterval == 0) { rc = SUCCESS; goto exit; } if (TimerIsExpired(&c->ping_timer)) { printf("keep alive counter expired\n"); if (!c->ping_outstanding) { printf("keep alive counter reset\n"); //Set the pingreq send timeout Timer timer; TimerInit(&timer); TimerCountdownMS(&timer, 1000); int len = MQTTSerialize_pingreq(c->buf, c->buf_size); /* If the sendPacket success, the keep alive works with keepAliveInterval */ if (len > 0 && (rc = sendPacket(c, len, &timer)) == SUCCESS) {// send the ping packet c->ping_outstanding = 1; TimerCountdown(&c->ping_timer, c->keepAliveInterval); // record the fact that we have successfully sent the packet } else { rc = FAILURE; } } else { printf("keep alive counter failure\n"); rc = FAILURE; } } exit: return rc; }