yuezonghe | c78e2ef | 2025-02-13 17:57:46 -0800 | [diff] [blame^] | 1 | /******************************************************************************* |
| 2 | * Copyright (c) 2014, 2017 IBM Corp. |
| 3 | * |
| 4 | * All rights reserved. This program and the accompanying materials |
| 5 | * are made available under the terms of the Eclipse Public License v1.0 |
| 6 | * and Eclipse Distribution License v1.0 which accompany this distribution. |
| 7 | * |
| 8 | * The Eclipse Public License is available at |
| 9 | * http://www.eclipse.org/legal/epl-v10.html |
| 10 | * and the Eclipse Distribution License is available at |
| 11 | * http://www.eclipse.org/org/documents/edl-v10.php. |
| 12 | * |
| 13 | * Contributors: |
| 14 | * Allan Stockdill-Mander/Ian Craggs - initial API and implementation and/or initial documentation |
| 15 | * Ian Craggs - fix for #96 - check rem_len in readPacket |
| 16 | * Ian Craggs - add ability to set message handler separately #6 |
| 17 | *******************************************************************************/ |
| 18 | #include "MQTTClient.h" |
| 19 | |
| 20 | #include <stdio.h> |
| 21 | #include <string.h> |
| 22 | |
| 23 | #define MQTT_RECONN_MINTIMESPACE (1*60*1000) //Reconnect min timespace, unit:ms |
| 24 | #define MQTT_RECONN_MAXCOUNT (30) //Reconnect max count |
| 25 | |
| 26 | static void NewMessageData(MessageData* md, MQTTString* aTopicName, MQTTMessage* aMessage) { |
| 27 | md->topicName = aTopicName; |
| 28 | md->message = aMessage; |
| 29 | } |
| 30 | |
| 31 | |
| 32 | static int getNextPacketId(MQTTClient *c) { |
| 33 | return c->next_packetid = (c->next_packetid == MAX_PACKET_ID) ? 1 : c->next_packetid + 1; |
| 34 | } |
| 35 | |
| 36 | |
| 37 | static int sendPacket(MQTTClient* c, int length, Timer* timer) |
| 38 | { |
| 39 | int rc = FAILURE, |
| 40 | sent = 0; |
| 41 | |
| 42 | while (sent < length && !TimerIsExpired(timer)) |
| 43 | { |
| 44 | rc = c->ipstack->mqttwrite(c->ipstack, &c->buf[sent], length, TimerLeftMS(timer)); |
| 45 | if (rc < 0) // there was an error writing the data |
| 46 | break; |
| 47 | sent += rc; |
| 48 | } |
| 49 | if (sent == length) |
| 50 | { |
| 51 | TimerCountdown(&c->last_sent, c->keepAliveInterval); // record the fact that we have successfully sent the packet |
| 52 | rc = SUCCESS; |
| 53 | } |
| 54 | else |
| 55 | rc = FAILURE; |
| 56 | return rc; |
| 57 | } |
| 58 | |
| 59 | |
| 60 | void MQTTClientInit(MQTTClient* c, Network* network, unsigned int command_timeout_ms, |
| 61 | unsigned char* sendbuf, size_t sendbuf_size, unsigned char* readbuf, size_t readbuf_size) |
| 62 | { |
| 63 | int i; |
| 64 | c->ipstack = network; |
| 65 | |
| 66 | for (i = 0; i < MAX_MESSAGE_HANDLERS; ++i) |
| 67 | c->messageHandlers[i].topicFilter = 0; |
| 68 | c->command_timeout_ms = command_timeout_ms; |
| 69 | c->buf = sendbuf; |
| 70 | c->buf_size = sendbuf_size; |
| 71 | c->readbuf = readbuf; |
| 72 | c->readbuf_size = readbuf_size; |
| 73 | c->isconnected = 0; |
| 74 | c->cleansession = 0; |
| 75 | c->ping_outstanding = 0; |
| 76 | c->defaultMessageHandler = NULL; |
| 77 | c->next_packetid = 1; |
| 78 | TimerInit(&c->last_sent); |
| 79 | TimerInit(&c->last_received); |
| 80 | #if defined(MQTT_TASK) |
| 81 | MutexInit(&c->mutex); |
| 82 | #endif |
| 83 | } |
| 84 | |
| 85 | |
| 86 | static int decodePacket(MQTTClient* c, int* value, int timeout) |
| 87 | { |
| 88 | unsigned char i; |
| 89 | int multiplier = 1; |
| 90 | int len = 0; |
| 91 | const int MAX_NO_OF_REMAINING_LENGTH_BYTES = 4; |
| 92 | |
| 93 | *value = 0; |
| 94 | do |
| 95 | { |
| 96 | int rc = MQTTPACKET_READ_ERROR; |
| 97 | |
| 98 | if (++len > MAX_NO_OF_REMAINING_LENGTH_BYTES) |
| 99 | { |
| 100 | rc = MQTTPACKET_READ_ERROR; /* bad data */ |
| 101 | goto exit; |
| 102 | } |
| 103 | rc = c->ipstack->mqttread(c->ipstack, &i, 1, timeout); |
| 104 | if (rc != 1) |
| 105 | goto exit; |
| 106 | *value += (i & 127) * multiplier; |
| 107 | multiplier *= 128; |
| 108 | } while ((i & 128) != 0); |
| 109 | exit: |
| 110 | return len; |
| 111 | } |
| 112 | |
| 113 | |
| 114 | static int readPacket(MQTTClient* c, Timer* timer) |
| 115 | { |
| 116 | MQTTHeader header = {0}; |
| 117 | int len = 0; |
| 118 | int rem_len = 0; |
| 119 | |
| 120 | /* 1. read the header byte. This has the packet type in it */ |
| 121 | printf("1. read the header\n"); |
| 122 | int rc = c->ipstack->mqttread(c->ipstack, c->readbuf, 1, TimerLeftMS(timer)); |
| 123 | if (rc != 1) |
| 124 | goto exit; |
| 125 | |
| 126 | len = 1; |
| 127 | /* 2. read the remaining length. This is variable in itself */ |
| 128 | printf("2. read the remaining length\n"); |
| 129 | decodePacket(c, &rem_len, TimerLeftMS(timer)); |
| 130 | len += MQTTPacket_encode(c->readbuf + 1, rem_len); /* put the original remaining length back into the buffer */ |
| 131 | |
| 132 | if (rem_len > (c->readbuf_size - len)) |
| 133 | { |
| 134 | rc = BUFFER_OVERFLOW; |
| 135 | printf("Buffer overflow error\n"); |
| 136 | goto exit; |
| 137 | } |
| 138 | |
| 139 | /* 3. read the rest of the buffer using a callback to supply the rest of the data */ |
| 140 | printf("3. read the rest of the buffer\n"); |
| 141 | if (rem_len > 0 && (rc = c->ipstack->mqttread(c->ipstack, c->readbuf + len, rem_len, TimerLeftMS(timer)) != rem_len)) { |
| 142 | printf("Failed to receive the rest of the packet\n"); |
| 143 | rc = 0; |
| 144 | goto exit; |
| 145 | } |
| 146 | |
| 147 | header.byte = c->readbuf[0]; |
| 148 | rc = header.bits.type; |
| 149 | if (c->keepAliveInterval > 0) |
| 150 | TimerCountdown(&c->last_received, c->keepAliveInterval); // record the fact that we have successfully received a packet |
| 151 | exit: |
| 152 | printf("readPacket rc = %d\n",rc); |
| 153 | return rc; |
| 154 | } |
| 155 | |
| 156 | |
| 157 | // assume topic filter and name is in correct format |
| 158 | // # can only be at end |
| 159 | // + and # can only be next to separator |
| 160 | static char isTopicMatched(char* topicFilter, MQTTString* topicName) |
| 161 | { |
| 162 | char* curf = topicFilter; |
| 163 | char* curn = topicName->lenstring.data; |
| 164 | char* curn_end = curn + topicName->lenstring.len; |
| 165 | |
| 166 | while (*curf && curn < curn_end) |
| 167 | { |
| 168 | if (*curn == '/' && *curf != '/') |
| 169 | break; |
| 170 | if (*curf != '+' && *curf != '#' && *curf != *curn) |
| 171 | break; |
| 172 | if (*curf == '+') |
| 173 | { // skip until we meet the next separator, or end of string |
| 174 | char* nextpos = curn + 1; |
| 175 | while (nextpos < curn_end && *nextpos != '/') |
| 176 | nextpos = ++curn + 1; |
| 177 | } |
| 178 | else if (*curf == '#') |
| 179 | curn = curn_end - 1; // skip until end of string |
| 180 | curf++; |
| 181 | curn++; |
| 182 | }; |
| 183 | |
| 184 | return (curn == curn_end) && (*curf == '\0'); |
| 185 | } |
| 186 | |
| 187 | |
| 188 | int deliverMessage(MQTTClient* c, MQTTString* topicName, MQTTMessage* message) |
| 189 | { |
| 190 | int i; |
| 191 | int rc = FAILURE; |
| 192 | |
| 193 | // we have to find the right message handler - indexed by topic |
| 194 | for (i = 0; i < MAX_MESSAGE_HANDLERS; ++i) |
| 195 | { |
| 196 | if (c->messageHandlers[i].topicFilter != 0 && (MQTTPacket_equals(topicName, (char*)c->messageHandlers[i].topicFilter) || |
| 197 | isTopicMatched((char*)c->messageHandlers[i].topicFilter, topicName))) |
| 198 | { |
| 199 | if (c->messageHandlers[i].fp != NULL) |
| 200 | { |
| 201 | MessageData md; |
| 202 | NewMessageData(&md, topicName, message); |
| 203 | c->messageHandlers[i].fp(&md); |
| 204 | rc = SUCCESS; |
| 205 | } |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | if (rc == FAILURE && c->defaultMessageHandler != NULL) |
| 210 | { |
| 211 | MessageData md; |
| 212 | NewMessageData(&md, topicName, message); |
| 213 | c->defaultMessageHandler(&md); |
| 214 | rc = SUCCESS; |
| 215 | } |
| 216 | |
| 217 | return rc; |
| 218 | } |
| 219 | |
| 220 | |
| 221 | int keepalive(MQTTClient* c) |
| 222 | { |
| 223 | int rc = SUCCESS; |
| 224 | |
| 225 | if (c->keepAliveInterval == 0) |
| 226 | goto exit; |
| 227 | |
| 228 | if (TimerIsExpired(&c->last_sent) || TimerIsExpired(&c->last_received)) |
| 229 | { |
| 230 | if (c->ping_outstanding) |
| 231 | rc = FAILURE; /* PINGRESP not received in keepalive interval */ |
| 232 | else |
| 233 | { |
| 234 | Timer timer; |
| 235 | TimerInit(&timer); |
| 236 | TimerCountdownMS(&timer, 1000); |
| 237 | int len = MQTTSerialize_pingreq(c->buf, c->buf_size); |
| 238 | printf("keepalive MQTTSerialize_pingreq len = %d\n",len); |
| 239 | if (len > 0 && (rc = sendPacket(c, len, &timer)) == SUCCESS) // send the ping packet |
| 240 | c->ping_outstanding = 1; |
| 241 | } |
| 242 | } |
| 243 | |
| 244 | exit: |
| 245 | return rc; |
| 246 | } |
| 247 | |
| 248 | |
| 249 | void MQTTCleanSession(MQTTClient* c) |
| 250 | { |
| 251 | int i = 0; |
| 252 | |
| 253 | for (i = 0; i < MAX_MESSAGE_HANDLERS; ++i) |
| 254 | c->messageHandlers[i].topicFilter = NULL; |
| 255 | } |
| 256 | |
| 257 | |
| 258 | void MQTTCloseSession(MQTTClient* c) |
| 259 | { |
| 260 | c->ping_outstanding = 0; |
| 261 | c->isconnected = 0; |
| 262 | if (c->cleansession) |
| 263 | MQTTCleanSession(c); |
| 264 | } |
| 265 | |
| 266 | |
| 267 | int cycle(MQTTClient* c, Timer* timer) |
| 268 | { |
| 269 | int len = 0, |
| 270 | rc = SUCCESS; |
| 271 | int packet_type = readPacket(c, timer); /* read the socket, see what work is due */ |
| 272 | printf("cycle packet_type = %d\n", packet_type); |
| 273 | |
| 274 | switch (packet_type) |
| 275 | { |
| 276 | default: |
| 277 | /* no more data to read, unrecoverable. Or read packet fails due to unexpected network error */ |
| 278 | rc = packet_type; |
| 279 | goto exit; |
| 280 | case 0: /* timed out reading packet */ |
| 281 | break; |
| 282 | case CONNACK: |
| 283 | case PUBACK: |
| 284 | case SUBACK: |
| 285 | case UNSUBACK: |
| 286 | break; |
| 287 | case PUBLISH: |
| 288 | { |
| 289 | MQTTString topicName; |
| 290 | MQTTMessage msg; |
| 291 | int intQoS; |
| 292 | msg.payloadlen = 0; /* this is a size_t, but deserialize publish sets this as int */ |
| 293 | if (MQTTDeserialize_publish(&msg.dup, &intQoS, &msg.retained, &msg.id, &topicName, |
| 294 | (unsigned char**)&msg.payload, (int*)&msg.payloadlen, c->readbuf, c->readbuf_size) != 1) |
| 295 | goto exit; |
| 296 | msg.qos = (enum QoS)intQoS; |
| 297 | deliverMessage(c, &topicName, &msg); |
| 298 | if (msg.qos != QOS0) |
| 299 | { |
| 300 | if (msg.qos == QOS1) |
| 301 | len = MQTTSerialize_ack(c->buf, c->buf_size, PUBACK, 0, msg.id); |
| 302 | else if (msg.qos == QOS2) |
| 303 | len = MQTTSerialize_ack(c->buf, c->buf_size, PUBREC, 0, msg.id); |
| 304 | if (len <= 0) |
| 305 | rc = FAILURE; |
| 306 | else |
| 307 | rc = sendPacket(c, len, timer); |
| 308 | if (rc == FAILURE) |
| 309 | goto exit; // there was a problem |
| 310 | } |
| 311 | break; |
| 312 | } |
| 313 | case PUBREC: |
| 314 | case PUBREL: |
| 315 | { |
| 316 | unsigned short mypacketid; |
| 317 | unsigned char dup, type; |
| 318 | if (MQTTDeserialize_ack(&type, &dup, &mypacketid, c->readbuf, c->readbuf_size) != 1) |
| 319 | rc = FAILURE; |
| 320 | else if ((len = MQTTSerialize_ack(c->buf, c->buf_size, |
| 321 | (packet_type == PUBREC) ? PUBREL : PUBCOMP, 0, mypacketid)) <= 0) |
| 322 | rc = FAILURE; |
| 323 | else if ((rc = sendPacket(c, len, timer)) != SUCCESS) // send the PUBREL packet |
| 324 | rc = FAILURE; // there was a problem |
| 325 | if (rc == FAILURE) |
| 326 | goto exit; // there was a problem |
| 327 | break; |
| 328 | } |
| 329 | |
| 330 | case PUBCOMP: |
| 331 | break; |
| 332 | case PINGRESP: |
| 333 | c->ping_outstanding = 0; |
| 334 | break; |
| 335 | } |
| 336 | |
| 337 | if (keepalive(c) != SUCCESS) { |
| 338 | //check only keepalive FAILURE status so that previous FAILURE status can be considered as FAULT |
| 339 | rc = FAILURE; |
| 340 | } |
| 341 | |
| 342 | exit: |
| 343 | if (rc == SUCCESS) |
| 344 | rc = packet_type; |
| 345 | else if (c->isconnected) |
| 346 | MQTTCloseSession(c); |
| 347 | return rc; |
| 348 | } |
| 349 | |
| 350 | |
| 351 | int MQTTYield(MQTTClient* c, int timeout_ms) |
| 352 | { |
| 353 | int rc = SUCCESS; |
| 354 | Timer timer; |
| 355 | |
| 356 | TimerInit(&timer); |
| 357 | TimerCountdownMS(&timer, timeout_ms); |
| 358 | |
| 359 | /* |
| 360 | do |
| 361 | { |
| 362 | if(cycle(c, &timer) < 0) |
| 363 | { |
| 364 | rc = FAILURE; |
| 365 | break; |
| 366 | } |
| 367 | }while(!TimerIsExpired(&timer)); |
| 368 | */ |
| 369 | |
| 370 | while(!TimerIsExpired(&timer)); |
| 371 | if(cycle(c, &timer) < 0) |
| 372 | { |
| 373 | rc = FAILURE; |
| 374 | } |
| 375 | |
| 376 | return rc; |
| 377 | } |
| 378 | |
| 379 | /* |
| 380 | int MqttClientYield(MQTTClient* c, int timeout_ms) |
| 381 | { |
| 382 | int rc = -100; |
| 383 | static Timer timer; |
| 384 | static uint16_t reconnCount = 0; |
| 385 | uint32_t nextReconnTime = 0; |
| 386 | |
| 387 | if (c == NULL) |
| 388 | { |
| 389 | printf("MQTTClient is NULL, please check!\n"); |
| 390 | rc = FAILURE; |
| 391 | } |
| 392 | |
| 393 | if (c -> isconnected) |
| 394 | { |
| 395 | rc = MQTTYield(c, timeout_ms); |
| 396 | if(rc != 0) |
| 397 | { |
| 398 | printf("MQTTYield failed, rc:%d\n", rc); |
| 399 | TimerCountdownMS(&reconntimer, MQTT_RECONN_MINTIMESPACE); |
| 400 | reconnCount = 0; |
| 401 | } |
| 402 | } |
| 403 | else |
| 404 | { |
| 405 | if(reconnCount == 0 || TimerIsExpired(&reconntimer) == 1) |
| 406 | { |
| 407 | reconnCount++; |
| 408 | if(reconnCount < MQTT_RECONN_MAXCOUNT) |
| 409 | { |
| 410 | nextReconnTime = (1 << (reconnCount/5))*MQTT_RECONN_MINTIMESPACE; |
| 411 | } |
| 412 | else |
| 413 | { |
| 414 | nextReconnTime = (1 << (MQTT_RECONN_MAXCOUNT/5))*MQTT_RECONN_MINTIMESPACE; |
| 415 | } |
| 416 | |
| 417 | printf("MQTT is disconnected, try to reconnect, count:%d, next reconnect need %ds!\n", reconnCount, nextReconnTime/1000); |
| 418 | |
| 419 | rc = MqttClientReconnect(c, &g_MqttParam); |
| 420 | if(rc != 0) |
| 421 | { |
| 422 | printf("MQTT reconnect failed, rc:%d\n", rc); |
| 423 | rc = FAILURE; |
| 424 | } |
| 425 | else |
| 426 | { |
| 427 | printf("MQTT reconnect success\n"); |
| 428 | rc = SUCCESS; |
| 429 | } |
| 430 | |
| 431 | TimerCountdownMS(&reconntimer, nextReconnTime); |
| 432 | } |
| 433 | } |
| 434 | |
| 435 | return rc; |
| 436 | } |
| 437 | */ |
| 438 | |
| 439 | int MQTTIsConnected(MQTTClient* client) |
| 440 | { |
| 441 | return client->isconnected; |
| 442 | } |
| 443 | |
| 444 | void MQTTRun(void* parm) |
| 445 | { |
| 446 | Timer timer; |
| 447 | MQTTClient* c = (MQTTClient*)parm; |
| 448 | |
| 449 | TimerInit(&timer); |
| 450 | |
| 451 | while (1) |
| 452 | { |
| 453 | #if defined(MQTT_TASK) |
| 454 | MutexLock(&c->mutex); |
| 455 | #endif |
| 456 | TimerCountdownMS(&timer, 500); /* Don't wait too long if no traffic is incoming */ |
| 457 | cycle(c, &timer); |
| 458 | #if defined(MQTT_TASK) |
| 459 | MutexUnlock(&c->mutex); |
| 460 | #endif |
| 461 | } |
| 462 | } |
| 463 | |
| 464 | |
| 465 | #if defined(MQTT_TASK) |
| 466 | int MQTTStartTask(MQTTClient* client) |
| 467 | { |
| 468 | return ThreadStart(&client->thread, &MQTTRun, client); |
| 469 | } |
| 470 | #endif |
| 471 | |
| 472 | |
| 473 | int waitfor(MQTTClient* c, int packet_type, Timer* timer) |
| 474 | { |
| 475 | int rc = FAILURE; |
| 476 | |
| 477 | do |
| 478 | { |
| 479 | if (TimerIsExpired(timer)) |
| 480 | break; // we timed out |
| 481 | rc = cycle(c, timer); |
| 482 | } |
| 483 | while (rc != packet_type && rc >= 0); |
| 484 | |
| 485 | return rc; |
| 486 | } |
| 487 | |
| 488 | |
| 489 | |
| 490 | |
| 491 | int MQTTConnectWithResults(MQTTClient* c, MQTTPacket_connectData* options, MQTTConnackData* data) |
| 492 | { |
| 493 | Timer connect_timer; |
| 494 | int rc = FAILURE; |
| 495 | MQTTPacket_connectData default_options = MQTTPacket_connectData_initializer; |
| 496 | int len = 0; |
| 497 | |
| 498 | #if defined(MQTT_TASK) |
| 499 | MutexLock(&c->mutex); |
| 500 | #endif |
| 501 | if (c->isconnected) /* don't send connect packet again if we are already connected */ |
| 502 | { |
| 503 | printf( "MQTTConnectWithResults: already connected\n" ); |
| 504 | goto exit; |
| 505 | } |
| 506 | |
| 507 | TimerInit(&connect_timer); |
| 508 | TimerCountdownMS(&connect_timer, c->command_timeout_ms); |
| 509 | |
| 510 | if (options == 0) |
| 511 | options = &default_options; /* set default options if none were supplied */ |
| 512 | |
| 513 | c->keepAliveInterval = options->keepAliveInterval; |
| 514 | c->cleansession = options->cleansession; |
| 515 | TimerCountdown(&c->last_received, c->keepAliveInterval); |
| 516 | if ((len = MQTTSerialize_connect(c->buf, c->buf_size, options)) <= 0) |
| 517 | { |
| 518 | printf("MQTTSerialize_connect fiiled\n"); |
| 519 | goto exit; |
| 520 | } |
| 521 | if ((rc = sendPacket(c, len, &connect_timer)) != SUCCESS) // send the connect packet |
| 522 | { |
| 523 | printf("sendPacket failed\n"); |
| 524 | goto exit; // there was a problem |
| 525 | } |
| 526 | // this will be a blocking call, wait for the connack |
| 527 | if (waitfor(c, CONNACK, &connect_timer) == CONNACK) |
| 528 | { |
| 529 | data->rc = 0; |
| 530 | data->sessionPresent = 0; |
| 531 | if (MQTTDeserialize_connack(&data->sessionPresent, &data->rc, c->readbuf, c->readbuf_size) == 1) |
| 532 | { |
| 533 | rc = data->rc; |
| 534 | } |
| 535 | else |
| 536 | { |
| 537 | printf("MQTTDeserialize_connack failed\n"); |
| 538 | rc = FAILURE; |
| 539 | } |
| 540 | } |
| 541 | else |
| 542 | { |
| 543 | printf("waitfor CONNACK failed\n"); |
| 544 | rc = FAILURE; |
| 545 | } |
| 546 | |
| 547 | exit: |
| 548 | if (rc == SUCCESS) |
| 549 | { |
| 550 | c->isconnected = 1; |
| 551 | c->ping_outstanding = 0; |
| 552 | } |
| 553 | |
| 554 | #if defined(MQTT_TASK) |
| 555 | MutexUnlock(&c->mutex); |
| 556 | #endif |
| 557 | |
| 558 | return rc; |
| 559 | } |
| 560 | |
| 561 | |
| 562 | int MQTTConnect(MQTTClient* c, MQTTPacket_connectData* options) |
| 563 | { |
| 564 | MQTTConnackData data; |
| 565 | return MQTTConnectWithResults(c, options, &data); |
| 566 | } |
| 567 | |
| 568 | |
| 569 | int MQTTSetMessageHandler(MQTTClient* c, const char* topicFilter, messageHandler messageHandler) |
| 570 | { |
| 571 | int rc = FAILURE; |
| 572 | int i = -1; |
| 573 | |
| 574 | /* first check for an existing matching slot */ |
| 575 | for (i = 0; i < MAX_MESSAGE_HANDLERS; ++i) |
| 576 | { |
| 577 | if (c->messageHandlers[i].topicFilter != NULL && strcmp(c->messageHandlers[i].topicFilter, topicFilter) == 0) |
| 578 | { |
| 579 | if (messageHandler == NULL) /* remove existing */ |
| 580 | { |
| 581 | c->messageHandlers[i].topicFilter = NULL; |
| 582 | c->messageHandlers[i].fp = NULL; |
| 583 | } |
| 584 | rc = SUCCESS; /* return i when adding new subscription */ |
| 585 | break; |
| 586 | } |
| 587 | } |
| 588 | /* if no existing, look for empty slot (unless we are removing) */ |
| 589 | if (messageHandler != NULL) { |
| 590 | if (rc == FAILURE) |
| 591 | { |
| 592 | for (i = 0; i < MAX_MESSAGE_HANDLERS; ++i) |
| 593 | { |
| 594 | if (c->messageHandlers[i].topicFilter == NULL) |
| 595 | { |
| 596 | rc = SUCCESS; |
| 597 | break; |
| 598 | } |
| 599 | } |
| 600 | } |
| 601 | if (i < MAX_MESSAGE_HANDLERS) |
| 602 | { |
| 603 | c->messageHandlers[i].topicFilter = topicFilter; |
| 604 | c->messageHandlers[i].fp = messageHandler; |
| 605 | } |
| 606 | } |
| 607 | return rc; |
| 608 | } |
| 609 | |
| 610 | |
| 611 | int MQTTSubscribeWithResults(MQTTClient* c, const char* topicFilter, enum QoS qos, |
| 612 | messageHandler messageHandler, MQTTSubackData* data) |
| 613 | { |
| 614 | int rc = FAILURE; |
| 615 | Timer timer; |
| 616 | int len = 0; |
| 617 | MQTTString topic = MQTTString_initializer; |
| 618 | topic.cstring = (char *)topicFilter; |
| 619 | |
| 620 | #if defined(MQTT_TASK) |
| 621 | MutexLock(&c->mutex); |
| 622 | #endif |
| 623 | if (!c->isconnected) |
| 624 | goto exit; |
| 625 | |
| 626 | TimerInit(&timer); |
| 627 | TimerCountdownMS(&timer, c->command_timeout_ms); |
| 628 | |
| 629 | len = MQTTSerialize_subscribe(c->buf, c->buf_size, 0, getNextPacketId(c), 1, &topic, (int*)&qos); |
| 630 | if (len <= 0) |
| 631 | goto exit; |
| 632 | if ((rc = sendPacket(c, len, &timer)) != SUCCESS) // send the subscribe packet |
| 633 | goto exit; // there was a problem |
| 634 | |
| 635 | if (waitfor(c, SUBACK, &timer) == SUBACK) // wait for suback |
| 636 | { |
| 637 | int count = 0; |
| 638 | unsigned short mypacketid; |
| 639 | data->grantedQoS = QOS0; |
| 640 | if (MQTTDeserialize_suback(&mypacketid, 1, &count, (int*)&data->grantedQoS, c->readbuf, c->readbuf_size) == 1) |
| 641 | { |
| 642 | if (data->grantedQoS != 0x80) |
| 643 | rc = MQTTSetMessageHandler(c, topicFilter, messageHandler); |
| 644 | } |
| 645 | } |
| 646 | else |
| 647 | rc = FAILURE; |
| 648 | |
| 649 | exit: |
| 650 | if (rc == FAILURE) |
| 651 | MQTTCloseSession(c); |
| 652 | #if defined(MQTT_TASK) |
| 653 | MutexUnlock(&c->mutex); |
| 654 | #endif |
| 655 | return rc; |
| 656 | } |
| 657 | |
| 658 | |
| 659 | int MQTTSubscribe(MQTTClient* c, const char* topicFilter, enum QoS qos, |
| 660 | messageHandler messageHandler) |
| 661 | { |
| 662 | MQTTSubackData data; |
| 663 | return MQTTSubscribeWithResults(c, topicFilter, qos, messageHandler, &data); |
| 664 | } |
| 665 | |
| 666 | |
| 667 | int MQTTUnsubscribe(MQTTClient* c, const char* topicFilter) |
| 668 | { |
| 669 | int rc = FAILURE; |
| 670 | Timer timer; |
| 671 | MQTTString topic = MQTTString_initializer; |
| 672 | topic.cstring = (char *)topicFilter; |
| 673 | int len = 0; |
| 674 | |
| 675 | #if defined(MQTT_TASK) |
| 676 | MutexLock(&c->mutex); |
| 677 | #endif |
| 678 | if (!c->isconnected) |
| 679 | goto exit; |
| 680 | |
| 681 | TimerInit(&timer); |
| 682 | TimerCountdownMS(&timer, c->command_timeout_ms); |
| 683 | |
| 684 | if ((len = MQTTSerialize_unsubscribe(c->buf, c->buf_size, 0, getNextPacketId(c), 1, &topic)) <= 0) |
| 685 | goto exit; |
| 686 | if ((rc = sendPacket(c, len, &timer)) != SUCCESS) // send the subscribe packet |
| 687 | goto exit; // there was a problem |
| 688 | |
| 689 | if (waitfor(c, UNSUBACK, &timer) == UNSUBACK) |
| 690 | { |
| 691 | unsigned short mypacketid; // should be the same as the packetid above |
| 692 | if (MQTTDeserialize_unsuback(&mypacketid, c->readbuf, c->readbuf_size) == 1) |
| 693 | { |
| 694 | /* remove the subscription message handler associated with this topic, if there is one */ |
| 695 | MQTTSetMessageHandler(c, topicFilter, NULL); |
| 696 | } |
| 697 | } |
| 698 | else |
| 699 | rc = FAILURE; |
| 700 | |
| 701 | exit: |
| 702 | if (rc == FAILURE) |
| 703 | MQTTCloseSession(c); |
| 704 | #if defined(MQTT_TASK) |
| 705 | MutexUnlock(&c->mutex); |
| 706 | #endif |
| 707 | return rc; |
| 708 | } |
| 709 | |
| 710 | |
| 711 | int MQTTPublish(MQTTClient* c, const char* topicName, MQTTMessage* message) |
| 712 | { |
| 713 | int rc = FAILURE; |
| 714 | Timer timer; |
| 715 | MQTTString topic = MQTTString_initializer; |
| 716 | topic.cstring = (char *)topicName; |
| 717 | int len = 0; |
| 718 | |
| 719 | #if defined(MQTT_TASK) |
| 720 | MutexLock(&c->mutex); |
| 721 | #endif |
| 722 | if (!c->isconnected) |
| 723 | goto exit; |
| 724 | |
| 725 | TimerInit(&timer); |
| 726 | TimerCountdownMS(&timer, c->command_timeout_ms); |
| 727 | |
| 728 | if (message->qos == QOS1 || message->qos == QOS2) |
| 729 | message->id = getNextPacketId(c); |
| 730 | |
| 731 | len = MQTTSerialize_publish(c->buf, c->buf_size, 0, message->qos, message->retained, message->id, |
| 732 | topic, (unsigned char*)message->payload, message->payloadlen); |
| 733 | printf("len = %d\n",len); |
| 734 | if (len <= 0) |
| 735 | goto exit; |
| 736 | if ((rc = sendPacket(c, len, &timer)) != SUCCESS) // send the subscribe packet |
| 737 | goto exit; // there was a problem |
| 738 | |
| 739 | if (message->qos == QOS1) |
| 740 | { |
| 741 | if (waitfor(c, PUBACK, &timer) == PUBACK) |
| 742 | { |
| 743 | unsigned short mypacketid; |
| 744 | unsigned char dup, type; |
| 745 | if (MQTTDeserialize_ack(&type, &dup, &mypacketid, c->readbuf, c->readbuf_size) != 1) |
| 746 | rc = FAILURE; |
| 747 | } |
| 748 | else |
| 749 | rc = FAILURE; |
| 750 | } |
| 751 | else if (message->qos == QOS2) |
| 752 | { |
| 753 | if (waitfor(c, PUBCOMP, &timer) == PUBCOMP) |
| 754 | { |
| 755 | unsigned short mypacketid; |
| 756 | unsigned char dup, type; |
| 757 | if (MQTTDeserialize_ack(&type, &dup, &mypacketid, c->readbuf, c->readbuf_size) != 1) |
| 758 | rc = FAILURE; |
| 759 | } |
| 760 | else |
| 761 | rc = FAILURE; |
| 762 | } |
| 763 | |
| 764 | exit: |
| 765 | if (rc == FAILURE) |
| 766 | MQTTCloseSession(c); |
| 767 | #if defined(MQTT_TASK) |
| 768 | MutexUnlock(&c->mutex); |
| 769 | #endif |
| 770 | return rc; |
| 771 | } |
| 772 | |
| 773 | |
| 774 | int MQTTDisconnect(MQTTClient* c) |
| 775 | { |
| 776 | int rc = FAILURE; |
| 777 | Timer timer; // we might wait for incomplete incoming publishes to complete |
| 778 | int len = 0; |
| 779 | |
| 780 | #if defined(MQTT_TASK) |
| 781 | MutexLock(&c->mutex); |
| 782 | #endif |
| 783 | TimerInit(&timer); |
| 784 | TimerCountdownMS(&timer, c->command_timeout_ms); |
| 785 | |
| 786 | len = MQTTSerialize_disconnect(c->buf, c->buf_size); |
| 787 | if (len > 0) |
| 788 | rc = sendPacket(c, len, &timer); // send the disconnect packet |
| 789 | MQTTCloseSession(c); |
| 790 | |
| 791 | #if defined(MQTT_TASK) |
| 792 | MutexUnlock(&c->mutex); |
| 793 | #endif |
| 794 | return rc; |
| 795 | } |