diff --git a/MQTTSNGateway/src/MQTTGWConnectionHandler.cpp b/MQTTSNGateway/src/MQTTGWConnectionHandler.cpp index 0e5d85e..f3bb526 100644 --- a/MQTTSNGateway/src/MQTTGWConnectionHandler.cpp +++ b/MQTTSNGateway/src/MQTTGWConnectionHandler.cpp @@ -22,7 +22,7 @@ using namespace MQTTSNGW; MQTTGWConnectionHandler::MQTTGWConnectionHandler(Gateway* gateway) { - _gateway = gateway; + _gateway = gateway; } MQTTGWConnectionHandler::~MQTTGWConnectionHandler() @@ -30,70 +30,79 @@ MQTTGWConnectionHandler::~MQTTGWConnectionHandler() } -void MQTTGWConnectionHandler::handleConnack(Client* client, MQTTGWPacket* packet) +void MQTTGWConnectionHandler::handleConnack(Client* client, + MQTTGWPacket* packet) { - uint8_t rc = MQTT_SERVER_UNAVAILABLE; - Connack resp; - packet->getCONNACK(&resp); + uint8_t rc = MQTT_SERVER_UNAVAILABLE; + Connack resp; + packet->getCONNACK(&resp); - /* convert MQTT ReturnCode to MQTT-SN one */ - if (resp.rc == MQTT_CONNECTION_ACCEPTED) - { - rc = MQTTSN_RC_ACCEPTED; - } - else if (resp.rc == MQTT_UNACCEPTABLE_PROTOCOL_VERSION) - { - rc = MQTTSN_RC_NOT_SUPPORTED; - WRITELOG(" ClientID : %s Requested Protocol version is not supported.\n", client->getClientId()); - } - else if (resp.rc == MQTT_IDENTIFIER_REJECTED) - { - rc = MQTTSN_RC_NOT_SUPPORTED; - WRITELOG(" ClientID : %s ClientID is collect UTF-8 but not allowed by the Server.\n", - client->getClientId()); - } - else if (resp.rc == MQTT_SERVER_UNAVAILABLE) - { - rc = MQTTSN_RC_REJECTED_CONGESTED; - WRITELOG(" ClientID : %s The Network Connection has been made but the MQTT service is unavailable.\n", - client->getClientId()); - } - else if (resp.rc == MQTT_BAD_USERNAME_OR_PASSWORD) - { - rc = MQTTSN_RC_NOT_SUPPORTED; - WRITELOG(" Gateway Configuration Error: The data in the user name or password is malformed.\n"); - } - else if (resp.rc == MQTT_NOT_AUTHORIZED) - { - rc = MQTTSN_RC_NOT_SUPPORTED; - WRITELOG(" Gateway Configuration Error: The Client is not authorized to connect.\n"); - } + /* convert MQTT ReturnCode to MQTT-SN one */ + if (resp.rc == MQTT_CONNECTION_ACCEPTED) + { + rc = MQTTSN_RC_ACCEPTED; + } + else if (resp.rc == MQTT_UNACCEPTABLE_PROTOCOL_VERSION) + { + rc = MQTTSN_RC_NOT_SUPPORTED; + WRITELOG( + " ClientID : %s Requested Protocol version is not supported.\n", + client->getClientId()); + } + else if (resp.rc == MQTT_IDENTIFIER_REJECTED) + { + rc = MQTTSN_RC_NOT_SUPPORTED; + WRITELOG( + " ClientID : %s ClientID is collect UTF-8 but not allowed by the Server.\n", + client->getClientId()); + } + else if (resp.rc == MQTT_SERVER_UNAVAILABLE) + { + rc = MQTTSN_RC_REJECTED_CONGESTED; + WRITELOG( + " ClientID : %s The Network Connection has been made but the MQTT service is unavailable.\n", + client->getClientId()); + } + else if (resp.rc == MQTT_BAD_USERNAME_OR_PASSWORD) + { + rc = MQTTSN_RC_NOT_SUPPORTED; + WRITELOG( + " Gateway Configuration Error: The data in the user name or password is malformed.\n"); + } + else if (resp.rc == MQTT_NOT_AUTHORIZED) + { + rc = MQTTSN_RC_NOT_SUPPORTED; + WRITELOG( + " Gateway Configuration Error: The Client is not authorized to connect.\n"); + } - MQTTSNPacket* snPacket = new MQTTSNPacket(); - snPacket->setCONNACK(rc); + MQTTSNPacket* snPacket = new MQTTSNPacket(); + snPacket->setCONNACK(rc); - Event* ev1 = new Event(); - ev1->setClientSendEvent(client, snPacket); - client->connackSended(rc); // update the client's status - _gateway->getClientSendQue()->post(ev1); + Event* ev1 = new Event(); + ev1->setClientSendEvent(client, snPacket); + client->connackSended(rc); // update the client's status + _gateway->getClientSendQue()->post(ev1); } -void MQTTGWConnectionHandler::handlePingresp(Client* client, MQTTGWPacket* packet) +void MQTTGWConnectionHandler::handlePingresp(Client* client, + MQTTGWPacket* packet) { - MQTTSNPacket* snPacket = new MQTTSNPacket(); - snPacket->setPINGRESP(); - Event* ev1 = new Event(); - ev1->setClientSendEvent(client, snPacket); - client->updateStatus(snPacket); - _gateway->getClientSendQue()->post(ev1); + MQTTSNPacket* snPacket = new MQTTSNPacket(); + snPacket->setPINGRESP(); + Event* ev1 = new Event(); + ev1->setClientSendEvent(client, snPacket); + client->updateStatus(snPacket); + _gateway->getClientSendQue()->post(ev1); } -void MQTTGWConnectionHandler::handleDisconnect(Client* client, MQTTGWPacket* packet) +void MQTTGWConnectionHandler::handleDisconnect(Client* client, + MQTTGWPacket* packet) { - MQTTSNPacket* snPacket = new MQTTSNPacket(); - snPacket->setDISCONNECT(0); - client->disconnected(); - client->getNetwork()->close(); - Event* ev1 = new Event(); - ev1->setClientSendEvent(client, snPacket); + MQTTSNPacket* snPacket = new MQTTSNPacket(); + snPacket->setDISCONNECT(0); + client->disconnected(); + client->getNetwork()->close(); + Event* ev1 = new Event(); + ev1->setClientSendEvent(client, snPacket); } diff --git a/MQTTSNGateway/src/MQTTGWConnectionHandler.h b/MQTTSNGateway/src/MQTTGWConnectionHandler.h index 125350d..d736c61 100644 --- a/MQTTSNGateway/src/MQTTGWConnectionHandler.h +++ b/MQTTSNGateway/src/MQTTGWConnectionHandler.h @@ -26,13 +26,13 @@ namespace MQTTSNGW class MQTTGWConnectionHandler { public: - MQTTGWConnectionHandler(Gateway* gateway); - ~MQTTGWConnectionHandler(); - void handleConnack(Client* client, MQTTGWPacket* packet); - void handlePingresp(Client* client, MQTTGWPacket* packet); - void handleDisconnect(Client* client, MQTTGWPacket* packet); + MQTTGWConnectionHandler(Gateway* gateway); + ~MQTTGWConnectionHandler(); + void handleConnack(Client* client, MQTTGWPacket* packet); + void handlePingresp(Client* client, MQTTGWPacket* packet); + void handleDisconnect(Client* client, MQTTGWPacket* packet); private: - Gateway* _gateway; + Gateway* _gateway; }; } diff --git a/MQTTSNGateway/src/MQTTGWPacket.cpp b/MQTTSNGateway/src/MQTTGWPacket.cpp index 45cb9d8..e3277db 100644 --- a/MQTTSNGateway/src/MQTTGWPacket.cpp +++ b/MQTTSNGateway/src/MQTTGWPacket.cpp @@ -29,8 +29,9 @@ void writeInt(unsigned char** pptr, int msgId); * List of the predefined MQTT v3 packet names. */ static const char* mqtt_packet_names[] = -{ "RESERVED", "CONNECT", "CONNACK", "PUBLISH", "PUBACK", "PUBREC", "PUBREL", "PUBCOMP", "SUBSCRIBE", "SUBACK", - "UNSUBSCRIBE", "UNSUBACK", "PINGREQ", "PINGRESP", "DISCONNECT" }; +{ "RESERVED", "CONNECT", "CONNACK", "PUBLISH", "PUBACK", "PUBREC", "PUBREL", + "PUBCOMP", "SUBSCRIBE", "SUBACK", "UNSUBSCRIBE", "UNSUBACK", "PINGREQ", + "PINGRESP", "DISCONNECT" }; /** * Encodes the message length according to the MQTT algorithm @@ -40,17 +41,17 @@ static const char* mqtt_packet_names[] = */ int MQTTPacket_encode(char* buf, int length) { - int rc = 0; - do - { - char d = length % 128; - length /= 128; - /* if there are more digits to encode, set the top bit of this digit */ - if (length > 0) - d |= 0x80; - buf[rc++] = d; - } while (length > 0); - return rc; + int rc = 0; + do + { + char d = length % 128; + length /= 128; + /* if there are more digits to encode, set the top bit of this digit */ + if (length > 0) + d |= 0x80; + buf[rc++] = d; + } while (length > 0); + return rc; } /** @@ -60,10 +61,10 @@ int MQTTPacket_encode(char* buf, int length) */ int readInt(char** pptr) { - char* ptr = *pptr; - int len = 256 * ((unsigned char) (*ptr)) + (unsigned char) (*(ptr + 1)); - *pptr += 2; - return len; + char* ptr = *pptr; + int len = 256 * ((unsigned char) (*ptr)) + (unsigned char) (*(ptr + 1)); + *pptr += 2; + return len; } /** @@ -80,20 +81,20 @@ int readInt(char** pptr) */ char* readUTFlen(char** pptr, char* enddata, int* len) { - char* string = NULL; + char* string = NULL; - if (enddata - (*pptr) > 1) /* enough length to read the integer? */ - { - *len = readInt(pptr); - if (&(*pptr)[*len] <= enddata) - { - string = (char*)calloc(*len + 1, 1); - memcpy(string, *pptr, (size_t)*len); - string[*len] = '\0'; - *pptr += *len; - } - } - return string; + if (enddata - (*pptr) > 1) /* enough length to read the integer? */ + { + *len = readInt(pptr); + if (&(*pptr)[*len] <= enddata) + { + string = (char*) calloc(*len + 1, 1); + memcpy(string, *pptr, (size_t) *len); + string[*len] = '\0'; + *pptr += *len; + } + } + return string; } /** @@ -108,8 +109,8 @@ char* readUTFlen(char** pptr, char* enddata, int* len) */ char* readUTF(char** pptr, char* enddata) { - int len; - return readUTFlen(pptr, enddata, &len); + int len; + return readUTFlen(pptr, enddata, &len); } /** @@ -119,9 +120,9 @@ char* readUTF(char** pptr, char* enddata) */ unsigned char readChar(char** pptr) { - unsigned char c = **pptr; - (*pptr)++; - return c; + unsigned char c = **pptr; + (*pptr)++; + return c; } /** @@ -131,8 +132,8 @@ unsigned char readChar(char** pptr) */ void writeChar(unsigned char** pptr, char c) { - **pptr = c; - (*pptr)++; + **pptr = c; + (*pptr)++; } /** @@ -142,10 +143,10 @@ void writeChar(unsigned char** pptr, char c) */ void writeInt(unsigned char** pptr, int anInt) { - **pptr = (unsigned char)(anInt / 256); - (*pptr)++; - **pptr = (unsigned char)(anInt % 256); - (*pptr)++; + **pptr = (unsigned char) (anInt / 256); + (*pptr)++; + **pptr = (unsigned char) (anInt % 256); + (*pptr)++; } /** @@ -155,10 +156,10 @@ void writeInt(unsigned char** pptr, int anInt) */ void writeUTF(unsigned char** pptr, const char* string) { - int len = (int)strlen(string); - writeInt(pptr, len); - memcpy(*pptr, string, (size_t)len); - *pptr += len; + int len = (int) strlen(string); + writeInt(pptr, len); + memcpy(*pptr, string, (size_t) len); + *pptr += len; } /** @@ -167,479 +168,485 @@ void writeUTF(unsigned char** pptr, const char* string) */ MQTTGWPacket::MQTTGWPacket() { - _data = 0; - _header.byte = 0; - _remainingLength = 0; + _data = 0; + _header.byte = 0; + _remainingLength = 0; } MQTTGWPacket::~MQTTGWPacket() { - if (_data) - { - free(_data); - } + if (_data) + { + free(_data); + } } int MQTTGWPacket::recv(Network* network) { - int len = 0; - int multiplier = 1; - unsigned char c; + int len = 0; + int multiplier = 1; + unsigned char c; - /* read First Byte of Packet */ - int rc = network->recv((unsigned char*)&_header.byte, 1); - if ( rc <= 0) - { - return rc; - } - /* read RemainingLength */ - do - { - if (++len > MAX_NO_OF_REMAINING_LENGTH_BYTES) - { - return -2; - } - if (network->recv(&c, 1) == -1) - { - return -1; - } - _remainingLength += (c & 127) * multiplier; - multiplier *= 128; - } while ((c & 128) != 0); + /* read First Byte of Packet */ + int rc = network->recv((unsigned char*) &_header.byte, 1); + if (rc <= 0) + { + return rc; + } + /* read RemainingLength */ + do + { + if (++len > MAX_NO_OF_REMAINING_LENGTH_BYTES) + { + return -2; + } + if (network->recv(&c, 1) == -1) + { + return -1; + } + _remainingLength += (c & 127) * multiplier; + multiplier *= 128; + } while ((c & 128) != 0); - if ( _remainingLength > 0 ) - { - /* allocate buffer */ - _data = (unsigned char*)calloc(_remainingLength, 1); - if ( !_data ) - { - return -3; - } + if (_remainingLength > 0) + { + /* allocate buffer */ + _data = (unsigned char*) calloc(_remainingLength, 1); + if (!_data) + { + return -3; + } - /* read Payload */ - int remlen = network->recv(_data, _remainingLength); + /* read Payload */ + int remlen = network->recv(_data, _remainingLength); - if (remlen == -1 ) - { - return -1; - } - else if ( remlen != _remainingLength ) - { - return -2; - } - } - return 1 + len + _remainingLength; + if (remlen == -1) + { + return -1; + } + else if (remlen != _remainingLength) + { + return -2; + } + } + return 1 + len + _remainingLength; } int MQTTGWPacket::send(Network* network) { - unsigned char buf[MQTTSNGW_MAX_PACKET_SIZE]; - memset(buf, 0, MQTTSNGW_MAX_PACKET_SIZE); - int len = getPacketData(buf); - return network->send(buf, len); + unsigned char buf[MQTTSNGW_MAX_PACKET_SIZE]; + memset(buf, 0, MQTTSNGW_MAX_PACKET_SIZE); + int len = getPacketData(buf); + return network->send(buf, len); } int MQTTGWPacket::getAck(Ack* ack) { - if (PUBACK != _header.bits.type && PUBREC != _header.bits.type && PUBREL != _header.bits.type - && PUBCOMP != _header.bits.type && UNSUBACK != _header.bits.type) - { - return 0; - } - char* ptr = (char*) _data; - ack->header.byte = _header.byte; - ack->msgId = readInt((char**) &ptr); - return 1; + if (PUBACK != _header.bits.type && PUBREC != _header.bits.type + && PUBREL != _header.bits.type && PUBCOMP != _header.bits.type + && UNSUBACK != _header.bits.type) + { + return 0; + } + char* ptr = (char*) _data; + ack->header.byte = _header.byte; + ack->msgId = readInt((char**) &ptr); + return 1; } int MQTTGWPacket::getCONNACK(Connack* resp) { - if (_header.bits.type != CONNACK) - { - return 0; - } - char* ptr = (char*) _data; - resp->header.byte = _header.byte; - resp->flags.all = *ptr++; - resp->rc = readChar(&ptr); - return 1; + if (_header.bits.type != CONNACK) + { + return 0; + } + char* ptr = (char*) _data; + resp->header.byte = _header.byte; + resp->flags.all = *ptr++; + resp->rc = readChar(&ptr); + return 1; } int MQTTGWPacket::getSUBACK(unsigned short* msgId, unsigned char* rc) { - if (_header.bits.type != SUBACK) - { - return 0; - } - char *ptr = (char*) _data; - *msgId = readInt((char**) &ptr); - *rc = readChar(&ptr); - return 1; + if (_header.bits.type != SUBACK) + { + return 0; + } + char *ptr = (char*) _data; + *msgId = readInt((char**) &ptr); + *rc = readChar(&ptr); + return 1; } int MQTTGWPacket::getPUBLISH(Publish* pub) { - if (_header.bits.type != PUBLISH) - { - return 0; - } - char* ptr = (char*) _data; - pub->header = _header; - pub->topiclen = readInt((char**) &ptr); - pub->topic = (char*) _data + 2; - ptr += pub->topiclen; - if (_header.bits.qos > 0) - { - pub->msgId = readInt(&ptr); - pub->payloadlen = _remainingLength - pub->topiclen - 4; - } - else - { - pub->msgId = 0; - pub->payloadlen = _remainingLength - pub->topiclen - 2; - } - pub->payload = ptr; - return 1; + if (_header.bits.type != PUBLISH) + { + return 0; + } + char* ptr = (char*) _data; + pub->header = _header; + pub->topiclen = readInt((char**) &ptr); + pub->topic = (char*) _data + 2; + ptr += pub->topiclen; + if (_header.bits.qos > 0) + { + pub->msgId = readInt(&ptr); + pub->payloadlen = _remainingLength - pub->topiclen - 4; + } + else + { + pub->msgId = 0; + pub->payloadlen = _remainingLength - pub->topiclen - 2; + } + pub->payload = ptr; + return 1; } -int MQTTGWPacket::setCONNECT(Connect* connect, unsigned char* username, unsigned char* password) +int MQTTGWPacket::setCONNECT(Connect* connect, unsigned char* username, + unsigned char* password) { - clearData(); - _header = connect->header; + clearData(); + _header = connect->header; - _remainingLength = ((connect->version == 3) ? 12 : 10) + (int)strlen(connect->clientID) + 2; - if (connect->flags.bits.will) - { - _remainingLength += (int)strlen(connect->willTopic) + 2 + (int)strlen(connect->willMsg) + 2; - } - if ( connect->flags.bits.username ) - { - _remainingLength += (int)strlen((char*) username) + 2; - } - if (connect->flags.bits.password) - { - _remainingLength += (int)strlen((char*) password) + 2; - } + _remainingLength = ((connect->version == 3) ? 12 : 10) + + (int) strlen(connect->clientID) + 2; + if (connect->flags.bits.will) + { + _remainingLength += (int) strlen(connect->willTopic) + 2 + + (int) strlen(connect->willMsg) + 2; + } + if (connect->flags.bits.username) + { + _remainingLength += (int) strlen((char*) username) + 2; + } + if (connect->flags.bits.password) + { + _remainingLength += (int) strlen((char*) password) + 2; + } - _data = (unsigned char*)calloc(_remainingLength, 1); - unsigned char* ptr = _data; + _data = (unsigned char*) calloc(_remainingLength, 1); + unsigned char* ptr = _data; - if (connect->version == 3) - { - writeUTF(&ptr, "MQIsdp"); - writeChar(&ptr, (char) 3); - } - else if (connect->version == 4) - { - writeUTF(&ptr, "MQTT"); - writeChar(&ptr, (char) 4); - } - else - { - return 0; - } + if (connect->version == 3) + { + writeUTF(&ptr, "MQIsdp"); + writeChar(&ptr, (char) 3); + } + else if (connect->version == 4) + { + writeUTF(&ptr, "MQTT"); + writeChar(&ptr, (char) 4); + } + else + { + return 0; + } - writeChar(&ptr, connect->flags.all); - writeInt(&ptr, connect->keepAliveTimer); - writeUTF(&ptr, connect->clientID); - if (connect->flags.bits.will) - { - writeUTF(&ptr, connect->willTopic); - writeUTF(&ptr, connect->willMsg); - } + writeChar(&ptr, connect->flags.all); + writeInt(&ptr, connect->keepAliveTimer); + writeUTF(&ptr, connect->clientID); + if (connect->flags.bits.will) + { + writeUTF(&ptr, connect->willTopic); + writeUTF(&ptr, connect->willMsg); + } - if (connect->flags.bits.username) - { - writeUTF(&ptr, (const char*) username); - } - if (connect->flags.bits.password) - { - writeUTF(&ptr, (const char*) password); - } - return 1; + if (connect->flags.bits.username) + { + writeUTF(&ptr, (const char*) username); + } + if (connect->flags.bits.password) + { + writeUTF(&ptr, (const char*) password); + } + return 1; } -int MQTTGWPacket::setSUBSCRIBE(const char* topic, unsigned char qos, unsigned short msgId) +int MQTTGWPacket::setSUBSCRIBE(const char* topic, unsigned char qos, + unsigned short msgId) { - clearData(); - _header.byte = 0; - _header.bits.type = SUBSCRIBE; - _header.bits.qos = 1; // Reserved - _remainingLength = (int)strlen(topic) + 5; - _data = (unsigned char*)calloc(_remainingLength, 1); - if (_data) - { - unsigned char* ptr = _data; - writeInt(&ptr, msgId); - writeUTF(&ptr, topic); - writeChar(&ptr, (char) qos); - return 1; - } - clearData(); - return 0; + clearData(); + _header.byte = 0; + _header.bits.type = SUBSCRIBE; + _header.bits.qos = 1; // Reserved + _remainingLength = (int) strlen(topic) + 5; + _data = (unsigned char*) calloc(_remainingLength, 1); + if (_data) + { + unsigned char* ptr = _data; + writeInt(&ptr, msgId); + writeUTF(&ptr, topic); + writeChar(&ptr, (char) qos); + return 1; + } + clearData(); + return 0; } int MQTTGWPacket::setUNSUBSCRIBE(const char* topic, unsigned short msgid) { - clearData(); - _header.byte = 0; - _header.bits.type = UNSUBSCRIBE; - _header.bits.qos = 1; - _remainingLength = (int)strlen(topic) + 4; - _data = (unsigned char*)calloc(_remainingLength, 1); - if (_data) - { - unsigned char* ptr = _data; - writeInt(&ptr, msgid); - writeUTF(&ptr, topic); - return 1; - } - clearData(); - return 0; + clearData(); + _header.byte = 0; + _header.bits.type = UNSUBSCRIBE; + _header.bits.qos = 1; + _remainingLength = (int) strlen(topic) + 4; + _data = (unsigned char*) calloc(_remainingLength, 1); + if (_data) + { + unsigned char* ptr = _data; + writeInt(&ptr, msgid); + writeUTF(&ptr, topic); + return 1; + } + clearData(); + return 0; } int MQTTGWPacket::setPUBLISH(Publish* pub) { - clearData(); - _header.byte = pub->header.byte; - _header.bits.type = PUBLISH; - _remainingLength = 4 + pub->topiclen + pub->payloadlen; - _data = (unsigned char*)calloc(_remainingLength, 1); - if (_data) - { - unsigned char* ptr = _data; - writeInt(&ptr, pub->topiclen); - memcpy(ptr, pub->topic, pub->topiclen); - ptr += pub->topiclen; - if ( _header.bits.qos > 0 ) - { - writeInt(&ptr, pub->msgId); - } - else - { - _remainingLength -= 2; - } - memcpy(ptr, pub->payload, pub->payloadlen); - return 1; - } - else - { - clearData(); - return 0; - } + clearData(); + _header.byte = pub->header.byte; + _header.bits.type = PUBLISH; + _remainingLength = 4 + pub->topiclen + pub->payloadlen; + _data = (unsigned char*) calloc(_remainingLength, 1); + if (_data) + { + unsigned char* ptr = _data; + writeInt(&ptr, pub->topiclen); + memcpy(ptr, pub->topic, pub->topiclen); + ptr += pub->topiclen; + if (_header.bits.qos > 0) + { + writeInt(&ptr, pub->msgId); + } + else + { + _remainingLength -= 2; + } + memcpy(ptr, pub->payload, pub->payloadlen); + return 1; + } + else + { + clearData(); + return 0; + } } int MQTTGWPacket::setAck(unsigned char msgType, unsigned short msgid) { - clearData(); - _remainingLength = 2; - _header.bits.type = msgType; - _header.bits.qos = (msgType == PUBREL) ? 1 : 0; + clearData(); + _remainingLength = 2; + _header.bits.type = msgType; + _header.bits.qos = (msgType == PUBREL) ? 1 : 0; - _data = (unsigned char*)calloc(_remainingLength, 1); - if (_data) - { - unsigned char* data = _data; - writeInt(&data, msgid); - return 1; - } - return 0; + _data = (unsigned char*) calloc(_remainingLength, 1); + if (_data) + { + unsigned char* data = _data; + writeInt(&data, msgid); + return 1; + } + return 0; } int MQTTGWPacket::setHeader(unsigned char msgType) { - clearData(); - if (msgType < CONNECT || msgType > DISCONNECT) - { - return 0; - } - _header.bits.type = msgType; - return 0; + clearData(); + if (msgType < CONNECT || msgType > DISCONNECT) + { + return 0; + } + _header.bits.type = msgType; + return 0; } int MQTTGWPacket::getType(void) { - return _header.bits.type; + return _header.bits.type; } const char* MQTTGWPacket::getName(void) { - return getType() > DISCONNECT ? "UNKNOWN" : mqtt_packet_names[getType()]; + return getType() > DISCONNECT ? "UNKNOWN" : mqtt_packet_names[getType()]; } int MQTTGWPacket::getPacketData(unsigned char* buf) { - unsigned char* ptr = buf; - *ptr++ = _header.byte; - int len = MQTTPacket_encode((char*)ptr, _remainingLength); - ptr += len; - memcpy(ptr, _data, _remainingLength); - return 1 + len + _remainingLength; + unsigned char* ptr = buf; + *ptr++ = _header.byte; + int len = MQTTPacket_encode((char*) ptr, _remainingLength); + ptr += len; + memcpy(ptr, _data, _remainingLength); + return 1 + len + _remainingLength; } int MQTTGWPacket::getPacketLength(void) { - char buf[4]; - return 1 + MQTTPacket_encode(buf, _remainingLength) + _remainingLength; + char buf[4]; + return 1 + MQTTPacket_encode(buf, _remainingLength) + _remainingLength; } void MQTTGWPacket::clearData(void) { - if (_data) - { - free(_data); - } - _header.byte = 0; - _remainingLength = 0; + if (_data) + { + free(_data); + } + _header.byte = 0; + _remainingLength = 0; } char* MQTTGWPacket::getMsgId(char* pbuf) { - int type = getType(); + int type = getType(); - switch ( type ) - { - case PUBLISH: - Publish pub; - pub.msgId = 0; - getPUBLISH(&pub); - if ( _header.bits.dup ) - { - sprintf(pbuf, "+%04X", pub.msgId); - } - else - { - sprintf(pbuf, " %04X", pub.msgId); - } - break; - case SUBSCRIBE: - case UNSUBSCRIBE: - case PUBACK: - case PUBREC: - case PUBREL: - case PUBCOMP: - case SUBACK: - case UNSUBACK: - sprintf(pbuf, " %02X%02X", _data[0], _data[1]); - break; - default: - sprintf(pbuf, " "); - break; - } - if ( strcmp(pbuf, " 0000") == 0 ) - { - sprintf(pbuf, " "); - } - return pbuf; + switch (type) + { + case PUBLISH: + Publish pub; + pub.msgId = 0; + getPUBLISH(&pub); + if (_header.bits.dup) + { + sprintf(pbuf, "+%04X", pub.msgId); + } + else + { + sprintf(pbuf, " %04X", pub.msgId); + } + break; + case SUBSCRIBE: + case UNSUBSCRIBE: + case PUBACK: + case PUBREC: + case PUBREL: + case PUBCOMP: + case SUBACK: + case UNSUBACK: + sprintf(pbuf, " %02X%02X", _data[0], _data[1]); + break; + default: + sprintf(pbuf, " "); + break; + } + if (strcmp(pbuf, " 0000") == 0) + { + sprintf(pbuf, " "); + } + return pbuf; } int MQTTGWPacket::getMsgId(void) { - int type = getType(); - int msgId = 0; + int type = getType(); + int msgId = 0; - switch ( type ) - { - case PUBLISH: - Publish pub; - pub.msgId = 0; - getPUBLISH(&pub); - msgId = pub.msgId; - break; - case PUBACK: - case PUBREC: - case PUBREL: - case PUBCOMP: - case SUBSCRIBE: - case UNSUBSCRIBE: - case SUBACK: - case UNSUBACK: - msgId = 256 * (unsigned char)_data[0] + (unsigned char)_data[1]; - break; - default: - break; - } - return msgId; + switch (type) + { + case PUBLISH: + Publish pub; + pub.msgId = 0; + getPUBLISH(&pub); + msgId = pub.msgId; + break; + case PUBACK: + case PUBREC: + case PUBREL: + case PUBCOMP: + case SUBSCRIBE: + case UNSUBSCRIBE: + case SUBACK: + case UNSUBACK: + msgId = 256 * (unsigned char) _data[0] + (unsigned char) _data[1]; + break; + default: + break; + } + return msgId; } void MQTTGWPacket::setMsgId(int msgId) { - int type = getType(); - unsigned char* ptr = 0; + int type = getType(); + unsigned char* ptr = 0; - switch ( type ) - { - case PUBLISH: - Publish pub; - pub.topiclen = 0; - pub.msgId = 0; - getPUBLISH(&pub); - pub.msgId = msgId; - ptr = _data + pub.topiclen; - writeInt(&ptr, pub.msgId); - *ptr++ = (unsigned char)(msgId / 256); - *ptr = (unsigned char)(msgId % 256); - break; - case SUBSCRIBE: - case UNSUBSCRIBE: - case PUBACK: - case PUBREC: - case PUBREL: - case PUBCOMP: - case SUBACK: - case UNSUBACK: - ptr = _data; - *ptr++ = (unsigned char)(msgId / 256); - *ptr = (unsigned char)(msgId % 256); - break; - default: - break; - } + switch (type) + { + case PUBLISH: + Publish pub; + pub.topiclen = 0; + pub.msgId = 0; + getPUBLISH(&pub); + pub.msgId = msgId; + ptr = _data + pub.topiclen; + writeInt(&ptr, pub.msgId); + *ptr++ = (unsigned char) (msgId / 256); + *ptr = (unsigned char) (msgId % 256); + break; + case SUBSCRIBE: + case UNSUBSCRIBE: + case PUBACK: + case PUBREC: + case PUBREL: + case PUBCOMP: + case SUBACK: + case UNSUBACK: + ptr = _data; + *ptr++ = (unsigned char) (msgId / 256); + *ptr = (unsigned char) (msgId % 256); + break; + default: + break; + } } char* MQTTGWPacket::print(char* pbuf) { - uint8_t packetData[MQTTSNGW_MAX_PACKET_SIZE]; - char* ptr = pbuf; - char** pptr = &pbuf; - int len = getPacketData(packetData); - int size = len > SIZE_OF_LOG_PACKET ? SIZE_OF_LOG_PACKET : len; - for (int i = 0; i < size; i++) - { - sprintf(*pptr, " %02X", packetData[i]); - *pptr += 3; - } - **pptr = 0; - return ptr; + uint8_t packetData[MQTTSNGW_MAX_PACKET_SIZE]; + char* ptr = pbuf; + char** pptr = &pbuf; + int len = getPacketData(packetData); + int size = len > SIZE_OF_LOG_PACKET ? SIZE_OF_LOG_PACKET : len; + for (int i = 0; i < size; i++) + { + sprintf(*pptr, " %02X", packetData[i]); + *pptr += 3; + } + **pptr = 0; + return ptr; } MQTTGWPacket& MQTTGWPacket::operator =(MQTTGWPacket& packet) { - clearData(); - this->_header.byte = packet._header.byte; - this->_remainingLength = packet._remainingLength; - _data = (unsigned char*)calloc(_remainingLength, 1); - if (_data) - { - memcpy(this->_data, packet._data, _remainingLength); - } - else - { - clearData(); - } - return *this; + clearData(); + this->_header.byte = packet._header.byte; + this->_remainingLength = packet._remainingLength; + _data = (unsigned char*) calloc(_remainingLength, 1); + if (_data) + { + memcpy(this->_data, packet._data, _remainingLength); + } + else + { + clearData(); + } + return *this; } UTF8String MQTTGWPacket::getTopic(void) { - UTF8String str = {0, nullptr}; - if ( _header.bits.type == SUBSCRIBE || _header.bits.type == UNSUBSCRIBE ) - { - char* ptr = (char*)(_data + 2); - str.len = readInt(&ptr); - str.data = (char*)(_data + 4); - } - return str; + UTF8String str = + { 0, nullptr }; + if (_header.bits.type == SUBSCRIBE || _header.bits.type == UNSUBSCRIBE) + { + char* ptr = (char*) (_data + 2); + str.len = readInt(&ptr); + str.data = (char*) (_data + 4); + } + return str; } diff --git a/MQTTSNGateway/src/MQTTGWPacket.h b/MQTTSNGateway/src/MQTTGWPacket.h index fb2ad86..46df326 100644 --- a/MQTTSNGateway/src/MQTTGWPacket.h +++ b/MQTTSNGateway/src/MQTTGWPacket.h @@ -31,89 +31,100 @@ typedef void* (*pf)(unsigned char, char*, size_t); enum msgTypes { - CONNECT = 1, CONNACK, PUBLISH, PUBACK, PUBREC, PUBREL, - PUBCOMP, SUBSCRIBE, SUBACK, UNSUBSCRIBE, UNSUBACK, - PINGREQ, PINGRESP, DISCONNECT + CONNECT = 1, + CONNACK, + PUBLISH, + PUBACK, + PUBREC, + PUBREL, + PUBCOMP, + SUBSCRIBE, + SUBACK, + UNSUBSCRIBE, + UNSUBACK, + PINGREQ, + PINGRESP, + DISCONNECT }; - /** * Bitfields for the MQTT header byte. */ typedef union { - /*unsigned*/ char byte; /**< the whole byte */ + /*unsigned*/ + char byte; /**< the whole byte */ #if defined(REVERSED) - struct - { - unsigned int type : 4; /**< message type nibble */ - bool dup : 1; /**< DUP flag bit */ - unsigned int qos : 2; /**< QoS value, 0, 1 or 2 */ - bool retain : 1; /**< retained flag bit */ - } bits; + struct + { + unsigned int type : 4; /**< message type nibble */ + bool dup : 1; /**< DUP flag bit */ + unsigned int qos : 2; /**< QoS value, 0, 1 or 2 */ + bool retain : 1; /**< retained flag bit */ + }bits; #else - struct - { - bool retain : 1; /**< retained flag bit */ - unsigned int qos : 2; /**< QoS value, 0, 1 or 2 */ - bool dup : 1; /**< DUP flag bit */ - unsigned int type : 4; /**< message type nibble */ - } bits; + struct + { + bool retain :1; /**< retained flag bit */ + unsigned int qos :2; /**< QoS value, 0, 1 or 2 */ + bool dup :1; /**< DUP flag bit */ + unsigned int type :4; /**< message type nibble */ + } bits; #endif } Header; - /** * Data for a connect packet. */ -enum MQTT_connackCodes{ - MQTT_CONNECTION_ACCEPTED , - MQTT_UNACCEPTABLE_PROTOCOL_VERSION, - MQTT_IDENTIFIER_REJECTED, - MQTT_SERVER_UNAVAILABLE, - MQTT_BAD_USERNAME_OR_PASSWORD, - MQTT_NOT_AUTHORIZED +enum MQTT_connackCodes +{ + MQTT_CONNECTION_ACCEPTED, + MQTT_UNACCEPTABLE_PROTOCOL_VERSION, + MQTT_IDENTIFIER_REJECTED, + MQTT_SERVER_UNAVAILABLE, + MQTT_BAD_USERNAME_OR_PASSWORD, + MQTT_NOT_AUTHORIZED }; typedef struct { - Header header; /**< MQTT header byte */ - union - { - unsigned char all; /**< all connect flags */ + Header header; /**< MQTT header byte */ + union + { + unsigned char all; /**< all connect flags */ #if defined(REVERSED) - struct - { - bool username : 1; /**< 3.1 user name */ - bool password : 1; /**< 3.1 password */ - bool willRetain : 1; /**< will retain setting */ - unsigned int willQoS : 2; /**< will QoS value */ - bool will : 1; /**< will flag */ - bool cleanstart : 1; /**< cleansession flag */ - int : 1; /**< unused */ - } bits; + struct + { + bool username : 1; /**< 3.1 user name */ + bool password : 1; /**< 3.1 password */ + bool willRetain : 1; /**< will retain setting */ + unsigned int willQoS : 2; /**< will QoS value */ + bool will : 1; /**< will flag */ + bool cleanstart : 1; /**< cleansession flag */ + int : 1; /**< unused */ + }bits; #else - struct - { - int : 1; /**< unused */ - bool cleanstart : 1; /**< cleansession flag */ - bool will : 1; /**< will flag */ - unsigned int willQoS : 2; /**< will QoS value */ - bool willRetain : 1; /**< will retain setting */ - bool password : 1; /**< 3.1 password */ - bool username : 1; /**< 3.1 user name */ - } bits; + struct + { + int :1; /**< unused */ + bool cleanstart :1; /**< cleansession flag */ + bool will :1; /**< will flag */ + unsigned int willQoS :2; /**< will QoS value */ + bool willRetain :1; /**< will retain setting */ + bool password :1; /**< 3.1 password */ + bool username :1; /**< 3.1 user name */ + } bits; #endif - } flags; /**< connect flags byte */ + } flags; /**< connect flags byte */ - char *Protocol, /**< MQTT protocol name */ - *clientID, /**< string client id */ - *willTopic, /**< will topic */ - *willMsg; /**< will payload */ + char *Protocol, /**< MQTT protocol name */ + *clientID, /**< string client id */ + *willTopic, /**< will topic */ + *willMsg; /**< will payload */ - int keepAliveTimer; /**< keepalive timeout value in seconds */ - unsigned char version; /**< MQTT version number */ + int keepAliveTimer; /**< keepalive timeout value in seconds */ + unsigned char version; /**< MQTT version number */ } Connect; #define MQTTPacket_Connect_Initializer {{0}, {0}, nullptr, nullptr, nullptr, nullptr, 0, 0} @@ -121,57 +132,54 @@ typedef struct #define MQTTPacket_connectData_initializer { {'M', 'Q', 'T', 'C'}, 0, 4, {NULL, {0, NULL}}, 60, 1, 0, \ MQTTPacket_willOptions_initializer, {NULL, {0, NULL}}, {NULL, {0, NULL}} } - - /** * Data for a willMessage. */ typedef struct { - char* topic; - char* msg; - int retained; - int qos; -}willMessages; + char* topic; + char* msg; + int retained; + int qos; +} willMessages; /** * Data for a connack packet. */ typedef struct { - Header header; /**< MQTT header byte */ - union - { - unsigned char all; /**< all connack flags */ + Header header; /**< MQTT header byte */ + union + { + unsigned char all; /**< all connack flags */ #if defined(REVERSED) - struct - { - unsigned int reserved : 7; /**< message type nibble */ - bool sessionPresent : 1; /**< was a session found on the server? */ - } bits; + struct + { + unsigned int reserved : 7; /**< message type nibble */ + bool sessionPresent : 1; /**< was a session found on the server? */ + }bits; #else - struct - { - bool sessionPresent : 1; /**< was a session found on the server? */ - unsigned int reserved : 7; /**< message type nibble */ - } bits; + struct + { + bool sessionPresent :1; /**< was a session found on the server? */ + unsigned int reserved :7; /**< message type nibble */ + } bits; #endif - } flags; /**< connack flags byte */ - char rc; /**< connack return code */ + } flags; /**< connack flags byte */ + char rc; /**< connack return code */ } Connack; - /** * Data for a publish packet. */ typedef struct { - Header header; /**< MQTT header byte */ - char* topic; /**< topic string */ - int topiclen; - int msgId; /**< MQTT message id */ - char* payload; /**< binary payload, length delimited */ - int payloadlen; /**< payload length */ + Header header; /**< MQTT header byte */ + char* topic; /**< topic string */ + int topiclen; + int msgId; /**< MQTT message id */ + char* payload; /**< binary payload, length delimited */ + int payloadlen; /**< payload length */ } Publish; #define MQTTPacket_Publish_Initializer {{0}, nullptr, 0, 0, nullptr, 0} @@ -181,8 +189,8 @@ typedef struct */ typedef struct { - Header header; /**< MQTT header byte */ - int msgId; /**< MQTT message id */ + Header header; /**< MQTT header byte */ + int msgId; /**< MQTT message id */ } Ack; /** @@ -190,8 +198,8 @@ typedef struct */ typedef struct { - unsigned char len; - char* data; + unsigned char len; + char* data; } UTF8String; /** @@ -200,39 +208,41 @@ typedef struct class MQTTGWPacket { public: - MQTTGWPacket(); - ~MQTTGWPacket(); - int recv(Network* network); - int send(Network* network); - int getType(void); - int getPacketData(unsigned char* buf); - int getPacketLength(void); - const char* getName(void); + MQTTGWPacket(); + ~MQTTGWPacket(); + int recv(Network* network); + int send(Network* network); + int getType(void); + int getPacketData(unsigned char* buf); + int getPacketLength(void); + const char* getName(void); - int getAck(Ack* ack); - int getCONNACK(Connack* resp); - int getSUBACK(unsigned short* msgId, unsigned char* rc); - int getPUBLISH(Publish* pub); + int getAck(Ack* ack); + int getCONNACK(Connack* resp); + int getSUBACK(unsigned short* msgId, unsigned char* rc); + int getPUBLISH(Publish* pub); - int setCONNECT(Connect* conect, unsigned char* username, unsigned char* password); - int setPUBLISH(Publish* pub); - int setAck(unsigned char msgType, unsigned short msgid); - int setHeader(unsigned char msgType); - int setSUBSCRIBE(const char* topic, unsigned char qos, unsigned short msgId); - int setUNSUBSCRIBE(const char* topics, unsigned short msgid); + int setCONNECT(Connect* conect, unsigned char* username, + unsigned char* password); + int setPUBLISH(Publish* pub); + int setAck(unsigned char msgType, unsigned short msgid); + int setHeader(unsigned char msgType); + int setSUBSCRIBE(const char* topic, unsigned char qos, + unsigned short msgId); + int setUNSUBSCRIBE(const char* topics, unsigned short msgid); - UTF8String getTopic(void); - char* getMsgId(char* buf); - int getMsgId(void); - void setMsgId(int msgId); - char* print(char* buf); - MQTTGWPacket& operator =(MQTTGWPacket& packet); + UTF8String getTopic(void); + char* getMsgId(char* buf); + int getMsgId(void); + void setMsgId(int msgId); + char* print(char* buf); + MQTTGWPacket& operator =(MQTTGWPacket& packet); private: - void clearData(void); - Header _header; - int _remainingLength; - unsigned char* _data; + void clearData(void); + Header _header; + int _remainingLength; + unsigned char* _data; }; } diff --git a/MQTTSNGateway/src/MQTTGWPublishHandler.cpp b/MQTTSNGateway/src/MQTTGWPublishHandler.cpp index e3abc79..e73a7cc 100644 --- a/MQTTSNGateway/src/MQTTGWPublishHandler.cpp +++ b/MQTTSNGateway/src/MQTTGWPublishHandler.cpp @@ -27,7 +27,7 @@ char* currentDateTime(void); MQTTGWPublishHandler::MQTTGWPublishHandler(Gateway* gateway) { - _gateway = gateway; + _gateway = gateway; } MQTTGWPublishHandler::~MQTTGWPublishHandler() @@ -37,266 +37,285 @@ MQTTGWPublishHandler::~MQTTGWPublishHandler() void MQTTGWPublishHandler::handlePublish(Client* client, MQTTGWPacket* packet) { - if ( !client->isActive() && !client->isSleep() && !client->isAwake()) - { - WRITELOG("%s The client is neither active nor sleep %s%s\n", ERRMSG_HEADER, client->getStatus(), ERRMSG_FOOTER); - return; - } + if (!client->isActive() && !client->isSleep() && !client->isAwake()) + { + WRITELOG("%s The client is neither active nor sleep %s%s\n", + ERRMSG_HEADER, client->getStatus(), ERRMSG_FOOTER); + return; + } - /* client is sleeping. save PUBLISH */ - if ( client->isSleep() ) - { - Publish pub; - packet->getPUBLISH(&pub); + /* client is sleeping. save PUBLISH */ + if (client->isSleep()) + { + Publish pub; + packet->getPUBLISH(&pub); - WRITELOG(FORMAT_Y_G_G, currentDateTime(), packet->getName(), - RIGHTARROW, client->getClientId(), "is sleeping. a message was saved."); + WRITELOG(FORMAT_Y_G_G, currentDateTime(), packet->getName(), + RIGHTARROW, client->getClientId(), "is sleeping. a message was saved."); - if (pub.header.bits.qos == 1) - { - replyACK(client, &pub, PUBACK); - } - else if ( pub.header.bits.qos == 2) - { - replyACK(client, &pub, PUBREC); - } + if (pub.header.bits.qos == 1) + { + replyACK(client, &pub, PUBACK); + } + else if (pub.header.bits.qos == 2) + { + replyACK(client, &pub, PUBREC); + } - MQTTGWPacket* msg = new MQTTGWPacket(); - *msg = *packet; - if ( msg->getType() == 0 ) - { - WRITELOG("%s MQTTGWPublishHandler::handlePublish can't allocate memories for Packet.%s\n", ERRMSG_HEADER,ERRMSG_FOOTER); - delete msg; - return; - } - client->setClientSleepPacket(msg); - return; - } + MQTTGWPacket* msg = new MQTTGWPacket(); + *msg = *packet; + if (msg->getType() == 0) + { + WRITELOG( + "%s MQTTGWPublishHandler::handlePublish can't allocate memories for Packet.%s\n", + ERRMSG_HEADER, ERRMSG_FOOTER); + delete msg; + return; + } + client->setClientSleepPacket(msg); + return; + } - Publish pub; - packet->getPUBLISH(&pub); + Publish pub; + packet->getPUBLISH(&pub); - MQTTSNPacket* snPacket = new MQTTSNPacket(); + MQTTSNPacket* snPacket = new MQTTSNPacket(); - /* create MQTTSN_topicid */ - MQTTSN_topicid topicId; - uint16_t id = 0; + /* create MQTTSN_topicid */ + MQTTSN_topicid topicId; + uint16_t id = 0; - if (pub.topiclen <= 2) - { - topicId.type = MQTTSN_TOPIC_TYPE_SHORT; - *(topicId.data.short_name) = *pub.topic; - *(topicId.data.short_name + 1) = *(pub.topic + 1); - } - else - { + if (pub.topiclen <= 2) + { + topicId.type = MQTTSN_TOPIC_TYPE_SHORT; + *(topicId.data.short_name) = *pub.topic; + *(topicId.data.short_name + 1) = *(pub.topic + 1); + } + else + { topicId.data.long_.len = pub.topiclen; topicId.data.long_.name = pub.topic; Topic* tp = client->getTopics()->getTopicByName(&topicId); - if ( tp ) + if (tp) { topicId.type = tp->getType(); topicId.data.long_.len = pub.topiclen; topicId.data.long_.name = pub.topic; topicId.data.id = tp->getTopicId(); } - else - { - /* This message might be subscribed with wild card. */ - topicId.type = MQTTSN_TOPIC_TYPE_NORMAL; - Topic* topic = client->getTopics()->match(&topicId); - if (topic == nullptr) - { - WRITELOG(" Invalid Topic. PUBLISH message is canceled.\n"); - if (pub.header.bits.qos == 1) - { - replyACK(client, &pub, PUBACK); - } - else if ( pub.header.bits.qos == 2 ) - { - replyACK(client, &pub, PUBREC); - } + else + { + /* This message might be subscribed with wild card. */ + topicId.type = MQTTSN_TOPIC_TYPE_NORMAL; + Topic* topic = client->getTopics()->match(&topicId); + if (topic == nullptr) + { + WRITELOG(" Invalid Topic. PUBLISH message is canceled.\n"); + if (pub.header.bits.qos == 1) + { + replyACK(client, &pub, PUBACK); + } + else if (pub.header.bits.qos == 2) + { + replyACK(client, &pub, PUBREC); + } - delete snPacket; - return; - } + delete snPacket; + return; + } - /* add the Topic and get a TopicId */ - topic = client->getTopics()->add(&topicId); - id = topic->getTopicId(); + /* add the Topic and get a TopicId */ + topic = client->getTopics()->add(&topicId); + id = topic->getTopicId(); - if (id > 0) - { - /* create REGISTER */ - MQTTSNPacket* regPacket = new MQTTSNPacket(); + if (id > 0) + { + /* create REGISTER */ + MQTTSNPacket* regPacket = new MQTTSNPacket(); - MQTTSNString topicName = MQTTSNString_initializer; - topicName.lenstring.len = topicId.data.long_.len; - topicName.lenstring.data = topicId.data.long_.name; + MQTTSNString topicName = MQTTSNString_initializer; + topicName.lenstring.len = topicId.data.long_.len; + topicName.lenstring.data = topicId.data.long_.name; - uint16_t regackMsgId = client->getNextSnMsgId(); - regPacket->setREGISTER(id, regackMsgId, &topicName); + uint16_t regackMsgId = client->getNextSnMsgId(); + regPacket->setREGISTER(id, regackMsgId, &topicName); - /* send REGISTER */ - Event* evrg = new Event(); - evrg->setClientSendEvent(client, regPacket); - _gateway->getClientSendQue()->post(evrg); + /* send REGISTER */ + Event* evrg = new Event(); + evrg->setClientSendEvent(client, regPacket); + _gateway->getClientSendQue()->post(evrg); - /* send PUBLISH */ - topicId.data.id = id; - snPacket->setPUBLISH((uint8_t) pub.header.bits.dup, (int) pub.header.bits.qos, - (uint8_t) pub.header.bits.retain, (uint16_t) pub.msgId, topicId, (uint8_t*) pub.payload, - pub.payloadlen); - client->getWaitREGACKPacketList()->setPacket(snPacket, regackMsgId); - return; - } - else - { - WRITELOG("%sMQTTGWPublishHandler Can't create a Topic.%s\n", ERRMSG_HEADER,ERRMSG_FOOTER); - delete snPacket; - return; - } - } - } + /* send PUBLISH */ + topicId.data.id = id; + snPacket->setPUBLISH((uint8_t) pub.header.bits.dup, + (int) pub.header.bits.qos, + (uint8_t) pub.header.bits.retain, (uint16_t) pub.msgId, + topicId, (uint8_t*) pub.payload, pub.payloadlen); + client->getWaitREGACKPacketList()->setPacket(snPacket, + regackMsgId); + return; + } + else + { + WRITELOG("%sMQTTGWPublishHandler Can't create a Topic.%s\n", + ERRMSG_HEADER, ERRMSG_FOOTER); + delete snPacket; + return; + } + } + } - snPacket->setPUBLISH((uint8_t) pub.header.bits.dup, (int) pub.header.bits.qos, (uint8_t) pub.header.bits.retain, - (uint16_t) pub.msgId, topicId, (uint8_t*) pub.payload, pub.payloadlen); - Event* ev1 = new Event(); - ev1->setClientSendEvent(client, snPacket); - _gateway->getClientSendQue()->post(ev1); + snPacket->setPUBLISH((uint8_t) pub.header.bits.dup, + (int) pub.header.bits.qos, (uint8_t) pub.header.bits.retain, + (uint16_t) pub.msgId, topicId, (uint8_t*) pub.payload, + pub.payloadlen); + Event* ev1 = new Event(); + ev1->setClientSendEvent(client, snPacket); + _gateway->getClientSendQue()->post(ev1); } void MQTTGWPublishHandler::replyACK(Client* client, Publish* pub, int type) { - MQTTGWPacket* pubAck = new MQTTGWPacket(); - pubAck->setAck(type, (uint16_t)pub->msgId); - Event* ev1 = new Event(); - ev1->setBrokerSendEvent(client, pubAck); - _gateway->getBrokerSendQue()->post(ev1); + MQTTGWPacket* pubAck = new MQTTGWPacket(); + pubAck->setAck(type, (uint16_t) pub->msgId); + Event* ev1 = new Event(); + ev1->setBrokerSendEvent(client, pubAck); + _gateway->getBrokerSendQue()->post(ev1); } void MQTTGWPublishHandler::handlePuback(Client* client, MQTTGWPacket* packet) { - Ack ack; - packet->getAck(&ack); - TopicIdMapElement* topicId = client->getWaitedPubTopicId((uint16_t)ack.msgId); - if (topicId) - { - MQTTSNPacket* mqttsnPacket = new MQTTSNPacket(); - mqttsnPacket->setPUBACK(topicId->getTopicId(), (uint16_t)ack.msgId, 0); + Ack ack; + packet->getAck(&ack); + TopicIdMapElement* topicId = client->getWaitedPubTopicId( + (uint16_t) ack.msgId); + if (topicId) + { + MQTTSNPacket* mqttsnPacket = new MQTTSNPacket(); + mqttsnPacket->setPUBACK(topicId->getTopicId(), (uint16_t) ack.msgId, 0); - client->eraseWaitedPubTopicId((uint16_t)ack.msgId); - Event* ev1 = new Event(); - ev1->setClientSendEvent(client, mqttsnPacket); - _gateway->getClientSendQue()->post(ev1); - return; - } - WRITELOG(" PUBACK from the Broker is invalid. PacketID : %04X ClientID : %s \n", (uint16_t)ack.msgId, client->getClientId()); + client->eraseWaitedPubTopicId((uint16_t) ack.msgId); + Event* ev1 = new Event(); + ev1->setClientSendEvent(client, mqttsnPacket); + _gateway->getClientSendQue()->post(ev1); + return; + } + WRITELOG( + " PUBACK from the Broker is invalid. PacketID : %04X ClientID : %s \n", + (uint16_t) ack.msgId, client->getClientId()); } -void MQTTGWPublishHandler::handleAck(Client* client, MQTTGWPacket* packet, int type) +void MQTTGWPublishHandler::handleAck(Client* client, MQTTGWPacket* packet, + int type) { - Ack ack; - packet->getAck(&ack); + Ack ack; + packet->getAck(&ack); - if ( client->isActive() || client->isAwake() ) - { - MQTTSNPacket* mqttsnPacket = new MQTTSNPacket(); - if (type == PUBREC) - { - mqttsnPacket->setPUBREC((uint16_t) ack.msgId); - } - else if (type == PUBREL) - { - mqttsnPacket->setPUBREL((uint16_t) ack.msgId); - } - else if (type == PUBCOMP) - { - mqttsnPacket->setPUBCOMP((uint16_t) ack.msgId); - } + if (client->isActive() || client->isAwake()) + { + MQTTSNPacket* mqttsnPacket = new MQTTSNPacket(); + if (type == PUBREC) + { + mqttsnPacket->setPUBREC((uint16_t) ack.msgId); + } + else if (type == PUBREL) + { + mqttsnPacket->setPUBREL((uint16_t) ack.msgId); + } + else if (type == PUBCOMP) + { + mqttsnPacket->setPUBCOMP((uint16_t) ack.msgId); + } - Event* ev1 = new Event(); - ev1->setClientSendEvent(client, mqttsnPacket); - _gateway->getClientSendQue()->post(ev1); - } - else if ( client->isSleep() ) - { - if (type == PUBREL) - { - MQTTGWPacket* pubComp = new MQTTGWPacket(); - pubComp->setAck(PUBCOMP, (uint16_t)ack.msgId); - Event* ev1 = new Event(); - ev1->setBrokerSendEvent(client, pubComp); - _gateway->getBrokerSendQue()->post(ev1); - } - } + Event* ev1 = new Event(); + ev1->setClientSendEvent(client, mqttsnPacket); + _gateway->getClientSendQue()->post(ev1); + } + else if (client->isSleep()) + { + if (type == PUBREL) + { + MQTTGWPacket* pubComp = new MQTTGWPacket(); + pubComp->setAck(PUBCOMP, (uint16_t) ack.msgId); + Event* ev1 = new Event(); + ev1->setBrokerSendEvent(client, pubComp); + _gateway->getBrokerSendQue()->post(ev1); + } + } } - - -void MQTTGWPublishHandler::handleAggregatePuback(Client* client, MQTTGWPacket* packet) +void MQTTGWPublishHandler::handleAggregatePuback(Client* client, + MQTTGWPacket* packet) { - uint16_t msgId = packet->getMsgId(); - uint16_t clientMsgId = 0; - Client* newClient = _gateway->getAdapterManager()->convertClient(msgId, &clientMsgId); - if ( newClient != nullptr ) - { - packet->setMsgId((int)clientMsgId); - handlePuback(newClient, packet); - } + uint16_t msgId = packet->getMsgId(); + uint16_t clientMsgId = 0; + Client* newClient = _gateway->getAdapterManager()->convertClient(msgId, + &clientMsgId); + if (newClient != nullptr) + { + packet->setMsgId((int) clientMsgId); + handlePuback(newClient, packet); + } } -void MQTTGWPublishHandler::handleAggregateAck(Client* client, MQTTGWPacket* packet, int type) +void MQTTGWPublishHandler::handleAggregateAck(Client* client, + MQTTGWPacket* packet, int type) { - uint16_t msgId = packet->getMsgId(); - uint16_t clientMsgId = 0; - Client* newClient = _gateway->getAdapterManager()->convertClient(msgId, &clientMsgId); - if ( newClient != nullptr ) - { - packet->setMsgId((int)clientMsgId); - handleAck(newClient, packet,type); - } + uint16_t msgId = packet->getMsgId(); + uint16_t clientMsgId = 0; + Client* newClient = _gateway->getAdapterManager()->convertClient(msgId, + &clientMsgId); + if (newClient != nullptr) + { + packet->setMsgId((int) clientMsgId); + handleAck(newClient, packet, type); + } } -void MQTTGWPublishHandler::handleAggregatePubrel(Client* client, MQTTGWPacket* packet) +void MQTTGWPublishHandler::handleAggregatePubrel(Client* client, + MQTTGWPacket* packet) { - Publish pub; - packet->getPUBLISH(&pub); - replyACK(client, &pub, PUBCOMP); + Publish pub; + packet->getPUBLISH(&pub); + replyACK(client, &pub, PUBCOMP); } -void MQTTGWPublishHandler::handleAggregatePublish(Client* client, MQTTGWPacket* packet) +void MQTTGWPublishHandler::handleAggregatePublish(Client* client, + MQTTGWPacket* packet) { - Publish pub; - packet->getPUBLISH(&pub); + Publish pub; + packet->getPUBLISH(&pub); + string* topicName = new string(pub.topic, pub.topiclen); // topic deletes topicName when the topic is deleted + Topic topic = Topic(topicName, MQTTSN_TOPIC_TYPE_NORMAL); - string* topicName = new string(pub.topic, pub.topiclen); // topic deletes topicName when the topic is deleted - Topic topic = Topic(topicName, MQTTSN_TOPIC_TYPE_NORMAL); + // ToDo: need to refactor + ClientTopicElement* elm = + _gateway->getAdapterManager()->getAggregater()->getClientElement( + &topic); - // ToDo: need to refactor - ClientTopicElement* elm = _gateway->getAdapterManager()->getAggregater()->getClientElement(&topic); + while (elm != nullptr) + { + Client* devClient = elm->getClient(); + MQTTGWPacket* msg = new MQTTGWPacket(); + *msg = *packet; - while ( elm != nullptr ) - { - Client* devClient = elm->getClient(); - MQTTGWPacket* msg = new MQTTGWPacket(); - *msg = *packet; + if (msg->getType() == 0) + { + WRITELOG( + "%s MQTTGWPublishHandler::handleAggregatePublish can't allocate memories for Packet.%s\n", + ERRMSG_HEADER, ERRMSG_FOOTER); + delete msg; + break; + } - if ( msg->getType() == 0 ) - { - WRITELOG("%s MQTTGWPublishHandler::handleAggregatePublish can't allocate memories for Packet.%s\n", ERRMSG_HEADER,ERRMSG_FOOTER); - delete msg; - break; - } + Event* ev = new Event(); + ev->setBrokerRecvEvent(devClient, msg); + _gateway->getPacketEventQue()->post(ev); - Event* ev = new Event(); - ev->setBrokerRecvEvent(devClient, msg); - _gateway->getPacketEventQue()->post(ev); - - elm = elm->getNextClientElement(); - } + elm = elm->getNextClientElement(); + } } diff --git a/MQTTSNGateway/src/MQTTGWPublishHandler.h b/MQTTSNGateway/src/MQTTGWPublishHandler.h index fee60e8..c32faee 100644 --- a/MQTTSNGateway/src/MQTTGWPublishHandler.h +++ b/MQTTSNGateway/src/MQTTGWPublishHandler.h @@ -26,25 +26,23 @@ namespace MQTTSNGW class MQTTGWPublishHandler { public: - MQTTGWPublishHandler(Gateway* gateway); - ~MQTTGWPublishHandler(); - void handlePublish(Client* client, MQTTGWPacket* packet); - void handlePuback(Client* client, MQTTGWPacket* packet); - void handleAck(Client* client, MQTTGWPacket* packet, int type); + MQTTGWPublishHandler(Gateway* gateway); + ~MQTTGWPublishHandler(); + void handlePublish(Client* client, MQTTGWPacket* packet); + void handlePuback(Client* client, MQTTGWPacket* packet); + void handleAck(Client* client, MQTTGWPacket* packet, int type); - void handleAggregatePublish(Client* client, MQTTGWPacket* packet); - void handleAggregatePuback(Client* client, MQTTGWPacket* packet); - void handleAggregateAck(Client* client, MQTTGWPacket* packet, int type); - void handleAggregatePubrel(Client* client, MQTTGWPacket* packet); + void handleAggregatePublish(Client* client, MQTTGWPacket* packet); + void handleAggregatePuback(Client* client, MQTTGWPacket* packet); + void handleAggregateAck(Client* client, MQTTGWPacket* packet, int type); + void handleAggregatePubrel(Client* client, MQTTGWPacket* packet); private: - void replyACK(Client* client, Publish* pub, int type); + void replyACK(Client* client, Publish* pub, int type); - Gateway* _gateway; + Gateway* _gateway; }; } - - #endif /* MQTTGWPUBLISHHANDLER_H_ */ diff --git a/MQTTSNGateway/src/MQTTGWSubscribeHandler.cpp b/MQTTSNGateway/src/MQTTGWSubscribeHandler.cpp index 2df4815..dd7425b 100644 --- a/MQTTSNGateway/src/MQTTGWSubscribeHandler.cpp +++ b/MQTTSNGateway/src/MQTTGWSubscribeHandler.cpp @@ -22,7 +22,7 @@ using namespace MQTTSNGW; MQTTGWSubscribeHandler::MQTTGWSubscribeHandler(Gateway* gateway) { - _gateway = gateway; + _gateway = gateway; } MQTTGWSubscribeHandler::~MQTTGWSubscribeHandler() @@ -32,68 +32,74 @@ MQTTGWSubscribeHandler::~MQTTGWSubscribeHandler() void MQTTGWSubscribeHandler::handleSuback(Client* client, MQTTGWPacket* packet) { - uint16_t msgId; - uint8_t rc; - uint8_t returnCode; - int qos = 0; + uint16_t msgId; + uint8_t rc; + uint8_t returnCode; + int qos = 0; - packet->getSUBACK(&msgId, &rc); - TopicIdMapElement* topicId = client->getWaitedSubTopicId(msgId); + packet->getSUBACK(&msgId, &rc); + TopicIdMapElement* topicId = client->getWaitedSubTopicId(msgId); - if (topicId) - { - MQTTSNPacket* snPacket = new MQTTSNPacket(); + if (topicId) + { + MQTTSNPacket* snPacket = new MQTTSNPacket(); - if (rc == 0x80) - { - returnCode = MQTTSN_RC_REJECTED_INVALID_TOPIC_ID; - } - else - { - returnCode = MQTTSN_RC_ACCEPTED; - qos = rc; - } - snPacket->setSUBACK(qos, topicId->getTopicId(), msgId, returnCode); - Event* evt = new Event(); - evt->setClientSendEvent(client, snPacket); - _gateway->getClientSendQue()->post(evt); + if (rc == 0x80) + { + returnCode = MQTTSN_RC_REJECTED_INVALID_TOPIC_ID; + } + else + { + returnCode = MQTTSN_RC_ACCEPTED; + qos = rc; + } + snPacket->setSUBACK(qos, topicId->getTopicId(), msgId, returnCode); + Event* evt = new Event(); + evt->setClientSendEvent(client, snPacket); + _gateway->getClientSendQue()->post(evt); client->eraseWaitedSubTopicId(msgId); - } + } } -void MQTTGWSubscribeHandler::handleUnsuback(Client* client, MQTTGWPacket* packet) +void MQTTGWSubscribeHandler::handleUnsuback(Client* client, + MQTTGWPacket* packet) { - Ack ack; - packet->getAck(&ack); - MQTTSNPacket* snPacket = new MQTTSNPacket(); - snPacket->setUNSUBACK(ack.msgId); - Event* evt = new Event(); - evt->setClientSendEvent(client, snPacket); - _gateway->getClientSendQue()->post(evt); + Ack ack; + packet->getAck(&ack); + MQTTSNPacket* snPacket = new MQTTSNPacket(); + snPacket->setUNSUBACK(ack.msgId); + Event* evt = new Event(); + evt->setClientSendEvent(client, snPacket); + _gateway->getClientSendQue()->post(evt); } -void MQTTGWSubscribeHandler::handleAggregateSuback(Client* client, MQTTGWPacket* packet) +void MQTTGWSubscribeHandler::handleAggregateSuback(Client* client, + MQTTGWPacket* packet) { - uint16_t msgId = packet->getMsgId(); - uint16_t clientMsgId = 0; - Client* newClient = _gateway->getAdapterManager()->getAggregater()->convertClient(msgId, &clientMsgId); - if ( newClient != nullptr ) - { - packet->setMsgId((int)clientMsgId); - handleSuback(newClient, packet); - } + uint16_t msgId = packet->getMsgId(); + uint16_t clientMsgId = 0; + Client* newClient = + _gateway->getAdapterManager()->getAggregater()->convertClient(msgId, + &clientMsgId); + if (newClient != nullptr) + { + packet->setMsgId((int) clientMsgId); + handleSuback(newClient, packet); + } } -void MQTTGWSubscribeHandler::handleAggregateUnsuback(Client* client, MQTTGWPacket* packet) +void MQTTGWSubscribeHandler::handleAggregateUnsuback(Client* client, + MQTTGWPacket* packet) { - uint16_t msgId = packet->getMsgId(); - uint16_t clientMsgId = 0; - Client* newClient = _gateway->getAdapterManager()->getAggregater()->convertClient(msgId, &clientMsgId); - if ( newClient != nullptr ) - { - packet->setMsgId((int)clientMsgId); - handleUnsuback(newClient, packet); - } + uint16_t msgId = packet->getMsgId(); + uint16_t clientMsgId = 0; + Client* newClient = + _gateway->getAdapterManager()->getAggregater()->convertClient(msgId, + &clientMsgId); + if (newClient != nullptr) + { + packet->setMsgId((int) clientMsgId); + handleUnsuback(newClient, packet); + } } - diff --git a/MQTTSNGateway/src/MQTTGWSubscribeHandler.h b/MQTTSNGateway/src/MQTTGWSubscribeHandler.h index d52b70f..7d86a3f 100644 --- a/MQTTSNGateway/src/MQTTGWSubscribeHandler.h +++ b/MQTTSNGateway/src/MQTTGWSubscribeHandler.h @@ -27,15 +27,15 @@ namespace MQTTSNGW class MQTTGWSubscribeHandler { public: - MQTTGWSubscribeHandler(Gateway* gateway); - ~MQTTGWSubscribeHandler(); - void handleSuback(Client* clnode, MQTTGWPacket* packet); - void handleUnsuback(Client* clnode, MQTTGWPacket* packet); - void handleAggregateSuback(Client* client, MQTTGWPacket* packet); - void handleAggregateUnsuback(Client* client, MQTTGWPacket* packet); + MQTTGWSubscribeHandler(Gateway* gateway); + ~MQTTGWSubscribeHandler(); + void handleSuback(Client* clnode, MQTTGWPacket* packet); + void handleUnsuback(Client* clnode, MQTTGWPacket* packet); + void handleAggregateSuback(Client* client, MQTTGWPacket* packet); + void handleAggregateUnsuback(Client* client, MQTTGWPacket* packet); private: - Gateway* _gateway; + Gateway* _gateway; }; } diff --git a/MQTTSNGateway/src/MQTTSNAggregateConnectionHandler.cpp b/MQTTSNGateway/src/MQTTSNAggregateConnectionHandler.cpp index 90672bf..b7a3a71 100644 --- a/MQTTSNGateway/src/MQTTSNAggregateConnectionHandler.cpp +++ b/MQTTSNGateway/src/MQTTSNAggregateConnectionHandler.cpp @@ -26,9 +26,10 @@ using namespace MQTTSNGW; /*===================================== Class MQTTSNAggregateConnectionHandler =====================================*/ -MQTTSNAggregateConnectionHandler::MQTTSNAggregateConnectionHandler(Gateway* gateway) +MQTTSNAggregateConnectionHandler::MQTTSNAggregateConnectionHandler( + Gateway* gateway) { - _gateway = gateway; + _gateway = gateway; } MQTTSNAggregateConnectionHandler::~MQTTSNAggregateConnectionHandler() @@ -36,130 +37,131 @@ MQTTSNAggregateConnectionHandler::~MQTTSNAggregateConnectionHandler() } - /* * CONNECT */ -void MQTTSNAggregateConnectionHandler::handleConnect(Client* client, MQTTSNPacket* packet) +void MQTTSNAggregateConnectionHandler::handleConnect(Client* client, + MQTTSNPacket* packet) { - MQTTSNPacket_connectData data; - if ( packet->getCONNECT(&data) == 0 ) - { - return; - } + MQTTSNPacket_connectData data; + if (packet->getCONNECT(&data) == 0) + { + return; + } - /* return CONNACK when the client is sleeping */ - if ( client->isSleep() || client->isAwake() ) - { - MQTTSNPacket* packet = new MQTTSNPacket(); - packet->setCONNACK(MQTTSN_RC_ACCEPTED); - Event* ev = new Event(); - ev->setClientSendEvent(client, packet); - _gateway->getClientSendQue()->post(ev); - sendStoredPublish(client); - return; - } + /* return CONNACK when the client is sleeping */ + if (client->isSleep() || client->isAwake()) + { + MQTTSNPacket* packet = new MQTTSNPacket(); + packet->setCONNACK(MQTTSN_RC_ACCEPTED); + Event* ev = new Event(); + ev->setClientSendEvent(client, packet); + _gateway->getClientSendQue()->post(ev); + sendStoredPublish(client); + return; + } - //* clear ConnectData of Client */ - Connect* connectData = client->getConnectData(); - memset(connectData, 0, sizeof(Connect)); + //* clear ConnectData of Client */ + Connect* connectData = client->getConnectData(); + memset(connectData, 0, sizeof(Connect)); - client->disconnected(); + client->disconnected(); - Topics* topics = client->getTopics(); + Topics* topics = client->getTopics(); - /* CONNECT was not sent yet. prepare Connect data */ + /* CONNECT was not sent yet. prepare Connect data */ + client->setSessionStatus(false); + if (data.cleansession) + { + /* reset the table of msgNo and TopicId pare */ + client->clearWaitedPubTopicId(); + client->clearWaitedSubTopicId(); - client->setSessionStatus(false); - if (data.cleansession) - { - /* reset the table of msgNo and TopicId pare */ - client->clearWaitedPubTopicId(); - client->clearWaitedSubTopicId(); + /* renew the TopicList */ + if (topics) + { + Topic* tp = topics->getFirstTopic(); + while (tp != nullptr) + { + if (tp->getType() == MQTTSN_TOPIC_TYPE_NORMAL) + { + _gateway->getAdapterManager()->getAggregater()->removeAggregateTopic( + tp, client); + } + tp = topics->getNextTopic(tp); + } + topics->eraseNormal(); + } + client->setSessionStatus(true); + } - /* renew the TopicList */ - if (topics) - { - Topic* tp = topics->getFirstTopic(); - while( tp != nullptr ) - { - if ( tp->getType() == MQTTSN_TOPIC_TYPE_NORMAL ) - { - _gateway->getAdapterManager()->getAggregater()->removeAggregateTopic(tp, client); - } - tp = topics->getNextTopic(tp); - } - topics->eraseNormal(); - } - client->setSessionStatus(true); - } + if (data.willFlag) + { + /* create & send WILLTOPICREQ message to the client */ + MQTTSNPacket* reqTopic = new MQTTSNPacket(); + reqTopic->setWILLTOPICREQ(); + Event* evwr = new Event(); + evwr->setClientSendEvent(client, reqTopic); - if (data.willFlag) - { - /* create & send WILLTOPICREQ message to the client */ - MQTTSNPacket* reqTopic = new MQTTSNPacket(); - reqTopic->setWILLTOPICREQ(); - Event* evwr = new Event(); - evwr->setClientSendEvent(client, reqTopic); - - /* Send WILLTOPICREQ to the client */ - _gateway->getClientSendQue()->post(evwr); - } - else - { - /* create CONNACK & send it to the client */ - MQTTSNPacket* packet = new MQTTSNPacket(); - packet->setCONNACK(MQTTSN_RC_ACCEPTED); - Event* ev = new Event(); - ev->setClientSendEvent(client, packet); - _gateway->getClientSendQue()->post(ev); - client->connackSended(MQTTSN_RC_ACCEPTED); - sendStoredPublish(client); - return; - } + /* Send WILLTOPICREQ to the client */ + _gateway->getClientSendQue()->post(evwr); + } + else + { + /* create CONNACK & send it to the client */ + MQTTSNPacket* packet = new MQTTSNPacket(); + packet->setCONNACK(MQTTSN_RC_ACCEPTED); + Event* ev = new Event(); + ev->setClientSendEvent(client, packet); + _gateway->getClientSendQue()->post(ev); + client->connackSended(MQTTSN_RC_ACCEPTED); + sendStoredPublish(client); + return; + } } - /* * WILLMSG */ -void MQTTSNAggregateConnectionHandler::handleWillmsg(Client* client, MQTTSNPacket* packet) +void MQTTSNAggregateConnectionHandler::handleWillmsg(Client* client, + MQTTSNPacket* packet) { - if ( !client->isWaitWillMsg() ) - { - DEBUGLOG(" MQTTSNConnectionHandler::handleWillmsg WaitWillMsgFlg is off.\n"); - return; - } + if (!client->isWaitWillMsg()) + { + DEBUGLOG(" MQTTSNConnectionHandler::handleWillmsg WaitWillMsgFlg is off.\n"); + return; + } - MQTTSNString willmsg = MQTTSNString_initializer; - //Connect* connectData = client->getConnectData(); + MQTTSNString willmsg = MQTTSNString_initializer; + //Connect* connectData = client->getConnectData(); - if( client->isConnectSendable() ) - { - /* save WillMsg in the client */ - if ( packet->getWILLMSG(&willmsg) == 0 ) - { - return; - } - client->setWillMsg(willmsg); + if (client->isConnectSendable()) + { + /* save WillMsg in the client */ + if (packet->getWILLMSG(&willmsg) == 0) + { + return; + } + client->setWillMsg(willmsg); - /* Send CONNACK to the client */ - MQTTSNPacket* packet = new MQTTSNPacket(); - packet->setCONNACK(MQTTSN_RC_ACCEPTED); - Event* ev = new Event(); - ev->setClientSendEvent(client, packet); - _gateway->getClientSendQue()->post(ev); + /* Send CONNACK to the client */ + MQTTSNPacket* packet = new MQTTSNPacket(); + packet->setCONNACK(MQTTSN_RC_ACCEPTED); + Event* ev = new Event(); + ev->setClientSendEvent(client, packet); + _gateway->getClientSendQue()->post(ev); - sendStoredPublish(client); - return; - } + sendStoredPublish(client); + return; + } } /* * DISCONNECT */ -void MQTTSNAggregateConnectionHandler::handleDisconnect(Client* client, MQTTSNPacket* packet) +void MQTTSNAggregateConnectionHandler::handleDisconnect(Client* client, + MQTTSNPacket* packet) { MQTTSNPacket* snMsg = new MQTTSNPacket(); snMsg->setDISCONNECT(0); @@ -171,33 +173,35 @@ void MQTTSNAggregateConnectionHandler::handleDisconnect(Client* client, MQTTSNPa /* * PINGREQ */ -void MQTTSNAggregateConnectionHandler::handlePingreq(Client* client, MQTTSNPacket* packet) +void MQTTSNAggregateConnectionHandler::handlePingreq(Client* client, + MQTTSNPacket* packet) { - if ( ( client->isSleep() || client->isAwake() ) && client->getClientSleepPacket() ) - { - sendStoredPublish(client); - client->holdPingRequest(); - } + if ((client->isSleep() || client->isAwake()) + && client->getClientSleepPacket()) + { + sendStoredPublish(client); + client->holdPingRequest(); + } - /* create and send PINGRESP to the PacketHandler */ - client->resetPingRequest(); + /* create and send PINGRESP to the PacketHandler */ + client->resetPingRequest(); - MQTTGWPacket* pingresp = new MQTTGWPacket(); + MQTTGWPacket* pingresp = new MQTTGWPacket(); - pingresp->setHeader(PINGRESP); + pingresp->setHeader(PINGRESP); - Event* evt = new Event(); - evt->setBrokerRecvEvent(client, pingresp); - _gateway->getPacketEventQue()->post(evt); + Event* evt = new Event(); + evt->setBrokerRecvEvent(client, pingresp); + _gateway->getPacketEventQue()->post(evt); } void MQTTSNAggregateConnectionHandler::sendStoredPublish(Client* client) { MQTTGWPacket* msg = nullptr; - while ( ( msg = client->getClientSleepPacket() ) != nullptr ) + while ((msg = client->getClientSleepPacket()) != nullptr) { - client->deleteFirstClientSleepPacket(); // pop the que to delete element. + client->deleteFirstClientSleepPacket(); // pop the que to delete element. Event* ev = new Event(); ev->setBrokerRecvEvent(client, msg); diff --git a/MQTTSNGateway/src/MQTTSNAggregateConnectionHandler.h b/MQTTSNGateway/src/MQTTSNAggregateConnectionHandler.h index 53282b3..15001b7 100644 --- a/MQTTSNGateway/src/MQTTSNAggregateConnectionHandler.h +++ b/MQTTSNGateway/src/MQTTSNAggregateConnectionHandler.h @@ -28,18 +28,18 @@ class MQTTSNPacket; class MQTTSNAggregateConnectionHandler { public: - MQTTSNAggregateConnectionHandler(Gateway* gateway); - ~MQTTSNAggregateConnectionHandler(void); + MQTTSNAggregateConnectionHandler(Gateway* gateway); + ~MQTTSNAggregateConnectionHandler(void); - void handleConnect(Client* client, MQTTSNPacket* packet); - void handleWillmsg(Client* client, MQTTSNPacket* packet); - void handleDisconnect(Client* client, MQTTSNPacket* packet); - void handlePingreq(Client* client, MQTTSNPacket* packet); + void handleConnect(Client* client, MQTTSNPacket* packet); + void handleWillmsg(Client* client, MQTTSNPacket* packet); + void handleDisconnect(Client* client, MQTTSNPacket* packet); + void handlePingreq(Client* client, MQTTSNPacket* packet); private: - void sendStoredPublish(Client* client); + void sendStoredPublish(Client* client); - Gateway* _gateway; + Gateway* _gateway; }; } diff --git a/MQTTSNGateway/src/MQTTSNGWAdapter.cpp b/MQTTSNGateway/src/MQTTSNGWAdapter.cpp index 2fa37b3..78994bf 100644 --- a/MQTTSNGateway/src/MQTTSNGWAdapter.cpp +++ b/MQTTSNGateway/src/MQTTSNGWAdapter.cpp @@ -24,116 +24,115 @@ #include using namespace MQTTSNGW; - /*===================================== - Class Adapter + Class Adapter =====================================*/ -Adapter:: Adapter(Gateway* gw) +Adapter::Adapter(Gateway* gw) { - _gateway = gw; - _proxy = new Proxy(gw); - _proxySecure = new Proxy(gw); + _gateway = gw; + _proxy = new Proxy(gw); + _proxySecure = new Proxy(gw); } Adapter::~Adapter(void) { - if ( _proxy ) + if (_proxy) { delete _proxy; } - if ( _proxySecure ) - { - delete _proxySecure; - } + if (_proxySecure) + { + delete _proxySecure; + } } - void Adapter::setup(const char* adpterName, AdapterType adapterType) { _isSecure = false; - if ( _gateway->hasSecureConnection() ) + if (_gateway->hasSecureConnection()) { - _isSecure = true; + _isSecure = true; } MQTTSNString id = MQTTSNString_initializer; - MQTTSNString idSecure = MQTTSNString_initializer; + MQTTSNString idSecure = MQTTSNString_initializer; - string name = string(adpterName); - id.cstring = const_cast(name.c_str()); - string nameSecure = string(adpterName) + "-S"; - idSecure.cstring = const_cast(nameSecure.c_str()); + string name = string(adpterName); + id.cstring = const_cast(name.c_str()); + string nameSecure = string(adpterName) + "-S"; + idSecure.cstring = const_cast(nameSecure.c_str()); - Client* client = _gateway->getClientList()->createClient(0, &id, true, false, TRANSPEARENT_TYPE); - setClient(client, false); - client->setAdapterType(adapterType); + Client* client = _gateway->getClientList()->createClient(0, &id, true, + false, TRANSPEARENT_TYPE); + setClient(client, false); + client->setAdapterType(adapterType); - client = _gateway->getClientList()->createClient(0, &idSecure, true, true, TRANSPEARENT_TYPE); - setClient(client, true); - client->setAdapterType(adapterType); + client = _gateway->getClientList()->createClient(0, &idSecure, true, true, + TRANSPEARENT_TYPE); + setClient(client, true); + client->setAdapterType(adapterType); } - Client* Adapter::getClient(SensorNetAddress* addr) { - Client* client = _gateway->getClientList()->getClient(addr); - if ( !client ) - { - return nullptr; - } - else if ( client->isQoSm1() ) - { - return client; - } - else - { - return nullptr; - } -} - -const char* Adapter::getClientId(SensorNetAddress* addr) -{ - Client* client = getClient(addr); - if ( !client ) + Client* client = _gateway->getClientList()->getClient(addr); + if (!client) { - return nullptr; + return nullptr; } - else if ( client->isQoSm1() ) + else if (client->isQoSm1()) { - return client->getClientId(); + return client; } else { - return nullptr; + return nullptr; + } +} + +const char* Adapter::getClientId(SensorNetAddress* addr) +{ + Client* client = getClient(addr); + if (!client) + { + return nullptr; + } + else if (client->isQoSm1()) + { + return client->getClientId(); + } + else + { + return nullptr; } } bool Adapter::isSecure(SensorNetAddress* addr) { - Client* client = getClient(addr); - if ( !client ) - { - return false; - } - else if ( client->isSecureNetwork() ) - { - return true; - } - else - { - return false; - } + Client* client = getClient(addr); + if (!client) + { + return false; + } + else if (client->isSecureNetwork()) + { + return true; + } + else + { + return false; + } } bool Adapter::isSecure(void) { - return _isSecure; + return _isSecure; } void Adapter::setClient(Client* client, bool secure) { - if ( secure ) + if (secure) { _clientSecure = client; } @@ -157,7 +156,7 @@ void Adapter::checkConnection(void) { _proxy->checkConnection(_client); - if ( _isSecure ) + if (_isSecure) { _proxySecure->checkConnection(_clientSecure); } @@ -166,15 +165,17 @@ void Adapter::checkConnection(void) void Adapter::send(MQTTSNPacket* packet, Client* client) { Proxy* proxy = _proxy; - if ( client->isSecureNetwork() && !_isSecure ) + if (client->isSecureNetwork() && !_isSecure) { - if ( _isSecure ) + if (_isSecure) { proxy = _proxySecure; } else { - WRITELOG("%s %s No Secure connections %s 's packet is discarded.%s\n", ERRMSG_HEADER, client->getClientId() , ERRMSG_FOOTER); + WRITELOG( + "%s %s No Secure connections %s 's packet is discarded.%s\n", + ERRMSG_HEADER, client->getClientId(), ERRMSG_FOOTER); return; } } @@ -185,13 +186,13 @@ void Adapter::send(MQTTSNPacket* packet, Client* client) void Adapter::resetPingTimer(bool secure) { - if ( secure ) + if (secure) { - _proxySecure->resetPingTimer(); + _proxySecure->resetPingTimer(); } else { - _proxy->resetPingTimer(); + _proxy->resetPingTimer(); } } @@ -202,48 +203,48 @@ bool Adapter::isActive(void) void Adapter::savePacket(Client* client, MQTTSNPacket* packet) { - if ( client->isSecureNetwork()) - { - _proxySecure->savePacket(client, packet); - } - else - { - _proxy->savePacket(client, packet); - } + if (client->isSecureNetwork()) + { + _proxySecure->savePacket(client, packet); + } + else + { + _proxy->savePacket(client, packet); + } } - Client* Adapter::getAdapterClient(Client* client) { - if ( client->isSecureNetwork() ) - { - return _clientSecure; - } - else - { - return _client; - } + if (client->isSecureNetwork()) + { + return _clientSecure; + } + else + { + return _client; + } } /*===================================== - Class Proxy + Class Proxy =====================================*/ Proxy::Proxy(Gateway* gw) { - _gateway = gw; - _suspendedPacketEventQue = new EventQue(); + _gateway = gw; + _suspendedPacketEventQue = new EventQue(); } Proxy::~Proxy(void) { - if ( _suspendedPacketEventQue ) - { - delete _suspendedPacketEventQue; - } + if (_suspendedPacketEventQue) + { + delete _suspendedPacketEventQue; + } } void Proxy::checkConnection(Client* client) { - if ( client->isDisconnect() || ( client->isConnecting() && _responseTimer.isTimeup()) ) + if (client->isDisconnect() + || (client->isConnecting() && _responseTimer.isTimeup())) { client->connectSended(); _responseTimer.start(PROXY_RESPONSE_DURATION * 1000UL); @@ -257,26 +258,26 @@ void Proxy::checkConnection(Client* client) ev->setClientRecvEvent(client, packet); _gateway->getPacketEventQue()->post(ev); } - else if ( (client->isActive() && _keepAliveTimer.isTimeup() ) || (_isWaitingResp && _responseTimer.isTimeup() ) ) + else if ((client->isActive() && _keepAliveTimer.isTimeup()) + || (_isWaitingResp && _responseTimer.isTimeup())) { - MQTTSNPacket* packet = new MQTTSNPacket(); - MQTTSNString clientId = MQTTSNString_initializer; - packet->setPINGREQ(&clientId); - Event* ev = new Event(); - ev->setClientRecvEvent(client, packet); - _gateway->getPacketEventQue()->post(ev); - _responseTimer.start(PROXY_RESPONSE_DURATION * 1000UL); - _isWaitingResp = true; + MQTTSNPacket* packet = new MQTTSNPacket(); + MQTTSNString clientId = MQTTSNString_initializer; + packet->setPINGREQ(&clientId); + Event* ev = new Event(); + ev->setClientRecvEvent(client, packet); + _gateway->getPacketEventQue()->post(ev); + _responseTimer.start(PROXY_RESPONSE_DURATION * 1000UL); + _isWaitingResp = true; - if ( ++_retryCnt > PROXY_MAX_RETRY_CNT ) - { - client->disconnected(); - } - resetPingTimer(); + if (++_retryCnt > PROXY_MAX_RETRY_CNT) + { + client->disconnected(); + } + resetPingTimer(); } } - void Proxy::resetPingTimer(void) { _keepAliveTimer.start(PROXY_KEEPALIVE_DURATION * 1000UL); @@ -284,24 +285,24 @@ void Proxy::resetPingTimer(void) void Proxy::recv(MQTTSNPacket* packet, Client* client) { - if ( packet->getType() == MQTTSN_CONNACK ) + if (packet->getType() == MQTTSN_CONNACK) { - if ( packet->isAccepted() ) - { + if (packet->isAccepted()) + { _responseTimer.stop(); _retryCnt = 0; resetPingTimer(); sendSuspendedPacket(); - } + } } - else if ( packet->getType() == MQTTSN_PINGRESP ) + else if (packet->getType() == MQTTSN_PINGRESP) { _isWaitingResp = false; _responseTimer.stop(); - _retryCnt = 0; - resetPingTimer(); + _retryCnt = 0; + resetPingTimer(); } - else if ( packet->getType() == MQTTSN_DISCONNECT ) + else if (packet->getType() == MQTTSN_DISCONNECT) { // blank } @@ -309,18 +310,18 @@ void Proxy::recv(MQTTSNPacket* packet, Client* client) void Proxy::savePacket(Client* client, MQTTSNPacket* packet) { - MQTTSNPacket* pk = new MQTTSNPacket(*packet); - Event* ev = new Event(); - ev->setClientRecvEvent(client, pk); - _suspendedPacketEventQue->post(ev); + MQTTSNPacket* pk = new MQTTSNPacket(*packet); + Event* ev = new Event(); + ev->setClientRecvEvent(client, pk); + _suspendedPacketEventQue->post(ev); } void Proxy::sendSuspendedPacket(void) { - while ( _suspendedPacketEventQue->size() ) - { - Event* ev = _suspendedPacketEventQue->wait(); - _gateway->getPacketEventQue()->post(ev); - } + while (_suspendedPacketEventQue->size()) + { + Event* ev = _suspendedPacketEventQue->wait(); + _gateway->getPacketEventQue()->post(ev); + } } diff --git a/MQTTSNGateway/src/MQTTSNGWAdapter.h b/MQTTSNGateway/src/MQTTSNGWAdapter.h index f126bf1..20c9a87 100644 --- a/MQTTSNGateway/src/MQTTSNGWAdapter.h +++ b/MQTTSNGateway/src/MQTTSNGWAdapter.h @@ -31,17 +31,18 @@ class EventQue; class Timer; /* When you add a new type, Client::setAdapterType() and Client::isAdapter() functions must be modified. */ -typedef enum{ - Atype_QoSm1Proxy, Atype_Aggregater -}AdapterType; +typedef enum +{ + Atype_QoSm1Proxy, Atype_Aggregater +} AdapterType; /*===================================== - Class Adapter + Class Adapter =====================================*/ class Adapter { public: - Adapter(Gateway* gw); + Adapter(Gateway* gw); ~Adapter(void); void setup(const char* adpterName, AdapterType adapterType); @@ -60,18 +61,17 @@ public: void savePacket(Client* client, MQTTSNPacket* packet); private: - Gateway* _gateway {nullptr}; - Proxy* _proxy {nullptr}; - Proxy* _proxySecure {nullptr}; - Client* _client {nullptr}; - Client* _clientSecure {nullptr}; - bool _isActive {false}; - bool _isSecure{false}; + Gateway* _gateway { nullptr }; + Proxy* _proxy { nullptr }; + Proxy* _proxySecure { nullptr }; + Client* _client { nullptr }; + Client* _clientSecure { nullptr }; + bool _isActive { false }; + bool _isSecure { false }; }; - /*===================================== - Class Proxy + Class Proxy =====================================*/ class Proxy { @@ -88,11 +88,12 @@ public: private: void sendSuspendedPacket(void); Gateway* _gateway; - EventQue* _suspendedPacketEventQue {nullptr}; - Timer _keepAliveTimer; - Timer _responseTimer; - bool _isWaitingResp {false}; - int _retryCnt {0}; + EventQue* _suspendedPacketEventQue + { nullptr }; + Timer _keepAliveTimer; + Timer _responseTimer; + bool _isWaitingResp { false }; + int _retryCnt { 0 }; }; } diff --git a/MQTTSNGateway/src/MQTTSNGWAdapterManager.cpp b/MQTTSNGateway/src/MQTTSNGWAdapterManager.cpp index 0d5fa55..5061ed7 100644 --- a/MQTTSNGateway/src/MQTTSNGWAdapterManager.cpp +++ b/MQTTSNGateway/src/MQTTSNGWAdapterManager.cpp @@ -33,42 +33,42 @@ char* currentDateTime(void); =====================================*/ AdapterManager::AdapterManager(Gateway* gw) { - _gateway = gw; - _forwarders = new ForwarderList(); - _qosm1Proxy = new QoSm1Proxy(gw); - _aggregater = new Aggregater(gw); + _gateway = gw; + _forwarders = new ForwarderList(); + _qosm1Proxy = new QoSm1Proxy(gw); + _aggregater = new Aggregater(gw); } - -void AdapterManager::initialize(char* gwName, bool aggregate, bool forwarder, bool qosM1) +void AdapterManager::initialize(char* gwName, bool aggregate, bool forwarder, + bool qosM1) { - if ( aggregate ) + if (aggregate) { - _aggregater->initialize(gwName); + _aggregater->initialize(gwName); } - if ( qosM1 ) + if (qosM1) { - _qosm1Proxy->initialize(gwName); + _qosm1Proxy->initialize(gwName); } - if ( forwarder ) + if (forwarder) { - _forwarders->initialize(_gateway); + _forwarders->initialize(_gateway); } } AdapterManager::~AdapterManager(void) { - if ( _forwarders ) + if (_forwarders) { delete _forwarders; } - if ( _qosm1Proxy ) + if (_qosm1Proxy) { delete _qosm1Proxy; } - if ( _aggregater ) + if (_aggregater) { delete _aggregater; } @@ -91,119 +91,124 @@ Aggregater* AdapterManager::getAggregater(void) bool AdapterManager::isAggregatedClient(Client* client) { - if ( !_aggregater->isActive() || client->isQoSm1() || client->isAggregater() || client->isQoSm1Proxy()) - { - return false; - } - else - { - return true; - } + if (!_aggregater->isActive() || client->isQoSm1() || client->isAggregater() + || client->isQoSm1Proxy()) + { + return false; + } + else + { + return true; + } } Client* AdapterManager::getClient(Client* client) { - bool secure = client->isSecureNetwork(); - Client* newClient = client; + bool secure = client->isSecureNetwork(); + Client* newClient = client; - if ( client->isQoSm1() ) - { - newClient = _qosm1Proxy->getAdapterClient(client); - _qosm1Proxy->resetPingTimer(secure); - } - else if ( client->isAggregated() ) - { - newClient = _aggregater->getAdapterClient(client); - _aggregater->resetPingTimer(secure); - } - else if ( client->isQoSm1Proxy() ) - { - _qosm1Proxy->resetPingTimer(secure); - } - else if ( client->isAggregater() ) - { - _aggregater->resetPingTimer(secure); - } - return newClient; + if (client->isQoSm1()) + { + newClient = _qosm1Proxy->getAdapterClient(client); + _qosm1Proxy->resetPingTimer(secure); + } + else if (client->isAggregated()) + { + newClient = _aggregater->getAdapterClient(client); + _aggregater->resetPingTimer(secure); + } + else if (client->isQoSm1Proxy()) + { + _qosm1Proxy->resetPingTimer(secure); + } + else if (client->isAggregater()) + { + _aggregater->resetPingTimer(secure); + } + return newClient; } -int AdapterManager::unicastToClient(Client* client, MQTTSNPacket* packet, ClientSendTask* task) +int AdapterManager::unicastToClient(Client* client, MQTTSNPacket* packet, + ClientSendTask* task) { - char pbuf[SIZE_OF_LOG_PACKET * 3]; - Forwarder* fwd = client->getForwarder(); - int rc = 0; + char pbuf[SIZE_OF_LOG_PACKET * 3]; + Forwarder* fwd = client->getForwarder(); + int rc = 0; - if ( fwd ) - { - MQTTSNGWEncapsulatedPacket encap(packet); - WirelessNodeId* wnId = fwd->getWirelessNodeId(client); - encap.setWirelessNodeId(wnId); - task->log(client, packet); - WRITELOG(FORMAT_Y_W_G, currentDateTime(), encap.getName(), RIGHTARROW, fwd->getId(), encap.print(pbuf)); - rc = encap.unicast(_gateway->getSensorNetwork(),fwd->getSensorNetAddr()); - } - else - { - task->log(client, packet); - if ( client->isQoSm1Proxy() ) - { - _qosm1Proxy->send(packet, client); - } - else if ( client->isAggregater() ) - { - _aggregater->send(packet, client); - } - else - { - rc = packet->unicast(_gateway->getSensorNetwork(), client->getSensorNetAddress()); - } - } - return rc; + if (fwd) + { + MQTTSNGWEncapsulatedPacket encap(packet); + WirelessNodeId* wnId = fwd->getWirelessNodeId(client); + encap.setWirelessNodeId(wnId); + task->log(client, packet); + WRITELOG(FORMAT_Y_W_G, currentDateTime(), encap.getName(), RIGHTARROW, + fwd->getId(), encap.print(pbuf)); + rc = encap.unicast(_gateway->getSensorNetwork(), + fwd->getSensorNetAddr()); + } + else + { + task->log(client, packet); + if (client->isQoSm1Proxy()) + { + _qosm1Proxy->send(packet, client); + } + else if (client->isAggregater()) + { + _aggregater->send(packet, client); + } + else + { + rc = packet->unicast(_gateway->getSensorNetwork(), + client->getSensorNetAddress()); + } + } + return rc; } void AdapterManager::checkConnection(void) { - if ( _aggregater->isActive()) - { - _aggregater->checkConnection(); - } + if (_aggregater->isActive()) + { + _aggregater->checkConnection(); + } - if ( _qosm1Proxy->isActive()) - { - _qosm1Proxy->checkConnection(); - } + if (_qosm1Proxy->isActive()) + { + _qosm1Proxy->checkConnection(); + } } Client* AdapterManager::convertClient(uint16_t msgId, uint16_t* clientMsgId) { - return _aggregater->convertClient(msgId, clientMsgId); + return _aggregater->convertClient(msgId, clientMsgId); } bool AdapterManager::isAggregaterActive(void) { - return _aggregater->isActive(); + return _aggregater->isActive(); } /* -AggregateTopicElement* AdapterManager::findTopic(Topic* topic) -{ - return _aggregater->findTopic(topic); -} + AggregateTopicElement* AdapterManager::findTopic(Topic* topic) + { + return _aggregater->findTopic(topic); + } -AggregateTopicElement* AdapterManager::addAggregateTopic(Topic* topic, Client* client) -{ - return _aggregater->addAggregateTopic(topic, client); -} + AggregateTopicElement* AdapterManager::addAggregateTopic(Topic* topic, Client* client) + { + return _aggregater->addAggregateTopic(topic, client); + } -void AdapterManager::removeAggregateTopic(Topic* topic, Client* client) -{ - //_aggregater->removeAggregateTopic(topic, client); -} + void AdapterManager::removeAggregateTopic(Topic* topic, Client* client) + { + //_aggregater->removeAggregateTopic(topic, client); + } -void AdapterManager::removeAggregateTopicList(Topics* topics, Client* client) -{ + void AdapterManager::removeAggregateTopicList(Topics* topics, Client* client) + { -} -*/ + } + */ diff --git a/MQTTSNGateway/src/MQTTSNGWAdapterManager.h b/MQTTSNGateway/src/MQTTSNGWAdapterManager.h index 58e5a03..42674be 100644 --- a/MQTTSNGateway/src/MQTTSNGWAdapterManager.h +++ b/MQTTSNGateway/src/MQTTSNGWAdapterManager.h @@ -33,12 +33,12 @@ class ClientRecvTask; class ClientSendTask; /*===================================== - Class AdapterManager + Class AdapterManager =====================================*/ class AdapterManager { public: - AdapterManager(Gateway* gw); + AdapterManager(Gateway* gw); ~AdapterManager(void); void initialize(char* gwName, bool aggregater, bool fowarder, bool qosM1); ForwarderList* getForwarderList(void); @@ -49,18 +49,16 @@ public: bool isAggregatedClient(Client* client); Client* getClient(Client* client); Client* convertClient(uint16_t msgId, uint16_t* clientMsgId); - int unicastToClient(Client* client, MQTTSNPacket* packet, ClientSendTask* task); + int unicastToClient(Client* client, MQTTSNPacket* packet, + ClientSendTask* task); bool isAggregaterActive(void); private: - Gateway* _gateway {nullptr}; - ForwarderList* _forwarders {nullptr}; - QoSm1Proxy* _qosm1Proxy {nullptr}; - Aggregater* _aggregater {nullptr}; + Gateway* _gateway { nullptr }; + ForwarderList* _forwarders { nullptr }; + QoSm1Proxy* _qosm1Proxy { nullptr }; + Aggregater* _aggregater { nullptr }; }; - - - } #endif /* MQTTSNGATEWAY_SRC_MQTTSNGWADAPTERMANAGER_H_ */ diff --git a/MQTTSNGateway/src/MQTTSNGWAggregateTopicTable.cpp b/MQTTSNGateway/src/MQTTSNGWAggregateTopicTable.cpp index 24dd23f..ed912eb 100644 --- a/MQTTSNGateway/src/MQTTSNGWAggregateTopicTable.cpp +++ b/MQTTSNGateway/src/MQTTSNGWAggregateTopicTable.cpp @@ -21,7 +21,7 @@ =====================================*/ ClientTopicElement::ClientTopicElement(Client* client) { - _client = client; + _client = client; } ClientTopicElement::~ClientTopicElement() @@ -31,12 +31,12 @@ ClientTopicElement::~ClientTopicElement() Client* ClientTopicElement::getClient(void) { - return _client; + return _client; } ClientTopicElement* ClientTopicElement::getNextClientElement(void) { - return _next; + return _next; } /*===================================== @@ -49,122 +49,123 @@ AggregateTopicElement::AggregateTopicElement(void) AggregateTopicElement::AggregateTopicElement(Topic* topic, Client* client) { - _topic = topic; - ClientTopicElement* elm = new ClientTopicElement(client); - if ( elm != nullptr ) - { - _head = elm; - _tail = elm; - } + _topic = topic; + ClientTopicElement* elm = new ClientTopicElement(client); + if (elm != nullptr) + { + _head = elm; + _tail = elm; + } } AggregateTopicElement::~AggregateTopicElement(void) { - _mutex.lock(); - if ( _head != nullptr ) - { - ClientTopicElement* p = _tail; - while ( p ) - { - ClientTopicElement* pPrev = p; - delete p; - p = pPrev->_prev; - } - _head = _tail = nullptr; - } - _mutex.unlock(); + _mutex.lock(); + if (_head != nullptr) + { + ClientTopicElement* p = _tail; + while (p) + { + ClientTopicElement* pPrev = p; + delete p; + p = pPrev->_prev; + } + _head = _tail = nullptr; + } + _mutex.unlock(); } ClientTopicElement* AggregateTopicElement::add(Client* client) { - ClientTopicElement* elm = new ClientTopicElement(client); - if ( elm == nullptr ) - { - return nullptr; - } + ClientTopicElement* elm = new ClientTopicElement(client); + if (elm == nullptr) + { + return nullptr; + } - _mutex.lock(); + _mutex.lock(); - if ( _head == nullptr ) - { - _head = elm; - _tail = elm; - } - else - { - ClientTopicElement* p = find(client); - if ( p == nullptr ) - { - p = _tail; - _tail = elm; - elm->_prev = p; - p->_next = elm; - } - else - { - delete elm; - elm = p; - } - } - _mutex.unlock(); - return elm; + if (_head == nullptr) + { + _head = elm; + _tail = elm; + } + else + { + ClientTopicElement* p = find(client); + if (p == nullptr) + { + p = _tail; + _tail = elm; + elm->_prev = p; + p->_next = elm; + } + else + { + delete elm; + elm = p; + } + } + _mutex.unlock(); + return elm; } ClientTopicElement* AggregateTopicElement::find(Client* client) { - ClientTopicElement* p = _head; - while ( p != nullptr ) - { - if ( p->_client == client) - { - break; - } - p = p->_next; - } - return p; + ClientTopicElement* p = _head; + while (p != nullptr) + { + if (p->_client == client) + { + break; + } + p = p->_next; + } + return p; } ClientTopicElement* AggregateTopicElement::getFirstClientTopicElement(void) { - return _head; + return _head; } -ClientTopicElement* AggregateTopicElement::getNextClientTopicElement(ClientTopicElement* elmClient) +ClientTopicElement* AggregateTopicElement::getNextClientTopicElement( + ClientTopicElement* elmClient) { - return elmClient->_next; + return elmClient->_next; } void AggregateTopicElement::eraseClient(Client* client) { - _mutex.lock(); + _mutex.lock(); - ClientTopicElement* p = find(client); - if ( p != nullptr ) - { - if ( p->_prev == nullptr ) // head element - { - _head = p->_next; - if ( p->_next == nullptr ) // head & only one - { - _tail = nullptr; - } - else - { - p->_next->_prev = nullptr; // head & midle - } - } - else if ( p->_next != nullptr ) // middle - { - p->_prev->_next = p->_next; - } - else // tail - { - p->_prev->_next = nullptr; - _tail = p->_prev; - } - delete p; - } - _mutex.unlock(); + ClientTopicElement* p = find(client); + if (p != nullptr) + { + if (p->_prev == nullptr) // head element + { + _head = p->_next; + if (p->_next == nullptr) // head & only one + { + _tail = nullptr; + } + else + { + p->_next->_prev = nullptr; // head & midle + } + } + else if (p->_next != nullptr) // middle + { + p->_prev->_next = p->_next; + } + else // tail + { + p->_prev->_next = nullptr; + _tail = p->_prev; + } + delete p; + } + _mutex.unlock(); } /*===================================== @@ -183,138 +184,139 @@ AggregateTopicTable::~AggregateTopicTable() AggregateTopicElement* AggregateTopicTable::add(Topic* topic, Client* client) { - AggregateTopicElement* elm = nullptr; - _mutex.lock(); - elm = getAggregateTopicElement(topic); - if ( elm != nullptr ) - { - if ( elm->find(client) == nullptr ) - { - elm->add(client); - } - } - else - { - Topic* newTopic = topic->duplicate(); - elm = new AggregateTopicElement(newTopic, client); - if ( _head == nullptr ) - { - _head = elm; - _tail = elm; - } - else - { - elm->_prev = _tail; - _tail->_next = elm; - _tail = elm; - } - } - _mutex.unlock(); - return elm; + AggregateTopicElement* elm = nullptr; + _mutex.lock(); + elm = getAggregateTopicElement(topic); + if (elm != nullptr) + { + if (elm->find(client) == nullptr) + { + elm->add(client); + } + } + else + { + Topic* newTopic = topic->duplicate(); + elm = new AggregateTopicElement(newTopic, client); + if (_head == nullptr) + { + _head = elm; + _tail = elm; + } + else + { + elm->_prev = _tail; + _tail->_next = elm; + _tail = elm; + } + } + _mutex.unlock(); + return elm; } void AggregateTopicTable::erase(Topic* topic, Client* client) { - AggregateTopicElement* elm = nullptr; + AggregateTopicElement* elm = nullptr; - _mutex.lock(); - elm = getAggregateTopicElement(topic); + _mutex.lock(); + elm = getAggregateTopicElement(topic); - if ( elm != nullptr ) - { - elm->eraseClient(client); - } - if ( elm->_head == nullptr ) - { - erase(elm); - } - _mutex.unlock(); - return; + if (elm != nullptr) + { + elm->eraseClient(client); + } + if (elm->_head == nullptr) + { + erase(elm); + } + _mutex.unlock(); + return; } void AggregateTopicTable::erase(AggregateTopicElement* elmTopic) { - if ( elmTopic != nullptr ) - { - if ( elmTopic->_prev == nullptr ) // head element - { - _head = elmTopic->_next; - if ( elmTopic->_next == nullptr ) // head & only one - { - _tail = nullptr; - } - else - { - elmTopic->_next->_prev = nullptr; // head & midle - } - } - else if ( elmTopic->_next != nullptr ) // middle - { - elmTopic->_prev->_next = elmTopic->_next; - } - else // tail - { - elmTopic->_prev->_next = nullptr; - _tail = elmTopic->_prev; - } - delete elmTopic; - } + if (elmTopic != nullptr) + { + if (elmTopic->_prev == nullptr) // head element + { + _head = elmTopic->_next; + if (elmTopic->_next == nullptr) // head & only one + { + _tail = nullptr; + } + else + { + elmTopic->_next->_prev = nullptr; // head & midle + } + } + else if (elmTopic->_next != nullptr) // middle + { + elmTopic->_prev->_next = elmTopic->_next; + } + else // tail + { + elmTopic->_prev->_next = nullptr; + _tail = elmTopic->_prev; + } + delete elmTopic; + } } -AggregateTopicElement* AggregateTopicTable::getAggregateTopicElement(Topic* topic) +AggregateTopicElement* AggregateTopicTable::getAggregateTopicElement( + Topic* topic) { - AggregateTopicElement* elm = _head; + AggregateTopicElement* elm = _head; - while( elm != nullptr ) - { - if ( elm->_topic->isMatch(topic->_topicName) ) - { - break; - } - elm = elm->_next; - } - return elm; + while (elm != nullptr) + { + if (elm->_topic->isMatch(topic->_topicName)) + { + break; + } + elm = elm->_next; + } + return elm; } ClientTopicElement* AggregateTopicTable::getClientElement(Topic* topic) { - AggregateTopicElement* elm = getAggregateTopicElement(topic); - if ( elm != nullptr ) - { - return elm->_head; - } - else - { - return nullptr; - } + AggregateTopicElement* elm = getAggregateTopicElement(topic); + if (elm != nullptr) + { + return elm->_head; + } + else + { + return nullptr; + } } void AggregateTopicTable::print(void) { - AggregateTopicElement* elm = _head; + AggregateTopicElement* elm = _head; - printf("Beginning of AggregateTopicTable\n"); - while( elm != nullptr ) - { - printf("%s\n", elm->_topic->getTopicName()->c_str()); + printf("Beginning of AggregateTopicTable\n"); + while (elm != nullptr) + { + printf("%s\n", elm->_topic->getTopicName()->c_str()); - ClientTopicElement* clElm = elm->getFirstClientTopicElement(); - Client* client = clElm->getClient(); + ClientTopicElement* clElm = elm->getFirstClientTopicElement(); + Client* client = clElm->getClient(); - while ( client != nullptr ) - { - printf(" %s\n", client->getClientId()); - clElm = clElm->getNextClientElement(); - if ( clElm != nullptr ) - { - client = clElm->getClient(); - } - else - { - client = nullptr; - } - } - elm = elm->_next; - } - printf("End of AggregateTopicTable\n"); + while (client != nullptr) + { + printf(" %s\n", client->getClientId()); + clElm = clElm->getNextClientElement(); + if (clElm != nullptr) + { + client = clElm->getClient(); + } + else + { + client = nullptr; + } + } + elm = elm->_next; + } + printf("End of AggregateTopicTable\n"); } diff --git a/MQTTSNGateway/src/MQTTSNGWAggregateTopicTable.h b/MQTTSNGateway/src/MQTTSNGWAggregateTopicTable.h index 87d9e82..6293c0d 100644 --- a/MQTTSNGateway/src/MQTTSNGWAggregateTopicTable.h +++ b/MQTTSNGateway/src/MQTTSNGWAggregateTopicTable.h @@ -35,24 +35,24 @@ class Mutex; class AggregateTopicTable { public: - AggregateTopicTable(); - ~AggregateTopicTable(); + AggregateTopicTable(); + ~AggregateTopicTable(); - AggregateTopicElement* add(Topic* topic, Client* client); - AggregateTopicElement* getAggregateTopicElement(Topic* topic); - ClientTopicElement* getClientElement(Topic* topic); - void erase(Topic* topic, Client* client); - void clear(void); + AggregateTopicElement* add(Topic* topic, Client* client); + AggregateTopicElement* getAggregateTopicElement(Topic* topic); + ClientTopicElement* getClientElement(Topic* topic); + void erase(Topic* topic, Client* client); + void clear(void); - void print(void); + void print(void); private: - void erase(AggregateTopicElement* elmTopic); - Mutex _mutex; - AggregateTopicElement* _head {nullptr}; - AggregateTopicElement* _tail {nullptr}; - int _cnt {0}; - int _maxSize {MAX_MESSAGEID_TABLE_SIZE}; + void erase(AggregateTopicElement* elmTopic); + Mutex _mutex; + AggregateTopicElement* _head { nullptr }; + AggregateTopicElement* _tail { nullptr }; + int _cnt { 0 }; + int _maxSize { MAX_MESSAGEID_TABLE_SIZE }; }; /*===================================== @@ -68,17 +68,18 @@ public: ClientTopicElement* add(Client* client); ClientTopicElement* getFirstClientTopicElement(void); - ClientTopicElement* getNextClientTopicElement(ClientTopicElement* elmClient); + ClientTopicElement* getNextClientTopicElement( + ClientTopicElement* elmClient); void eraseClient(Client* client); ClientTopicElement* find(Client* client); private: Mutex _mutex; - Topic* _topic {nullptr}; - AggregateTopicElement* _next {nullptr}; - AggregateTopicElement* _prev {nullptr}; - ClientTopicElement* _head {nullptr}; - ClientTopicElement* _tail {nullptr}; + Topic* _topic { nullptr }; + AggregateTopicElement* _next { nullptr }; + AggregateTopicElement* _prev { nullptr }; + ClientTopicElement* _head { nullptr }; + ClientTopicElement* _tail { nullptr }; }; /*===================================== @@ -96,13 +97,11 @@ public: Client* getClient(void); private: - Client* _client {nullptr}; - ClientTopicElement* _next {nullptr}; - ClientTopicElement* _prev {nullptr}; + Client* _client { nullptr }; + ClientTopicElement* _next { nullptr }; + ClientTopicElement* _prev { nullptr }; }; } - - #endif /* MQTTSNGATEWAY_SRC_MQTTSNGWAGGREGATETOPICTABLE_H_ */ diff --git a/MQTTSNGateway/src/MQTTSNGWAggregater.cpp b/MQTTSNGateway/src/MQTTSNGWAggregater.cpp index 93718db..79bdc61 100644 --- a/MQTTSNGateway/src/MQTTSNGWAggregater.cpp +++ b/MQTTSNGateway/src/MQTTSNGWAggregater.cpp @@ -26,9 +26,10 @@ using namespace MQTTSNGW; -Aggregater::Aggregater(Gateway* gw) : Adapter(gw) +Aggregater::Aggregater(Gateway* gw) : + Adapter(gw) { - _gateway = gw; + _gateway = gw; } Aggregater::~Aggregater(void) @@ -38,10 +39,10 @@ Aggregater::~Aggregater(void) void Aggregater::initialize(char* gwName) { - /* Create Aggregater Client */ - string name = string(gwName) + string("_Aggregater"); - setup(name.c_str(), Atype_Aggregater); - _isActive = true; + /* Create Aggregater Client */ + string name = string(gwName) + string("_Aggregater"); + setup(name.c_str(), Atype_Aggregater); + _isActive = true; //testMessageIdTable(); @@ -49,100 +50,99 @@ void Aggregater::initialize(char* gwName) bool Aggregater::isActive(void) { - return _isActive; + return _isActive; } uint16_t Aggregater::msgId(void) { - // Only SecureClient generates msgId to avoid duplication of msgId. Client does not generate it. - return Adapter::getSecureClient()->getNextPacketId(); + // Only SecureClient generates msgId to avoid duplication of msgId. Client does not generate it. + return Adapter::getSecureClient()->getNextPacketId(); } Client* Aggregater::convertClient(uint16_t msgId, uint16_t* clientMsgId) { - return _msgIdTable.getClientMsgId(msgId, clientMsgId); + return _msgIdTable.getClientMsgId(msgId, clientMsgId); } - uint16_t Aggregater::addMessageIdTable(Client* client, uint16_t msgId) { - /* set Non secure client`s nextMsgId. otherwise Id is duplicated.*/ + /* set Non secure client`s nextMsgId. otherwise Id is duplicated.*/ - MessageIdElement* elm = _msgIdTable.add(this, client, msgId); - if ( elm == nullptr ) - { - return 0; - } - else - { - return elm->_msgId; - } + MessageIdElement* elm = _msgIdTable.add(this, client, msgId); + if (elm == nullptr) + { + return 0; + } + else + { + return elm->_msgId; + } } uint16_t Aggregater::getMsgId(Client* client, uint16_t clientMsgId) { - return _msgIdTable.getMsgId(client, clientMsgId); + return _msgIdTable.getMsgId(client, clientMsgId); } -AggregateTopicElement* Aggregater::addAggregateTopic(Topic* topic, Client* client) +AggregateTopicElement* Aggregater::addAggregateTopic(Topic* topic, + Client* client) { - return _topicTable.add(topic, client); + return _topicTable.add(topic, client); } - void Aggregater::removeAggregateTopic(Topic* topic, Client* client) { - _topicTable.erase(topic, client); + _topicTable.erase(topic, client); } AggregateTopicElement* Aggregater::findTopic(Topic* topic) { - return _topicTable.getAggregateTopicElement(topic); + return _topicTable.getAggregateTopicElement(topic); } ClientTopicElement* Aggregater::getClientElement(Topic* topic) { - AggregateTopicElement* elm = findTopic(topic); - if ( elm != nullptr ) - { - return elm->getFirstClientTopicElement(); - } - else - { - return nullptr; - } + AggregateTopicElement* elm = findTopic(topic); + if (elm != nullptr) + { + return elm->getFirstClientTopicElement(); + } + else + { + return nullptr; + } } void Aggregater::printAggregateTopicTable(void) { - _topicTable.print(); + _topicTable.print(); } bool Aggregater::testMessageIdTable(void) { - Client* client = new Client(); - uint16_t msgId = 0; + Client* client = new Client(); + uint16_t msgId = 0; - printf("msgId=%d\n", addMessageIdTable(client,1)); - printf("msgId=%d\n", addMessageIdTable(client,2)); - printf("msgId=%d\n", addMessageIdTable(client,3)); - printf("msgId=%d\n", addMessageIdTable(client,1)); - printf("msgId=%d\n", addMessageIdTable(client,2)); - printf("msgId=%d\n", addMessageIdTable(client,3)); - printf("msgId=%d\n", addMessageIdTable(client,4)); - printf("msgId=%d\n", addMessageIdTable(client,4)); - printf("msgId=%d\n", addMessageIdTable(client,4)); + printf("msgId=%d\n", addMessageIdTable(client, 1)); + printf("msgId=%d\n", addMessageIdTable(client, 2)); + printf("msgId=%d\n", addMessageIdTable(client, 3)); + printf("msgId=%d\n", addMessageIdTable(client, 1)); + printf("msgId=%d\n", addMessageIdTable(client, 2)); + printf("msgId=%d\n", addMessageIdTable(client, 3)); + printf("msgId=%d\n", addMessageIdTable(client, 4)); + printf("msgId=%d\n", addMessageIdTable(client, 4)); + printf("msgId=%d\n", addMessageIdTable(client, 4)); - convertClient(1,&msgId); - printf("msgId=%d\n",msgId); - convertClient(2,&msgId); - printf("msgId=%d\n",msgId); - convertClient(5,&msgId); - printf("msgId=%d\n",msgId); - convertClient(4,&msgId); - printf("msgId=%d\n",msgId); - convertClient(3,&msgId); - printf("msgId=%d\n",msgId); - return true; + convertClient(1, &msgId); + printf("msgId=%d\n", msgId); + convertClient(2, &msgId); + printf("msgId=%d\n", msgId); + convertClient(5, &msgId); + printf("msgId=%d\n", msgId); + convertClient(4, &msgId); + printf("msgId=%d\n", msgId); + convertClient(3, &msgId); + printf("msgId=%d\n", msgId); + return true; } diff --git a/MQTTSNGateway/src/MQTTSNGWAggregater.h b/MQTTSNGateway/src/MQTTSNGWAggregater.h index 959ff87..490b71f 100644 --- a/MQTTSNGateway/src/MQTTSNGWAggregater.h +++ b/MQTTSNGateway/src/MQTTSNGWAggregater.h @@ -32,11 +32,11 @@ class AggregateTopicTable; class Topics; /*===================================== - Class Aggregater + Class Aggregater =====================================*/ -class Aggregater : public Adapter +class Aggregater: public Adapter { - friend class MessageIdTable; + friend class MessageIdTable; public: Aggregater(Gateway* gw); ~Aggregater(void); @@ -44,39 +44,35 @@ public: void initialize(char* gwName); const char* getClientId(SensorNetAddress* addr); - Client* getClient(SensorNetAddress* addr); - Client* convertClient(uint16_t msgId, uint16_t* clientMsgId); - uint16_t addMessageIdTable(Client* client, uint16_t msgId); - uint16_t getMsgId(Client* client, uint16_t clientMsgId); + Client* getClient(SensorNetAddress* addr); + Client* convertClient(uint16_t msgId, uint16_t* clientMsgId); + uint16_t addMessageIdTable(Client* client, uint16_t msgId); + uint16_t getMsgId(Client* client, uint16_t clientMsgId); - ClientTopicElement* getClientElement(Topic* topic); - ClientTopicElement* getNextClientElement(ClientTopicElement* clientElement); - Client* getClient(ClientTopicElement* clientElement); + ClientTopicElement* getClientElement(Topic* topic); + ClientTopicElement* getNextClientElement(ClientTopicElement* clientElement); + Client* getClient(ClientTopicElement* clientElement); - AggregateTopicElement* findTopic(Topic* topic); - AggregateTopicElement* addAggregateTopic(Topic* topic, Client* client); + AggregateTopicElement* findTopic(Topic* topic); + AggregateTopicElement* addAggregateTopic(Topic* topic, Client* client); - void removeAggregateTopic(Topic* topic, Client* client); - void removeAggregateAllTopic(Client* client); - bool isActive(void); + void removeAggregateTopic(Topic* topic, Client* client); + void removeAggregateAllTopic(Client* client); + bool isActive(void); - void printAggregateTopicTable(void); - bool testMessageIdTable(void); + void printAggregateTopicTable(void); + bool testMessageIdTable(void); private: - uint16_t msgId(void); - Gateway* _gateway {nullptr}; + uint16_t msgId(void); + Gateway* _gateway { nullptr }; MessageIdTable _msgIdTable; AggregateTopicTable _topicTable; - bool _isActive {false}; - bool _isSecure {false}; + bool _isActive { false }; + bool _isSecure { false }; }; - - } - - #endif /* MQTTSNGATEWAY_SRC_MQTTSNGWAGGREGATER_H_ */ diff --git a/MQTTSNGateway/src/MQTTSNGWBrokerRecvTask.cpp b/MQTTSNGateway/src/MQTTSNGWBrokerRecvTask.cpp index 99b0ce5..9a570b6 100644 --- a/MQTTSNGateway/src/MQTTSNGWBrokerRecvTask.cpp +++ b/MQTTSNGateway/src/MQTTSNGWBrokerRecvTask.cpp @@ -29,9 +29,9 @@ char* currentDateTime(void); =====================================*/ BrokerRecvTask::BrokerRecvTask(Gateway* gateway) { - _gateway = gateway; - _gateway->attach((Thread*)this); - _light = nullptr; + _gateway = gateway; + _gateway->attach((Thread*) this); + _light = nullptr; } BrokerRecvTask::~BrokerRecvTask() @@ -44,7 +44,7 @@ BrokerRecvTask::~BrokerRecvTask() */ void BrokerRecvTask::initialize(int argc, char** argv) { - _light = _gateway->getLightIndicator(); + _light = _gateway->getLightIndicator(); } /** @@ -52,133 +52,147 @@ void BrokerRecvTask::initialize(int argc, char** argv) */ void BrokerRecvTask::run(void) { - struct timeval timeout; - MQTTGWPacket* packet = nullptr; - int rc; - Event* ev = nullptr; - fd_set rset; - fd_set wset; + struct timeval timeout; + MQTTGWPacket* packet = nullptr; + int rc; + Event* ev = nullptr; + fd_set rset; + fd_set wset; - while (true) - { - _light->blueLight(false); - if (CHK_SIGINT) - { - WRITELOG("\n%s BrokerRecvTask stopped.", currentDateTime()); - return; - } - timeout.tv_sec = 0; - timeout.tv_usec = 500000; // 500 msec - FD_ZERO(&rset); - FD_ZERO(&wset); - int maxSock = 0; - int sockfd = 0; + while (true) + { + _light->blueLight(false); + if (CHK_SIGINT) + { + WRITELOG("\n%s BrokerRecvTask stopped.", currentDateTime()); + return; + } + timeout.tv_sec = 0; + timeout.tv_usec = 500000; // 500 msec + FD_ZERO(&rset); + FD_ZERO(&wset); + int maxSock = 0; + int sockfd = 0; - /* Prepare sockets list to read */ - Client* client = _gateway->getClientList()->getClient(0); + /* Prepare sockets list to read */ + Client* client = _gateway->getClientList()->getClient(0); - while ( client ) - { - if (client->getNetwork()->isValid()) - { - sockfd = client->getNetwork()->getSock(); - FD_SET(sockfd, &rset); - FD_SET(sockfd, &wset); - if (sockfd > maxSock) - { - maxSock = sockfd; - } - } - client = client->getNextClient(); - } + while (client) + { + if (client->getNetwork()->isValid()) + { + sockfd = client->getNetwork()->getSock(); + FD_SET(sockfd, &rset); + FD_SET(sockfd, &wset); + if (sockfd > maxSock) + { + maxSock = sockfd; + } + } + client = client->getNextClient(); + } - if (maxSock == 0) - { - usleep(500 * 1000); - } - else - { - /* Check sockets is ready to read */ - int activity = select(maxSock + 1, &rset, 0, 0, &timeout); - if (activity > 0) - { - client = _gateway->getClientList()->getClient(0); + if (maxSock == 0) + { + usleep(500 * 1000); + } + else + { + /* Check sockets is ready to read */ + int activity = select(maxSock + 1, &rset, 0, 0, &timeout); + if (activity > 0) + { + client = _gateway->getClientList()->getClient(0); - while ( client ) - { - _light->blueLight(false); - if (client->getNetwork()->isValid()) - { - int sockfd = client->getNetwork()->getSock(); - if (FD_ISSET(sockfd, &rset)) - { - packet = new MQTTGWPacket(); - rc = 0; - /* read sockets */ - _light->blueLight(true); - rc = packet->recv(client->getNetwork()); - if ( rc > 0 ) - { - if ( log(client, packet) == -1 ) - { - delete packet; - goto nextClient; - } + while (client) + { + _light->blueLight(false); + if (client->getNetwork()->isValid()) + { + int sockfd = client->getNetwork()->getSock(); + if (FD_ISSET(sockfd, &rset)) + { + packet = new MQTTGWPacket(); + rc = 0; + /* read sockets */ + _light->blueLight(true); + rc = packet->recv(client->getNetwork()); + if (rc > 0) + { + if (log(client, packet) == -1) + { + delete packet; + goto nextClient; + } - /* post a BrokerRecvEvent */ - ev = new Event(); - ev->setBrokerRecvEvent(client, packet); - _gateway->getPacketEventQue()->post(ev); - } - else - { - if ( rc == 0 ) // Disconnected - { - client->getNetwork()->close(); - delete packet; + /* post a BrokerRecvEvent */ + ev = new Event(); + ev->setBrokerRecvEvent(client, packet); + _gateway->getPacketEventQue()->post(ev); + } + else + { + if (rc == 0) // Disconnected + { + client->getNetwork()->close(); + delete packet; - /* delete client when the client is not authorized & session is clean */ - _gateway->getClientList()->erase(client); + /* delete client when the client is not authorized & session is clean */ + _gateway->getClientList()->erase(client); - if ( client ) - { - client = client->getNextClient(); - } - continue; - } - else if (rc == -1) - { - WRITELOG("%s BrokerRecvTask can't receive a packet from the broker errno=%d %s%s\n", ERRMSG_HEADER, errno, client->getClientId(), ERRMSG_FOOTER); - } - else if ( rc == -2 ) - { - WRITELOG("%s BrokerRecvTask receive invalid length of packet from the broker. DISCONNECT %s %s\n", ERRMSG_HEADER, client->getClientId(),ERRMSG_FOOTER); - } - else if ( rc == -3 ) - { - WRITELOG("%s BrokerRecvTask can't get memories for the packet %s%s\n", ERRMSG_HEADER, client->getClientId(), ERRMSG_FOOTER); - } + if (client) + { + client = client->getNextClient(); + } + continue; + } + else if (rc == -1) + { + WRITELOG( + "%s BrokerRecvTask can't receive a packet from the broker errno=%d %s%s\n", + ERRMSG_HEADER, errno, + client->getClientId(), + ERRMSG_FOOTER); + } + else if (rc == -2) + { + WRITELOG( + "%s BrokerRecvTask receive invalid length of packet from the broker. DISCONNECT %s %s\n", + ERRMSG_HEADER, + client->getClientId(), + ERRMSG_FOOTER); + } + else if (rc == -3) + { + WRITELOG( + "%s BrokerRecvTask can't get memories for the packet %s%s\n", + ERRMSG_HEADER, + client->getClientId(), + ERRMSG_FOOTER); + } - delete packet; + delete packet; - if ( (rc == -1 || rc == -2) && ( client->isActive() || client->isSleep() || client->isAwake() )) - { - /* disconnect the client */ - packet = new MQTTGWPacket(); - packet->setHeader(DISCONNECT); - ev = new Event(); - ev->setBrokerRecvEvent(client, packet); - _gateway->getPacketEventQue()->post(ev); - } - } - } - } - nextClient: - client = client->getNextClient(); - } - } - } - } + if ((rc == -1 || rc == -2) + && (client->isActive() + || client->isSleep() + || client->isAwake())) + { + /* disconnect the client */ + packet = new MQTTGWPacket(); + packet->setHeader(DISCONNECT); + ev = new Event(); + ev->setBrokerRecvEvent(client, packet); + _gateway->getPacketEventQue()->post(ev); + } + } + } + } + nextClient: client = client->getNextClient(); + } + } + } + } } /** @@ -186,35 +200,43 @@ void BrokerRecvTask::run(void) */ int BrokerRecvTask::log(Client* client, MQTTGWPacket* packet) { - char pbuf[(SIZE_OF_LOG_PACKET + 5 )* 3]; - char msgId[6]; - int rc = 0; + char pbuf[(SIZE_OF_LOG_PACKET + 5) * 3]; + char msgId[6]; + int rc = 0; - switch (packet->getType()) - { - case CONNACK: - WRITELOG(FORMAT_Y_Y_W, currentDateTime(), packet->getName(), LEFTARROWB, client->getClientId(), packet->print(pbuf)); - break; - case PUBLISH: - WRITELOG(FORMAT_W_MSGID_Y_W_NL, currentDateTime(), packet->getName(), packet->getMsgId(msgId), LEFTARROWB, client->getClientId(), packet->print(pbuf)); - break; - case PUBACK: - case PUBREC: - case PUBREL: - case PUBCOMP: - WRITELOG(FORMAT_W_MSGID_Y_W, currentDateTime(), packet->getName(), packet->getMsgId(msgId), LEFTARROWB, client->getClientId(), packet->print(pbuf)); - break; - case SUBACK: - case UNSUBACK: - WRITELOG(FORMAT_W_MSGID_Y_W, currentDateTime(), packet->getName(), packet->getMsgId(msgId), LEFTARROWB, client->getClientId(), packet->print(pbuf)); - break; - case PINGRESP: - WRITELOG(FORMAT_Y_Y_W, currentDateTime(), packet->getName(), LEFTARROWB, client->getClientId(), packet->print(pbuf)); - break; - default: - WRITELOG("Type=%x\n", packet->getType()); - rc = -1; - break; - } - return rc; + switch (packet->getType()) + { + case CONNACK: + WRITELOG(FORMAT_Y_Y_W, currentDateTime(), packet->getName(), LEFTARROWB, + client->getClientId(), packet->print(pbuf)); + break; + case PUBLISH: + WRITELOG(FORMAT_W_MSGID_Y_W_NL, currentDateTime(), packet->getName(), + packet->getMsgId(msgId), LEFTARROWB, client->getClientId(), + packet->print(pbuf)); + break; + case PUBACK: + case PUBREC: + case PUBREL: + case PUBCOMP: + WRITELOG(FORMAT_W_MSGID_Y_W, currentDateTime(), packet->getName(), + packet->getMsgId(msgId), LEFTARROWB, client->getClientId(), + packet->print(pbuf)); + break; + case SUBACK: + case UNSUBACK: + WRITELOG(FORMAT_W_MSGID_Y_W, currentDateTime(), packet->getName(), + packet->getMsgId(msgId), LEFTARROWB, client->getClientId(), + packet->print(pbuf)); + break; + case PINGRESP: + WRITELOG(FORMAT_Y_Y_W, currentDateTime(), packet->getName(), LEFTARROWB, + client->getClientId(), packet->print(pbuf)); + break; + default: + WRITELOG("Type=%x\n", packet->getType()); + rc = -1; + break; + } + return rc; } diff --git a/MQTTSNGateway/src/MQTTSNGWBrokerRecvTask.h b/MQTTSNGateway/src/MQTTSNGWBrokerRecvTask.h index 4177015..ae532b7 100644 --- a/MQTTSNGateway/src/MQTTSNGWBrokerRecvTask.h +++ b/MQTTSNGateway/src/MQTTSNGWBrokerRecvTask.h @@ -28,21 +28,20 @@ namespace MQTTSNGW class BrokerRecvTask: public Thread { MAGIC_WORD_FOR_THREAD; - ; + public: - BrokerRecvTask(Gateway* gateway); - ~BrokerRecvTask(); - void initialize(int argc, char** argv); - void run(void); + BrokerRecvTask(Gateway* gateway); + ~BrokerRecvTask(); + void initialize(int argc, char** argv); + void run(void); private: - int log(Client*, MQTTGWPacket*); + int log(Client*, MQTTGWPacket*); - Gateway* _gateway; - LightIndicator* _light; + Gateway* _gateway; + LightIndicator* _light; }; } - #endif /* MQTTSNGWBROKERRECVTASK_H_ */ diff --git a/MQTTSNGateway/src/MQTTSNGWBrokerSendTask.cpp b/MQTTSNGateway/src/MQTTSNGWBrokerSendTask.cpp index ff58a8d..ebe8a3c 100644 --- a/MQTTSNGateway/src/MQTTSNGWBrokerSendTask.cpp +++ b/MQTTSNGateway/src/MQTTSNGWBrokerSendTask.cpp @@ -33,10 +33,10 @@ char* currentDateTime(); =====================================*/ BrokerSendTask::BrokerSendTask(Gateway* gateway) { - _gateway = gateway; - _gateway->attach((Thread*)this); - _gwparams = nullptr; - _light = nullptr; + _gateway = gateway; + _gateway->attach((Thread*) this); + _gwparams = nullptr; + _light = nullptr; } BrokerSendTask::~BrokerSendTask() @@ -49,8 +49,8 @@ BrokerSendTask::~BrokerSendTask() */ void BrokerSendTask::initialize(int argc, char** argv) { - _gwparams = _gateway->getGWParams(); - _light = _gateway->getLightIndicator(); + _gwparams = _gateway->getGWParams(); + _light = _gateway->getLightIndicator(); } /** @@ -58,132 +58,149 @@ void BrokerSendTask::initialize(int argc, char** argv) */ void BrokerSendTask::run() { - Event* ev = nullptr; - MQTTGWPacket* packet = nullptr; - Client* client = nullptr; - AdapterManager* adpMgr = _gateway->getAdapterManager(); - int rc = 0; + Event* ev = nullptr; + MQTTGWPacket* packet = nullptr; + Client* client = nullptr; + AdapterManager* adpMgr = _gateway->getAdapterManager(); + int rc = 0; - while (true) - { - ev = _gateway->getBrokerSendQue()->wait(); + while (true) + { + ev = _gateway->getBrokerSendQue()->wait(); - if ( ev->getEventType() == EtStop ) - { - WRITELOG("\n%s BrokerSendTask stopped.", currentDateTime()); - delete ev; - return; - } + if (ev->getEventType() == EtStop) + { + WRITELOG("\n%s BrokerSendTask stopped.", currentDateTime()); + delete ev; + return; + } - if ( ev->getEventType() == EtBrokerSend) - { - client = ev->getClient(); - packet = ev->getMQTTGWPacket(); + if (ev->getEventType() == EtBrokerSend) + { + client = ev->getClient(); + packet = ev->getMQTTGWPacket(); - /* Check Client is managed by Adapters */ - client = adpMgr->getClient(client); + /* Check Client is managed by Adapters */ + client = adpMgr->getClient(client); - if ( packet->getType() == CONNECT && client->getNetwork()->isValid() ) - { - client->getNetwork()->close(); - } + if (packet->getType() == CONNECT && client->getNetwork()->isValid()) + { + client->getNetwork()->close(); + } - if ( !client->getNetwork()->isValid() ) - { - /* connect to the broker and send a packet */ + if (!client->getNetwork()->isValid()) + { + /* connect to the broker and send a packet */ - if (client->isSecureNetwork()) - { - rc = client->getNetwork()->connect((const char*)_gwparams->brokerName, (const char*)_gwparams->portSecure, (const char*)_gwparams->rootCApath, - (const char*)_gwparams->rootCAfile, (const char*)_gwparams->certKey, (const char*)_gwparams->privateKey); - } - else - { - rc = client->getNetwork()->connect((const char*)_gwparams->brokerName, (const char*)_gwparams->port); - } + if (client->isSecureNetwork()) + { + rc = client->getNetwork()->connect( + (const char*) _gwparams->brokerName, + (const char*) _gwparams->portSecure, + (const char*) _gwparams->rootCApath, + (const char*) _gwparams->rootCAfile, + (const char*) _gwparams->certKey, + (const char*) _gwparams->privateKey); + } + else + { + rc = client->getNetwork()->connect( + (const char*) _gwparams->brokerName, + (const char*) _gwparams->port); + } - if ( !rc ) - { - /* disconnect the broker and the client */ - WRITELOG("%s BrokerSendTask: %s can't connect to the broker. errno=%d %s %s\n", - ERRMSG_HEADER, client->getClientId(), errno, strerror(errno), ERRMSG_FOOTER); - delete ev; - client->getNetwork()->close(); - continue; - } - } + if (!rc) + { + /* disconnect the broker and the client */ + WRITELOG( + "%s BrokerSendTask: %s can't connect to the broker. errno=%d %s %s\n", + ERRMSG_HEADER, client->getClientId(), errno, + strerror(errno), ERRMSG_FOOTER); + delete ev; + client->getNetwork()->close(); + continue; + } + } - /* send a packet */ - _light->blueLight(true); - if ( (rc = packet->send(client->getNetwork())) > 0 ) - { - if ( packet->getType() == CONNECT ) - { - client->connectSended(); - } - else if ( packet->getType() == DISCONNECT ) - { - client->getNetwork()->close(); - client->disconnected(); - } - log(client, packet); - } - else - { - WRITELOG("%s BrokerSendTask: %s can't send a packet to the broker. errno=%d %s %s\n", - ERRMSG_HEADER, client->getClientId(), rc == -1 ? errno : 0, strerror(errno), ERRMSG_FOOTER); - if ( errno != EBADF ) - { - client->getNetwork()->close(); - } + /* send a packet */ + _light->blueLight(true); + if ((rc = packet->send(client->getNetwork())) > 0) + { + if (packet->getType() == CONNECT) + { + client->connectSended(); + } + else if (packet->getType() == DISCONNECT) + { + client->getNetwork()->close(); + client->disconnected(); + } + log(client, packet); + } + else + { + WRITELOG( + "%s BrokerSendTask: %s can't send a packet to the broker. errno=%d %s %s\n", + ERRMSG_HEADER, client->getClientId(), + rc == -1 ? errno : 0, strerror(errno), ERRMSG_FOOTER); + if ( errno != EBADF) + { + client->getNetwork()->close(); + } - /* Disconnect the client */ - packet = new MQTTGWPacket(); - packet->setHeader(DISCONNECT); - Event* ev1 = new Event(); - ev1->setBrokerRecvEvent(client, packet); - _gateway->getPacketEventQue()->post(ev1); - } + /* Disconnect the client */ + packet = new MQTTGWPacket(); + packet->setHeader(DISCONNECT); + Event* ev1 = new Event(); + ev1->setBrokerRecvEvent(client, packet); + _gateway->getPacketEventQue()->post(ev1); + } - _light->blueLight(false); - } - delete ev; - } + _light->blueLight(false); + } + delete ev; + } } - /** * write message content into stdout or Ringbuffer */ void BrokerSendTask::log(Client* client, MQTTGWPacket* packet) { - char pbuf[(SIZE_OF_LOG_PACKET + 5 )* 3]; - char msgId[6]; + char pbuf[(SIZE_OF_LOG_PACKET + 5) * 3]; + char msgId[6]; - switch (packet->getType()) - { - case CONNECT: - WRITELOG(FORMAT_Y_Y_W, currentDateTime(), packet->getName(), RIGHTARROWB, client->getClientId(), packet->print(pbuf)); - break; - case PUBLISH: - WRITELOG(FORMAT_W_MSGID_Y_W, currentDateTime(), packet->getName(), packet->getMsgId(msgId), RIGHTARROWB, client->getClientId(), packet->print(pbuf)); - break; - case SUBSCRIBE: - case UNSUBSCRIBE: - case PUBACK: - case PUBREC: - case PUBREL: - case PUBCOMP: - WRITELOG(FORMAT_W_MSGID_Y_W, currentDateTime(), packet->getName(), packet->getMsgId(msgId), RIGHTARROWB, client->getClientId(), packet->print(pbuf)); - break; - case PINGREQ: - WRITELOG(FORMAT_Y_Y_W, currentDateTime(), packet->getName(), RIGHTARROWB, client->getClientId(), packet->print(pbuf)); - break; - case DISCONNECT: - WRITELOG(FORMAT_Y_Y_W, currentDateTime(), packet->getName(), RIGHTARROWB, client->getClientId(), packet->print(pbuf)); - break; - default: - break; - } + switch (packet->getType()) + { + case CONNECT: + WRITELOG(FORMAT_Y_Y_W, currentDateTime(), packet->getName(), + RIGHTARROWB, client->getClientId(), packet->print(pbuf)); + break; + case PUBLISH: + WRITELOG(FORMAT_W_MSGID_Y_W, currentDateTime(), packet->getName(), + packet->getMsgId(msgId), RIGHTARROWB, client->getClientId(), + packet->print(pbuf)); + break; + case SUBSCRIBE: + case UNSUBSCRIBE: + case PUBACK: + case PUBREC: + case PUBREL: + case PUBCOMP: + WRITELOG(FORMAT_W_MSGID_Y_W, currentDateTime(), packet->getName(), + packet->getMsgId(msgId), RIGHTARROWB, client->getClientId(), + packet->print(pbuf)); + break; + case PINGREQ: + WRITELOG(FORMAT_Y_Y_W, currentDateTime(), packet->getName(), + RIGHTARROWB, client->getClientId(), packet->print(pbuf)); + break; + case DISCONNECT: + WRITELOG(FORMAT_Y_Y_W, currentDateTime(), packet->getName(), + RIGHTARROWB, client->getClientId(), packet->print(pbuf)); + break; + default: + break; + } } diff --git a/MQTTSNGateway/src/MQTTSNGWBrokerSendTask.h b/MQTTSNGateway/src/MQTTSNGWBrokerSendTask.h index 8244112..7361692 100644 --- a/MQTTSNGateway/src/MQTTSNGWBrokerSendTask.h +++ b/MQTTSNGateway/src/MQTTSNGWBrokerSendTask.h @@ -25,22 +25,22 @@ namespace MQTTSNGW class Adapter; /*===================================== - Class BrokerSendTask + Class BrokerSendTask =====================================*/ -class BrokerSendTask : public Thread +class BrokerSendTask: public Thread { - MAGIC_WORD_FOR_THREAD; - friend AdapterManager; +MAGIC_WORD_FOR_THREAD; + friend AdapterManager; public: - BrokerSendTask(Gateway* gateway); - ~BrokerSendTask(); - void initialize(int argc, char** argv); - void run(); + BrokerSendTask(Gateway* gateway); + ~BrokerSendTask(); + void initialize(int argc, char** argv); + void run(); private: - void log(Client*, MQTTGWPacket*); - Gateway* _gateway; - GatewayParams* _gwparams; - LightIndicator* _light; + void log(Client*, MQTTGWPacket*); + Gateway* _gateway; + GatewayParams* _gwparams; + LightIndicator* _light; }; } diff --git a/MQTTSNGateway/src/MQTTSNGWClient.cpp b/MQTTSNGateway/src/MQTTSNGWClient.cpp index 746f1af..a971bc2 100644 --- a/MQTTSNGateway/src/MQTTSNGWClient.cpp +++ b/MQTTSNGateway/src/MQTTSNGWClient.cpp @@ -28,104 +28,107 @@ using namespace MQTTSNGW; char* currentDateTime(void); - /*===================================== Class Client =====================================*/ -static const char* theClientStatus[] = { "Disconnected", "TryConnecting", "Connecting", "Active", "Asleep", "Awake", "Lost" }; +static const char* theClientStatus[] = +{ "Disconnected", "TryConnecting", "Connecting", "Active", "Asleep", "Awake", + "Lost" }; Client::Client(bool secure) { - _packetId = 0; - _snMsgId = 0; - _status = Cstat_Disconnected; - _keepAliveMsec = 0; - _topics = new Topics(); - _clientId = nullptr; - _willTopic = nullptr; - _willMsg = nullptr; - _connectData = MQTTPacket_Connect_Initializer; - _network = new Network(secure); - _secureNetwork = secure; - _sensorNetype = true; - _connAck = nullptr; - _waitWillMsgFlg = false; - _sessionStatus = false; - _prevClient = nullptr; - _nextClient = nullptr; - _clientSleepPacketQue.setMaxSize(MAX_SAVED_PUBLISH); - _proxyPacketQue.setMaxSize(MAX_SAVED_PUBLISH); - _hasPredefTopic = false; - _holdPingRequest = false; - _forwarder = nullptr; - _clientType = Ctype_Regular; + _packetId = 0; + _snMsgId = 0; + _status = Cstat_Disconnected; + _keepAliveMsec = 0; + _topics = new Topics(); + _clientId = nullptr; + _willTopic = nullptr; + _willMsg = nullptr; + _connectData = MQTTPacket_Connect_Initializer; + _network = new Network(secure); + _secureNetwork = secure; + _sensorNetype = true; + _connAck = nullptr; + _waitWillMsgFlg = false; + _sessionStatus = false; + _prevClient = nullptr; + _nextClient = nullptr; + _clientSleepPacketQue.setMaxSize(MAX_SAVED_PUBLISH); + _proxyPacketQue.setMaxSize(MAX_SAVED_PUBLISH); + _hasPredefTopic = false; + _holdPingRequest = false; + _forwarder = nullptr; + _clientType = Ctype_Regular; } Client::~Client() { - if ( _topics ) - { - delete _topics; - } + if (_topics) + { + delete _topics; + } - if ( _clientId ) - { - free(_clientId); - } + if (_clientId) + { + free(_clientId); + } - if ( _willTopic ) - { - free(_willTopic); - } + if (_willTopic) + { + free(_willTopic); + } - if ( _willMsg ) - { - free(_willMsg); - } + if (_willMsg) + { + free(_willMsg); + } - if (_connAck) - { - delete _connAck; - } + if (_connAck) + { + delete _connAck; + } - if (_network) - { - delete _network; - } + if (_network) + { + delete _network; + } } TopicIdMapElement* Client::getWaitedPubTopicId(uint16_t msgId) { - return _waitedPubTopicIdMap.getElement(msgId); + return _waitedPubTopicIdMap.getElement(msgId); } TopicIdMapElement* Client::getWaitedSubTopicId(uint16_t msgId) { - return _waitedSubTopicIdMap.getElement(msgId); + return _waitedSubTopicIdMap.getElement(msgId); } MQTTGWPacket* Client::getClientSleepPacket() { - return _clientSleepPacketQue.getPacket(); + return _clientSleepPacketQue.getPacket(); } void Client::deleteFirstClientSleepPacket() { - _clientSleepPacketQue.pop(); + _clientSleepPacketQue.pop(); } int Client::setClientSleepPacket(MQTTGWPacket* packet) { - int rc = _clientSleepPacketQue.post(packet); - if ( rc ) - { - WRITELOG("%s %s is sleeping. the packet was saved.\n", currentDateTime(), _clientId); - } - else - { - WRITELOG("%s %s is sleeping but discard the packet.\n", currentDateTime(), _clientId); - } - return rc; + int rc = _clientSleepPacketQue.post(packet); + if (rc) + { + WRITELOG("%s %s is sleeping. the packet was saved.\n", + currentDateTime(), _clientId); + } + else + { + WRITELOG("%s %s is sleeping but discard the packet.\n", + currentDateTime(), _clientId); + } + return rc; } MQTTSNPacket* Client::getProxyPacket(void) @@ -141,64 +144,68 @@ void Client::deleteFirstProxyPacket() int Client::setProxyPacket(MQTTSNPacket* packet) { int rc = _proxyPacketQue.post(packet); - if ( rc ) + if (rc) { - WRITELOG("%s %s is Disconnected. the packet was saved.\n", currentDateTime(), _clientId); + WRITELOG("%s %s is Disconnected. the packet was saved.\n", + currentDateTime(), _clientId); } else { - WRITELOG("%s %s is Disconnected and discard the packet.\n", currentDateTime(), _clientId); + WRITELOG("%s %s is Disconnected and discard the packet.\n", + currentDateTime(), _clientId); } return rc; } Connect* Client::getConnectData(void) { - return &_connectData; + return &_connectData; } void Client::eraseWaitedPubTopicId(uint16_t msgId) { - _waitedPubTopicIdMap.erase(msgId); + _waitedPubTopicIdMap.erase(msgId); } void Client::eraseWaitedSubTopicId(uint16_t msgId) { - _waitedSubTopicIdMap.erase(msgId); + _waitedSubTopicIdMap.erase(msgId); } void Client::clearWaitedPubTopicId(void) { - _waitedPubTopicIdMap.clear(); + _waitedPubTopicIdMap.clear(); } void Client::clearWaitedSubTopicId(void) { - _waitedSubTopicIdMap.clear(); + _waitedSubTopicIdMap.clear(); } -void Client::setWaitedPubTopicId(uint16_t msgId, uint16_t topicId, MQTTSN_topicTypes type) +void Client::setWaitedPubTopicId(uint16_t msgId, uint16_t topicId, + MQTTSN_topicTypes type) { - _waitedPubTopicIdMap.add(msgId, topicId, type); + _waitedPubTopicIdMap.add(msgId, topicId, type); } -void Client::setWaitedSubTopicId(uint16_t msgId, uint16_t topicId, MQTTSN_topicTypes type) +void Client::setWaitedSubTopicId(uint16_t msgId, uint16_t topicId, + MQTTSN_topicTypes type) { - _waitedSubTopicIdMap.add(msgId, topicId, type); + _waitedSubTopicIdMap.add(msgId, topicId, type); } bool Client::checkTimeover(void) { - return (_status == Cstat_Active && _keepAliveTimer.isTimeup()); + return (_status == Cstat_Active && _keepAliveTimer.isTimeup()); } void Client::setKeepAlive(MQTTSNPacket* packet) { - MQTTSNPacket_connectData param; - if (packet->getCONNECT(¶m)) - { - _keepAliveMsec = param.duration * 1000UL; - _keepAliveTimer.start(_keepAliveMsec * 1.5); - } + MQTTSNPacket_connectData param; + if (packet->getCONNECT(¶m)) + { + _keepAliveMsec = param.duration * 1000UL; + _keepAliveTimer.start(_keepAliveMsec * 1.5); + } } void Client::setForwarder(Forwarder* forwarder) @@ -214,102 +221,102 @@ Forwarder* Client::getForwarder(void) void Client::setSessionStatus(bool status) { - _sessionStatus = status; + _sessionStatus = status; } bool Client::erasable(void) { - return _sessionStatus && !_hasPredefTopic && _forwarder == nullptr; + return _sessionStatus && !_hasPredefTopic && _forwarder == nullptr; } void Client::updateStatus(MQTTSNPacket* packet) { - if (((_status == Cstat_Disconnected) || (_status == Cstat_Lost)) && packet->getType() == MQTTSN_CONNECT) - { - setKeepAlive(packet); - } - else if (_status == Cstat_Active) - { - switch (packet->getType()) - { - case MQTTSN_PINGREQ: - case MQTTSN_PUBLISH: - case MQTTSN_SUBSCRIBE: - case MQTTSN_UNSUBSCRIBE: - case MQTTSN_PUBACK: - case MQTTSN_PUBCOMP: - case MQTTSN_PUBREL: - case MQTTSN_PUBREC: - if ( _clientType != Ctype_Proxy ) - { - _keepAliveTimer.start(_keepAliveMsec * 1.5); - } - break; - case MQTTSN_DISCONNECT: - uint16_t duration; - packet->getDISCONNECT(&duration); - if (duration) - { - _status = Cstat_Asleep; - } - else - { - disconnected(); - } - break; - default: - break; - } - } - else if (_status == Cstat_Awake || _status == Cstat_Asleep) - { - switch (packet->getType()) - { - case MQTTSN_CONNECT: - _status = Cstat_Active; - break; - case MQTTSN_DISCONNECT: - disconnected(); - break; - case MQTTSN_PINGREQ: - _status = Cstat_Awake; - break; - case MQTTSN_PINGRESP: - _status = Cstat_Asleep; - break; - default: - break; - } - } - DEBUGLOG("Client Status = %s\n", theClientStatus[_status]); + if (((_status == Cstat_Disconnected) || (_status == Cstat_Lost)) + && packet->getType() == MQTTSN_CONNECT) + { + setKeepAlive(packet); + } + else if (_status == Cstat_Active) + { + switch (packet->getType()) + { + case MQTTSN_PINGREQ: + case MQTTSN_PUBLISH: + case MQTTSN_SUBSCRIBE: + case MQTTSN_UNSUBSCRIBE: + case MQTTSN_PUBACK: + case MQTTSN_PUBCOMP: + case MQTTSN_PUBREL: + case MQTTSN_PUBREC: + if (_clientType != Ctype_Proxy) + { + _keepAliveTimer.start(_keepAliveMsec * 1.5); + } + break; + case MQTTSN_DISCONNECT: + uint16_t duration; + packet->getDISCONNECT(&duration); + if (duration) + { + _status = Cstat_Asleep; + } + else + { + disconnected(); + } + break; + default: + break; + } + } + else if (_status == Cstat_Awake || _status == Cstat_Asleep) + { + switch (packet->getType()) + { + case MQTTSN_CONNECT: + _status = Cstat_Active; + break; + case MQTTSN_DISCONNECT: + disconnected(); + break; + case MQTTSN_PINGREQ: + _status = Cstat_Awake; + break; + case MQTTSN_PINGRESP: + _status = Cstat_Asleep; + break; + default: + break; + } + } DEBUGLOG("Client Status = %s\n", theClientStatus[_status]); } void Client::updateStatus(ClientStatus stat) { - _status = stat; + _status = stat; } void Client::connectSended() { - _status = Cstat_Connecting; + _status = Cstat_Connecting; } void Client::connackSended(int rc) { - if (rc == MQTTSN_RC_ACCEPTED) - { - _status = Cstat_Active; - } - else - { - disconnected(); - } + if (rc == MQTTSN_RC_ACCEPTED) + { + _status = Cstat_Active; + } + else + { + disconnected(); + } } void Client::disconnected(void) { - _status = Cstat_Disconnected; - _waitWillMsgFlg = false; + _status = Cstat_Disconnected; + _waitWillMsgFlg = false; } void Client::tryConnect(void) @@ -319,64 +326,64 @@ void Client::tryConnect(void) bool Client::isConnectSendable(void) { - if ( _status == Cstat_Lost || _status == Cstat_TryConnecting ) - { - return false; - } - else - { - return true; - } + if (_status == Cstat_Lost || _status == Cstat_TryConnecting) + { + return false; + } + else + { + return true; + } } uint16_t Client::getNextPacketId(void) { - _packetId++; - if ( _packetId == 0xffff ) - { - _packetId = 1; - } - return _packetId; + _packetId++; + if (_packetId == 0xffff) + { + _packetId = 1; + } + return _packetId; } uint8_t Client::getNextSnMsgId(void) { - _snMsgId++; - if (_snMsgId == 0) - { - _snMsgId++; - } - return _snMsgId; + _snMsgId++; + if (_snMsgId == 0) + { + _snMsgId++; + } + return _snMsgId; } Topics* Client::getTopics(void) { - return _topics; + return _topics; } Network* Client::getNetwork(void) { - return _network; + return _network; } void Client::setClientAddress(SensorNetAddress* sensorNetAddr) { - _sensorNetAddr = *sensorNetAddr; + _sensorNetAddr = *sensorNetAddr; } SensorNetAddress* Client::getSensorNetAddress(void) { - return &_sensorNetAddr; + return &_sensorNetAddr; } void Client::setSensorNetType(bool stable) { - _sensorNetype = stable; + _sensorNetype = stable; } void Client::setTopics(Topics* topics) { - _topics = topics; + _topics = topics; } ClientStatus Client::getClientStatus(void) @@ -386,32 +393,32 @@ ClientStatus Client::getClientStatus(void) void Client::setWaitWillMsgFlg(bool flg) { - _waitWillMsgFlg = flg; + _waitWillMsgFlg = flg; } bool Client::isWaitWillMsg(void) { - return _waitWillMsgFlg; + return _waitWillMsgFlg; } bool Client::isDisconnect(void) { - return (_status == Cstat_Disconnected); + return (_status == Cstat_Disconnected); } bool Client::isActive(void) { - return (_status == Cstat_Active); + return (_status == Cstat_Active); } bool Client::isSleep(void) { - return (_status == Cstat_Asleep); + return (_status == Cstat_Asleep); } bool Client::isAwake(void) { - return (_status == Cstat_Awake); + return (_status == Cstat_Awake); } bool Client::isConnecting(void) @@ -421,94 +428,94 @@ bool Client::isConnecting(void) bool Client::isSecureNetwork(void) { - return _secureNetwork; + return _secureNetwork; } bool Client::isSensorNetStable(void) { - return _sensorNetype; + return _sensorNetype; } WaitREGACKPacketList* Client::getWaitREGACKPacketList() { - return &_waitREGACKList; + return &_waitREGACKList; } Client* Client::getNextClient(void) { - return _nextClient; + return _nextClient; } void Client::setClientId(MQTTSNString id) { - if ( _clientId ) - { - free(_clientId); - } + if (_clientId) + { + free(_clientId); + } - if ( id.cstring ) - { - _clientId = (char*)calloc(strlen(id.cstring) + 1, 1); - memcpy(_clientId, id.cstring, strlen(id.cstring)); - } - else - { + if (id.cstring) + { + _clientId = (char*) calloc(strlen(id.cstring) + 1, 1); + memcpy(_clientId, id.cstring, strlen(id.cstring)); + } + else + { /* save clientId into (char*)_clientId NULL terminated */ - _clientId = (char*)calloc(MQTTSNstrlen(id) + 1, 1); - unsigned char* ptr = (unsigned char*)_clientId; - writeMQTTSNString((unsigned char**)&ptr, id); - } + _clientId = (char*) calloc(MQTTSNstrlen(id) + 1, 1); + unsigned char* ptr = (unsigned char*) _clientId; + writeMQTTSNString((unsigned char**) &ptr, id); + } } void Client::setWillTopic(MQTTSNString willTopic) { - if ( _willTopic ) - { - free(_willTopic); - } + if (_willTopic) + { + free(_willTopic); + } - _willTopic = (char*)calloc(MQTTSNstrlen(willTopic) + 1, 1); - /* save willTopic into (char*)_willTopic with NULL termination */ - unsigned char* ptr = (unsigned char*)_willTopic; - writeMQTTSNString((unsigned char**)&ptr, willTopic); + _willTopic = (char*) calloc(MQTTSNstrlen(willTopic) + 1, 1); + /* save willTopic into (char*)_willTopic with NULL termination */ + unsigned char* ptr = (unsigned char*) _willTopic; + writeMQTTSNString((unsigned char**) &ptr, willTopic); } void Client::setWillMsg(MQTTSNString willMsg) { - if ( _willMsg) - { - free(_willMsg); - } + if (_willMsg) + { + free(_willMsg); + } - _willMsg = (char*)calloc(MQTTSNstrlen(willMsg) + 1, 1); - /* save willMsg into (char*)_willMsg with NULL termination */ - unsigned char* ptr = (unsigned char*)_willMsg; - writeMQTTSNString((unsigned char**)&ptr, willMsg); + _willMsg = (char*) calloc(MQTTSNstrlen(willMsg) + 1, 1); + /* save willMsg into (char*)_willMsg with NULL termination */ + unsigned char* ptr = (unsigned char*) _willMsg; + writeMQTTSNString((unsigned char**) &ptr, willMsg); } char* Client::getClientId(void) { - return _clientId; + return _clientId; } char* Client::getWillTopic(void) { - return _willTopic; + return _willTopic; } char* Client::getWillMsg(void) { - return _willMsg; + return _willMsg; } const char* Client::getStatus(void) { - return theClientStatus[_status]; + return theClientStatus[_status]; } bool Client::isQoSm1Proxy(void) { - return _clientType == Ctype_Proxy; + return _clientType == Ctype_Proxy; } bool Client::isForwarded(void) @@ -528,23 +535,23 @@ bool Client::isAggregater(void) void Client::setAdapterType(AdapterType type) { - switch ( type ) + switch (type) { case Atype_QoSm1Proxy: - _clientType = Ctype_Proxy; - break; + _clientType = Ctype_Proxy; + break; case Atype_Aggregater: - _clientType = Ctype_Aggregater; - break; + _clientType = Ctype_Aggregater; + break; default: - throw Exception("Client::setAdapterType(): Invalid Type."); - break; + throw Exception("Client::setAdapterType(): Invalid Type."); + break; } } bool Client::isAdapter(void) { - return _clientType == Ctype_Proxy || _clientType == Ctype_Aggregater; + return _clientType == Ctype_Proxy || _clientType == Ctype_Aggregater; } bool Client::isQoSm1(void) @@ -554,12 +561,12 @@ bool Client::isQoSm1(void) void Client::setQoSm1(void) { - _clientType = Ctype_QoS_1; + _clientType = Ctype_QoS_1; } void Client::setAggregated(void) { - _clientType = Ctype_Aggregated; + _clientType = Ctype_Aggregated; } void Client::holdPingRequest(void) @@ -577,22 +584,20 @@ bool Client::isHoldPingReqest(void) return _holdPingRequest; } - - /*===================================== Class WaitREGACKPacket =====================================*/ waitREGACKPacket::waitREGACKPacket(MQTTSNPacket* packet, uint16_t REGACKMsgId) { - _packet = packet; - _msgId = REGACKMsgId; - _next = nullptr; - _prev = nullptr; + _packet = packet; + _msgId = REGACKMsgId; + _next = nullptr; + _prev = nullptr; } waitREGACKPacket::~waitREGACKPacket() { - delete _packet; + delete _packet; } /*===================================== @@ -601,89 +606,89 @@ waitREGACKPacket::~waitREGACKPacket() WaitREGACKPacketList::WaitREGACKPacketList() { - _first = nullptr; - _end = nullptr; - _cnt = 0; + _first = nullptr; + _end = nullptr; + _cnt = 0; } WaitREGACKPacketList::~WaitREGACKPacketList() { - waitREGACKPacket* p = _first; - while (p) - { - waitREGACKPacket* q = p->_next; - delete p; - p = q; - } + waitREGACKPacket* p = _first; + while (p) + { + waitREGACKPacket* q = p->_next; + delete p; + p = q; + } } int WaitREGACKPacketList::setPacket(MQTTSNPacket* packet, uint16_t REGACKMsgId) { - waitREGACKPacket* elm = new waitREGACKPacket(packet, REGACKMsgId); - if (elm == nullptr) - { - return 0; - } + waitREGACKPacket* elm = new waitREGACKPacket(packet, REGACKMsgId); + if (elm == nullptr) + { + return 0; + } - if (_first == nullptr) - { - _first = elm; - _end = elm; - } - else - { - _end->_next = elm; - elm->_prev = _end; - _end = elm; - } - _cnt++; - return 1; + if (_first == nullptr) + { + _first = elm; + _end = elm; + } + else + { + _end->_next = elm; + elm->_prev = _end; + _end = elm; + } + _cnt++; + return 1; } MQTTSNPacket* WaitREGACKPacketList::getPacket(uint16_t REGACKMsgId) { - waitREGACKPacket* p = _first; - while (p) - { - if (p->_msgId == REGACKMsgId) - { - return p->_packet; - } - p = p->_next; - } - return nullptr; + waitREGACKPacket* p = _first; + while (p) + { + if (p->_msgId == REGACKMsgId) + { + return p->_packet; + } + p = p->_next; + } + return nullptr; } void WaitREGACKPacketList::erase(uint16_t REGACKMsgId) { - waitREGACKPacket* p = _first; - while (p) - { - if (p->_msgId == REGACKMsgId) - { - if (p->_prev == nullptr) - { - _first = p->_next; + waitREGACKPacket* p = _first; + while (p) + { + if (p->_msgId == REGACKMsgId) + { + if (p->_prev == nullptr) + { + _first = p->_next; - } - else - { - p->_prev->_next = p->_next; - } - if (p->_next == nullptr) - { - _end = p->_prev; - } - else - { - p->_next->_prev = p->_prev; - } - _cnt--; + } + else + { + p->_prev->_next = p->_next; + } + if (p->_next == nullptr) + { + _end = p->_prev; + } + else + { + p->_next->_prev = p->_prev; + } + _cnt--; break; // Do not delete element. Element is deleted after sending to Client. - } - p = p->_next; - } + } + p = p->_next; + } } uint8_t WaitREGACKPacketList::getCount(void) @@ -691,4 +696,3 @@ uint8_t WaitREGACKPacketList::getCount(void) return _cnt; } - diff --git a/MQTTSNGateway/src/MQTTSNGWClient.h b/MQTTSNGateway/src/MQTTSNGWClient.h index 5071710..1774ad9 100644 --- a/MQTTSNGateway/src/MQTTSNGWClient.h +++ b/MQTTSNGateway/src/MQTTSNGWClient.h @@ -49,7 +49,6 @@ public: _que = new Que; } - ~PacketQue() { clear(); @@ -72,8 +71,7 @@ public: } } - int - post(T* packet) + int post(T* packet) { int rc; _mutex.lock(); @@ -113,8 +111,6 @@ private: Mutex _mutex; }; - - /*===================================== Class WaitREGACKPacket =====================================*/ @@ -151,20 +147,29 @@ private: waitREGACKPacket* _end; }; - - /*===================================== Class Client =====================================*/ typedef enum { - Cstat_Disconnected = 0, Cstat_TryConnecting, Cstat_Connecting, Cstat_Active, Cstat_Asleep, Cstat_Awake, Cstat_Lost + Cstat_Disconnected = 0, + Cstat_TryConnecting, + Cstat_Connecting, + Cstat_Active, + Cstat_Asleep, + Cstat_Awake, + Cstat_Lost } ClientStatus; typedef enum { - Ctype_Regular = 0, Ctype_Forwarded, Ctype_QoS_1, Ctype_Aggregated, Ctype_Proxy, Ctype_Aggregater -}ClientType; + Ctype_Regular = 0, + Ctype_Forwarded, + Ctype_QoS_1, + Ctype_Aggregated, + Ctype_Proxy, + Ctype_Aggregater +} ClientType; class Forwarder; @@ -191,10 +196,12 @@ public: void clearWaitedPubTopicId(void); void clearWaitedSubTopicId(void); - int setClientSleepPacket(MQTTGWPacket*); + int setClientSleepPacket(MQTTGWPacket*); int setProxyPacket(MQTTSNPacket* packet); - void setWaitedPubTopicId(uint16_t msgId, uint16_t topicId, MQTTSN_topicTypes type); - void setWaitedSubTopicId(uint16_t msgId, uint16_t topicId, MQTTSN_topicTypes type); + void setWaitedPubTopicId(uint16_t msgId, uint16_t topicId, + MQTTSN_topicTypes type); + void setWaitedSubTopicId(uint16_t msgId, uint16_t topicId, + MQTTSN_topicTypes type); bool checkTimeover(void); void updateStatus(MQTTSNPacket*); @@ -260,7 +267,7 @@ private: PacketQue _clientSleepPacketQue; PacketQue _proxyPacketQue; - WaitREGACKPacketList _waitREGACKList; + WaitREGACKPacketList _waitREGACKList; Topics* _topics; TopicIdMap _waitedPubTopicIdMap; @@ -285,7 +292,7 @@ private: uint8_t _snMsgId; Network* _network; // Broker - bool _secureNetwork; // SSL + bool _secureNetwork; // SSL bool _sensorNetype; // false: unstable network like a G3 SensorNetAddress _sensorNetAddr; @@ -299,7 +306,5 @@ private: Client* _prevClient; }; - - } #endif /* MQTTSNGWCLIENT_H_ */ diff --git a/MQTTSNGateway/src/MQTTSNGWClientList.cpp b/MQTTSNGateway/src/MQTTSNGWClientList.cpp index f164996..a1e0dfb 100644 --- a/MQTTSNGateway/src/MQTTSNGWClientList.cpp +++ b/MQTTSNGateway/src/MQTTSNGWClientList.cpp @@ -51,38 +51,41 @@ ClientList::~ClientList() void ClientList::initialize(bool aggregate) { - if (theGateway->getGWParams()->clientAuthentication ) + if (theGateway->getGWParams()->clientAuthentication) { - int type = TRANSPEARENT_TYPE; - if ( aggregate ) - { - type = AGGREGATER_TYPE; - } - setClientList(type); + int type = TRANSPEARENT_TYPE; + if (aggregate) + { + type = AGGREGATER_TYPE; + } + setClientList(type); _authorize = true; } - if ( theGateway->getGWParams()->predefinedTopic ) + if (theGateway->getGWParams()->predefinedTopic) { - setPredefinedTopics(aggregate); + setPredefinedTopics(aggregate); } } void ClientList::setClientList(int type) { - if (!createList(theGateway->getGWParams()->clientListName, type)) - { - throw Exception("ClientList::setClientList No client list defined by config file."); - } + if (!createList(theGateway->getGWParams()->clientListName, type)) + { + throw Exception( + "ClientList::setClientList No client list defined by config file."); + } } void ClientList::setPredefinedTopics(bool aggrecate) { - if ( !readPredefinedList(theGateway->getGWParams()->predefinedTopicFileName, aggrecate) ) - { - throw Exception("ClientList::setPredefinedTopics No predefindTopi list defined by config file."); + if (!readPredefinedList(theGateway->getGWParams()->predefinedTopicFileName, + aggrecate)) + { + throw Exception( + "ClientList::setPredefinedTopics No predefindTopi list defined by config file."); - } + } } /** @@ -148,17 +151,19 @@ bool ClientList::createList(const char* fileName, int type) forwarder = (data.find("forwarder") != string::npos); secure = (data.find("secureConnection") != string::npos); stable = !(data.find("unstableLine") != string::npos); - if ( (qos_1 && type == QOSM1PROXY_TYPE) || (!qos_1 && type == AGGREGATER_TYPE) ) + if ((qos_1 && type == QOSM1PROXY_TYPE) + || (!qos_1 && type == AGGREGATER_TYPE)) { - createClient(&netAddr, &clientId, stable, secure, type); + createClient(&netAddr, &clientId, stable, secure, type); } - else if ( forwarder && type == FORWARDER_TYPE) + else if (forwarder && type == FORWARDER_TYPE) { - theGateway->getAdapterManager()->getForwarderList()->addForwarder(&netAddr, &clientId); + theGateway->getAdapterManager()->getForwarderList()->addForwarder( + &netAddr, &clientId); } - else if (type == TRANSPEARENT_TYPE ) + else if (type == TRANSPEARENT_TYPE) { - createClient(&netAddr, &clientId, stable, secure, type); + createClient(&netAddr, &clientId, stable, secure, type); } } else @@ -179,7 +184,8 @@ bool ClientList::readPredefinedList(const char* fileName, bool aggregate) FILE* fp; char buf[MAX_CLIENTID_LENGTH + 256]; size_t pos0, pos1; - MQTTSNString clientId = MQTTSNString_initializer;; + MQTTSNString clientId = MQTTSNString_initializer; + ; bool rc = false; if ((fp = fopen(fileName, "r")) != 0) @@ -201,12 +207,12 @@ bool ClientList::readPredefinedList(const char* fileName, bool aggregate) } pos0 = data.find_first_of(","); - pos1 = data.find(",", pos0 + 1) ; + pos1 = data.find(",", pos0 + 1); string id = data.substr(0, pos0); clientId.cstring = strdup(id.c_str()); - string topicName = data.substr(pos0 + 1, pos1 - pos0 -1); + string topicName = data.substr(pos0 + 1, pos1 - pos0 - 1); uint16_t topicID = stoul(data.substr(pos1 + 1)); - createPredefinedTopic( &clientId, topicName, topicID, aggregate); + createPredefinedTopic(&clientId, topicName, topicID, aggregate); free(clientId.cstring); } fclose(fp); @@ -214,7 +220,8 @@ bool ClientList::readPredefinedList(const char* fileName, bool aggregate) } else { - WRITELOG("ClientList can not open the Predefined Topic List. %s\n", fileName); + WRITELOG("ClientList can not open the Predefined Topic List. %s\n", + fileName); return false; } return rc; @@ -222,7 +229,7 @@ bool ClientList::readPredefinedList(const char* fileName, bool aggregate) void ClientList::erase(Client*& client) { - if ( !_authorize && client->erasable()) + if (!_authorize && client->erasable()) { _mutex.lock(); Client* prev = client->_prevClient; @@ -247,7 +254,7 @@ void ClientList::erase(Client*& client) } _clientCnt--; Forwarder* fwd = client->getForwarder(); - if ( fwd ) + if (fwd) { fwd->eraseClient(client); } @@ -259,14 +266,14 @@ void ClientList::erase(Client*& client) Client* ClientList::getClient(SensorNetAddress* addr) { - if ( addr ) + if (addr) { _mutex.lock(); Client* client = _firstClient; while (client != nullptr) { - if (client->getSensorNetAddress()->isMatch(addr) ) + if (client->getSensorNetAddress()->isMatch(addr)) { _mutex.unlock(); return client; @@ -280,38 +287,38 @@ Client* ClientList::getClient(SensorNetAddress* addr) Client* ClientList::getClient(int index) { - Client* client = _firstClient; - int p = 0; - while ( client != nullptr ) - { - if ( p == index ) - { - return client; - } - else - { - client = client->_nextClient; - p++; - } - } - return nullptr; + Client* client = _firstClient; + int p = 0; + while (client != nullptr) + { + if (p == index) + { + return client; + } + else + { + client = client->_nextClient; + p++; + } + } + return nullptr; } - Client* ClientList::getClient(MQTTSNString* clientId) { _mutex.lock(); Client* client = _firstClient; - const char* clID =clientId->cstring; + const char* clID = clientId->cstring; - if (clID == nullptr ) + if (clID == nullptr) { clID = clientId->lenstring.data; } while (client != nullptr) { - if (strncmp((const char*)client->getClientId(), clID, MQTTSNstrlen(*clientId)) == 0 ) + if (strncmp((const char*) client->getClientId(), clID, + MQTTSNstrlen(*clientId)) == 0) { _mutex.unlock(); return client; @@ -322,51 +329,53 @@ Client* ClientList::getClient(MQTTSNString* clientId) return 0; } -Client* ClientList::createClient(SensorNetAddress* addr, MQTTSNString* clientId, int type) +Client* ClientList::createClient(SensorNetAddress* addr, MQTTSNString* clientId, + int type) { - return createClient(addr, clientId, false, false, type); + return createClient(addr, clientId, false, false, type); } -Client* ClientList::createClient(SensorNetAddress* addr, MQTTSNString* clientId, bool unstableLine, bool secure, int type) +Client* ClientList::createClient(SensorNetAddress* addr, MQTTSNString* clientId, + bool unstableLine, bool secure, int type) { Client* client = nullptr; /* anonimous clients */ - if ( _clientCnt > MAX_CLIENTS ) + if (_clientCnt > MAX_CLIENTS) { return 0; // full of clients } client = getClient(addr); - if ( client ) + if (client) { return client; } /* creat a new client */ client = new Client(secure); - if ( addr ) + if (addr) { client->setClientAddress(addr); } client->setSensorNetType(unstableLine); - if ( MQTTSNstrlen(*clientId) ) + if (MQTTSNstrlen(*clientId)) { client->setClientId(*clientId); } else { - MQTTSNString dummyId MQTTSNString_initializer; + MQTTSNString dummyId MQTTSNString_initializer; dummyId.cstring = strdup(""); client->setClientId(dummyId); - free(dummyId.cstring); + free(dummyId.cstring); } - if ( type == AGGREGATER_TYPE ) + if (type == AGGREGATER_TYPE) { - client->setAggregated(); + client->setAggregated(); } - else if ( type == QOSM1PROXY_TYPE ) + else if (type == QOSM1PROXY_TYPE) { client->setQoSm1(); } @@ -374,7 +383,7 @@ Client* ClientList::createClient(SensorNetAddress* addr, MQTTSNString* clientId, _mutex.lock(); /* add the list */ - if ( _firstClient == nullptr ) + if (_firstClient == nullptr) { _firstClient = client; _endClient = client; @@ -390,66 +399,68 @@ Client* ClientList::createClient(SensorNetAddress* addr, MQTTSNString* clientId, return client; } -Client* ClientList::createPredefinedTopic( MQTTSNString* clientId, string topicName, uint16_t topicId, bool aggregate) +Client* ClientList::createPredefinedTopic(MQTTSNString* clientId, + string topicName, uint16_t topicId, bool aggregate) { - if ( topicId == 0 ) - { - WRITELOG("Invalid TopicId. Predefined Topic %s, TopicId is 0. \n", topicName.c_str()); - return nullptr; - } + if (topicId == 0) + { + WRITELOG("Invalid TopicId. Predefined Topic %s, TopicId is 0. \n", + topicName.c_str()); + return nullptr; + } - if ( strcmp(clientId->cstring, common_topic) == 0 ) - { - theGateway->getTopics()->add((const char*)topicName.c_str(), topicId); - return nullptr; - } - else - { - Client* client = getClient(clientId); + if (strcmp(clientId->cstring, common_topic) == 0) + { + theGateway->getTopics()->add((const char*) topicName.c_str(), topicId); + return nullptr; + } + else + { + Client* client = getClient(clientId); - if ( _authorize && client == nullptr ) - { - return nullptr; - } + if (_authorize && client == nullptr) + { + return nullptr; + } - /* anonimous clients */ - if ( _clientCnt > MAX_CLIENTS ) - { - return nullptr; // full of clients - } + /* anonimous clients */ + if (_clientCnt > MAX_CLIENTS) + { + return nullptr; // full of clients + } - if ( client == nullptr ) - { - /* creat a new client */ - client = new Client(); - client->setClientId(*clientId); - if ( aggregate ) - { - client->setAggregated(); - } - _mutex.lock(); + if (client == nullptr) + { + /* creat a new client */ + client = new Client(); + client->setClientId(*clientId); + if (aggregate) + { + client->setAggregated(); + } + _mutex.lock(); - /* add the list */ - if ( _firstClient == nullptr ) - { - _firstClient = client; - _endClient = client; - } - else - { - _endClient->_nextClient = client; - client->_prevClient = _endClient; - _endClient = client; - } - _clientCnt++; - _mutex.unlock(); - } + /* add the list */ + if (_firstClient == nullptr) + { + _firstClient = client; + _endClient = client; + } + else + { + _endClient->_nextClient = client; + client->_prevClient = _endClient; + _endClient = client; + } + _clientCnt++; + _mutex.unlock(); + } - // create Topic & Add it - client->getTopics()->add((const char*)topicName.c_str(), topicId); - client->_hasPredefTopic = true; - return client; - } + // create Topic & Add it + client->getTopics()->add((const char*) topicName.c_str(), topicId); + client->_hasPredefTopic = true; + return client; + } } uint16_t ClientList::getClientCount() @@ -462,4 +473,3 @@ bool ClientList::isAuthorized() return _authorize; } - diff --git a/MQTTSNGateway/src/MQTTSNGWClientList.h b/MQTTSNGateway/src/MQTTSNGWClientList.h index 135f365..e3542bb 100644 --- a/MQTTSNGateway/src/MQTTSNGWClientList.h +++ b/MQTTSNGateway/src/MQTTSNGWClientList.h @@ -43,8 +43,10 @@ public: void setClientList(int type); void setPredefinedTopics(bool aggregate); void erase(Client*&); - Client* createClient(SensorNetAddress* addr, MQTTSNString* clientId,int type); - Client* createClient(SensorNetAddress* addr, MQTTSNString* clientId, bool unstableLine, bool secure, int type); + Client* createClient(SensorNetAddress* addr, MQTTSNString* clientId, + int type); + Client* createClient(SensorNetAddress* addr, MQTTSNString* clientId, + bool unstableLine, bool secure, int type); bool createList(const char* fileName, int type); Client* getClient(SensorNetAddress* addr); Client* getClient(MQTTSNString* clientId); @@ -55,18 +57,16 @@ public: private: bool readPredefinedList(const char* fileName, bool _aggregate); - Gateway* _gateway {nullptr}; - Client* createPredefinedTopic( MQTTSNString* clientId, string topicName, uint16_t toipcId, bool _aggregate); + Gateway* _gateway { nullptr }; + Client* createPredefinedTopic(MQTTSNString* clientId, string topicName, + uint16_t toipcId, bool _aggregate); Client* _firstClient; Client* _endClient; Mutex _mutex; uint16_t _clientCnt; - bool _authorize {false}; + bool _authorize { false }; }; - } - - #endif /* MQTTSNGATEWAY_SRC_MQTTSNGWCLIENTLIST_H_ */ diff --git a/MQTTSNGateway/src/MQTTSNGWClientRecvTask.cpp b/MQTTSNGateway/src/MQTTSNGWClientRecvTask.cpp index 03f3415..49568b5 100644 --- a/MQTTSNGateway/src/MQTTSNGWClientRecvTask.cpp +++ b/MQTTSNGateway/src/MQTTSNGWClientRecvTask.cpp @@ -29,9 +29,9 @@ char* currentDateTime(void); =====================================*/ ClientRecvTask::ClientRecvTask(Gateway* gateway) { - _gateway = gateway; - _gateway->attach((Thread*)this); - _sensorNetwork = _gateway->getSensorNetwork(); + _gateway = gateway; + _gateway->attach((Thread*) this); + _sensorNetwork = _gateway->getSensorNetwork(); } ClientRecvTask::~ClientRecvTask() @@ -44,10 +44,10 @@ ClientRecvTask::~ClientRecvTask() */ void ClientRecvTask::initialize(int argc, char** argv) { - if ( _sensorNetwork->initialize() < 0 ) - { - throw Exception(" Can't open the sensor network.\n"); - } + if (_sensorNetwork->initialize() < 0) + { + throw Exception(" Can't open the sensor network.\n"); + } } /* @@ -57,214 +57,237 @@ void ClientRecvTask::initialize(int argc, char** argv) */ void ClientRecvTask::run() { - Event* ev = nullptr; - AdapterManager* adpMgr = _gateway->getAdapterManager(); - QoSm1Proxy* qosm1Proxy = adpMgr->getQoSm1Proxy(); - int clientType = adpMgr->isAggregaterActive() ? AGGREGATER_TYPE : TRANSPEARENT_TYPE; - ClientList* clientList = _gateway->getClientList(); - EventQue* packetEventQue = _gateway->getPacketEventQue(); + Event* ev = nullptr; + AdapterManager* adpMgr = _gateway->getAdapterManager(); + QoSm1Proxy* qosm1Proxy = adpMgr->getQoSm1Proxy(); + int clientType = + adpMgr->isAggregaterActive() ? AGGREGATER_TYPE : TRANSPEARENT_TYPE; + ClientList* clientList = _gateway->getClientList(); + EventQue* packetEventQue = _gateway->getPacketEventQue(); - char buf[128]; + char buf[128]; - while (true) - { - Client* client = nullptr; - Forwarder* fwd = nullptr; - WirelessNodeId nodeId; + while (true) + { + Client* client = nullptr; + Forwarder* fwd = nullptr; + WirelessNodeId nodeId; - MQTTSNPacket* packet = new MQTTSNPacket(); - int packetLen = packet->recv(_sensorNetwork); + MQTTSNPacket* packet = new MQTTSNPacket(); + int packetLen = packet->recv(_sensorNetwork); - if (CHK_SIGINT) - { - WRITELOG("\n%s ClientRecvTask stopped.", currentDateTime()); - delete packet; - return; - } + if (CHK_SIGINT) + { + WRITELOG("\n%s ClientRecvTask stopped.", currentDateTime()); + delete packet; + return; + } - if (packetLen < 2 ) - { - delete packet; - continue; - } + if (packetLen < 2) + { + delete packet; + continue; + } - if ( packet->getType() <= MQTTSN_ADVERTISE || packet->getType() == MQTTSN_GWINFO ) - { - delete packet; - continue; - } + if (packet->getType() <= MQTTSN_ADVERTISE + || packet->getType() == MQTTSN_GWINFO) + { + delete packet; + continue; + } - if ( packet->getType() == MQTTSN_SEARCHGW ) - { - /* write log and post Event */ - log(0, packet, 0); - ev = new Event(); - ev->setBrodcastEvent(packet); - packetEventQue->post(ev); - continue; - } + if (packet->getType() == MQTTSN_SEARCHGW) + { + /* write log and post Event */ + log(0, packet, 0); + ev = new Event(); + ev->setBrodcastEvent(packet); + packetEventQue->post(ev); + continue; + } + SensorNetAddress* senderAddr = + _gateway->getSensorNetwork()->getSenderAddress(); - SensorNetAddress* senderAddr = _gateway->getSensorNetwork()->getSenderAddress(); + if (packet->getType() == MQTTSN_ENCAPSULATED) + { + fwd = + _gateway->getAdapterManager()->getForwarderList()->getForwarder( + senderAddr); - if ( packet->getType() == MQTTSN_ENCAPSULATED ) - { - fwd = _gateway->getAdapterManager()->getForwarderList()->getForwarder(senderAddr); + if (fwd != nullptr) + { + MQTTSNString fwdName = MQTTSNString_initializer; + fwdName.cstring = const_cast(fwd->getName()); + log(0, packet, &fwdName); - if ( fwd != nullptr ) - { - MQTTSNString fwdName = MQTTSNString_initializer; - fwdName.cstring = const_cast( fwd->getName() ); - log(0, packet, &fwdName); + /* get the packet from the encapsulation message */ + MQTTSNGWEncapsulatedPacket encap; + encap.desirialize(packet->getPacketData(), + packet->getPacketLength()); + nodeId.setId(encap.getWirelessNodeId()); + client = fwd->getClient(&nodeId); + packet = encap.getMQTTSNPacket(); + } + } + else + { + /* Check the client belonging to QoS-1Proxy ? */ - /* get the packet from the encapsulation message */ - MQTTSNGWEncapsulatedPacket encap; - encap.desirialize(packet->getPacketData(), packet->getPacketLength()); - nodeId.setId( encap.getWirelessNodeId() ); - client = fwd->getClient(&nodeId); - packet = encap.getMQTTSNPacket(); - } - } - else - { - /* Check the client belonging to QoS-1Proxy ? */ + if (qosm1Proxy->isActive()) + { + const char* clientName = qosm1Proxy->getClientId(senderAddr); - if ( qosm1Proxy->isActive() ) - { - const char* clientName = qosm1Proxy->getClientId(senderAddr); + if (clientName != nullptr) + { + client = qosm1Proxy->getClient(); - if ( clientName != nullptr ) - { - client = qosm1Proxy->getClient(); + if (!packet->isQoSMinusPUBLISH()) + { + log(clientName, packet); + WRITELOG( + "%s %s %s can send only PUBLISH with QoS-1.%s\n", + ERRMSG_HEADER, clientName, + senderAddr->sprint(buf), ERRMSG_FOOTER); + delete packet; + continue; + } + } + } - if ( !packet->isQoSMinusPUBLISH() ) - { - log(clientName, packet); - WRITELOG("%s %s %s can send only PUBLISH with QoS-1.%s\n", ERRMSG_HEADER, clientName, senderAddr->sprint(buf), ERRMSG_FOOTER); - delete packet; - continue; - } - } - } + if (client == nullptr) + { + client = _gateway->getClientList()->getClient(senderAddr); + } + } - if ( client == nullptr ) - { - client = _gateway->getClientList()->getClient(senderAddr); - } - } + if (client != nullptr) + { + /* write log and post Event */ + log(client, packet, 0); + ev = new Event(); + ev->setClientRecvEvent(client, packet); + packetEventQue->post(ev); + } + else + { + /* new client */ + if (packet->getType() == MQTTSN_CONNECT) + { + MQTTSNPacket_connectData data; + memset(&data, 0, sizeof(MQTTSNPacket_connectData)); + if (!packet->getCONNECT(&data)) + { + log(0, packet, &data.clientID); + WRITELOG("%s CONNECT message form %s is incorrect.%s\n", + ERRMSG_HEADER, senderAddr->sprint(buf), + ERRMSG_FOOTER); + delete packet; + continue; + } - if ( client != nullptr ) - { - /* write log and post Event */ - log(client, packet, 0); - ev = new Event(); - ev->setClientRecvEvent(client,packet); - packetEventQue->post(ev); - } - else - { - /* new client */ - if (packet->getType() == MQTTSN_CONNECT) - { - MQTTSNPacket_connectData data; - memset(&data, 0, sizeof(MQTTSNPacket_connectData)); - if ( !packet->getCONNECT(&data) ) - { - log(0, packet, &data.clientID); - WRITELOG("%s CONNECT message form %s is incorrect.%s\n", ERRMSG_HEADER, senderAddr->sprint(buf), ERRMSG_FOOTER); - delete packet; - continue; - } + client = clientList->getClient(&data.clientID); - client = clientList->getClient(&data.clientID); - - if ( fwd != nullptr ) - { - if ( client == nullptr ) - { - /* create a new client */ - client = clientList->createClient(0, &data.clientID, clientType); - } - /* Add to a forwarded client list of forwarder. */ + if (fwd != nullptr) + { + if (client == nullptr) + { + /* create a new client */ + client = clientList->createClient(0, &data.clientID, + clientType); + } + /* Add to a forwarded client list of forwarder. */ fwd->addClient(client, &nodeId); - } - else - { - if ( client ) + } + else + { + if (client) { /* Authentication is not required */ - if ( _gateway->getGWParams()->clientAuthentication == false) - { - client->setClientAddress(senderAddr); - } + if (_gateway->getGWParams()->clientAuthentication + == false) + { + client->setClientAddress(senderAddr); + } } else { /* create a new client */ - client = clientList->createClient(senderAddr, &data.clientID, clientType); + client = clientList->createClient(senderAddr, + &data.clientID, clientType); } - } + } - log(client, packet, &data.clientID); + log(client, packet, &data.clientID); - if ( client == nullptr ) - { - WRITELOG("%s Client(%s) was rejected. CONNECT message has been discarded.%s\n", ERRMSG_HEADER, senderAddr->sprint(buf), ERRMSG_FOOTER); - delete packet; - continue; - } + if (client == nullptr) + { + WRITELOG( + "%s Client(%s) was rejected. CONNECT message has been discarded.%s\n", + ERRMSG_HEADER, senderAddr->sprint(buf), + ERRMSG_FOOTER); + delete packet; + continue; + } - /* post Client RecvEvent */ - ev = new Event(); - ev->setClientRecvEvent(client, packet); - packetEventQue->post(ev); - } - else - { - log(client, packet, 0); - if ( packet->getType() == MQTTSN_ENCAPSULATED ) - { - WRITELOG("%s MQTTSNGWClientRecvTask Forwarder(%s) is not declared by ClientList file. message has been discarded.%s\n", ERRMSG_HEADER, _sensorNetwork->getSenderAddress()->sprint(buf), ERRMSG_FOOTER); - } - else - { - WRITELOG("%s MQTTSNGWClientRecvTask Client(%s) is not connecting. message has been discarded.%s\n", ERRMSG_HEADER, senderAddr->sprint(buf), ERRMSG_FOOTER); - } - delete packet; - } - } - } + /* post Client RecvEvent */ + ev = new Event(); + ev->setClientRecvEvent(client, packet); + packetEventQue->post(ev); + } + else + { + log(client, packet, 0); + if (packet->getType() == MQTTSN_ENCAPSULATED) + { + WRITELOG( + "%s MQTTSNGWClientRecvTask Forwarder(%s) is not declared by ClientList file. message has been discarded.%s\n", + ERRMSG_HEADER, + _sensorNetwork->getSenderAddress()->sprint(buf), + ERRMSG_FOOTER); + } + else + { + WRITELOG( + "%s MQTTSNGWClientRecvTask Client(%s) is not connecting. message has been discarded.%s\n", + ERRMSG_HEADER, senderAddr->sprint(buf), + ERRMSG_FOOTER); + } + delete packet; + } + } + } } void ClientRecvTask::log(Client* client, MQTTSNPacket* packet, MQTTSNString* id) { - const char* clientId; - char cstr[MAX_CLIENTID_LENGTH + 1]; + const char* clientId; + char cstr[MAX_CLIENTID_LENGTH + 1]; - if ( id ) - { - if ( id->cstring ) - { - strncpy(cstr, id->cstring, strlen(id->cstring) ); - clientId = cstr; - } - else - { - memset((void*)cstr, 0, id->lenstring.len + 1); - strncpy(cstr, id->lenstring.data, id->lenstring.len ); + if (id) + { + if (id->cstring) + { + strncpy(cstr, id->cstring, strlen(id->cstring)); clientId = cstr; - } - } - else if ( client ) - { - clientId = client->getClientId(); - } - else - { - clientId = UNKNOWNCL; - } + } + else + { + memset((void*) cstr, 0, id->lenstring.len + 1); + strncpy(cstr, id->lenstring.data, id->lenstring.len); + clientId = cstr; + } + } + else if (client) + { + clientId = client->getClientId(); + } + else + { + clientId = UNKNOWNCL; + } - log(clientId, packet); + log(clientId, packet); } void ClientRecvTask::log(const char* clientId, MQTTSNPacket* packet) @@ -275,37 +298,46 @@ void ClientRecvTask::log(const char* clientId, MQTTSNPacket* packet) switch (packet->getType()) { case MQTTSN_SEARCHGW: - WRITELOG(FORMAT_Y_G_G_NL, currentDateTime(), packet->getName(), LEFTARROW, CLIENT, packet->print(pbuf)); + WRITELOG(FORMAT_Y_G_G_NL, currentDateTime(), packet->getName(), + LEFTARROW, CLIENT, packet->print(pbuf)); break; case MQTTSN_CONNECT: case MQTTSN_PINGREQ: - WRITELOG(FORMAT_Y_G_G_NL, currentDateTime(), packet->getName(), LEFTARROW, clientId, packet->print(pbuf)); + WRITELOG(FORMAT_Y_G_G_NL, currentDateTime(), packet->getName(), + LEFTARROW, clientId, packet->print(pbuf)); break; case MQTTSN_DISCONNECT: case MQTTSN_WILLTOPICUPD: case MQTTSN_WILLMSGUPD: case MQTTSN_WILLTOPIC: case MQTTSN_WILLMSG: - WRITELOG(FORMAT_Y_G_G, currentDateTime(), packet->getName(), LEFTARROW, clientId, packet->print(pbuf)); + WRITELOG(FORMAT_Y_G_G, currentDateTime(), packet->getName(), LEFTARROW, + clientId, packet->print(pbuf)); break; case MQTTSN_PUBLISH: case MQTTSN_REGISTER: case MQTTSN_SUBSCRIBE: case MQTTSN_UNSUBSCRIBE: - WRITELOG(FORMAT_G_MSGID_G_G_NL, currentDateTime(), packet->getName(), packet->getMsgId(msgId), LEFTARROW, clientId, packet->print(pbuf)); + WRITELOG(FORMAT_G_MSGID_G_G_NL, currentDateTime(), packet->getName(), + packet->getMsgId(msgId), LEFTARROW, clientId, + packet->print(pbuf)); break; case MQTTSN_REGACK: case MQTTSN_PUBACK: case MQTTSN_PUBREC: case MQTTSN_PUBREL: case MQTTSN_PUBCOMP: - WRITELOG(FORMAT_G_MSGID_G_G, currentDateTime(), packet->getName(), packet->getMsgId(msgId), LEFTARROW, clientId, packet->print(pbuf)); + WRITELOG(FORMAT_G_MSGID_G_G, currentDateTime(), packet->getName(), + packet->getMsgId(msgId), LEFTARROW, clientId, + packet->print(pbuf)); break; case MQTTSN_ENCAPSULATED: - WRITELOG(FORMAT_Y_G_G, currentDateTime(), packet->getName(), LEFTARROW, clientId, packet->print(pbuf)); - break; + WRITELOG(FORMAT_Y_G_G, currentDateTime(), packet->getName(), LEFTARROW, + clientId, packet->print(pbuf)); + break; default: - WRITELOG(FORMAT_W_NL, currentDateTime(), packet->getName(), LEFTARROW, clientId, packet->print(pbuf)); + WRITELOG(FORMAT_W_NL, currentDateTime(), packet->getName(), LEFTARROW, + clientId, packet->print(pbuf)); break; } } diff --git a/MQTTSNGateway/src/MQTTSNGWClientRecvTask.h b/MQTTSNGateway/src/MQTTSNGWClientRecvTask.h index 30a63e9..9428d3a 100644 --- a/MQTTSNGateway/src/MQTTSNGWClientRecvTask.h +++ b/MQTTSNGateway/src/MQTTSNGWClientRecvTask.h @@ -24,24 +24,24 @@ namespace MQTTSNGW class AdapterManager; /*===================================== - Class ClientRecvTask + Class ClientRecvTask =====================================*/ -class ClientRecvTask:public Thread +class ClientRecvTask: public Thread { - MAGIC_WORD_FOR_THREAD; - friend AdapterManager; +MAGIC_WORD_FOR_THREAD; + friend AdapterManager; public: - ClientRecvTask(Gateway*); - ~ClientRecvTask(void); - virtual void initialize(int argc, char** argv); - void run(void); + ClientRecvTask(Gateway*); + ~ClientRecvTask(void); + virtual void initialize(int argc, char** argv); + void run(void); private: - void log(Client*, MQTTSNPacket*, MQTTSNString* id); - void log(const char* clientId, MQTTSNPacket* packet); + void log(Client*, MQTTSNPacket*, MQTTSNString* id); + void log(const char* clientId, MQTTSNPacket* packet); - Gateway* _gateway; - SensorNetwork* _sensorNetwork; + Gateway* _gateway; + SensorNetwork* _sensorNetwork; }; } diff --git a/MQTTSNGateway/src/MQTTSNGWClientSendTask.cpp b/MQTTSNGateway/src/MQTTSNGWClientSendTask.cpp index b0af063..0734a5e 100644 --- a/MQTTSNGateway/src/MQTTSNGWClientSendTask.cpp +++ b/MQTTSNGateway/src/MQTTSNGWClientSendTask.cpp @@ -28,9 +28,9 @@ char* currentDateTime(void); =====================================*/ ClientSendTask::ClientSendTask(Gateway* gateway) { - _gateway = gateway; - _gateway->attach((Thread*)this); - _sensorNetwork = _gateway->getSensorNetwork(); + _gateway = gateway; + _gateway->attach((Thread*) this); + _sensorNetwork = _gateway->getSensorNetwork(); } ClientSendTask::~ClientSendTask() @@ -40,94 +40,106 @@ ClientSendTask::~ClientSendTask() void ClientSendTask::run() { - Client* client = nullptr; - MQTTSNPacket* packet = nullptr; - AdapterManager* adpMgr = _gateway->getAdapterManager(); - int rc = 0; + Client* client = nullptr; + MQTTSNPacket* packet = nullptr; + AdapterManager* adpMgr = _gateway->getAdapterManager(); + int rc = 0; - while (true) - { - Event* ev = _gateway->getClientSendQue()->wait(); + while (true) + { + Event* ev = _gateway->getClientSendQue()->wait(); - if (ev->getEventType() == EtStop || _gateway->IsStopping() ) - { - WRITELOG("\n%s ClientSendTask stopped.", currentDateTime()); - delete ev; - break; - } + if (ev->getEventType() == EtStop || _gateway->IsStopping()) + { + WRITELOG("\n%s ClientSendTask stopped.", currentDateTime()); + delete ev; + break; + } - if (ev->getEventType() == EtBroadcast) - { - packet = ev->getMQTTSNPacket(); - log(client, packet); + if (ev->getEventType() == EtBroadcast) + { + packet = ev->getMQTTSNPacket(); + log(client, packet); - if ( packet->broadcast(_sensorNetwork) < 0 ) - { - WRITELOG("%s ClientSendTask can't multicast a packet Error=%d%s\n", - ERRMSG_HEADER, errno, ERRMSG_FOOTER); - } - } - else - { - if (ev->getEventType() == EtClientSend) - { - client = ev->getClient(); - packet = ev->getMQTTSNPacket(); - rc = adpMgr->unicastToClient(client, packet, this); - } - else if (ev->getEventType() == EtSensornetSend) - { - packet = ev->getMQTTSNPacket(); - log(client, packet); - rc = packet->unicast(_sensorNetwork, ev->getSensorNetAddress()); - } + if (packet->broadcast(_sensorNetwork) < 0) + { + WRITELOG( + "%s ClientSendTask can't multicast a packet Error=%d%s\n", + ERRMSG_HEADER, errno, ERRMSG_FOOTER); + } + } + else + { + if (ev->getEventType() == EtClientSend) + { + client = ev->getClient(); + packet = ev->getMQTTSNPacket(); + rc = adpMgr->unicastToClient(client, packet, this); + } + else if (ev->getEventType() == EtSensornetSend) + { + packet = ev->getMQTTSNPacket(); + log(client, packet); + rc = packet->unicast(_sensorNetwork, ev->getSensorNetAddress()); + } - if ( rc < 0 ) - { - WRITELOG("%s ClientSendTask can't send a packet to the client %s. Error=%d%s\n", - ERRMSG_HEADER, (client ? (const char*)client->getClientId() : UNKNOWNCL ), errno, ERRMSG_FOOTER); - } - } - delete ev; - } + if (rc < 0) + { + WRITELOG( + "%s ClientSendTask can't send a packet to the client %s. Error=%d%s\n", + ERRMSG_HEADER, + (client ? + (const char*) client->getClientId() : UNKNOWNCL), + errno, ERRMSG_FOOTER); + } + } + delete ev; + } } void ClientSendTask::log(Client* client, MQTTSNPacket* packet) { - char pbuf[SIZE_OF_LOG_PACKET * 3 + 1]; - char msgId[6]; - const char* clientId = client ? (const char*)client->getClientId() : UNKNOWNCL ; + char pbuf[SIZE_OF_LOG_PACKET * 3 + 1]; + char msgId[6]; + const char* clientId = + client ? (const char*) client->getClientId() : UNKNOWNCL; - switch (packet->getType()) - { - case MQTTSN_ADVERTISE: - case MQTTSN_GWINFO: - WRITELOG(FORMAT_Y_W_G, currentDateTime(), packet->getName(), RIGHTARROW, CLIENTS, packet->print(pbuf)); - break; - case MQTTSN_CONNACK: - case MQTTSN_DISCONNECT: - case MQTTSN_WILLTOPICREQ: - case MQTTSN_WILLMSGREQ: - case MQTTSN_WILLTOPICRESP: - case MQTTSN_WILLMSGRESP: - case MQTTSN_PINGRESP: - WRITELOG(FORMAT_Y_W_G, currentDateTime(), packet->getName(), RIGHTARROW, clientId, packet->print(pbuf)); - break; - case MQTTSN_REGISTER: - case MQTTSN_PUBLISH: - WRITELOG(FORMAT_W_MSGID_W_G, currentDateTime(), packet->getName(), packet->getMsgId(msgId), RIGHTARROW, clientId, packet->print(pbuf)); - break; - case MQTTSN_REGACK: - case MQTTSN_PUBACK: - case MQTTSN_PUBREC: - case MQTTSN_PUBREL: - case MQTTSN_PUBCOMP: - case MQTTSN_SUBACK: - case MQTTSN_UNSUBACK: - WRITELOG(FORMAT_W_MSGID_W_G, currentDateTime(), packet->getName(), packet->getMsgId(msgId), RIGHTARROW, clientId, packet->print(pbuf)); - break; - default: - break; - } + switch (packet->getType()) + { + case MQTTSN_ADVERTISE: + case MQTTSN_GWINFO: + WRITELOG(FORMAT_Y_W_G, currentDateTime(), packet->getName(), RIGHTARROW, + CLIENTS, packet->print(pbuf)); + break; + case MQTTSN_CONNACK: + case MQTTSN_DISCONNECT: + case MQTTSN_WILLTOPICREQ: + case MQTTSN_WILLMSGREQ: + case MQTTSN_WILLTOPICRESP: + case MQTTSN_WILLMSGRESP: + case MQTTSN_PINGRESP: + WRITELOG(FORMAT_Y_W_G, currentDateTime(), packet->getName(), RIGHTARROW, + clientId, packet->print(pbuf)); + break; + case MQTTSN_REGISTER: + case MQTTSN_PUBLISH: + WRITELOG(FORMAT_W_MSGID_W_G, currentDateTime(), packet->getName(), + packet->getMsgId(msgId), RIGHTARROW, clientId, + packet->print(pbuf)); + break; + case MQTTSN_REGACK: + case MQTTSN_PUBACK: + case MQTTSN_PUBREC: + case MQTTSN_PUBREL: + case MQTTSN_PUBCOMP: + case MQTTSN_SUBACK: + case MQTTSN_UNSUBACK: + WRITELOG(FORMAT_W_MSGID_W_G, currentDateTime(), packet->getName(), + packet->getMsgId(msgId), RIGHTARROW, clientId, + packet->print(pbuf)); + break; + default: + break; + } } diff --git a/MQTTSNGateway/src/MQTTSNGWClientSendTask.h b/MQTTSNGateway/src/MQTTSNGWClientSendTask.h index 3eaf84f..1e4d14d 100644 --- a/MQTTSNGateway/src/MQTTSNGWClientSendTask.h +++ b/MQTTSNGateway/src/MQTTSNGWClientSendTask.h @@ -28,18 +28,18 @@ class AdapterManager; =====================================*/ class ClientSendTask: public Thread { - MAGIC_WORD_FOR_THREAD; - friend AdapterManager; +MAGIC_WORD_FOR_THREAD; + friend AdapterManager; public: - ClientSendTask(Gateway* gateway); - ~ClientSendTask(void); - void run(void); + ClientSendTask(Gateway* gateway); + ~ClientSendTask(void); + void run(void); private: - void log(Client* client, MQTTSNPacket* packet); + void log(Client* client, MQTTSNPacket* packet); - Gateway* _gateway; - SensorNetwork* _sensorNetwork; + Gateway* _gateway; + SensorNetwork* _sensorNetwork; }; } diff --git a/MQTTSNGateway/src/MQTTSNGWConnectionHandler.cpp b/MQTTSNGateway/src/MQTTSNGWConnectionHandler.cpp index 76367ce..f0133ff 100644 --- a/MQTTSNGateway/src/MQTTSNGWConnectionHandler.cpp +++ b/MQTTSNGateway/src/MQTTSNGWConnectionHandler.cpp @@ -28,7 +28,7 @@ using namespace MQTTSNGW; =====================================*/ MQTTSNConnectionHandler::MQTTSNConnectionHandler(Gateway* gateway) { - _gateway = gateway; + _gateway = gateway; } MQTTSNConnectionHandler::~MQTTSNConnectionHandler() @@ -41,11 +41,12 @@ MQTTSNConnectionHandler::~MQTTSNConnectionHandler() */ void MQTTSNConnectionHandler::sendADVERTISE() { - MQTTSNPacket* adv = new MQTTSNPacket(); - adv->setADVERTISE(_gateway->getGWParams()->gatewayId, _gateway->getGWParams()->keepAlive); - Event* ev1 = new Event(); - ev1->setBrodcastEvent(adv); //broadcast - _gateway->getClientSendQue()->post(ev1); + MQTTSNPacket* adv = new MQTTSNPacket(); + adv->setADVERTISE(_gateway->getGWParams()->gatewayId, + _gateway->getGWParams()->keepAlive); + Event* ev1 = new Event(); + ev1->setBrodcastEvent(adv); //broadcast + _gateway->getClientSendQue()->post(ev1); } /* @@ -53,182 +54,191 @@ void MQTTSNConnectionHandler::sendADVERTISE() */ void MQTTSNConnectionHandler::handleSearchgw(MQTTSNPacket* packet) { - if (packet->getType() == MQTTSN_SEARCHGW) - { - MQTTSNPacket* gwinfo = new MQTTSNPacket(); - gwinfo->setGWINFO(_gateway->getGWParams()->gatewayId); - Event* ev1 = new Event(); - ev1->setBrodcastEvent(gwinfo); - _gateway->getClientSendQue()->post(ev1); - } + if (packet->getType() == MQTTSN_SEARCHGW) + { + MQTTSNPacket* gwinfo = new MQTTSNPacket(); + gwinfo->setGWINFO(_gateway->getGWParams()->gatewayId); + Event* ev1 = new Event(); + ev1->setBrodcastEvent(gwinfo); + _gateway->getClientSendQue()->post(ev1); + } } /* * CONNECT */ -void MQTTSNConnectionHandler::handleConnect(Client* client, MQTTSNPacket* packet) +void MQTTSNConnectionHandler::handleConnect(Client* client, + MQTTSNPacket* packet) { - MQTTSNPacket_connectData data; - if ( packet->getCONNECT(&data) == 0 ) - { - return; - } + MQTTSNPacket_connectData data; + if (packet->getCONNECT(&data) == 0) + { + return; + } - /* return CONNACK when the client is sleeping */ - if ( client->isSleep() || client->isAwake() ) - { - MQTTSNPacket* packet = new MQTTSNPacket(); - packet->setCONNACK(MQTTSN_RC_ACCEPTED); - Event* ev = new Event(); - ev->setClientSendEvent(client, packet); - _gateway->getClientSendQue()->post(ev); + /* return CONNACK when the client is sleeping */ + if (client->isSleep() || client->isAwake()) + { + MQTTSNPacket* packet = new MQTTSNPacket(); + packet->setCONNACK(MQTTSN_RC_ACCEPTED); + Event* ev = new Event(); + ev->setClientSendEvent(client, packet); + _gateway->getClientSendQue()->post(ev); - sendStoredPublish(client); - return; - } + sendStoredPublish(client); + return; + } - //* clear ConnectData of Client */ - Connect* connectData = client->getConnectData(); - memset(connectData, 0, sizeof(Connect)); - if ( !client->isAdapter() ) - { - client->disconnected(); - } + //* clear ConnectData of Client */ + Connect* connectData = client->getConnectData(); + memset(connectData, 0, sizeof(Connect)); + if (!client->isAdapter()) + { + client->disconnected(); + } - Topics* topics = client->getTopics(); + Topics* topics = client->getTopics(); - /* CONNECT was not sent yet. prepare Connect data */ - connectData->header.bits.type = CONNECT; - connectData->clientID = client->getClientId(); - connectData->version = _gateway->getGWParams()->mqttVersion; - connectData->keepAliveTimer = data.duration; - connectData->flags.bits.will = data.willFlag; + /* CONNECT was not sent yet. prepare Connect data */ + connectData->header.bits.type = CONNECT; + connectData->clientID = client->getClientId(); + connectData->version = _gateway->getGWParams()->mqttVersion; + connectData->keepAliveTimer = data.duration; + connectData->flags.bits.will = data.willFlag; - if ((const char*) _gateway->getGWParams()->loginId != nullptr) - { - connectData->flags.bits.username = 1; - } + if ((const char*) _gateway->getGWParams()->loginId != nullptr) + { + connectData->flags.bits.username = 1; + } - if ((const char*) _gateway->getGWParams()->password != 0) - { - connectData->flags.bits.password = 1; - } + if ((const char*) _gateway->getGWParams()->password != 0) + { + connectData->flags.bits.password = 1; + } - client->setSessionStatus(false); - if (data.cleansession) - { - connectData->flags.bits.cleanstart = 1; - /* reset the table of msgNo and TopicId pare */ - client->clearWaitedPubTopicId(); - client->clearWaitedSubTopicId(); + client->setSessionStatus(false); + if (data.cleansession) + { + connectData->flags.bits.cleanstart = 1; + /* reset the table of msgNo and TopicId pare */ + client->clearWaitedPubTopicId(); + client->clearWaitedSubTopicId(); - /* renew the TopicList */ - if (topics) - { - topics->eraseNormal();; - } - client->setSessionStatus(true); - } + /* renew the TopicList */ + if (topics) + { + topics->eraseNormal(); + ; + } + client->setSessionStatus(true); + } - if (data.willFlag) - { - /* create & send WILLTOPICREQ message to the client */ - MQTTSNPacket* reqTopic = new MQTTSNPacket(); - reqTopic->setWILLTOPICREQ(); - Event* evwr = new Event(); - evwr->setClientSendEvent(client, reqTopic); + if (data.willFlag) + { + /* create & send WILLTOPICREQ message to the client */ + MQTTSNPacket* reqTopic = new MQTTSNPacket(); + reqTopic->setWILLTOPICREQ(); + Event* evwr = new Event(); + evwr->setClientSendEvent(client, reqTopic); - /* Send WILLTOPICREQ to the client */ - _gateway->getClientSendQue()->post(evwr); - } - else - { - /* CONNECT message was not qued in. - * create CONNECT message & send it to the broker */ - MQTTGWPacket* mqMsg = new MQTTGWPacket(); - mqMsg->setCONNECT(client->getConnectData(), (unsigned char*)_gateway->getGWParams()->loginId, (unsigned char*)_gateway->getGWParams()->password); - Event* ev1 = new Event(); - ev1->setBrokerSendEvent(client, mqMsg); - _gateway->getBrokerSendQue()->post(ev1); - } + /* Send WILLTOPICREQ to the client */ + _gateway->getClientSendQue()->post(evwr); + } + else + { + /* CONNECT message was not qued in. + * create CONNECT message & send it to the broker */ + MQTTGWPacket* mqMsg = new MQTTGWPacket(); + mqMsg->setCONNECT(client->getConnectData(), + (unsigned char*) _gateway->getGWParams()->loginId, + (unsigned char*) _gateway->getGWParams()->password); + Event* ev1 = new Event(); + ev1->setBrokerSendEvent(client, mqMsg); + _gateway->getBrokerSendQue()->post(ev1); + } } /* * WILLTOPIC */ -void MQTTSNConnectionHandler::handleWilltopic(Client* client, MQTTSNPacket* packet) +void MQTTSNConnectionHandler::handleWilltopic(Client* client, + MQTTSNPacket* packet) { - int willQos; - uint8_t willRetain; - MQTTSNString willTopic = MQTTSNString_initializer; + int willQos; + uint8_t willRetain; + MQTTSNString willTopic = MQTTSNString_initializer; - if ( packet->getWILLTOPIC(&willQos, &willRetain, &willTopic) == 0 ) - { - return; - } - client->setWillTopic(willTopic); - Connect* connectData = client->getConnectData(); + if (packet->getWILLTOPIC(&willQos, &willRetain, &willTopic) == 0) + { + return; + } + client->setWillTopic(willTopic); + Connect* connectData = client->getConnectData(); - /* add the connectData for MQTT CONNECT message */ - connectData->willTopic = client->getWillTopic(); - connectData->flags.bits.willQoS = willQos; - connectData->flags.bits.willRetain = willRetain; + /* add the connectData for MQTT CONNECT message */ + connectData->willTopic = client->getWillTopic(); + connectData->flags.bits.willQoS = willQos; + connectData->flags.bits.willRetain = willRetain; - /* Send WILLMSGREQ to the client */ - client->setWaitWillMsgFlg(true); - MQTTSNPacket* reqMsg = new MQTTSNPacket(); - reqMsg->setWILLMSGREQ(); - Event* evt = new Event(); - evt->setClientSendEvent(client, reqMsg); - _gateway->getClientSendQue()->post(evt); + /* Send WILLMSGREQ to the client */ + client->setWaitWillMsgFlg(true); + MQTTSNPacket* reqMsg = new MQTTSNPacket(); + reqMsg->setWILLMSGREQ(); + Event* evt = new Event(); + evt->setClientSendEvent(client, reqMsg); + _gateway->getClientSendQue()->post(evt); } /* * WILLMSG */ -void MQTTSNConnectionHandler::handleWillmsg(Client* client, MQTTSNPacket* packet) +void MQTTSNConnectionHandler::handleWillmsg(Client* client, + MQTTSNPacket* packet) { - if ( !client->isWaitWillMsg() ) - { - DEBUGLOG(" MQTTSNConnectionHandler::handleWillmsg WaitWillMsgFlg is off.\n"); - return; - } + if (!client->isWaitWillMsg()) + { + DEBUGLOG(" MQTTSNConnectionHandler::handleWillmsg WaitWillMsgFlg is off.\n"); + return; + } - MQTTSNString willmsg = MQTTSNString_initializer; - Connect* connectData = client->getConnectData(); + MQTTSNString willmsg = MQTTSNString_initializer; + Connect* connectData = client->getConnectData(); - if( client->isConnectSendable() ) - { - /* save WillMsg in the client */ - if ( packet->getWILLMSG(&willmsg) == 0 ) - { - return; - } - client->setWillMsg(willmsg); + if (client->isConnectSendable()) + { + /* save WillMsg in the client */ + if (packet->getWILLMSG(&willmsg) == 0) + { + return; + } + client->setWillMsg(willmsg); - /* create CONNECT message */ - MQTTGWPacket* mqttPacket = new MQTTGWPacket(); - connectData->willMsg = client->getWillMsg(); - mqttPacket->setCONNECT(connectData, (unsigned char*)_gateway->getGWParams()->loginId, (unsigned char*)_gateway->getGWParams()->password); + /* create CONNECT message */ + MQTTGWPacket* mqttPacket = new MQTTGWPacket(); + connectData->willMsg = client->getWillMsg(); + mqttPacket->setCONNECT(connectData, + (unsigned char*) _gateway->getGWParams()->loginId, + (unsigned char*) _gateway->getGWParams()->password); - /* Send CONNECT to the broker */ - Event* evt = new Event(); - evt->setBrokerSendEvent(client, mqttPacket); - client->setWaitWillMsgFlg(false); - _gateway->getBrokerSendQue()->post(evt); - } + /* Send CONNECT to the broker */ + Event* evt = new Event(); + evt->setBrokerSendEvent(client, mqttPacket); + client->setWaitWillMsgFlg(false); + _gateway->getBrokerSendQue()->post(evt); + } } /* * DISCONNECT */ -void MQTTSNConnectionHandler::handleDisconnect(Client* client, MQTTSNPacket* packet) +void MQTTSNConnectionHandler::handleDisconnect(Client* client, + MQTTSNPacket* packet) { uint16_t duration = 0; - if ( packet->getDISCONNECT(&duration) != 0 ) + if (packet->getDISCONNECT(&duration) != 0) { - if ( duration == 0 ) + if (duration == 0) { MQTTGWPacket* mqMsg = new MQTTGWPacket(); mqMsg->setHeader(DISCONNECT); @@ -248,59 +258,63 @@ void MQTTSNConnectionHandler::handleDisconnect(Client* client, MQTTSNPacket* pac /* * WILLTOPICUPD */ -void MQTTSNConnectionHandler::handleWilltopicupd(Client* client, MQTTSNPacket* packet) +void MQTTSNConnectionHandler::handleWilltopicupd(Client* client, + MQTTSNPacket* packet) { - /* send NOT_SUPPORTED responce to the client */ - MQTTSNPacket* respMsg = new MQTTSNPacket(); - respMsg->setWILLTOPICRESP(MQTTSN_RC_NOT_SUPPORTED); - Event* evt = new Event(); - evt->setClientSendEvent(client, respMsg); - _gateway->getClientSendQue()->post(evt); + /* send NOT_SUPPORTED responce to the client */ + MQTTSNPacket* respMsg = new MQTTSNPacket(); + respMsg->setWILLTOPICRESP(MQTTSN_RC_NOT_SUPPORTED); + Event* evt = new Event(); + evt->setClientSendEvent(client, respMsg); + _gateway->getClientSendQue()->post(evt); } /* * WILLMSGUPD */ -void MQTTSNConnectionHandler::handleWillmsgupd(Client* client, MQTTSNPacket* packet) +void MQTTSNConnectionHandler::handleWillmsgupd(Client* client, + MQTTSNPacket* packet) { - /* send NOT_SUPPORTED responce to the client */ - MQTTSNPacket* respMsg = new MQTTSNPacket(); - respMsg->setWILLMSGRESP(MQTTSN_RC_NOT_SUPPORTED); - Event* evt = new Event(); - evt->setClientSendEvent(client, respMsg); - _gateway->getClientSendQue()->post(evt); + /* send NOT_SUPPORTED responce to the client */ + MQTTSNPacket* respMsg = new MQTTSNPacket(); + respMsg->setWILLMSGRESP(MQTTSN_RC_NOT_SUPPORTED); + Event* evt = new Event(); + evt->setClientSendEvent(client, respMsg); + _gateway->getClientSendQue()->post(evt); } /* * PINGREQ */ -void MQTTSNConnectionHandler::handlePingreq(Client* client, MQTTSNPacket* packet) +void MQTTSNConnectionHandler::handlePingreq(Client* client, + MQTTSNPacket* packet) { - if ( ( client->isSleep() || client->isAwake() ) && client->getClientSleepPacket() ) - { - sendStoredPublish(client); - client->holdPingRequest(); - } - else - { + if ((client->isSleep() || client->isAwake()) + && client->getClientSleepPacket()) + { + sendStoredPublish(client); + client->holdPingRequest(); + } + else + { /* send PINGREQ to the broker */ - client->resetPingRequest(); + client->resetPingRequest(); MQTTGWPacket* pingreq = new MQTTGWPacket(); pingreq->setHeader(PINGREQ); Event* evt = new Event(); evt->setBrokerSendEvent(client, pingreq); _gateway->getBrokerSendQue()->post(evt); - } + } } void MQTTSNConnectionHandler::sendStoredPublish(Client* client) { MQTTGWPacket* msg = nullptr; - while ( ( msg = client->getClientSleepPacket() ) != nullptr ) + while ((msg = client->getClientSleepPacket()) != nullptr) { // ToDo: This version can't re-send PUBLISH when PUBACK is not returned. - client->deleteFirstClientSleepPacket(); // pop the que to delete element. + client->deleteFirstClientSleepPacket(); // pop the que to delete element. Event* ev = new Event(); ev->setBrokerRecvEvent(client, msg); diff --git a/MQTTSNGateway/src/MQTTSNGWConnectionHandler.h b/MQTTSNGateway/src/MQTTSNGWConnectionHandler.h index 6af6113..eb75177 100644 --- a/MQTTSNGateway/src/MQTTSNGWConnectionHandler.h +++ b/MQTTSNGateway/src/MQTTSNGWConnectionHandler.h @@ -25,21 +25,21 @@ namespace MQTTSNGW class MQTTSNConnectionHandler { public: - MQTTSNConnectionHandler(Gateway* gateway); - ~MQTTSNConnectionHandler(); - void sendADVERTISE(void); - void handleSearchgw(MQTTSNPacket* packet); - void handleConnect(Client* client, MQTTSNPacket* packet); - void handleWilltopic(Client* client, MQTTSNPacket* packet); - void handleWillmsg(Client* client, MQTTSNPacket* packet); - void handleDisconnect(Client* client, MQTTSNPacket* packet); - void handleWilltopicupd(Client* client, MQTTSNPacket* packet); - void handleWillmsgupd(Client* client, MQTTSNPacket* packet); - void handlePingreq(Client* client, MQTTSNPacket* packet); + MQTTSNConnectionHandler(Gateway* gateway); + ~MQTTSNConnectionHandler(); + void sendADVERTISE(void); + void handleSearchgw(MQTTSNPacket* packet); + void handleConnect(Client* client, MQTTSNPacket* packet); + void handleWilltopic(Client* client, MQTTSNPacket* packet); + void handleWillmsg(Client* client, MQTTSNPacket* packet); + void handleDisconnect(Client* client, MQTTSNPacket* packet); + void handleWilltopicupd(Client* client, MQTTSNPacket* packet); + void handleWillmsgupd(Client* client, MQTTSNPacket* packet); + void handlePingreq(Client* client, MQTTSNPacket* packet); private: - void sendStoredPublish(Client* client); + void sendStoredPublish(Client* client); - Gateway* _gateway; + Gateway* _gateway; }; } diff --git a/MQTTSNGateway/src/MQTTSNGWDefines.h b/MQTTSNGateway/src/MQTTSNGWDefines.h index d73827d..7a10fcd 100644 --- a/MQTTSNGateway/src/MQTTSNGWDefines.h +++ b/MQTTSNGateway/src/MQTTSNGWDefines.h @@ -53,16 +53,15 @@ namespace MQTTSNGW /*================================= * Data Type ==================================*/ -typedef unsigned char uint8_t; +typedef unsigned char uint8_t; typedef unsigned short uint16_t; -typedef unsigned int uint32_t; +typedef unsigned int uint32_t; /*================================= * Log controls ==================================*/ //#define DEBUG // print out log for debug //#define DEBUG_NWSTACK // print out SensorNetwork log - #ifdef DEBUG #define DEBUGLOG(...) printf(__VA_ARGS__) #else diff --git a/MQTTSNGateway/src/MQTTSNGWEncapsulatedPacket.cpp b/MQTTSNGateway/src/MQTTSNGWEncapsulatedPacket.cpp index 750867f..dccde79 100644 --- a/MQTTSNGateway/src/MQTTSNGWEncapsulatedPacket.cpp +++ b/MQTTSNGateway/src/MQTTSNGWEncapsulatedPacket.cpp @@ -21,17 +21,17 @@ using namespace MQTTSNGW; using namespace std; -WirelessNodeId::WirelessNodeId() - : - _len{0}, - _nodeId{0} +WirelessNodeId::WirelessNodeId() : + _len + { 0 }, _nodeId + { 0 } { } WirelessNodeId::~WirelessNodeId() { - if ( _nodeId ) + if (_nodeId) { free(_nodeId); } @@ -39,12 +39,12 @@ WirelessNodeId::~WirelessNodeId() void WirelessNodeId::setId(uint8_t* id, uint8_t len) { - if ( _nodeId ) - { - free(_nodeId); - } - uint8_t* buf = (uint8_t*)malloc(len); - if ( buf ) + if (_nodeId) + { + free(_nodeId); + } + uint8_t* buf = (uint8_t*) malloc(len); + if (buf) { memcpy(buf, id, len); _len = len; @@ -64,7 +64,7 @@ void WirelessNodeId::setId(WirelessNodeId* id) bool WirelessNodeId::operator ==(WirelessNodeId& id) { - if ( _len == id._len ) + if (_len == id._len) { return memcmp(_nodeId, id._nodeId, _len) == 0; } @@ -77,16 +77,18 @@ bool WirelessNodeId::operator ==(WirelessNodeId& id) /* * Class MQTTSNGWEncapsulatedPacket */ -MQTTSNGWEncapsulatedPacket::MQTTSNGWEncapsulatedPacket() - : _mqttsn{0}, - _ctrl{0} +MQTTSNGWEncapsulatedPacket::MQTTSNGWEncapsulatedPacket() : + _mqttsn + { 0 }, _ctrl + { 0 } { } -MQTTSNGWEncapsulatedPacket::MQTTSNGWEncapsulatedPacket(MQTTSNPacket* packet) - : _mqttsn{packet}, - _ctrl{0} +MQTTSNGWEncapsulatedPacket::MQTTSNGWEncapsulatedPacket(MQTTSNPacket* packet) : + _mqttsn + { packet }, _ctrl + { 0 } { } @@ -96,7 +98,8 @@ MQTTSNGWEncapsulatedPacket::~MQTTSNGWEncapsulatedPacket() /* Do not delete the MQTTSNPacket. MQTTSNPacket is deleted by delete Event */ } -int MQTTSNGWEncapsulatedPacket::unicast(SensorNetwork* network, SensorNetAddress* sendTo) +int MQTTSNGWEncapsulatedPacket::unicast(SensorNetwork* network, + SensorNetAddress* sendTo) { uint8_t buf[MQTTSNGW_MAX_PACKET_SIZE]; int len = serialize(buf); @@ -109,18 +112,19 @@ int MQTTSNGWEncapsulatedPacket::serialize(uint8_t* buf) buf[0] = _id._len + 3; buf[1] = MQTTSN_ENCAPSULATED; buf[2] = _ctrl; - memcpy( buf + 3, _id._nodeId, _id._len); - if ( _mqttsn ) + memcpy(buf + 3, _id._nodeId, _id._len); + if (_mqttsn) { len = _mqttsn->getPacketLength(); memcpy(buf + buf[0], _mqttsn->getPacketData(), len); } - return buf[0] + len; + return buf[0] + len; } -int MQTTSNGWEncapsulatedPacket::desirialize(unsigned char* buf, unsigned short len) +int MQTTSNGWEncapsulatedPacket::desirialize(unsigned char* buf, + unsigned short len) { - if ( _mqttsn ) + if (_mqttsn) { delete _mqttsn; _mqttsn = nullptr; diff --git a/MQTTSNGateway/src/MQTTSNGWEncapsulatedPacket.h b/MQTTSNGateway/src/MQTTSNGWEncapsulatedPacket.h index eb2cba6..080b9ab 100644 --- a/MQTTSNGateway/src/MQTTSNGWEncapsulatedPacket.h +++ b/MQTTSNGateway/src/MQTTSNGWEncapsulatedPacket.h @@ -60,6 +60,4 @@ private: } - - #endif /* MQTTSNGATEWAY_SRC_MQTTSNGWENCAPSULATEDPACKET_H_ */ diff --git a/MQTTSNGateway/src/MQTTSNGWForwarder.cpp b/MQTTSNGateway/src/MQTTSNGWForwarder.cpp index 71b2e83..92875f3 100644 --- a/MQTTSNGateway/src/MQTTSNGWForwarder.cpp +++ b/MQTTSNGateway/src/MQTTSNGWForwarder.cpp @@ -22,7 +22,7 @@ using namespace MQTTSNGW; using namespace std; /*===================================== - Class ForwarderList + Class ForwarderList =====================================*/ ForwarderList::ForwarderList() @@ -32,10 +32,10 @@ ForwarderList::ForwarderList() ForwarderList::~ForwarderList() { - if ( _head ) + if (_head) { Forwarder* p = _head; - while ( p ) + while (p) { Forwarder* next = p->_next; delete p; @@ -44,20 +44,18 @@ ForwarderList::~ForwarderList() } } - void ForwarderList::initialize(Gateway* gw) { - /* Create Fowarders from clients.conf */ - gw->getClientList()->setClientList(FORWARDER_TYPE); + /* Create Fowarders from clients.conf */ + gw->getClientList()->setClientList(FORWARDER_TYPE); } - Forwarder* ForwarderList::getForwarder(SensorNetAddress* addr) { Forwarder* p = _head; - while ( p ) + while (p) { - if ( p->_sensorNetAddr.isMatch(addr) ) + if (p->_sensorNetAddr.isMatch(addr)) { break; } @@ -66,19 +64,20 @@ Forwarder* ForwarderList::getForwarder(SensorNetAddress* addr) return p; } -Forwarder* ForwarderList::addForwarder(SensorNetAddress* addr, MQTTSNString* forwarderId) +Forwarder* ForwarderList::addForwarder(SensorNetAddress* addr, + MQTTSNString* forwarderId) { Forwarder* fdr = new Forwarder(addr, forwarderId); - if ( _head == nullptr ) + if (_head == nullptr) { _head = fdr; } else { Forwarder* p = _head; - while ( p ) + while (p) { - if ( p->_next == nullptr ) + if (p->_next == nullptr) { p->_next = fdr; break; @@ -99,10 +98,10 @@ Forwarder::Forwarder() } /*===================================== - Class ForwarderList + Class ForwarderList =====================================*/ -Forwarder::Forwarder(SensorNetAddress* addr, MQTTSNString* forwarderId) +Forwarder::Forwarder(SensorNetAddress* addr, MQTTSNString* forwarderId) { _forwarderName = string(forwarderId->cstring); _sensorNetAddr = *addr; @@ -112,10 +111,10 @@ Forwarder::Forwarder(SensorNetAddress* addr, MQTTSNString* forwarderId) Forwarder::~Forwarder(void) { - if ( _headClient ) + if (_headClient) { ForwarderElement* p = _headClient; - while ( p ) + while (p) { ForwarderElement* next = p->_next; delete p; @@ -136,11 +135,11 @@ void Forwarder::addClient(Client* client, WirelessNodeId* id) client->setForwarder(this); - if ( p != nullptr ) + if (p != nullptr) { - while ( p ) + while (p) { - if ( p->_client == client ) + if (p->_client == client) { client->setForwarder(this); p->setWirelessNodeId(id); @@ -156,7 +155,7 @@ void Forwarder::addClient(Client* client, WirelessNodeId* id) fclient->setClient(client); fclient->setWirelessNodeId(id); - if ( prev ) + if (prev) { prev->_next = fclient; } @@ -171,9 +170,9 @@ Client* Forwarder::getClient(WirelessNodeId* id) Client* cl = nullptr; _mutex.lock(); ForwarderElement* p = _headClient; - while ( p ) + while (p) { - if ( *(p->_wirelessNodeId) == *id ) + if (*(p->_wirelessNodeId) == *id) { cl = p->_client; break; @@ -197,9 +196,9 @@ WirelessNodeId* Forwarder::getWirelessNodeId(Client* client) WirelessNodeId* nodeId = nullptr; _mutex.lock(); ForwarderElement* p = _headClient; - while ( p ) + while (p) { - if ( p->_client == client ) + if (p->_client == client) { nodeId = p->_wirelessNodeId; break; @@ -219,11 +218,11 @@ void Forwarder::eraseClient(Client* client) _mutex.lock(); ForwarderElement* p = _headClient; - while ( p ) + while (p) { - if ( p->_client == client ) + if (p->_client == client) { - if ( prev ) + if (prev) { prev->_next = p->_next; } @@ -251,10 +250,11 @@ SensorNetAddress* Forwarder::getSensorNetAddr(void) * Class ForwardedClient */ -ForwarderElement::ForwarderElement() - : _client{0} - , _wirelessNodeId{0} - , _next{0} +ForwarderElement::ForwarderElement() : + _client + { 0 }, _wirelessNodeId + { 0 }, _next + { 0 } { } @@ -273,7 +273,7 @@ void ForwarderElement::setClient(Client* client) void ForwarderElement::setWirelessNodeId(WirelessNodeId* id) { - if ( _wirelessNodeId == nullptr ) + if (_wirelessNodeId == nullptr) { _wirelessNodeId = new WirelessNodeId(); } diff --git a/MQTTSNGateway/src/MQTTSNGWForwarder.h b/MQTTSNGateway/src/MQTTSNGWForwarder.h index a7279d2..9730030 100644 --- a/MQTTSNGateway/src/MQTTSNGWForwarder.h +++ b/MQTTSNGateway/src/MQTTSNGWForwarder.h @@ -22,7 +22,6 @@ #include "MQTTSNGWEncapsulatedPacket.h" #include "SensorNetwork.h" - namespace MQTTSNGW { class Gateway; @@ -30,7 +29,7 @@ class Client; class WirelessNodeId; /*===================================== - Class ForwarderElement + Class ForwarderElement =====================================*/ class ForwarderElement { @@ -48,14 +47,14 @@ private: }; /*===================================== - Class Forwarder + Class Forwarder =====================================*/ class Forwarder { friend class ForwarderList; public: Forwarder(void); - Forwarder(SensorNetAddress* addr, MQTTSNString* forwarderId); + Forwarder(SensorNetAddress* addr, MQTTSNString* forwarderId); ~Forwarder(); void initialize(void); @@ -70,13 +69,13 @@ public: private: string _forwarderName; SensorNetAddress _sensorNetAddr; - ForwarderElement* _headClient{nullptr}; - Forwarder* _next {nullptr}; + ForwarderElement* _headClient { nullptr }; + Forwarder* _next { nullptr }; Mutex _mutex; }; /*===================================== - Class ForwarderList + Class ForwarderList =====================================*/ class ForwarderList { @@ -86,7 +85,7 @@ public: void initialize(Gateway* gw); Forwarder* getForwarder(SensorNetAddress* addr); - Forwarder* addForwarder(SensorNetAddress* addr, MQTTSNString* forwarderId); + Forwarder* addForwarder(SensorNetAddress* addr, MQTTSNString* forwarderId); private: Forwarder* _head; @@ -94,6 +93,4 @@ private: } - - #endif /* MQTTSNGATEWAY_SRC_MQTTSNGWFORWARDER_H_ */ diff --git a/MQTTSNGateway/src/MQTTSNGWLogmonitor.cpp b/MQTTSNGateway/src/MQTTSNGWLogmonitor.cpp index 692e3fe..be4587f 100644 --- a/MQTTSNGateway/src/MQTTSNGWLogmonitor.cpp +++ b/MQTTSNGateway/src/MQTTSNGWLogmonitor.cpp @@ -22,7 +22,7 @@ using namespace MQTTSNGW; Logmonitor::Logmonitor() { - theProcess = this; + theProcess = this; } Logmonitor::~Logmonitor() @@ -32,17 +32,17 @@ Logmonitor::~Logmonitor() void Logmonitor::run() { - while (true) - { - const char* data = getLog(); - if ( *data == 0 ) - { - break; - } - else - { - printf("%s", data); - } - } + while (true) + { + const char* data = getLog(); + if (*data == 0) + { + break; + } + else + { + printf("%s", data); + } + } } diff --git a/MQTTSNGateway/src/MQTTSNGWLogmonitor.h b/MQTTSNGateway/src/MQTTSNGWLogmonitor.h index cb5838a..a0745bf 100644 --- a/MQTTSNGateway/src/MQTTSNGWLogmonitor.h +++ b/MQTTSNGateway/src/MQTTSNGWLogmonitor.h @@ -23,9 +23,9 @@ namespace MQTTSNGW class Logmonitor: public Process { public: - Logmonitor(); - ~Logmonitor(); - void run(); + Logmonitor(); + ~Logmonitor(); + void run(); }; } diff --git a/MQTTSNGateway/src/MQTTSNGWMessageIdTable.cpp b/MQTTSNGateway/src/MQTTSNGWMessageIdTable.cpp index b87e06c..63e32a2 100644 --- a/MQTTSNGateway/src/MQTTSNGWMessageIdTable.cpp +++ b/MQTTSNGateway/src/MQTTSNGWMessageIdTable.cpp @@ -29,187 +29,188 @@ MessageIdTable::MessageIdTable() MessageIdTable::~MessageIdTable() { - _mutex.lock(); - if ( _head != nullptr ) - { - MessageIdElement* p = _tail; - while ( p ) - { - MessageIdElement* pPrev = p; - delete p; - _cnt--; - p = pPrev->_prev; - } - _head = _tail = nullptr; - } - _mutex.unlock(); + _mutex.lock(); + if (_head != nullptr) + { + MessageIdElement* p = _tail; + while (p) + { + MessageIdElement* pPrev = p; + delete p; + _cnt--; + p = pPrev->_prev; + } + _head = _tail = nullptr; + } + _mutex.unlock(); } -MessageIdElement* MessageIdTable::add(Aggregater* aggregater, Client* client, uint16_t clientMsgId) +MessageIdElement* MessageIdTable::add(Aggregater* aggregater, Client* client, + uint16_t clientMsgId) { - if ( _cnt > _maxSize ) - { - return nullptr; - } + if (_cnt > _maxSize) + { + return nullptr; + } - MessageIdElement* elm = new MessageIdElement(0, client, clientMsgId); - if ( elm == nullptr ) - { - return nullptr; - } - _mutex.lock(); - if ( _head == nullptr ) - { - elm->_msgId = aggregater->msgId(); - _head = elm; - _tail = elm; - _cnt++; - } - else - { - MessageIdElement* p = find(client, clientMsgId); - if ( p == nullptr ) - { - elm->_msgId = aggregater->msgId(); - p = _tail; - _tail = elm; - elm->_prev = p; - p->_next = elm; - _cnt++; - } - else - { - delete elm; - elm = nullptr; - } - } - _mutex.unlock(); - return elm; + MessageIdElement* elm = new MessageIdElement(0, client, clientMsgId); + if (elm == nullptr) + { + return nullptr; + } + _mutex.lock(); + if (_head == nullptr) + { + elm->_msgId = aggregater->msgId(); + _head = elm; + _tail = elm; + _cnt++; + } + else + { + MessageIdElement* p = find(client, clientMsgId); + if (p == nullptr) + { + elm->_msgId = aggregater->msgId(); + p = _tail; + _tail = elm; + elm->_prev = p; + p->_next = elm; + _cnt++; + } + else + { + delete elm; + elm = nullptr; + } + } + _mutex.unlock(); + return elm; } MessageIdElement* MessageIdTable::find(uint16_t msgId) { - MessageIdElement* p = _head; - while ( p ) - { - if ( p->_msgId == msgId) - { - break; - } - p = p->_next; - } - return p; + MessageIdElement* p = _head; + while (p) + { + if (p->_msgId == msgId) + { + break; + } + p = p->_next; + } + return p; } MessageIdElement* MessageIdTable::find(Client* client, uint16_t clientMsgId) { - MessageIdElement* p = _head; - while ( p ) - { - if ( p->_clientMsgId == clientMsgId && p->_client == client) - { - break; - } - p = p->_next; - } - return p; + MessageIdElement* p = _head; + while (p) + { + if (p->_clientMsgId == clientMsgId && p->_client == client) + { + break; + } + p = p->_next; + } + return p; } - Client* MessageIdTable::getClientMsgId(uint16_t msgId, uint16_t* clientMsgId) { - Client* clt = nullptr; - *clientMsgId = 0; - _mutex.lock(); - MessageIdElement* p = find(msgId); - if ( p != nullptr ) - { - clt = p->_client; - *clientMsgId = p->_clientMsgId; - clear(p); - } - _mutex.unlock(); - return clt; + Client* clt = nullptr; + *clientMsgId = 0; + _mutex.lock(); + MessageIdElement* p = find(msgId); + if (p != nullptr) + { + clt = p->_client; + *clientMsgId = p->_clientMsgId; + clear(p); + } + _mutex.unlock(); + return clt; } void MessageIdTable::erase(uint16_t msgId) { - _mutex.lock(); - MessageIdElement* p = find(msgId); - clear(p); - _mutex.unlock(); + _mutex.lock(); + MessageIdElement* p = find(msgId); + clear(p); + _mutex.unlock(); } void MessageIdTable::clear(MessageIdElement* elm) { - if ( elm == nullptr ) - { - return; - } + if (elm == nullptr) + { + return; + } - if ( elm->_prev == nullptr ) - { - _head = elm->_next; - if ( _head == nullptr) - { - _tail = nullptr; - } - else - { - _head->_prev = nullptr; - } - delete elm; - _cnt--; - return; - } - else - { - elm->_prev->_next = elm->_next; - if ( elm->_next == nullptr ) - { - _tail = elm->_prev; - } - else - { - elm->_next->_prev = elm->_prev; - } - delete elm; - _cnt--; - return; - } + if (elm->_prev == nullptr) + { + _head = elm->_next; + if (_head == nullptr) + { + _tail = nullptr; + } + else + { + _head->_prev = nullptr; + } + delete elm; + _cnt--; + return; + } + else + { + elm->_prev->_next = elm->_next; + if (elm->_next == nullptr) + { + _tail = elm->_prev; + } + else + { + elm->_next->_prev = elm->_prev; + } + delete elm; + _cnt--; + return; + } } - uint16_t MessageIdTable::getMsgId(Client* client, uint16_t clientMsgId) { - uint16_t msgId = 0; - MessageIdElement* p = find(client, clientMsgId); - if ( p != nullptr ) - { - msgId = p->_msgId; - } - return msgId; + uint16_t msgId = 0; + MessageIdElement* p = find(client, clientMsgId); + if (p != nullptr) + { + msgId = p->_msgId; + } + return msgId; } /*=============================== * Class MessageIdElement ===============================*/ -MessageIdElement::MessageIdElement(void) - : _msgId{0} - , _clientMsgId {0} - , _client {nullptr} - , _next {nullptr} - , _prev {nullptr} +MessageIdElement::MessageIdElement(void) : + _msgId + { 0 }, _clientMsgId + { 0 }, _client + { nullptr }, _next + { nullptr }, _prev + { nullptr } { } -MessageIdElement::MessageIdElement(uint16_t msgId, Client* client, uint16_t clientMsgId) - : MessageIdElement() +MessageIdElement::MessageIdElement(uint16_t msgId, Client* client, + uint16_t clientMsgId) : + MessageIdElement() { - _msgId = msgId; - _client = client; - _clientMsgId = clientMsgId; + _msgId = msgId; + _client = client; + _clientMsgId = clientMsgId; } MessageIdElement::~MessageIdElement(void) diff --git a/MQTTSNGateway/src/MQTTSNGWMessageIdTable.h b/MQTTSNGateway/src/MQTTSNGWMessageIdTable.h index 59f7be6..2f0b5e6 100644 --- a/MQTTSNGateway/src/MQTTSNGWMessageIdTable.h +++ b/MQTTSNGateway/src/MQTTSNGWMessageIdTable.h @@ -34,22 +34,23 @@ class Aggregater; class MessageIdTable { public: - MessageIdTable(); - ~MessageIdTable(); + MessageIdTable(); + ~MessageIdTable(); - MessageIdElement* add(Aggregater* aggregater, Client* client, uint16_t clientMsgId); - Client* getClientMsgId(uint16_t msgId, uint16_t* clientMsgId); - uint16_t getMsgId(Client* client, uint16_t clientMsgId); - void erase(uint16_t msgId); - void clear(MessageIdElement* elm); + MessageIdElement* add(Aggregater* aggregater, Client* client, + uint16_t clientMsgId); + Client* getClientMsgId(uint16_t msgId, uint16_t* clientMsgId); + uint16_t getMsgId(Client* client, uint16_t clientMsgId); + void erase(uint16_t msgId); + void clear(MessageIdElement* elm); private: - MessageIdElement* find(uint16_t msgId); - MessageIdElement* find(Client* client, uint16_t clientMsgId); - MessageIdElement* _head {nullptr}; - MessageIdElement* _tail {nullptr}; - int _cnt {0}; - int _maxSize {MAX_MESSAGEID_TABLE_SIZE}; - Mutex _mutex; + MessageIdElement* find(uint16_t msgId); + MessageIdElement* find(Client* client, uint16_t clientMsgId); + MessageIdElement* _head { nullptr }; + MessageIdElement* _tail{ nullptr }; + int _cnt { 0 }; + int _maxSize { MAX_MESSAGEID_TABLE_SIZE }; + Mutex _mutex; }; /*===================================== @@ -67,12 +68,11 @@ public: private: uint16_t _msgId; uint16_t _clientMsgId; - Client* _client; + Client* _client; MessageIdElement* _next; MessageIdElement* _prev; }; - } #endif /* MQTTSNGATEWAY_SRC_MQTTSNGWMESSAGEIDTABLE_H_ */ diff --git a/MQTTSNGateway/src/MQTTSNGWPacket.cpp b/MQTTSNGateway/src/MQTTSNGWPacket.cpp index c2a017a..0e1f2ec 100644 --- a/MQTTSNGateway/src/MQTTSNGWPacket.cpp +++ b/MQTTSNGateway/src/MQTTSNGWPacket.cpp @@ -29,286 +29,293 @@ void writeInt(unsigned char** pptr, int msgId); MQTTSNPacket::MQTTSNPacket(void) { - _buf = nullptr; - _bufLen = 0; + _buf = nullptr; + _bufLen = 0; } MQTTSNPacket::MQTTSNPacket(MQTTSNPacket& packet) { - _buf = (unsigned char*)malloc(packet._bufLen); - if (_buf) - { - _bufLen = packet._bufLen; - memcpy(_buf, packet._buf, _bufLen); - } - else - { - _buf = nullptr; - _bufLen = 0; - } + _buf = (unsigned char*) malloc(packet._bufLen); + if (_buf) + { + _bufLen = packet._bufLen; + memcpy(_buf, packet._buf, _bufLen); + } + else + { + _buf = nullptr; + _bufLen = 0; + } } MQTTSNPacket::~MQTTSNPacket() { - if (_buf) - { - free(_buf); - } + if (_buf) + { + free(_buf); + } } int MQTTSNPacket::unicast(SensorNetwork* network, SensorNetAddress* sendTo) { - return network->unicast(_buf, _bufLen, sendTo); + return network->unicast(_buf, _bufLen, sendTo); } int MQTTSNPacket::broadcast(SensorNetwork* network) { - return network->broadcast(_buf, _bufLen); + return network->broadcast(_buf, _bufLen); } int MQTTSNPacket::serialize(uint8_t* buf) { - buf = _buf; - return _bufLen; + buf = _buf; + return _bufLen; } int MQTTSNPacket::desirialize(unsigned char* buf, unsigned short len) { - if ( _buf ) - { - free(_buf); - } + if (_buf) + { + free(_buf); + } - _buf = (unsigned char*)calloc(len, sizeof(unsigned char)); - if ( _buf ) - { - memcpy(_buf, buf, len); - _bufLen = len; - } - else - { - _bufLen = 0; - } - return _bufLen; + _buf = (unsigned char*) calloc(len, sizeof(unsigned char)); + if (_buf) + { + memcpy(_buf, buf, len); + _bufLen = len; + } + else + { + _bufLen = 0; + } + return _bufLen; } int MQTTSNPacket::recv(SensorNetwork* network) { - uint8_t buf[MQTTSNGW_MAX_PACKET_SIZE]; - int len = network->read((uint8_t*) buf, MQTTSNGW_MAX_PACKET_SIZE); - if (len > 1) - { - len = desirialize(buf, len); - } - else - { - len = 0; - } - return len; + uint8_t buf[MQTTSNGW_MAX_PACKET_SIZE]; + int len = network->read((uint8_t*) buf, MQTTSNGW_MAX_PACKET_SIZE); + if (len > 1) + { + len = desirialize(buf, len); + } + else + { + len = 0; + } + return len; } int MQTTSNPacket::getType(void) { - if ( _bufLen == 0 ) - { - return 0; - } - int value = 0; - int p = MQTTSNPacket_decode(_buf, _bufLen, &value); - return _buf[p]; + if (_bufLen == 0) + { + return 0; + } + int value = 0; + int p = MQTTSNPacket_decode(_buf, _bufLen, &value); + return _buf[p]; } bool MQTTSNPacket::isQoSMinusPUBLISH(void) { - if ( _bufLen == 0 ) + if (_bufLen == 0) { return false;; } int value = 0; int p = MQTTSNPacket_decode(_buf, _bufLen, &value); - return ( (_buf[p] == MQTTSN_PUBLISH) && ((_buf[p + 1] & 0x60 ) == 0x60 )); + return ((_buf[p] == MQTTSN_PUBLISH) && ((_buf[p + 1] & 0x60) == 0x60)); } unsigned char* MQTTSNPacket::getPacketData(void) { - return _buf; + return _buf; } int MQTTSNPacket::getPacketLength(void) { - return _bufLen; + return _bufLen; } const char* MQTTSNPacket::getName() { - return MQTTSNPacket_name(getType()); + return MQTTSNPacket_name(getType()); } int MQTTSNPacket::setADVERTISE(uint8_t gatewayid, uint16_t duration) { - unsigned char buf[5]; - int buflen = sizeof(buf); - int len = MQTTSNSerialize_advertise(buf, buflen, (unsigned char) gatewayid, - (unsigned short) duration); - return desirialize(buf, len); + unsigned char buf[5]; + int buflen = sizeof(buf); + int len = MQTTSNSerialize_advertise(buf, buflen, (unsigned char) gatewayid, + (unsigned short) duration); + return desirialize(buf, len); } int MQTTSNPacket::setGWINFO(uint8_t gatewayId) { - unsigned char buf[3]; - int buflen = sizeof(buf); - int len = MQTTSNSerialize_gwinfo(buf, buflen, (unsigned char) gatewayId, 0, 0); - return desirialize(buf, len); + unsigned char buf[3]; + int buflen = sizeof(buf); + int len = MQTTSNSerialize_gwinfo(buf, buflen, (unsigned char) gatewayId, 0, + 0); + return desirialize(buf, len); } int MQTTSNPacket::setConnect(void) { - unsigned char buf[40]; - int buflen = sizeof(buf); - MQTTSNPacket_connectData data; - data.clientID.cstring = (char*)"client01"; - int len = MQTTSNSerialize_connect(buf, buflen, &data); - return desirialize(buf, len); + unsigned char buf[40]; + int buflen = sizeof(buf); + MQTTSNPacket_connectData data; + data.clientID.cstring = (char*) "client01"; + int len = MQTTSNSerialize_connect(buf, buflen, &data); + return desirialize(buf, len); } bool MQTTSNPacket::isAccepted(void) { - return ( getType() == MQTTSN_CONNACK) && (_buf[2] == MQTTSN_RC_ACCEPTED); + return (getType() == MQTTSN_CONNACK) && (_buf[2] == MQTTSN_RC_ACCEPTED); } int MQTTSNPacket::setCONNACK(uint8_t returnCode) { - unsigned char buf[3]; - int buflen = sizeof(buf); - int len = MQTTSNSerialize_connack(buf, buflen, (int) returnCode); - return desirialize(buf, len); + unsigned char buf[3]; + int buflen = sizeof(buf); + int len = MQTTSNSerialize_connack(buf, buflen, (int) returnCode); + return desirialize(buf, len); } int MQTTSNPacket::setWILLTOPICREQ(void) { - unsigned char buf[2]; - int buflen = sizeof(buf); - int len = MQTTSNSerialize_willtopicreq(buf, buflen); - return desirialize(buf, len); + unsigned char buf[2]; + int buflen = sizeof(buf); + int len = MQTTSNSerialize_willtopicreq(buf, buflen); + return desirialize(buf, len); } int MQTTSNPacket::setWILLMSGREQ(void) { - unsigned char buf[2]; - int buflen = sizeof(buf); - int len = MQTTSNSerialize_willmsgreq(buf, buflen); - return desirialize(buf, len); + unsigned char buf[2]; + int buflen = sizeof(buf); + int len = MQTTSNSerialize_willmsgreq(buf, buflen); + return desirialize(buf, len); } -int MQTTSNPacket::setREGISTER(uint16_t topicId, uint16_t msgId, MQTTSNString* topicName) +int MQTTSNPacket::setREGISTER(uint16_t topicId, uint16_t msgId, + MQTTSNString* topicName) { - unsigned char buf[MQTTSNGW_MAX_PACKET_SIZE]; - int buflen = sizeof(buf); - int len = MQTTSNSerialize_register(buf, buflen, (unsigned short) topicId, (unsigned short) msgId, - topicName); - return desirialize(buf, len); + unsigned char buf[MQTTSNGW_MAX_PACKET_SIZE]; + int buflen = sizeof(buf); + int len = MQTTSNSerialize_register(buf, buflen, (unsigned short) topicId, + (unsigned short) msgId, topicName); + return desirialize(buf, len); } -int MQTTSNPacket::setREGACK(uint16_t topicId, uint16_t msgId, uint8_t returnCode) +int MQTTSNPacket::setREGACK(uint16_t topicId, uint16_t msgId, + uint8_t returnCode) { - unsigned char buf[7]; - int buflen = sizeof(buf); - int len = MQTTSNSerialize_regack(buf, buflen, (unsigned short) topicId, (unsigned short) msgId, - (unsigned char) returnCode); - return desirialize(buf, len); + unsigned char buf[7]; + int buflen = sizeof(buf); + int len = MQTTSNSerialize_regack(buf, buflen, (unsigned short) topicId, + (unsigned short) msgId, (unsigned char) returnCode); + return desirialize(buf, len); } -int MQTTSNPacket::setPUBLISH(uint8_t dup, int qos, uint8_t retained, uint16_t msgId, MQTTSN_topicid topic, - uint8_t* payload, uint16_t payloadlen) +int MQTTSNPacket::setPUBLISH(uint8_t dup, int qos, uint8_t retained, + uint16_t msgId, MQTTSN_topicid topic, uint8_t* payload, + uint16_t payloadlen) { - unsigned char buf[MQTTSNGW_MAX_PACKET_SIZE]; - int buflen = sizeof(buf); - int len = MQTTSNSerialize_publish(buf, buflen, (unsigned char) dup, qos, (unsigned char) retained, - (unsigned short) msgId, topic, (unsigned char*) payload, (int) payloadlen); - return desirialize(buf, len); + unsigned char buf[MQTTSNGW_MAX_PACKET_SIZE]; + int buflen = sizeof(buf); + int len = MQTTSNSerialize_publish(buf, buflen, (unsigned char) dup, qos, + (unsigned char) retained, (unsigned short) msgId, topic, + (unsigned char*) payload, (int) payloadlen); + return desirialize(buf, len); } -int MQTTSNPacket::setPUBACK(uint16_t topicId, uint16_t msgId, uint8_t returnCode) +int MQTTSNPacket::setPUBACK(uint16_t topicId, uint16_t msgId, + uint8_t returnCode) { - unsigned char buf[7]; - int buflen = sizeof(buf); - int len = MQTTSNSerialize_puback(buf, buflen, (unsigned short) topicId, (unsigned short) msgId, - (unsigned char) returnCode); - return desirialize(buf, len); + unsigned char buf[7]; + int buflen = sizeof(buf); + int len = MQTTSNSerialize_puback(buf, buflen, (unsigned short) topicId, + (unsigned short) msgId, (unsigned char) returnCode); + return desirialize(buf, len); } int MQTTSNPacket::setPUBREC(uint16_t msgId) { - unsigned char buf[4]; - int buflen = sizeof(buf); - int len = MQTTSNSerialize_pubrec(buf, buflen, (unsigned short) msgId); - return desirialize(buf, len); + unsigned char buf[4]; + int buflen = sizeof(buf); + int len = MQTTSNSerialize_pubrec(buf, buflen, (unsigned short) msgId); + return desirialize(buf, len); } int MQTTSNPacket::setPUBREL(uint16_t msgId) { - unsigned char buf[4]; - int buflen = sizeof(buf); - int len = MQTTSNSerialize_pubrel(buf, buflen, (unsigned short) msgId); - return desirialize(buf, len); + unsigned char buf[4]; + int buflen = sizeof(buf); + int len = MQTTSNSerialize_pubrel(buf, buflen, (unsigned short) msgId); + return desirialize(buf, len); } int MQTTSNPacket::setPUBCOMP(uint16_t msgId) { - unsigned char buf[4]; - int buflen = sizeof(buf); - int len = MQTTSNSerialize_pubcomp(buf, buflen, (unsigned short) msgId); - return desirialize(buf, len); + unsigned char buf[4]; + int buflen = sizeof(buf); + int len = MQTTSNSerialize_pubcomp(buf, buflen, (unsigned short) msgId); + return desirialize(buf, len); } -int MQTTSNPacket::setSUBACK(int qos, uint16_t topicId, uint16_t msgId, uint8_t returnCode) +int MQTTSNPacket::setSUBACK(int qos, uint16_t topicId, uint16_t msgId, + uint8_t returnCode) { - unsigned char buf[8]; - int buflen = sizeof(buf); - int len = MQTTSNSerialize_suback(buf, buflen, qos, (unsigned short) topicId, - (unsigned short) msgId, (unsigned char) returnCode); - return desirialize(buf, len); + unsigned char buf[8]; + int buflen = sizeof(buf); + int len = MQTTSNSerialize_suback(buf, buflen, qos, (unsigned short) topicId, + (unsigned short) msgId, (unsigned char) returnCode); + return desirialize(buf, len); } int MQTTSNPacket::setUNSUBACK(uint16_t msgId) { - unsigned char buf[4]; - int buflen = sizeof(buf); - int len = MQTTSNSerialize_unsuback(buf, buflen, (unsigned short) msgId); - return desirialize(buf, len); + unsigned char buf[4]; + int buflen = sizeof(buf); + int len = MQTTSNSerialize_unsuback(buf, buflen, (unsigned short) msgId); + return desirialize(buf, len); } int MQTTSNPacket::setPINGRESP(void) { - unsigned char buf[32]; - int buflen = sizeof(buf); - int len = MQTTSNSerialize_pingresp(buf, buflen); - return desirialize(buf, len); + unsigned char buf[32]; + int buflen = sizeof(buf); + int len = MQTTSNSerialize_pingresp(buf, buflen); + return desirialize(buf, len); } int MQTTSNPacket::setDISCONNECT(uint16_t duration) { - unsigned char buf[4]; - int buflen = sizeof(buf); - int len = MQTTSNSerialize_disconnect(buf, buflen, (int) duration); - return desirialize(buf, len); + unsigned char buf[4]; + int buflen = sizeof(buf); + int len = MQTTSNSerialize_disconnect(buf, buflen, (int) duration); + return desirialize(buf, len); } int MQTTSNPacket::setWILLTOPICRESP(uint8_t returnCode) { - unsigned char buf[MQTTSNGW_MAX_PACKET_SIZE]; - int buflen = sizeof(buf); - int len = MQTTSNSerialize_willtopicresp(buf, buflen, (int) returnCode); - return desirialize(buf, len); + unsigned char buf[MQTTSNGW_MAX_PACKET_SIZE]; + int buflen = sizeof(buf); + int len = MQTTSNSerialize_willtopicresp(buf, buflen, (int) returnCode); + return desirialize(buf, len); } int MQTTSNPacket::setWILLMSGRESP(uint8_t returnCode) { - unsigned char buf[MQTTSNGW_MAX_PACKET_SIZE]; - int buflen = sizeof(buf); - int len = MQTTSNSerialize_willmsgresp(buf, buflen, (int) returnCode); - return desirialize(buf, len); + unsigned char buf[MQTTSNGW_MAX_PACKET_SIZE]; + int buflen = sizeof(buf); + int len = MQTTSNSerialize_willmsgresp(buf, buflen, (int) returnCode); + return desirialize(buf, len); } int MQTTSNPacket::setCONNECT(MQTTSNPacket_connectData* options) @@ -323,262 +330,276 @@ int MQTTSNPacket::setPINGREQ(MQTTSNString* clientId) { unsigned char buf[MQTTSNGW_MAX_PACKET_SIZE]; int buflen = sizeof(buf); - int len = MQTTSNSerialize_pingreq( buf, buflen, *clientId); + int len = MQTTSNSerialize_pingreq(buf, buflen, *clientId); return desirialize(buf, len); } int MQTTSNPacket::getSERCHGW(uint8_t* radius) { - return MQTTSNDeserialize_searchgw((unsigned char*) radius, (unsigned char*) _buf, _bufLen); + return MQTTSNDeserialize_searchgw((unsigned char*) radius, + (unsigned char*) _buf, _bufLen); } int MQTTSNPacket::getCONNECT(MQTTSNPacket_connectData* data) { - return MQTTSNDeserialize_connect(data, _buf, _bufLen); + return MQTTSNDeserialize_connect(data, _buf, _bufLen); } int MQTTSNPacket::getCONNACK(uint8_t* returnCode) { - return MQTTSNSerialize_connack(_buf, _bufLen, (int) *returnCode); + return MQTTSNSerialize_connack(_buf, _bufLen, (int) *returnCode); } -int MQTTSNPacket::getWILLTOPIC(int* willQoS, uint8_t* willRetain, MQTTSNString* willTopic) +int MQTTSNPacket::getWILLTOPIC(int* willQoS, uint8_t* willRetain, + MQTTSNString* willTopic) { - return MQTTSNDeserialize_willtopic((int*) willQoS, (unsigned char*) willRetain, willTopic, _buf, _bufLen); + return MQTTSNDeserialize_willtopic((int*) willQoS, + (unsigned char*) willRetain, willTopic, _buf, _bufLen); } int MQTTSNPacket::getWILLMSG(MQTTSNString* willmsg) { - return MQTTSNDeserialize_willmsg(willmsg, _buf, _bufLen); + return MQTTSNDeserialize_willmsg(willmsg, _buf, _bufLen); } -int MQTTSNPacket::getREGISTER(uint16_t* topicId, uint16_t* msgId, MQTTSNString* topicName) +int MQTTSNPacket::getREGISTER(uint16_t* topicId, uint16_t* msgId, + MQTTSNString* topicName) { - return MQTTSNDeserialize_register((unsigned short*) topicId, (unsigned short*) msgId, topicName, - _buf, _bufLen); + return MQTTSNDeserialize_register((unsigned short*) topicId, + (unsigned short*) msgId, topicName, _buf, _bufLen); } -int MQTTSNPacket::getREGACK(uint16_t* topicId, uint16_t* msgId, uint8_t* returnCode) +int MQTTSNPacket::getREGACK(uint16_t* topicId, uint16_t* msgId, + uint8_t* returnCode) { - return MQTTSNDeserialize_regack((unsigned short*) topicId, (unsigned short*) msgId, (unsigned char*) returnCode, _buf, _bufLen); + return MQTTSNDeserialize_regack((unsigned short*) topicId, + (unsigned short*) msgId, (unsigned char*) returnCode, _buf, _bufLen); } -int MQTTSNPacket::getPUBLISH(uint8_t* dup, int* qos, uint8_t* retained, uint16_t* msgId, MQTTSN_topicid* topic, - uint8_t** payload, int* payloadlen) +int MQTTSNPacket::getPUBLISH(uint8_t* dup, int* qos, uint8_t* retained, + uint16_t* msgId, MQTTSN_topicid* topic, uint8_t** payload, + int* payloadlen) { - return MQTTSNDeserialize_publish((unsigned char*) dup, qos, (unsigned char*) retained, (unsigned short*) msgId, - topic, (unsigned char**) payload, (int*) payloadlen, _buf, _bufLen); + return MQTTSNDeserialize_publish((unsigned char*) dup, qos, + (unsigned char*) retained, (unsigned short*) msgId, topic, + (unsigned char**) payload, (int*) payloadlen, _buf, _bufLen); } -int MQTTSNPacket::getPUBACK(uint16_t* topicId, uint16_t* msgId, uint8_t* returnCode) +int MQTTSNPacket::getPUBACK(uint16_t* topicId, uint16_t* msgId, + uint8_t* returnCode) { - return MQTTSNDeserialize_puback((unsigned short*) topicId, (unsigned short*) msgId, (unsigned char*) returnCode, - _buf, _bufLen); + return MQTTSNDeserialize_puback((unsigned short*) topicId, + (unsigned short*) msgId, (unsigned char*) returnCode, _buf, _bufLen); } int MQTTSNPacket::getACK(uint16_t* msgId) { - unsigned char type; - return MQTTSNDeserialize_ack(&type, (unsigned short*) msgId, _buf, _bufLen); + unsigned char type; + return MQTTSNDeserialize_ack(&type, (unsigned short*) msgId, _buf, _bufLen); } -int MQTTSNPacket::getSUBSCRIBE(uint8_t* dup, int* qos, uint16_t* msgId, MQTTSN_topicid* topicFilter) +int MQTTSNPacket::getSUBSCRIBE(uint8_t* dup, int* qos, uint16_t* msgId, + MQTTSN_topicid* topicFilter) { - return MQTTSNDeserialize_subscribe((unsigned char*) dup, qos, (unsigned short*) msgId, topicFilter, _buf, _bufLen); + return MQTTSNDeserialize_subscribe((unsigned char*) dup, qos, + (unsigned short*) msgId, topicFilter, _buf, _bufLen); } int MQTTSNPacket::getUNSUBSCRIBE(uint16_t* msgId, MQTTSN_topicid* topicFilter) { - return MQTTSNDeserialize_unsubscribe((unsigned short*) msgId, topicFilter, _buf, _bufLen); + return MQTTSNDeserialize_unsubscribe((unsigned short*) msgId, topicFilter, + _buf, _bufLen); } int MQTTSNPacket::getPINGREQ(void) { - if (getType() == MQTTSN_PINGRESP && _bufLen > 2 ) - { - return _bufLen - 2; - } - return 0; + if (getType() == MQTTSN_PINGRESP && _bufLen > 2) + { + return _bufLen - 2; + } + return 0; } int MQTTSNPacket::getDISCONNECT(uint16_t* duration) { - int dur = 0; - int rc = MQTTSNDeserialize_disconnect(&dur, _buf, _bufLen); - *duration = (uint16_t)dur; - return rc; + int dur = 0; + int rc = MQTTSNDeserialize_disconnect(&dur, _buf, _bufLen); + *duration = (uint16_t) dur; + return rc; } -int MQTTSNPacket::getWILLTOPICUPD(uint8_t* willQoS, uint8_t* willRetain, MQTTSNString* willTopic) +int MQTTSNPacket::getWILLTOPICUPD(uint8_t* willQoS, uint8_t* willRetain, + MQTTSNString* willTopic) { - return MQTTSNDeserialize_willtopicupd((int*) willQoS, (unsigned char*) willRetain, willTopic, _buf, _bufLen); + return MQTTSNDeserialize_willtopicupd((int*) willQoS, + (unsigned char*) willRetain, willTopic, _buf, _bufLen); } int MQTTSNPacket::getWILLMSGUPD(MQTTSNString* willMsg) { - return MQTTSNDeserialize_willmsgupd(willMsg, _buf, _bufLen); + return MQTTSNDeserialize_willmsgupd(willMsg, _buf, _bufLen); } char* MQTTSNPacket::print(char* pbuf) { - char* ptr = pbuf; - char** pptr = &pbuf; - int size = _bufLen > SIZE_OF_LOG_PACKET ? SIZE_OF_LOG_PACKET : _bufLen; + char* ptr = pbuf; + char** pptr = &pbuf; + int size = _bufLen > SIZE_OF_LOG_PACKET ? SIZE_OF_LOG_PACKET : _bufLen; - for (int i = 0; i < size; i++) - { - sprintf(*pptr, " %02X", *(_buf + i)); - *pptr += 3; - } - **pptr = 0; - return ptr; + for (int i = 0; i < size; i++) + { + sprintf(*pptr, " %02X", *(_buf + i)); + *pptr += 3; + } + **pptr = 0; + return ptr; } char* MQTTSNPacket::getMsgId(char* pbuf) { - int value = 0; - int p = 0; + int value = 0; + int p = 0; - switch ( getType() ) - { - case MQTTSN_PUBLISH: - p = MQTTSNPacket_decode(_buf, _bufLen, &value); - if ( _buf[p + 1] & 0x80 ) - { - sprintf(pbuf, "+%02X%02X", _buf[p + 4], _buf[p + 5]); - } - else - { - sprintf(pbuf, " %02X%02X", _buf[p + 4], _buf[p + 5]); - } - break; - case MQTTSN_PUBACK: - case MQTTSN_REGISTER: - case MQTTSN_REGACK: - sprintf(pbuf, " %02X%02X", _buf[4], _buf[5]); - break; - case MQTTSN_PUBREC: - case MQTTSN_PUBREL: - case MQTTSN_PUBCOMP: - case MQTTSN_UNSUBACK: - sprintf(pbuf, " %02X%02X", _buf[2], _buf[3]); - break; - case MQTTSN_SUBSCRIBE: - case MQTTSN_UNSUBSCRIBE: - p = MQTTSNPacket_decode(_buf, _bufLen, &value); - sprintf(pbuf, " %02X%02X", _buf[p + 2], _buf[p + 3]); - break; - case MQTTSN_SUBACK: - sprintf(pbuf, " %02X%02X", _buf[5], _buf[6]); - break; - default: - sprintf(pbuf, " "); - break; - } - if ( strcmp(pbuf, " 0000") == 0 ) - { - sprintf(pbuf, " "); - } - return pbuf; + switch (getType()) + { + case MQTTSN_PUBLISH: + p = MQTTSNPacket_decode(_buf, _bufLen, &value); + if (_buf[p + 1] & 0x80) + { + sprintf(pbuf, "+%02X%02X", _buf[p + 4], _buf[p + 5]); + } + else + { + sprintf(pbuf, " %02X%02X", _buf[p + 4], _buf[p + 5]); + } + break; + case MQTTSN_PUBACK: + case MQTTSN_REGISTER: + case MQTTSN_REGACK: + sprintf(pbuf, " %02X%02X", _buf[4], _buf[5]); + break; + case MQTTSN_PUBREC: + case MQTTSN_PUBREL: + case MQTTSN_PUBCOMP: + case MQTTSN_UNSUBACK: + sprintf(pbuf, " %02X%02X", _buf[2], _buf[3]); + break; + case MQTTSN_SUBSCRIBE: + case MQTTSN_UNSUBSCRIBE: + p = MQTTSNPacket_decode(_buf, _bufLen, &value); + sprintf(pbuf, " %02X%02X", _buf[p + 2], _buf[p + 3]); + break; + case MQTTSN_SUBACK: + sprintf(pbuf, " %02X%02X", _buf[5], _buf[6]); + break; + default: + sprintf(pbuf, " "); + break; + } + if (strcmp(pbuf, " 0000") == 0) + { + sprintf(pbuf, " "); + } + return pbuf; } int MQTTSNPacket::getMsgId(void) { - int value = 0; - int p = 0; - int msgId = 0; - char* ptr = 0; + int value = 0; + int p = 0; + int msgId = 0; + char* ptr = 0; - switch ( getType() ) - { - case MQTTSN_PUBLISH: - p = MQTTSNPacket_decode(_buf, _bufLen, &value); - ptr = (char*)_buf + p + 4; - msgId = readInt((char**)&ptr); - break; - case MQTTSN_PUBACK: - case MQTTSN_REGISTER: - case MQTTSN_REGACK: - ptr = (char*)_buf + 4; - msgId = readInt((char**)&ptr); - break; - case MQTTSN_PUBREC: - case MQTTSN_PUBREL: - case MQTTSN_PUBCOMP: - case MQTTSN_UNSUBACK: - ptr = (char*)_buf + 2; - msgId = readInt((char**)&ptr); - break; - case MQTTSN_SUBSCRIBE: - case MQTTSN_UNSUBSCRIBE: - p = MQTTSNPacket_decode(_buf, _bufLen, &value); - ptr = (char*)_buf + p + 2; - msgId = readInt((char**)&ptr); - break; - case MQTTSN_SUBACK: - ptr = (char*)_buf + 5; - msgId = readInt((char**)&ptr); - break; - default: - break; - } - return msgId; + switch (getType()) + { + case MQTTSN_PUBLISH: + p = MQTTSNPacket_decode(_buf, _bufLen, &value); + ptr = (char*) _buf + p + 4; + msgId = readInt((char**) &ptr); + break; + case MQTTSN_PUBACK: + case MQTTSN_REGISTER: + case MQTTSN_REGACK: + ptr = (char*) _buf + 4; + msgId = readInt((char**) &ptr); + break; + case MQTTSN_PUBREC: + case MQTTSN_PUBREL: + case MQTTSN_PUBCOMP: + case MQTTSN_UNSUBACK: + ptr = (char*) _buf + 2; + msgId = readInt((char**) &ptr); + break; + case MQTTSN_SUBSCRIBE: + case MQTTSN_UNSUBSCRIBE: + p = MQTTSNPacket_decode(_buf, _bufLen, &value); + ptr = (char*) _buf + p + 2; + msgId = readInt((char**) &ptr); + break; + case MQTTSN_SUBACK: + ptr = (char*) _buf + 5; + msgId = readInt((char**) &ptr); + break; + default: + break; + } + return msgId; } void MQTTSNPacket::setMsgId(uint16_t msgId) { - int value = 0; - int p = 0; - //unsigned char* ptr = 0; + int value = 0; + int p = 0; + //unsigned char* ptr = 0; - switch ( getType() ) - { - case MQTTSN_PUBLISH: - p = MQTTSNPacket_decode(_buf, _bufLen, &value); - _buf[p + 4] = (unsigned char)(msgId / 256); - _buf[p + 5] = (unsigned char)(msgId % 256); - //ptr = _buf + p + 4; - //writeInt(&ptr, msgId); - break; - case MQTTSN_PUBACK: - case MQTTSN_REGISTER: - case MQTTSN_REGACK: - _buf[4] = (unsigned char)(msgId / 256); - _buf[5] = (unsigned char)(msgId % 256); - //ptr = _buf + 4; - //writeInt(&ptr, msgId); - break; - case MQTTSN_PUBREC: - case MQTTSN_PUBREL: - case MQTTSN_PUBCOMP: - case MQTTSN_UNSUBACK: - _buf[2] = (unsigned char)(msgId / 256); - _buf[3] = (unsigned char)(msgId % 256); - //ptr = _buf + 2; - //writeInt(&ptr, msgId); - break; - case MQTTSN_SUBSCRIBE: - case MQTTSN_UNSUBSCRIBE: - p = MQTTSNPacket_decode(_buf, _bufLen, &value); - _buf[p + 2] = (unsigned char)(msgId / 256); - _buf[p + 3] = (unsigned char)(msgId % 256); - //ptr = _buf + p + 2; - //writeInt(&ptr, msgId); -break; - case MQTTSN_SUBACK: - _buf[5] = (unsigned char)(msgId / 256); - _buf[6] = (unsigned char)(msgId % 256); - //ptr = _buf + 5; - //writeInt(&ptr, msgId); -break; - default: - break; - } + switch (getType()) + { + case MQTTSN_PUBLISH: + p = MQTTSNPacket_decode(_buf, _bufLen, &value); + _buf[p + 4] = (unsigned char) (msgId / 256); + _buf[p + 5] = (unsigned char) (msgId % 256); + //ptr = _buf + p + 4; + //writeInt(&ptr, msgId); + break; + case MQTTSN_PUBACK: + case MQTTSN_REGISTER: + case MQTTSN_REGACK: + _buf[4] = (unsigned char) (msgId / 256); + _buf[5] = (unsigned char) (msgId % 256); + //ptr = _buf + 4; + //writeInt(&ptr, msgId); + break; + case MQTTSN_PUBREC: + case MQTTSN_PUBREL: + case MQTTSN_PUBCOMP: + case MQTTSN_UNSUBACK: + _buf[2] = (unsigned char) (msgId / 256); + _buf[3] = (unsigned char) (msgId % 256); + //ptr = _buf + 2; + //writeInt(&ptr, msgId); + break; + case MQTTSN_SUBSCRIBE: + case MQTTSN_UNSUBSCRIBE: + p = MQTTSNPacket_decode(_buf, _bufLen, &value); + _buf[p + 2] = (unsigned char) (msgId / 256); + _buf[p + 3] = (unsigned char) (msgId % 256); + //ptr = _buf + p + 2; + //writeInt(&ptr, msgId); + break; + case MQTTSN_SUBACK: + _buf[5] = (unsigned char) (msgId / 256); + _buf[6] = (unsigned char) (msgId % 256); + //ptr = _buf + 5; + //writeInt(&ptr, msgId); + break; + default: + break; + } } bool MQTTSNPacket::isDuplicate(void) { - int value = 0; - int p = MQTTSNPacket_decode(_buf, _bufLen, &value); - return ( _buf[p + 1] & 0x80 ); + int value = 0; + int p = MQTTSNPacket_decode(_buf, _bufLen, &value); + return (_buf[p + 1] & 0x80); } diff --git a/MQTTSNGateway/src/MQTTSNGWPacket.h b/MQTTSNGateway/src/MQTTSNGWPacket.h index 7a624a3..c6fd4fc 100644 --- a/MQTTSNGateway/src/MQTTSNGWPacket.h +++ b/MQTTSNGateway/src/MQTTSNGWPacket.h @@ -26,72 +26,77 @@ namespace MQTTSNGW class MQTTSNPacket { public: - MQTTSNPacket(void); - MQTTSNPacket(MQTTSNPacket &packet); - ~MQTTSNPacket(void); - int unicast(SensorNetwork* network, SensorNetAddress* sendTo); - int broadcast(SensorNetwork* network); - int recv(SensorNetwork* network); - int serialize(uint8_t* buf); - int desirialize(unsigned char* buf, unsigned short len); - int getType(void); - unsigned char* getPacketData(void); - int getPacketLength(void); - const char* getName(); + MQTTSNPacket(void); + MQTTSNPacket(MQTTSNPacket &packet); + ~MQTTSNPacket(void); + int unicast(SensorNetwork* network, SensorNetAddress* sendTo); + int broadcast(SensorNetwork* network); + int recv(SensorNetwork* network); + int serialize(uint8_t* buf); + int desirialize(unsigned char* buf, unsigned short len); + int getType(void); + unsigned char* getPacketData(void); + int getPacketLength(void); + const char* getName(); - int setConnect(void); // Debug - int setADVERTISE(uint8_t gatewayid, uint16_t duration); - int setGWINFO(uint8_t gatewayId); - int setCONNACK(uint8_t returnCode); - int setWILLTOPICREQ(void); - int setWILLMSGREQ(void); - int setREGISTER(uint16_t topicId, uint16_t msgId, MQTTSNString* TopicName); - int setREGACK(uint16_t topicId, uint16_t msgId, uint8_t returnCode); - int setPUBLISH(uint8_t dup, int qos, uint8_t retained, uint16_t msgId, - MQTTSN_topicid topic, uint8_t* payload, uint16_t payloadlen); - int setPUBACK(uint16_t topicId, uint16_t msgId, uint8_t returnCode); - int setPUBREC(uint16_t msgId); - int setPUBREL(uint16_t msgId); - int setPUBCOMP(uint16_t msgId); - int setSUBACK(int qos, uint16_t topicId, uint16_t msgId, uint8_t returnCode); - int setUNSUBACK(uint16_t msgId); - int setPINGRESP(void); - int setDISCONNECT(uint16_t duration); - int setWILLTOPICRESP(uint8_t returnCode); - int setWILLMSGRESP(uint8_t returnCode); + int setConnect(void); // Debug + int setADVERTISE(uint8_t gatewayid, uint16_t duration); + int setGWINFO(uint8_t gatewayId); + int setCONNACK(uint8_t returnCode); + int setWILLTOPICREQ(void); + int setWILLMSGREQ(void); + int setREGISTER(uint16_t topicId, uint16_t msgId, MQTTSNString* TopicName); + int setREGACK(uint16_t topicId, uint16_t msgId, uint8_t returnCode); + int setPUBLISH(uint8_t dup, int qos, uint8_t retained, uint16_t msgId, + MQTTSN_topicid topic, uint8_t* payload, uint16_t payloadlen); + int setPUBACK(uint16_t topicId, uint16_t msgId, uint8_t returnCode); + int setPUBREC(uint16_t msgId); + int setPUBREL(uint16_t msgId); + int setPUBCOMP(uint16_t msgId); + int setSUBACK(int qos, uint16_t topicId, uint16_t msgId, + uint8_t returnCode); + int setUNSUBACK(uint16_t msgId); + int setPINGRESP(void); + int setDISCONNECT(uint16_t duration); + int setWILLTOPICRESP(uint8_t returnCode); + int setWILLMSGRESP(uint8_t returnCode); - int setCONNECT(MQTTSNPacket_connectData* options); - int setPINGREQ(MQTTSNString* clientId); + int setCONNECT(MQTTSNPacket_connectData* options); + int setPINGREQ(MQTTSNString* clientId); - int getSERCHGW(uint8_t* radius); - int getCONNECT(MQTTSNPacket_connectData* option); - int getCONNACK(uint8_t* returnCode); - int getWILLTOPIC(int* willQoS, uint8_t* willRetain, MQTTSNString* willTopic); - int getWILLMSG(MQTTSNString* willmsg); - int getREGISTER(uint16_t* topicId, uint16_t* msgId, MQTTSNString* topicName); - int getREGACK(uint16_t* topicId, uint16_t* msgId, uint8_t* returnCode); - int getPUBLISH(uint8_t* dup, int* qos, uint8_t* retained, uint16_t* msgId, - MQTTSN_topicid* topic, unsigned char** payload, int* payloadlen); - int getPUBACK(uint16_t* topicId, uint16_t* msgId, uint8_t* returnCode); - int getACK(uint16_t* msgId); - int getSUBSCRIBE(uint8_t* dup, int* qos, uint16_t* msgId, MQTTSN_topicid* topicFilter); - int getUNSUBSCRIBE(uint16_t* msgId, MQTTSN_topicid* topicFilter); - int getPINGREQ(void); - int getDISCONNECT(uint16_t* duration); - int getWILLTOPICUPD(uint8_t* willQoS, uint8_t* willRetain, MQTTSNString* willTopic); - int getWILLMSGUPD(MQTTSNString* willMsg); + int getSERCHGW(uint8_t* radius); + int getCONNECT(MQTTSNPacket_connectData* option); + int getCONNACK(uint8_t* returnCode); + int getWILLTOPIC(int* willQoS, uint8_t* willRetain, + MQTTSNString* willTopic); + int getWILLMSG(MQTTSNString* willmsg); + int getREGISTER(uint16_t* topicId, uint16_t* msgId, + MQTTSNString* topicName); + int getREGACK(uint16_t* topicId, uint16_t* msgId, uint8_t* returnCode); + int getPUBLISH(uint8_t* dup, int* qos, uint8_t* retained, uint16_t* msgId, + MQTTSN_topicid* topic, unsigned char** payload, int* payloadlen); + int getPUBACK(uint16_t* topicId, uint16_t* msgId, uint8_t* returnCode); + int getACK(uint16_t* msgId); + int getSUBSCRIBE(uint8_t* dup, int* qos, uint16_t* msgId, + MQTTSN_topicid* topicFilter); + int getUNSUBSCRIBE(uint16_t* msgId, MQTTSN_topicid* topicFilter); + int getPINGREQ(void); + int getDISCONNECT(uint16_t* duration); + int getWILLTOPICUPD(uint8_t* willQoS, uint8_t* willRetain, + MQTTSNString* willTopic); + int getWILLMSGUPD(MQTTSNString* willMsg); - bool isAccepted(void); - bool isDuplicate(void); - bool isQoSMinusPUBLISH(void); - char* getMsgId(char* buf); - int getMsgId(void); - void setMsgId(uint16_t msgId); - char* print(char* buf); + bool isAccepted(void); + bool isDuplicate(void); + bool isQoSMinusPUBLISH(void); + char* getMsgId(char* buf); + int getMsgId(void); + void setMsgId(uint16_t msgId); + char* print(char* buf); private: - unsigned char* _buf; // Ptr to a packet data - int _bufLen; // length of the packet data + unsigned char* _buf; // Ptr to a packet data + int _bufLen; // length of the packet data }; } diff --git a/MQTTSNGateway/src/MQTTSNGWPacketHandleTask.cpp b/MQTTSNGateway/src/MQTTSNGWPacketHandleTask.cpp index f195d76..c94ccb5 100644 --- a/MQTTSNGateway/src/MQTTSNGWPacketHandleTask.cpp +++ b/MQTTSNGateway/src/MQTTSNGWPacketHandleTask.cpp @@ -44,16 +44,16 @@ char* currentDateTime(void); PacketHandleTask::PacketHandleTask(Gateway* gateway) { - _gateway = gateway; - _gateway->attach((Thread*)this); - _mqttConnection = new MQTTGWConnectionHandler(_gateway); - _mqttPublish = new MQTTGWPublishHandler(_gateway); - _mqttSubscribe = new MQTTGWSubscribeHandler(_gateway); - _mqttsnConnection = new MQTTSNConnectionHandler(_gateway); - _mqttsnPublish = new MQTTSNPublishHandler(_gateway); - _mqttsnSubscribe = new MQTTSNSubscribeHandler(_gateway); + _gateway = gateway; + _gateway->attach((Thread*) this); + _mqttConnection = new MQTTGWConnectionHandler(_gateway); + _mqttPublish = new MQTTGWPublishHandler(_gateway); + _mqttSubscribe = new MQTTGWSubscribeHandler(_gateway); + _mqttsnConnection = new MQTTSNConnectionHandler(_gateway); + _mqttsnPublish = new MQTTSNPublishHandler(_gateway); + _mqttsnSubscribe = new MQTTSNSubscribeHandler(_gateway); - _mqttsnAggrConnection = new MQTTSNAggregateConnectionHandler(_gateway); + _mqttsnAggrConnection = new MQTTSNAggregateConnectionHandler(_gateway); } /** @@ -61,315 +61,314 @@ PacketHandleTask::PacketHandleTask(Gateway* gateway) */ PacketHandleTask::~PacketHandleTask() { - if ( _mqttConnection ) - { - delete _mqttConnection; - } - if ( _mqttPublish ) - { - delete _mqttPublish; - } - if ( _mqttSubscribe ) - { - delete _mqttSubscribe; - } - if ( _mqttsnConnection ) - { - delete _mqttsnConnection; - } - if ( _mqttsnPublish ) - { - delete _mqttsnPublish; - } - if ( _mqttsnSubscribe ) - { - delete _mqttsnSubscribe; - } + if (_mqttConnection) + { + delete _mqttConnection; + } + if (_mqttPublish) + { + delete _mqttPublish; + } + if (_mqttSubscribe) + { + delete _mqttSubscribe; + } + if (_mqttsnConnection) + { + delete _mqttsnConnection; + } + if (_mqttsnPublish) + { + delete _mqttsnPublish; + } + if (_mqttsnSubscribe) + { + delete _mqttsnSubscribe; + } - if ( _mqttsnAggrConnection ) - { - delete _mqttsnAggrConnection; - } + if (_mqttsnAggrConnection) + { + delete _mqttsnAggrConnection; + } } void PacketHandleTask::run() { - Event* ev = nullptr; - EventQue* eventQue = _gateway->getPacketEventQue(); + Event* ev = nullptr; + EventQue* eventQue = _gateway->getPacketEventQue(); AdapterManager* adpMgr = _gateway->getAdapterManager(); - Client* client = nullptr; - MQTTSNPacket* snPacket = nullptr; - MQTTGWPacket* brPacket = nullptr; - char msgId[6]; - memset(msgId, 0, 6); + Client* client = nullptr; + MQTTSNPacket* snPacket = nullptr; + MQTTGWPacket* brPacket = nullptr; + char msgId[6]; + memset(msgId, 0, 6); - _advertiseTimer.start(_gateway->getGWParams()->keepAlive * 1000UL); + _advertiseTimer.start(_gateway->getGWParams()->keepAlive * 1000UL); - while (true) - { - /* wait Event */ - ev = eventQue->timedwait(EVENT_QUE_TIME_OUT); + while (true) + { + /* wait Event */ + ev = eventQue->timedwait(EVENT_QUE_TIME_OUT); - if (ev->getEventType() == EtStop) - { - WRITELOG("\n%s PacketHandleTask stopped.", currentDateTime()); - delete ev; - return; - } + if (ev->getEventType() == EtStop) + { + WRITELOG("\n%s PacketHandleTask stopped.", currentDateTime()); + delete ev; + return; + } - if (ev->getEventType() == EtTimeout) - { - /*------ Check Keep Alive Timer & send Advertise ------*/ - if (_advertiseTimer.isTimeup()) - { - _mqttsnConnection->sendADVERTISE(); - _advertiseTimer.start(_gateway->getGWParams()->keepAlive * 1000UL); - } + if (ev->getEventType() == EtTimeout) + { + /*------ Check Keep Alive Timer & send Advertise ------*/ + if (_advertiseTimer.isTimeup()) + { + _mqttsnConnection->sendADVERTISE(); + _advertiseTimer.start( + _gateway->getGWParams()->keepAlive * 1000UL); + } - /*------ Check Adapters Connect or PINGREQ ------*/ - adpMgr->checkConnection(); - } + /*------ Check Adapters Connect or PINGREQ ------*/ + adpMgr->checkConnection(); + } - /*------ Handle SEARCHGW Message ---------*/ - else if (ev->getEventType() == EtBroadcast) - { - snPacket = ev->getMQTTSNPacket(); - _mqttsnConnection->handleSearchgw(snPacket); - } + /*------ Handle SEARCHGW Message ---------*/ + else if (ev->getEventType() == EtBroadcast) + { + snPacket = ev->getMQTTSNPacket(); + _mqttsnConnection->handleSearchgw(snPacket); + } - /*------ Handle Messages form Clients ---------*/ - else if (ev->getEventType() == EtClientRecv) - { - client = ev->getClient(); - snPacket = ev->getMQTTSNPacket(); + /*------ Handle Messages form Clients ---------*/ + else if (ev->getEventType() == EtClientRecv) + { + client = ev->getClient(); + snPacket = ev->getMQTTSNPacket(); - DEBUGLOG(" PacketHandleTask gets %s %s from the client.\n", snPacket->getName(), snPacket->getMsgId(msgId)); + DEBUGLOG(" PacketHandleTask gets %s %s from the client.\n", snPacket->getName(), snPacket->getMsgId(msgId)); - if ( adpMgr->isAggregatedClient(client) ) - { - aggregatePacketHandler(client, snPacket); // client is converted to Aggregater by BrokerSendTask - } - else - { - transparentPacketHandler(client, snPacket); - } + if (adpMgr->isAggregatedClient(client)) + { + aggregatePacketHandler(client, snPacket); // client is converted to Aggregater by BrokerSendTask + } + else + { + transparentPacketHandler(client, snPacket); + } + /* Reset the Timer for PINGREQ. */ + client->updateStatus(snPacket); + } + /*------ Handle Messages form Broker ---------*/ + else if (ev->getEventType() == EtBrokerRecv) + { + client = ev->getClient(); + brPacket = ev->getMQTTGWPacket(); + DEBUGLOG(" PacketHandleTask gets %s %s from the broker.\n", brPacket->getName(), brPacket->getMsgId(msgId)); - /* Reset the Timer for PINGREQ. */ - client->updateStatus(snPacket); - } - /*------ Handle Messages form Broker ---------*/ - else if ( ev->getEventType() == EtBrokerRecv ) - { - client = ev->getClient(); - brPacket = ev->getMQTTGWPacket(); - DEBUGLOG(" PacketHandleTask gets %s %s from the broker.\n", brPacket->getName(), brPacket->getMsgId(msgId)); - - - if ( client->isAggregater() ) - { - aggregatePacketHandler(client, brPacket); - } - else - { - transparentPacketHandler(client, brPacket); - } - } - delete ev; - } + if (client->isAggregater()) + { + aggregatePacketHandler(client, brPacket); + } + else + { + transparentPacketHandler(client, brPacket); + } + } + delete ev; + } } - - -void PacketHandleTask::aggregatePacketHandler(Client*client, MQTTSNPacket* packet) +void PacketHandleTask::aggregatePacketHandler(Client*client, + MQTTSNPacket* packet) { - switch (packet->getType()) - { - case MQTTSN_CONNECT: - _mqttsnAggrConnection->handleConnect(client, packet); - break; - case MQTTSN_WILLTOPIC: - _mqttsnConnection->handleWilltopic(client, packet); - break; - case MQTTSN_WILLMSG: - _mqttsnAggrConnection->handleWillmsg(client, packet); - break; - case MQTTSN_DISCONNECT: - _mqttsnAggrConnection->handleDisconnect(client, packet); - break; - case MQTTSN_WILLTOPICUPD: - _mqttsnConnection->handleWilltopicupd(client, packet); - break; - case MQTTSN_WILLMSGUPD: - _mqttsnConnection->handleWillmsgupd(client, packet); - break; - case MQTTSN_PINGREQ: - _mqttsnAggrConnection->handlePingreq(client, packet); - break; - case MQTTSN_PUBLISH: - _mqttsnPublish->handleAggregatePublish(client, packet); - break; - case MQTTSN_PUBACK: - _mqttsnPublish->handleAggregateAck(client, packet, MQTTSN_PUBACK); - break; - case MQTTSN_PUBREC: - _mqttsnPublish->handleAggregateAck(client, packet, MQTTSN_PUBREC); - break; - case MQTTSN_PUBREL: - _mqttsnPublish->handleAggregateAck(client, packet, MQTTSN_PUBREL); - break; - case MQTTSN_PUBCOMP: - _mqttsnPublish->handleAggregateAck(client, packet, MQTTSN_PUBCOMP); - break; - case MQTTSN_REGISTER: - _mqttsnPublish->handleRegister(client, packet); - break; - case MQTTSN_REGACK: - _mqttsnPublish->handleRegAck(client, packet); - break; - case MQTTSN_SUBSCRIBE: - _mqttsnSubscribe->handleAggregateSubscribe(client, packet); - break; - case MQTTSN_UNSUBSCRIBE: - _mqttsnSubscribe->handleAggregateUnsubscribe(client, packet); - break; - default: - break; - } + switch (packet->getType()) + { + case MQTTSN_CONNECT: + _mqttsnAggrConnection->handleConnect(client, packet); + break; + case MQTTSN_WILLTOPIC: + _mqttsnConnection->handleWilltopic(client, packet); + break; + case MQTTSN_WILLMSG: + _mqttsnAggrConnection->handleWillmsg(client, packet); + break; + case MQTTSN_DISCONNECT: + _mqttsnAggrConnection->handleDisconnect(client, packet); + break; + case MQTTSN_WILLTOPICUPD: + _mqttsnConnection->handleWilltopicupd(client, packet); + break; + case MQTTSN_WILLMSGUPD: + _mqttsnConnection->handleWillmsgupd(client, packet); + break; + case MQTTSN_PINGREQ: + _mqttsnAggrConnection->handlePingreq(client, packet); + break; + case MQTTSN_PUBLISH: + _mqttsnPublish->handleAggregatePublish(client, packet); + break; + case MQTTSN_PUBACK: + _mqttsnPublish->handleAggregateAck(client, packet, MQTTSN_PUBACK); + break; + case MQTTSN_PUBREC: + _mqttsnPublish->handleAggregateAck(client, packet, MQTTSN_PUBREC); + break; + case MQTTSN_PUBREL: + _mqttsnPublish->handleAggregateAck(client, packet, MQTTSN_PUBREL); + break; + case MQTTSN_PUBCOMP: + _mqttsnPublish->handleAggregateAck(client, packet, MQTTSN_PUBCOMP); + break; + case MQTTSN_REGISTER: + _mqttsnPublish->handleRegister(client, packet); + break; + case MQTTSN_REGACK: + _mqttsnPublish->handleRegAck(client, packet); + break; + case MQTTSN_SUBSCRIBE: + _mqttsnSubscribe->handleAggregateSubscribe(client, packet); + break; + case MQTTSN_UNSUBSCRIBE: + _mqttsnSubscribe->handleAggregateUnsubscribe(client, packet); + break; + default: + break; + } } - -void PacketHandleTask::aggregatePacketHandler(Client*client, MQTTGWPacket* packet) +void PacketHandleTask::aggregatePacketHandler(Client*client, + MQTTGWPacket* packet) { - switch (packet->getType()) - { - case CONNACK: - _mqttConnection->handleConnack(client, packet); - break; - case PINGRESP: - _mqttConnection->handlePingresp(client, packet); - break; - case PUBLISH: - _mqttPublish->handleAggregatePublish(client, packet); - break; - case PUBACK: - _mqttPublish->handleAggregatePuback(client, packet); - break; - case PUBREC: - _mqttPublish->handleAggregateAck(client, packet, PUBREC); - break; - case PUBREL: - _mqttPublish->handleAggregatePubrel(client, packet); - break; - case PUBCOMP: - _mqttPublish->handleAggregateAck(client, packet, PUBCOMP); - break; - case SUBACK: - _mqttSubscribe->handleAggregateSuback(client, packet); - break; - case UNSUBACK: - _mqttSubscribe->handleAggregateUnsuback(client, packet); - break; - default: - break; - } + switch (packet->getType()) + { + case CONNACK: + _mqttConnection->handleConnack(client, packet); + break; + case PINGRESP: + _mqttConnection->handlePingresp(client, packet); + break; + case PUBLISH: + _mqttPublish->handleAggregatePublish(client, packet); + break; + case PUBACK: + _mqttPublish->handleAggregatePuback(client, packet); + break; + case PUBREC: + _mqttPublish->handleAggregateAck(client, packet, PUBREC); + break; + case PUBREL: + _mqttPublish->handleAggregatePubrel(client, packet); + break; + case PUBCOMP: + _mqttPublish->handleAggregateAck(client, packet, PUBCOMP); + break; + case SUBACK: + _mqttSubscribe->handleAggregateSuback(client, packet); + break; + case UNSUBACK: + _mqttSubscribe->handleAggregateUnsuback(client, packet); + break; + default: + break; + } } -void PacketHandleTask::transparentPacketHandler(Client*client, MQTTSNPacket* packet) +void PacketHandleTask::transparentPacketHandler(Client*client, + MQTTSNPacket* packet) { - switch (packet->getType()) - { - case MQTTSN_CONNECT: - _mqttsnConnection->handleConnect(client, packet); - break; - case MQTTSN_WILLTOPIC: - _mqttsnConnection->handleWilltopic(client, packet); - break; - case MQTTSN_WILLMSG: - _mqttsnConnection->handleWillmsg(client, packet); - break; - case MQTTSN_DISCONNECT: - _mqttsnConnection->handleDisconnect(client, packet); - break; - case MQTTSN_WILLTOPICUPD: - _mqttsnConnection->handleWilltopicupd(client, packet); - break; - case MQTTSN_WILLMSGUPD: - _mqttsnConnection->handleWillmsgupd(client, packet); - break; - case MQTTSN_PINGREQ: - _mqttsnConnection->handlePingreq(client, packet); - break; - case MQTTSN_PUBLISH: - _mqttsnPublish->handlePublish(client, packet); - break; - case MQTTSN_PUBACK: - _mqttsnPublish->handlePuback(client, packet); - break; - case MQTTSN_PUBREC: - _mqttsnPublish->handleAck(client, packet, PUBREC); - break; - case MQTTSN_PUBREL: - _mqttsnPublish->handleAck(client, packet, PUBREL); - break; - case MQTTSN_PUBCOMP: - _mqttsnPublish->handleAck(client, packet, PUBCOMP); - break; - case MQTTSN_REGISTER: - _mqttsnPublish->handleRegister(client, packet); - break; - case MQTTSN_REGACK: - _mqttsnPublish->handleRegAck(client, packet); - break; - case MQTTSN_SUBSCRIBE: - _mqttsnSubscribe->handleSubscribe(client, packet); - break; - case MQTTSN_UNSUBSCRIBE: - _mqttsnSubscribe->handleUnsubscribe(client, packet); - break; - default: - break; - } + switch (packet->getType()) + { + case MQTTSN_CONNECT: + _mqttsnConnection->handleConnect(client, packet); + break; + case MQTTSN_WILLTOPIC: + _mqttsnConnection->handleWilltopic(client, packet); + break; + case MQTTSN_WILLMSG: + _mqttsnConnection->handleWillmsg(client, packet); + break; + case MQTTSN_DISCONNECT: + _mqttsnConnection->handleDisconnect(client, packet); + break; + case MQTTSN_WILLTOPICUPD: + _mqttsnConnection->handleWilltopicupd(client, packet); + break; + case MQTTSN_WILLMSGUPD: + _mqttsnConnection->handleWillmsgupd(client, packet); + break; + case MQTTSN_PINGREQ: + _mqttsnConnection->handlePingreq(client, packet); + break; + case MQTTSN_PUBLISH: + _mqttsnPublish->handlePublish(client, packet); + break; + case MQTTSN_PUBACK: + _mqttsnPublish->handlePuback(client, packet); + break; + case MQTTSN_PUBREC: + _mqttsnPublish->handleAck(client, packet, PUBREC); + break; + case MQTTSN_PUBREL: + _mqttsnPublish->handleAck(client, packet, PUBREL); + break; + case MQTTSN_PUBCOMP: + _mqttsnPublish->handleAck(client, packet, PUBCOMP); + break; + case MQTTSN_REGISTER: + _mqttsnPublish->handleRegister(client, packet); + break; + case MQTTSN_REGACK: + _mqttsnPublish->handleRegAck(client, packet); + break; + case MQTTSN_SUBSCRIBE: + _mqttsnSubscribe->handleSubscribe(client, packet); + break; + case MQTTSN_UNSUBSCRIBE: + _mqttsnSubscribe->handleUnsubscribe(client, packet); + break; + default: + break; + } } - -void PacketHandleTask::transparentPacketHandler(Client*client, MQTTGWPacket* packet) +void PacketHandleTask::transparentPacketHandler(Client*client, + MQTTGWPacket* packet) { - switch (packet->getType()) - { - case CONNACK: - _mqttConnection->handleConnack(client, packet); - break; - case PINGRESP: - _mqttConnection->handlePingresp(client, packet); - break; - case PUBLISH: - _mqttPublish->handlePublish(client, packet); - break; - case PUBACK: - _mqttPublish->handlePuback(client, packet); - break; - case PUBREC: - _mqttPublish->handleAck(client, packet, PUBREC); - break; - case PUBREL: - _mqttPublish->handleAck(client, packet, PUBREL); - break; - case PUBCOMP: - _mqttPublish->handleAck(client, packet, PUBCOMP); - break; - case SUBACK: - _mqttSubscribe->handleSuback(client, packet); - break; - case UNSUBACK: - _mqttSubscribe->handleUnsuback(client, packet); - break; - case DISCONNECT: - client->disconnected(); // Just change Client's status to "Disconnected" - break; - default: - break; - } + switch (packet->getType()) + { + case CONNACK: + _mqttConnection->handleConnack(client, packet); + break; + case PINGRESP: + _mqttConnection->handlePingresp(client, packet); + break; + case PUBLISH: + _mqttPublish->handlePublish(client, packet); + break; + case PUBACK: + _mqttPublish->handlePuback(client, packet); + break; + case PUBREC: + _mqttPublish->handleAck(client, packet, PUBREC); + break; + case PUBREL: + _mqttPublish->handleAck(client, packet, PUBREL); + break; + case PUBCOMP: + _mqttPublish->handleAck(client, packet, PUBCOMP); + break; + case SUBACK: + _mqttSubscribe->handleSuback(client, packet); + break; + case UNSUBACK: + _mqttSubscribe->handleUnsuback(client, packet); + break; + case DISCONNECT: + client->disconnected(); // Just change Client's status to "Disconnected" + break; + default: + break; + } } diff --git a/MQTTSNGateway/src/MQTTSNGWPacketHandleTask.h b/MQTTSNGateway/src/MQTTSNGWPacketHandleTask.h index a77eb65..43cc57e 100644 --- a/MQTTSNGateway/src/MQTTSNGWPacketHandleTask.h +++ b/MQTTSNGateway/src/MQTTSNGWPacketHandleTask.h @@ -40,40 +40,39 @@ class MQTTSNAggregateConnectionHandler; class Thread; class Timer; /*===================================== - Class PacketHandleTask + Class PacketHandleTask =====================================*/ -class PacketHandleTask : public Thread +class PacketHandleTask: public Thread { - MAGIC_WORD_FOR_THREAD; - friend class MQTTGWAggregatePublishHandler; - friend class MQTTGWAggregateSubscribeHandler; - friend class MQTTSNAggregateConnectionHandler; - friend class MQTTSNAggregatePublishHandler; - friend class MQTTSNAggregateSubscribeHandler; +MAGIC_WORD_FOR_THREAD; + friend class MQTTGWAggregatePublishHandler; + friend class MQTTGWAggregateSubscribeHandler; + friend class MQTTSNAggregateConnectionHandler; + friend class MQTTSNAggregatePublishHandler; + friend class MQTTSNAggregateSubscribeHandler; public: - PacketHandleTask(Gateway* gateway); - ~PacketHandleTask(); - void run(); + PacketHandleTask(Gateway* gateway); + ~PacketHandleTask(); + void run(); private: - void aggregatePacketHandler(Client*client, MQTTSNPacket* packet); - void aggregatePacketHandler(Client*client, MQTTGWPacket* packet); - void transparentPacketHandler(Client*client, MQTTSNPacket* packet); - void transparentPacketHandler(Client*client, MQTTGWPacket* packet); + void aggregatePacketHandler(Client*client, MQTTSNPacket* packet); + void aggregatePacketHandler(Client*client, MQTTGWPacket* packet); + void transparentPacketHandler(Client*client, MQTTSNPacket* packet); + void transparentPacketHandler(Client*client, MQTTGWPacket* packet); - Gateway* _gateway {nullptr}; - Timer _advertiseTimer; - Timer _sendUnixTimer; - MQTTGWConnectionHandler* _mqttConnection {nullptr}; - MQTTGWPublishHandler* _mqttPublish {nullptr}; - MQTTGWSubscribeHandler* _mqttSubscribe {nullptr}; - MQTTSNConnectionHandler* _mqttsnConnection {nullptr}; - MQTTSNPublishHandler* _mqttsnPublish {nullptr}; - MQTTSNSubscribeHandler* _mqttsnSubscribe {nullptr}; - - MQTTSNAggregateConnectionHandler* _mqttsnAggrConnection {nullptr}; + Gateway* _gateway + { nullptr }; + Timer _advertiseTimer; + Timer _sendUnixTimer; + MQTTGWConnectionHandler* _mqttConnection { nullptr }; + MQTTGWPublishHandler* _mqttPublish { nullptr }; + MQTTGWSubscribeHandler* _mqttSubscribe { nullptr }; + MQTTSNConnectionHandler* _mqttsnConnection { nullptr }; + MQTTSNPublishHandler* _mqttsnPublish { nullptr }; + MQTTSNSubscribeHandler* _mqttsnSubscribe { nullptr }; + MQTTSNAggregateConnectionHandler* _mqttsnAggrConnection { nullptr }; }; - } #endif /* MQTTSNGWPACKETHANDLETASK_H_ */ diff --git a/MQTTSNGateway/src/MQTTSNGWProcess.cpp b/MQTTSNGateway/src/MQTTSNGWProcess.cpp index 90accea..897aa29 100644 --- a/MQTTSNGateway/src/MQTTSNGWProcess.cpp +++ b/MQTTSNGateway/src/MQTTSNGWProcess.cpp @@ -44,7 +44,7 @@ volatile int theSignaled = 0; static void signalHandler(int sig) { - theSignaled = sig; + theSignaled = sig; } /*===================================== @@ -52,23 +52,23 @@ static void signalHandler(int sig) ====================================*/ Process::Process() { - _argc = 0; - _argv = 0; - _configDir = CONFIG_DIRECTORY; - _configFile = CONFIG_FILE; - _log = 0; + _argc = 0; + _argv = 0; + _configDir = CONFIG_DIRECTORY; + _configFile = CONFIG_FILE; + _log = 0; } Process::~Process() { - if (_rb ) - { - delete _rb; - } - if ( _rbsem ) - { - delete _rbsem; - } + if (_rb) + { + delete _rb; + } + if (_rbsem) + { + delete _rbsem; + } } void Process::run() @@ -78,168 +78,169 @@ void Process::run() void Process::initialize(int argc, char** argv) { - char param[MQTTSNGW_PARAM_MAX]; - _argc = argc; - _argv = argv; - signal(SIGINT, signalHandler); - signal(SIGTERM, signalHandler); - signal(SIGHUP, signalHandler); + char param[MQTTSNGW_PARAM_MAX]; + _argc = argc; + _argv = argv; + signal(SIGINT, signalHandler); + signal(SIGTERM, signalHandler); + signal(SIGHUP, signalHandler); - int opt; - while ((opt = getopt(_argc, _argv, "f:")) != -1) - { - if ( opt == 'f' ) - { - string config = string(optarg); - size_t pos = 0; - if ( (pos = config.find_last_of("/")) == string::npos ) - { - _configFile = optarg; - } - else - { - _configFile = config.substr(pos + 1, config.size() - pos - 1);; - _configDir = config.substr(0, pos + 1); - } - } - } - _rbsem = new NamedSemaphore(MQTTSNGW_RB_SEMAPHOR_NAME, 0); - _rb = new RingBuffer(_configDir.c_str()); + int opt; + while ((opt = getopt(_argc, _argv, "f:")) != -1) + { + if (opt == 'f') + { + string config = string(optarg); + size_t pos = 0; + if ((pos = config.find_last_of("/")) == string::npos) + { + _configFile = optarg; + } + else + { + _configFile = config.substr(pos + 1, config.size() - pos - 1); + ; + _configDir = config.substr(0, pos + 1); + } + } + } + _rbsem = new NamedSemaphore(MQTTSNGW_RB_SEMAPHOR_NAME, 0); + _rb = new RingBuffer(_configDir.c_str()); - if (getParam("ShearedMemory", param) == 0) - { - if (!strcasecmp(param, "YES")) - { - _log = 1; - } - else - { - _log = 0; - } - } + if (getParam("ShearedMemory", param) == 0) + { + if (!strcasecmp(param, "YES")) + { + _log = 1; + } + else + { + _log = 0; + } + } } void Process::putLog(const char* format, ...) { - _mt.lock(); - va_list arg; - va_start(arg, format); - vsprintf(_rbdata, format, arg); - va_end(arg); - if (strlen(_rbdata)) - { - if ( _log > 0 ) - { - _rb->put(_rbdata); - _rbsem->post(); - } - else - { - printf("%s", _rbdata); - } - } - _mt.unlock(); + _mt.lock(); + va_list arg; + va_start(arg, format); + vsprintf(_rbdata, format, arg); + va_end(arg); + if (strlen(_rbdata)) + { + if (_log > 0) + { + _rb->put(_rbdata); + _rbsem->post(); + } + else + { + printf("%s", _rbdata); + } + } + _mt.unlock(); } int Process::getArgc() { - return _argc; + return _argc; } char** Process::getArgv() { - return _argv; + return _argv; } int Process::getParam(const char* parameter, char* value) { - char str[MQTTSNGW_PARAM_MAX]; - char param[MQTTSNGW_PARAM_MAX]; - FILE *fp; + char str[MQTTSNGW_PARAM_MAX]; + char param[MQTTSNGW_PARAM_MAX]; + FILE *fp; - int i = 0, j = 0; - string configPath = _configDir + _configFile; + int i = 0, j = 0; + string configPath = _configDir + _configFile; - if ((fp = fopen(configPath.c_str(), "r")) == NULL) - { - throw Exception("No config file:[" + configPath + "]\n"); - } + if ((fp = fopen(configPath.c_str(), "r")) == NULL) + { + throw Exception("No config file:[" + configPath + "]\n"); + } - while (true) - { - if (fgets(str, MQTTSNGW_PARAM_MAX - 1, fp) == NULL) - { - fclose(fp); - return -3; - } - if (!strncmp(str, parameter, strlen(parameter))) - { - while (str[i++] != '=') - { - ; - } - while (str[i] != '\n') - { - param[j++] = str[i++]; - } - param[j] = '\0'; + while (true) + { + if (fgets(str, MQTTSNGW_PARAM_MAX - 1, fp) == NULL) + { + fclose(fp); + return -3; + } + if (!strncmp(str, parameter, strlen(parameter))) + { + while (str[i++] != '=') + { + ; + } + while (str[i] != '\n') + { + param[j++] = str[i++]; + } + param[j] = '\0'; - for (i = strlen(param) - 1; i >= 0 && isspace(param[i]); i--) - ; - param[i + 1] = '\0'; - for (i = 0; isspace(param[i]); i++) - ; - if (i > 0) - { - j = 0; - while (param[i]) - param[j++] = param[i++]; - param[j] = '\0'; - } - strcpy(value, param); - fclose(fp); - return 0; - } - } - fclose(fp); - return -2; + for (i = strlen(param) - 1; i >= 0 && isspace(param[i]); i--) + ; + param[i + 1] = '\0'; + for (i = 0; isspace(param[i]); i++) + ; + if (i > 0) + { + j = 0; + while (param[i]) + param[j++] = param[i++]; + param[j] = '\0'; + } + strcpy(value, param); + fclose(fp); + return 0; + } + } + fclose(fp); + return -2; } const char* Process::getLog() { - int len = 0; - _mt.lock(); - while ((len = _rb->get(_rbdata, PROCESS_LOG_BUFFER_SIZE)) == 0) - { - _rbsem->timedwait(1000); - if ( checkSignal() == SIGINT) - { - break; - } - } - *(_rbdata + len) = 0; - _mt.unlock(); - return _rbdata; + int len = 0; + _mt.lock(); + while ((len = _rb->get(_rbdata, PROCESS_LOG_BUFFER_SIZE)) == 0) + { + _rbsem->timedwait(1000); + if (checkSignal() == SIGINT) + { + break; + } + } + *(_rbdata + len) = 0; + _mt.unlock(); + return _rbdata; } void Process::resetRingBuffer() { - _rb->reset(); + _rb->reset(); } int Process::checkSignal(void) { - return theSignaled; + return theSignaled; } const string* Process::getConfigDirName(void) { - return &_configDir; + return &_configDir; } const string* Process::getConfigFileName(void) { - return &_configFile; + return &_configFile; } /*===================================== @@ -247,99 +248,97 @@ const string* Process::getConfigFileName(void) ====================================*/ MultiTaskProcess::MultiTaskProcess() { - theMultiTaskProcess = this; - _threadCount = 0; - _stopCount = 0; + theMultiTaskProcess = this; + _threadCount = 0; + _stopCount = 0; } MultiTaskProcess::~MultiTaskProcess() { - for (int i = 0; i < _threadCount; i++) - { - _threadList[i]->stop(); - } + for (int i = 0; i < _threadCount; i++) + { + _threadList[i]->stop(); + } } void MultiTaskProcess::initialize(int argc, char** argv) { - Process::initialize(argc, argv); - for (int i = 0; i < _threadCount; i++) - { - _threadList[i]->initialize(argc, argv); - } + Process::initialize(argc, argv); + for (int i = 0; i < _threadCount; i++) + { + _threadList[i]->initialize(argc, argv); + } } void MultiTaskProcess::run(void) { - for (int i = 0; i < _threadCount; i++) - { - _threadList[i]->start(); - } + for (int i = 0; i < _threadCount; i++) + { + _threadList[i]->start(); + } - try - { - while(true) - { - if (theProcess->checkSignal() == SIGINT) - { - return; - } - sleep(1); - } - } - catch(Exception* ex) - { - ex->writeMessage(); - } - catch(...) - { - throw; - } + try + { + while (true) + { + if (theProcess->checkSignal() == SIGINT) + { + return; + } + sleep(1); + } + } catch (Exception* ex) + { + ex->writeMessage(); + } catch (...) + { + throw; + } } void MultiTaskProcess::waitStop(void) { - while (_stopCount < _threadCount) - { - sleep(1); - } + while (_stopCount < _threadCount) + { + sleep(1); + } } void MultiTaskProcess::threadStopped(void) { - _mutex.lock(); - _stopCount++; - _mutex.unlock(); + _mutex.lock(); + _stopCount++; + _mutex.unlock(); } void MultiTaskProcess::attach(Thread* thread) { - _mutex.lock(); - if (_threadCount < MQTTSNGW_MAX_TASK) - { - _threadList[_threadCount] = thread; - _threadCount++; - } - else - { - _mutex.unlock(); - throw Exception("Full of Threads"); - } - _mutex.unlock(); + _mutex.lock(); + if (_threadCount < MQTTSNGW_MAX_TASK) + { + _threadList[_threadCount] = thread; + _threadCount++; + } + else + { + _mutex.unlock(); + throw Exception("Full of Threads"); + } + _mutex.unlock(); } int MultiTaskProcess::getParam(const char* parameter, char* value) { - _mutex.lock(); - int rc = Process::getParam(parameter, value); - _mutex.unlock(); - if (rc == -1) - { - throw Exception("No config file."); - } - return rc; + _mutex.lock(); + int rc = Process::getParam(parameter, value); + _mutex.unlock(); + if (rc == -1) + { + throw Exception("No config file."); + } + return rc; } /*===================================== @@ -347,30 +346,30 @@ int MultiTaskProcess::getParam(const char* parameter, char* value) ======================================*/ Exception::Exception(const string& message) { - _message = message; - _exNo = 0; - _fileName = 0; - _functionName = 0; - _line = 0; + _message = message; + _exNo = 0; + _fileName = 0; + _functionName = 0; + _line = 0; } Exception::Exception(const int exNo, const string& message) { - _message = message; - _exNo = exNo; - _fileName = nullptr; - _functionName = nullptr; - _line = 0; + _message = message; + _exNo = exNo; + _fileName = nullptr; + _functionName = nullptr; + _line = 0; } Exception::Exception(const int exNo, const string& message, const char* file, - const char* function, const int line) + const char* function, const int line) { - _message = message; - _exNo = exNo; - _fileName = file; - _functionName = function; - _line = line; + _message = message; + _exNo = exNo; + _fileName = file; + _functionName = function; + _line = line; } Exception::~Exception() throw () @@ -380,38 +379,39 @@ Exception::~Exception() throw () const char* Exception::what() const throw () { - return _message.c_str(); + return _message.c_str(); } const char* Exception::getFileName() { - return _fileName; + return _fileName; } const char* Exception::getFunctionName() { - return _functionName; + return _functionName; } const int Exception::getLineNo() { - return _line; + return _line; } const int Exception::getExceptionNo() { - return _exNo; + return _exNo; } void Exception::writeMessage() { - if (getExceptionNo() == 0 ) - { - WRITELOG("%s %s\n", currentDateTime(), what()); - } - else - { - WRITELOG("%s:%-6d %s line %-4d %s() : %s\n", currentDateTime(), getExceptionNo(), - getFileName(), getLineNo(), getFunctionName(), what()); - } + if (getExceptionNo() == 0) + { + WRITELOG("%s %s\n", currentDateTime(), what()); + } + else + { + WRITELOG("%s:%-6d %s line %-4d %s() : %s\n", currentDateTime(), + getExceptionNo(), getFileName(), getLineNo(), getFunctionName(), + what()); + } } diff --git a/MQTTSNGateway/src/MQTTSNGWProcess.h b/MQTTSNGateway/src/MQTTSNGWProcess.h index 42ff2a2..723bb72 100644 --- a/MQTTSNGateway/src/MQTTSNGWProcess.h +++ b/MQTTSNGateway/src/MQTTSNGWProcess.h @@ -47,29 +47,29 @@ namespace MQTTSNGW class Process { public: - Process(); - virtual ~Process(); - virtual void initialize(int argc, char** argv); - virtual void run(void); - void putLog(const char* format, ...); - void resetRingBuffer(void); - int getArgc(void); - char** getArgv(void); - int getParam(const char* parameter, char* value); - const char* getLog(void); - int checkSignal(void); - const string* getConfigDirName(void); - const string* getConfigFileName(void); + Process(); + virtual ~Process(); + virtual void initialize(int argc, char** argv); + virtual void run(void); + void putLog(const char* format, ...); + void resetRingBuffer(void); + int getArgc(void); + char** getArgv(void); + int getParam(const char* parameter, char* value); + const char* getLog(void); + int checkSignal(void); + const string* getConfigDirName(void); + const string* getConfigFileName(void); private: - int _argc; - char** _argv; - string _configDir; - string _configFile; - RingBuffer* _rb; - NamedSemaphore* _rbsem; - Mutex _mt; - int _log; - char _rbdata[PROCESS_LOG_BUFFER_SIZE + 1]; + int _argc; + char** _argv; + string _configDir; + string _configFile; + RingBuffer* _rb; + NamedSemaphore* _rbsem; + Mutex _mt; + int _log; + char _rbdata[PROCESS_LOG_BUFFER_SIZE + 1]; }; /*===================================== @@ -78,20 +78,20 @@ private: class MultiTaskProcess: public Process { public: - MultiTaskProcess(void); - ~MultiTaskProcess(); - void initialize(int argc, char** argv); - int getParam(const char* parameter, char* value); - void run(void); - void waitStop(void); - void threadStopped(void); - void attach(Thread* thread); + MultiTaskProcess(void); + ~MultiTaskProcess(); + void initialize(int argc, char** argv); + int getParam(const char* parameter, char* value); + void run(void); + void waitStop(void); + void threadStopped(void); + void attach(Thread* thread); private: - Thread* _threadList[MQTTSNGW_MAX_TASK]; - Mutex _mutex; - int _threadCount; - int _stopCount; + Thread* _threadList[MQTTSNGW_MAX_TASK]; + Mutex _mutex; + int _threadCount; + int _stopCount; }; /*===================================== @@ -100,50 +100,49 @@ private: class Exception: public exception { public: - Exception(const string& message); - Exception(const int exNo, const string& message); - Exception(const int exNo, const string& message, - const char* file, const char* func, const int line); - virtual ~Exception() throw (); - const char* getFileName(); - const char* getFunctionName(); - const int getLineNo(); - const int getExceptionNo(); - virtual const char* what() const throw (); - void writeMessage(); + Exception(const string& message); + Exception(const int exNo, const string& message); + Exception(const int exNo, const string& message, const char* file, + const char* func, const int line); + virtual ~Exception() throw (); + const char* getFileName(); + const char* getFunctionName(); + const int getLineNo(); + const int getExceptionNo(); + virtual const char* what() const throw (); + void writeMessage(); private: - int _exNo; - string _message; - const char* _fileName; - const char* _functionName; - int _line; + int _exNo; + string _message; + const char* _fileName; + const char* _functionName; + int _line; }; - /*===================================== Class QueElement ====================================*/ template class QueElement { - template friend class Que; + template friend class Que; public: - QueElement(T* t) - { - _element = t; - _next = nullptr; - _prev = nullptr; - } + QueElement(T* t) + { + _element = t; + _next = nullptr; + _prev = nullptr; + } - ~QueElement() - { - } + ~QueElement() + { + } private: - T* _element; - QueElement* _next; - QueElement* _prev; + T* _element; + QueElement* _next; + QueElement* _prev; }; /*===================================== @@ -153,105 +152,105 @@ template class Que { public: - Que() - { - _head = nullptr; - _tail = nullptr; - _cnt = 0; - _maxSize = 0; - } + Que() + { + _head = nullptr; + _tail = nullptr; + _cnt = 0; + _maxSize = 0; + } - ~Que() - { - QueElement* elm = _head; - while (elm) - { - QueElement* next = elm->_next; - delete elm->_element; - delete elm; - elm = next; - } - } + ~Que() + { + QueElement* elm = _head; + while (elm) + { + QueElement* next = elm->_next; + delete elm->_element; + delete elm; + elm = next; + } + } - void pop(void) - { - if ( _head ) - { - QueElement* head = _head; - if ( _head == _tail ) - { - _head = _tail = nullptr; - } - else - { - _head = head->_next; - head->_prev = nullptr; - } - delete head; - _cnt--; - } - } + void pop(void) + { + if (_head) + { + QueElement* head = _head; + if (_head == _tail) + { + _head = _tail = nullptr; + } + else + { + _head = head->_next; + head->_prev = nullptr; + } + delete head; + _cnt--; + } + } - T* front(void) - { - { - if ( _head ) - { - return _head->_element; - } - else - { - return 0; - } - } - } + T* front(void) + { + { + if (_head) + { + return _head->_element; + } + else + { + return 0; + } + } + } - int post(T* t) - { - if ( t && ( _maxSize == 0 || _cnt < _maxSize )) - { - QueElement* elm = new QueElement(t); - if ( _head ) - { - if ( _tail == _head ) - { - elm->_prev = _tail; - _tail = elm; - _head->_next = elm; - } - else - { - _tail->_next = elm; - elm->_prev = _tail; - _tail = elm; - } - } - else - { - _head = elm; - _tail = elm; - } - _cnt++; - return _cnt; - } - return 0; - } + int post(T* t) + { + if (t && (_maxSize == 0 || _cnt < _maxSize)) + { + QueElement* elm = new QueElement(t); + if (_head) + { + if (_tail == _head) + { + elm->_prev = _tail; + _tail = elm; + _head->_next = elm; + } + else + { + _tail->_next = elm; + elm->_prev = _tail; + _tail = elm; + } + } + else + { + _head = elm; + _tail = elm; + } + _cnt++; + return _cnt; + } + return 0; + } - int size(void) - { - return _cnt; - } + int size(void) + { + return _cnt; + } - void setMaxSize(int maxSize) - { - _maxSize = maxSize; - } + void setMaxSize(int maxSize) + { + _maxSize = maxSize; + } private: - int _cnt; - int _maxSize; - QueElement* _head; - QueElement* _tail; + int _cnt; + int _maxSize; + QueElement* _head; + QueElement* _tail; }; /*===================================== @@ -262,722 +261,760 @@ private: #define TREE23_BI_NODE (2) #define TREE23_TRI_NODE (3) -template -class Tree23Elm{ - template friend class Tree23; +template +class Tree23Elm +{ + template friend class Tree23; public: - Tree23Elm() - { - _key = 0; - _val = 0; - } + Tree23Elm() + { + _key = 0; + _val = 0; + } - Tree23Elm(K* key, V* val) - { - _key = key; - _val = val; - } + Tree23Elm(K* key, V* val) + { + _key = key; + _val = val; + } - ~Tree23Elm() - { + ~Tree23Elm() + { - } + } - int compare(Tree23Elm* elm) - { - return _key->compare(elm->_key); - } + int compare(Tree23Elm* elm) + { + return _key->compare(elm->_key); + } private: - K* _key; - V* _val; + K* _key; + V* _val; }; - -template -class Tree23Node{ - template friend class Tree23; +template +class Tree23Node +{ + template friend class Tree23; public: - Tree23Node(const int type) - { - _type = type; - _telm0 = _telm1 = NULL; - _left = _midle = _right = NULL; - } + Tree23Node(const int type) + { + _type = type; + _telm0 = _telm1 = NULL; + _left = _midle = _right = NULL; + } - Tree23Node(const int type, Tree23Node* midle) - { - _type = type; - _telm0 = _telm1 = NULL; - _left = _right = NULL; - _midle = midle; - } + Tree23Node(const int type, Tree23Node* midle) + { + _type = type; + _telm0 = _telm1 = NULL; + _left = _right = NULL; + _midle = midle; + } - Tree23Node(const int type, Tree23Elm* telm) - { - _type = type; - _telm0 = telm; - _telm1 = NULL; - _left = _midle = _right = NULL; - } + Tree23Node(const int type, Tree23Elm* telm) + { + _type = type; + _telm0 = telm; + _telm1 = NULL; + _left = _midle = _right = NULL; + } - Tree23Node(const int type, Tree23Elm* telm, Tree23Node* left, Tree23Node* right) - { - _type = type; - _telm0 = telm; - _telm1 = NULL; - _left = left; - _midle = NULL; - _right = right; - } + Tree23Node(const int type, Tree23Elm* telm, Tree23Node* left, + Tree23Node* right) + { + _type = type; + _telm0 = telm; + _telm1 = NULL; + _left = left; + _midle = NULL; + _right = right; + } - Tree23Node(const int type, Tree23Elm* telm0, Tree23Elm* telm1, Tree23Node* left, Tree23Node* midle, Tree23Node* right) - { - _type = type; - _telm0 = telm0; - _telm1 = telm1; - _left = left; - _midle = midle; - _right = right; - } + Tree23Node(const int type, Tree23Elm* telm0, Tree23Elm* telm1, + Tree23Node* left, Tree23Node* midle, + Tree23Node* right) + { + _type = type; + _telm0 = telm0; + _telm1 = telm1; + _left = left; + _midle = midle; + _right = right; + } - ~Tree23Node() - { + ~Tree23Node() + { - } + } private: - int _type; - Tree23Elm* _telm0; - Tree23Elm* _telm1; - Tree23Node* _left; - Tree23Node* _midle; - Tree23Node* _right; + int _type; + Tree23Elm* _telm0; + Tree23Elm* _telm1; + Tree23Node* _left; + Tree23Node* _midle; + Tree23Node* _right; }; -template -class Tree23{ +template +class Tree23 +{ public: - Tree23() - { - _root = NULL; - } + Tree23() + { + _root = NULL; + } - ~Tree23() - { - if ( _root ) - { - delete _root; - } - } + ~Tree23() + { + if (_root) + { + delete _root; + } + } - void add(K* key, V* val) - { - _root = add( _root, new Tree23Elm(key, val)); - _root->_type = abs(_root->_type); - } + void add(K* key, V* val) + { + _root = add(_root, new Tree23Elm(key, val)); + _root->_type = abs(_root->_type); + } - Tree23Node* add(Tree23Node* n, Tree23Elm* elm) - { - if ( n == 0 ) - { - return new Tree23Node(TREE23_INSERT_ACTIVE, elm); - } + Tree23Node* add(Tree23Node* n, Tree23Elm* elm) + { + if (n == 0) + { + return new Tree23Node(TREE23_INSERT_ACTIVE, elm); + } - int cmp0 = elm->compare(n->_telm0); - int cmp1 = 0; - switch ( n->_type ) - { - case 2: - if ( cmp0 < 0 ) - { - n->_left = add(n->_left, elm); - return addLeft2(n); - } - else if ( cmp0 == 0 ) - { - n->_telm0 = elm; - return n; - } - else - { - n->_right = add(n->_right, elm); - return addRight2(n); - } - break; - case 3: - cmp1 = elm->compare(n->_telm1); - if ( cmp0 < 0 ) - { - n->_left = add(n->_left, elm); - return addLeft3(n); - } - else if ( cmp0 == 0 ) - { - n->_telm0 = elm; - return n; - } - else if ( cmp1 < 0 ) - { - n->_midle = add(n->_midle, elm); - return addMidle3(n); - } - else if ( cmp1 == 0 ) - { - n->_telm1 = elm; - return n; - } - else - { - n->_right = add(n->_right, elm); - return addRight3(n); - } - break; - default: - break; - } - return 0; - } + int cmp0 = elm->compare(n->_telm0); + int cmp1 = 0; + switch (n->_type) + { + case 2: + if (cmp0 < 0) + { + n->_left = add(n->_left, elm); + return addLeft2(n); + } + else if (cmp0 == 0) + { + n->_telm0 = elm; + return n; + } + else + { + n->_right = add(n->_right, elm); + return addRight2(n); + } + break; + case 3: + cmp1 = elm->compare(n->_telm1); + if (cmp0 < 0) + { + n->_left = add(n->_left, elm); + return addLeft3(n); + } + else if (cmp0 == 0) + { + n->_telm0 = elm; + return n; + } + else if (cmp1 < 0) + { + n->_midle = add(n->_midle, elm); + return addMidle3(n); + } + else if (cmp1 == 0) + { + n->_telm1 = elm; + return n; + } + else + { + n->_right = add(n->_right, elm); + return addRight3(n); + } + break; + default: + break; + } + return 0; + } - void remove(K* k) - { - _root = remove(_root, k); - if ( _root != NULL && _root->_type == TREE23_DELETE_ACTIVE ) - { - _root = _root->_midle; - } - } + void remove(K* k) + { + _root = remove(_root, k); + if (_root != NULL && _root->_type == TREE23_DELETE_ACTIVE) + { + _root = _root->_midle; + } + } - Tree23Node* remove(Tree23Node* node, K* k) - { - if ( node == NULL ) - { - return NULL; - } - int cmp0 = k->compare(node->_telm0->_key); - int cmp1 = 0; - switch ( node->_type ) - { - case 2: - if ( cmp0 < 0 ) - { - node->_left = remove( node->_left, k); - return removeLeft2(node); - } - else if ( cmp0 == 0 ) - { - if ( node->_left == NULL) - { - return new Tree23Node(TREE23_DELETE_ACTIVE); - } - Tree23Elm* maxLeft = new Tree23Elm(); - node->_left = removeMax(node->_left, maxLeft); - node->_telm0 = maxLeft; - return removeLeft2(node); - } - else - { - node->_right = remove(node->_right, k); - return removeRight2(node); - } - case 3: - cmp1 = k->compare(node->_telm1->_key); - if ( cmp0 < 0 ) - { - node->_left = remove(node->_left, k); - return removeLeft3(node); - } - else if ( cmp0 == 0 ) - { - if ( node->_left == NULL ) - { - return new Tree23Node(TREE23_BI_NODE, node->_telm1); - } - Tree23Elm* maxLeft = new Tree23Elm(); - node->_left = removeMax(node->_left, maxLeft); - node->_telm0 = maxLeft; - return removeLeft3(node); - } - else if ( cmp1 < 0 ) - { - node->_midle = remove(node->_midle, k); - return removeMidle3(node); - } - else if ( cmp1 == 0 ) - { - if ( node->_midle == NULL ) - { - return new Tree23Node(TREE23_BI_NODE, node->_telm0); - } - Tree23Elm* maxMidle = new Tree23Elm(); - node->_midle = removeMax(node->_midle, maxMidle); - node->_telm1 = maxMidle; - return removeMidle3(node); - } - else - { - node->_right = remove(node->_right, k); - return removeRight3(node); - } - default: - break; - } - return NULL; - } + Tree23Node* remove(Tree23Node* node, K* k) + { + if (node == NULL) + { + return NULL; + } + int cmp0 = k->compare(node->_telm0->_key); + int cmp1 = 0; + switch (node->_type) + { + case 2: + if (cmp0 < 0) + { + node->_left = remove(node->_left, k); + return removeLeft2(node); + } + else if (cmp0 == 0) + { + if (node->_left == NULL) + { + return new Tree23Node(TREE23_DELETE_ACTIVE); + } + Tree23Elm* maxLeft = new Tree23Elm(); + node->_left = removeMax(node->_left, maxLeft); + node->_telm0 = maxLeft; + return removeLeft2(node); + } + else + { + node->_right = remove(node->_right, k); + return removeRight2(node); + } + case 3: + cmp1 = k->compare(node->_telm1->_key); + if (cmp0 < 0) + { + node->_left = remove(node->_left, k); + return removeLeft3(node); + } + else if (cmp0 == 0) + { + if (node->_left == NULL) + { + return new Tree23Node(TREE23_BI_NODE, node->_telm1); + } + Tree23Elm* maxLeft = new Tree23Elm(); + node->_left = removeMax(node->_left, maxLeft); + node->_telm0 = maxLeft; + return removeLeft3(node); + } + else if (cmp1 < 0) + { + node->_midle = remove(node->_midle, k); + return removeMidle3(node); + } + else if (cmp1 == 0) + { + if (node->_midle == NULL) + { + return new Tree23Node(TREE23_BI_NODE, node->_telm0); + } + Tree23Elm* maxMidle = new Tree23Elm(); + node->_midle = removeMax(node->_midle, maxMidle); + node->_telm1 = maxMidle; + return removeMidle3(node); + } + else + { + node->_right = remove(node->_right, k); + return removeRight3(node); + } + default: + break; + } + return NULL; + } - bool find(K* key) - { - Tree23Node* node = _root; - while (node != NULL) - { - int cmp0 = key->compare(node->_telm0->_key); - int cmp1 = 0; - switch (node->_type) - { - case 2: - if ( cmp0 < 0 ) node = node->_left; - else if ( cmp0 == 0 ) - { - return true; - } - else - { - node = node->_right; - } - break; - case 3: - cmp1 = key->compare(node->_telm1->_key); - if ( cmp0 < 0 ) - { - node = node->_left; - } - else if ( cmp0 == 0 ) - { - return true; - } - else if ( cmp1 < 0 ) - { - node = node->_midle; - } - else if ( cmp1 == 0 ) - { - return true; - } - else - { - node = node->_right; - } - break; - default: - break; - } - } - return false; - } + bool find(K* key) + { + Tree23Node* node = _root; + while (node != NULL) + { + int cmp0 = key->compare(node->_telm0->_key); + int cmp1 = 0; + switch (node->_type) + { + case 2: + if (cmp0 < 0) + node = node->_left; + else if (cmp0 == 0) + { + return true; + } + else + { + node = node->_right; + } + break; + case 3: + cmp1 = key->compare(node->_telm1->_key); + if (cmp0 < 0) + { + node = node->_left; + } + else if (cmp0 == 0) + { + return true; + } + else if (cmp1 < 0) + { + node = node->_midle; + } + else if (cmp1 == 0) + { + return true; + } + else + { + node = node->_right; + } + break; + default: + break; + } + } + return false; + } - - V* getVal(K* key) - { - Tree23Node* node = _root; - while (node != NULL) - { - int cmp0 = key->compare(node->_telm0->_key); - int cmp1 = 0; - switch (node->_type) - { - case 2: - if ( cmp0 < 0 ) - { - node = node->_left; - } - else if ( cmp0 == 0 ) - { - return node->_telm0->_val; - } - else - { - node = node->_right; - } - break; - case 3: - cmp1 = key->compare(node->_telm1->_key); - if ( cmp0 < 0 ) - { - node = node->_left; - } - else if ( cmp0 == 0 ) - { - return node->_telm0->_val; - } - else if ( cmp1 < 0 ) - { - node = node->_midle; - } - else if ( cmp1 == 0 ) - { - return node->_telm1->_val; - } - else - { - node = node->_right; - } - break; - default: - break; - } - } - return NULL; - } + V* getVal(K* key) + { + Tree23Node* node = _root; + while (node != NULL) + { + int cmp0 = key->compare(node->_telm0->_key); + int cmp1 = 0; + switch (node->_type) + { + case 2: + if (cmp0 < 0) + { + node = node->_left; + } + else if (cmp0 == 0) + { + return node->_telm0->_val; + } + else + { + node = node->_right; + } + break; + case 3: + cmp1 = key->compare(node->_telm1->_key); + if (cmp0 < 0) + { + node = node->_left; + } + else if (cmp0 == 0) + { + return node->_telm0->_val; + } + else if (cmp1 < 0) + { + node = node->_midle; + } + else if (cmp1 == 0) + { + return node->_telm1->_val; + } + else + { + node = node->_right; + } + break; + default: + break; + } + } + return NULL; + } private: - Tree23Node* addLeft2(Tree23Node* node) - { - Tree23Node* n = node->_left; - if ( n != NULL && n->_type == TREE23_INSERT_ACTIVE ) - { - return new Tree23Node(TREE23_TRI_NODE, n->_telm0, node->_telm0, n->_left, n->_right, node->_right); - } - return node; - } + Tree23Node* addLeft2(Tree23Node* node) + { + Tree23Node* n = node->_left; + if (n != NULL && n->_type == TREE23_INSERT_ACTIVE) + { + return new Tree23Node(TREE23_TRI_NODE, n->_telm0, + node->_telm0, n->_left, n->_right, node->_right); + } + return node; + } - Tree23Node* addLeft3(Tree23Node* node) - { - Tree23Node* n = node->_left; - if ( n != NULL && n->_type == TREE23_INSERT_ACTIVE) - { - n->_type = TREE23_BI_NODE; - Tree23Node* nn = new Tree23Node(TREE23_BI_NODE, node->_telm1, node->_midle, node->_right); - return new Tree23Node(TREE23_INSERT_ACTIVE, node->_telm0, n, nn); - } - return node; - } + Tree23Node* addLeft3(Tree23Node* node) + { + Tree23Node* n = node->_left; + if (n != NULL && n->_type == TREE23_INSERT_ACTIVE) + { + n->_type = TREE23_BI_NODE; + Tree23Node* nn = new Tree23Node(TREE23_BI_NODE, + node->_telm1, node->_midle, node->_right); + return new Tree23Node(TREE23_INSERT_ACTIVE, node->_telm0, n, + nn); + } + return node; + } - Tree23Node* addRight2(Tree23Node* node) - { - Tree23Node* n = node->_right; - if (n != NULL && n->_type == TREE23_INSERT_ACTIVE) - { - return new Tree23Node(TREE23_TRI_NODE, node->_telm0, n->_telm0, node->_left, n->_left, n->_right); - } - return node; - } + Tree23Node* addRight2(Tree23Node* node) + { + Tree23Node* n = node->_right; + if (n != NULL && n->_type == TREE23_INSERT_ACTIVE) + { + return new Tree23Node(TREE23_TRI_NODE, node->_telm0, + n->_telm0, node->_left, n->_left, n->_right); + } + return node; + } - Tree23Node* addRight3(Tree23Node* node) - { - Tree23Node* n = node->_right; - if (n != NULL && n->_type == TREE23_INSERT_ACTIVE) { - n->_type = TREE23_BI_NODE; - Tree23Node* nn = new Tree23Node(TREE23_BI_NODE, node->_telm0, node->_left, node->_midle); - return new Tree23Node(TREE23_INSERT_ACTIVE, node->_telm1, nn, n); - } - return node; - } + Tree23Node* addRight3(Tree23Node* node) + { + Tree23Node* n = node->_right; + if (n != NULL && n->_type == TREE23_INSERT_ACTIVE) + { + n->_type = TREE23_BI_NODE; + Tree23Node* nn = new Tree23Node(TREE23_BI_NODE, + node->_telm0, node->_left, node->_midle); + return new Tree23Node(TREE23_INSERT_ACTIVE, node->_telm1, nn, + n); + } + return node; + } - Tree23Node* addMidle3(Tree23Node* node) - { - Tree23Node* n = node->_midle; - if ( n != NULL && n->_type == TREE23_INSERT_ACTIVE ) - { - n->_left = new Tree23Node(TREE23_BI_NODE, node->_telm0, node->_left, n->_left); - n->_right = new Tree23Node(TREE23_BI_NODE, node->_telm1, n->_right, node->_right); - return n; - } - return node; - } + Tree23Node* addMidle3(Tree23Node* node) + { + Tree23Node* n = node->_midle; + if (n != NULL && n->_type == TREE23_INSERT_ACTIVE) + { + n->_left = new Tree23Node(TREE23_BI_NODE, node->_telm0, + node->_left, n->_left); + n->_right = new Tree23Node(TREE23_BI_NODE, node->_telm1, + n->_right, node->_right); + return n; + } + return node; + } + Tree23Node* removeMax(Tree23Node* node, Tree23Elm* elm) + { + if (node->_right == NULL) + { + switch (node->_type) + { + case 2: + elm->_key = node->_telm0->_key; + elm->_val = node->_telm0->_val; + return new Tree23Node(TREE23_DELETE_ACTIVE); + case 3: + elm->_key = node->_telm1->_key; + elm->_val = node->_telm1->_val; + return new Tree23Node(TREE23_BI_NODE, node->_telm0); + default: + break; + } + } + else + { + node->_right = removeMax(node->_right, elm); + switch (node->_type) + { + case 2: + return removeRight2(node); + case 3: + return removeRight3(node); + default: + break; + } + } + return NULL; + } - Tree23Node* removeMax(Tree23Node* node, Tree23Elm* elm) - { - if (node->_right == NULL) - { - switch (node->_type) - { - case 2: - elm->_key = node->_telm0->_key; - elm->_val = node->_telm0->_val; - return new Tree23Node(TREE23_DELETE_ACTIVE); - case 3: - elm->_key = node->_telm1->_key; - elm->_val = node->_telm1->_val; - return new Tree23Node(TREE23_BI_NODE, node->_telm0); - default: - break; - } - } - else - { - node->_right = removeMax(node->_right, elm); - switch (node->_type) - { - case 2: - return removeRight2(node); - case 3: - return removeRight3(node); - default: - break; - } - } - return NULL; - } + Tree23Node* removeLeft2(Tree23Node* node) + { + Tree23Node* n = node->_left; + if (n != NULL && n->_type == TREE23_DELETE_ACTIVE) + { + Tree23Node* r = node->_right; + Tree23Node* midle; + Tree23Node* left; + Tree23Node* right; + switch (r->_type) + { + case 2: + midle = new Tree23Node(TREE23_TRI_NODE, node->_telm0, + r->_telm0, n->_midle, r->_left, r->_right); + return new Tree23Node(TREE23_DELETE_ACTIVE, midle); + case 3: + left = new Tree23Node(TREE23_BI_NODE, node->_telm0, + n->_midle, r->_left); + right = new Tree23Node(TREE23_BI_NODE, r->_telm1, + r->_midle, r->_right); + return new Tree23Node(TREE23_BI_NODE, r->_telm0, left, + right); + default: + break; + } + } + return node; + } - Tree23Node* removeLeft2(Tree23Node* node) - { - Tree23Node* n = node->_left; - if ( n != NULL && n->_type == TREE23_DELETE_ACTIVE ) - { - Tree23Node* r = node->_right; - Tree23Node* midle; - Tree23Node* left; - Tree23Node* right; + Tree23Node* removeRight2(Tree23Node* node) + { + Tree23Node* n = node->_right; + if (n != NULL && n->_type == TREE23_DELETE_ACTIVE) + { + Tree23Node* l = node->_left; + Tree23Node* midle; + Tree23Node* left; + Tree23Node* right; - switch ( r->_type ) - { - case 2: - midle = new Tree23Node(TREE23_TRI_NODE, node->_telm0, r->_telm0, n->_midle, r->_left, r->_right); - return new Tree23Node(TREE23_DELETE_ACTIVE, midle); - case 3: - left = new Tree23Node(TREE23_BI_NODE, node->_telm0, n->_midle, r->_left); - right = new Tree23Node(TREE23_BI_NODE, r->_telm1, r->_midle, r->_right); - return new Tree23Node(TREE23_BI_NODE, r->_telm0, left, right); - default: - break; - } - } - return node; - } + switch (l->_type) + { + case 2: + midle = new Tree23Node(TREE23_TRI_NODE, l->_telm0, + node->_telm0, l->_left, l->_right, n->_midle); + return new Tree23Node(-1, midle); + case 3: + right = new Tree23Node(TREE23_BI_NODE, node->_telm0, + l->_right, n->_midle); + left = new Tree23Node(TREE23_BI_NODE, l->_telm0, l->_left, + l->_midle); + return new Tree23Node(TREE23_BI_NODE, l->_telm1, left, + right); + default: + break; + } + } + return node; + } - Tree23Node* removeRight2(Tree23Node* node) - { - Tree23Node* n = node->_right; - if ( n != NULL && n->_type == TREE23_DELETE_ACTIVE ) - { - Tree23Node* l = node->_left; - Tree23Node* midle; - Tree23Node* left; - Tree23Node* right; + Tree23Node* removeLeft3(Tree23Node* node) + { + Tree23Node* n = node->_left; + if (n != NULL && n->_type == TREE23_DELETE_ACTIVE) + { + Tree23Node* m = node->_midle; + Tree23Node* r = node->_right; + Tree23Node* left; + Tree23Node* midle; - switch (l->_type) - { - case 2: - midle = new Tree23Node(TREE23_TRI_NODE, l->_telm0, node->_telm0, l->_left, l->_right, n->_midle); - return new Tree23Node(-1, midle); - case 3: - right = new Tree23Node(TREE23_BI_NODE, node->_telm0, l->_right, n->_midle); - left = new Tree23Node(TREE23_BI_NODE, l->_telm0, l->_left, l->_midle); - return new Tree23Node(TREE23_BI_NODE, l->_telm1, left, right); - default: - break; - } - } - return node; - } + switch (m->_type) + { + case 2: + left = new Tree23Node(TREE23_TRI_NODE, node->_telm0, + m->_telm0, n->_midle, m->_left, m->_right); + return new Tree23Node(TREE23_BI_NODE, node->_telm1, left, + r); + case 3: + left = new Tree23Node(TREE23_BI_NODE, node->_telm0, + n->_midle, m->_left); + midle = new Tree23Node(TREE23_BI_NODE, m->_telm1, + m->_midle, m->_right); + return new Tree23Node(TREE23_TRI_NODE, m->_telm0, + node->_telm1, left, midle, r); + default: + break; + } + } + return node; + } - Tree23Node* removeLeft3(Tree23Node* node) - { - Tree23Node* n = node->_left; - if ( n != NULL && n->_type == TREE23_DELETE_ACTIVE ) - { - Tree23Node* m = node->_midle; - Tree23Node* r = node->_right; - Tree23Node* left; - Tree23Node* midle; + Tree23Node* removeMidle3(Tree23Node* node) + { + Tree23Node* n = node->_midle; + if (n != NULL && n->_type == TREE23_DELETE_ACTIVE) + { + Tree23Node* l = node->_left; + Tree23Node* r = node->_right; + Tree23Node* midle; + Tree23Node* right; + switch (r->_type) + { + case 2: + right = new Tree23Node(TREE23_TRI_NODE, node->_telm1, + r->_telm0, n->_midle, r->_left, r->_right); + return new Tree23Node(TREE23_BI_NODE, node->_telm0, l, + right); + case 3: + midle = new Tree23Node(TREE23_BI_NODE, node->_telm1, + n->_midle, r->_left); + right = new Tree23Node(TREE23_BI_NODE, r->_telm1, + r->_midle, r->_right); + return new Tree23Node(TREE23_TRI_NODE, node->_telm0, + r->_telm0, l, midle, right); + default: + break; + } + } + return node; + } - switch (m->_type) { - case 2: - left = new Tree23Node(TREE23_TRI_NODE, node->_telm0, m->_telm0, n->_midle, m->_left, m->_right); - return new Tree23Node(TREE23_BI_NODE, node->_telm1, left, r); - case 3: - left = new Tree23Node(TREE23_BI_NODE, node->_telm0, n->_midle, m->_left); - midle = new Tree23Node(TREE23_BI_NODE, m->_telm1, m->_midle, m->_right); - return new Tree23Node(TREE23_TRI_NODE, m->_telm0, node->_telm1, left, midle, r); - default: - break; - } - } - return node; - } + Tree23Node* removeRight3(Tree23Node* node) + { + Tree23Node* n = node->_right; + if (n != NULL && n->_type == TREE23_DELETE_ACTIVE) + { + Tree23Node* l = node->_left; + Tree23Node* m = node->_midle; + Tree23Node* midle; + Tree23Node* right; + switch (m->_type) + { + case 2: + right = new Tree23Node(TREE23_TRI_NODE, m->_telm0, + node->_telm1, m->_left, m->_right, n->_midle); + return new Tree23Node(TREE23_BI_NODE, node->_telm0, l, + right); + case 3: + right = new Tree23Node(TREE23_BI_NODE, node->_telm1, + m->_right, n->_midle); + midle = new Tree23Node(TREE23_BI_NODE, m->_telm0, + m->_left, m->_midle); + return new Tree23Node(TREE23_TRI_NODE, node->_telm0, + m->_telm1, l, midle, right); + default: + break; + } + } + return node; + } - Tree23Node* removeMidle3(Tree23Node* node) - { - Tree23Node* n = node->_midle; - if ( n != NULL && n->_type == TREE23_DELETE_ACTIVE ) - { - Tree23Node* l = node->_left; - Tree23Node* r = node->_right; - Tree23Node* midle; - Tree23Node* right; - switch (r->_type) - { - case 2: - right = new Tree23Node(TREE23_TRI_NODE, node->_telm1, r->_telm0, n->_midle, r->_left, r->_right); - return new Tree23Node(TREE23_BI_NODE, node->_telm0, l, right); - case 3: - midle = new Tree23Node(TREE23_BI_NODE, node->_telm1, n->_midle, r->_left); - right = new Tree23Node(TREE23_BI_NODE, r->_telm1, r->_midle, r->_right); - return new Tree23Node(TREE23_TRI_NODE, node->_telm0, r->_telm0, l, midle, right); - default: - break; - } - } - return node; - } - - Tree23Node* removeRight3(Tree23Node* node) - { - Tree23Node* n = node->_right; - if ( n != NULL && n->_type == TREE23_DELETE_ACTIVE ) - { - Tree23Node* l = node->_left; - Tree23Node* m = node->_midle; - Tree23Node* midle; - Tree23Node* right; - switch (m->_type) - { - case 2: - right = new Tree23Node(TREE23_TRI_NODE, m->_telm0, node->_telm1, m->_left, m->_right, n->_midle); - return new Tree23Node(TREE23_BI_NODE, node->_telm0, l, right); - case 3: - right = new Tree23Node(TREE23_BI_NODE, node->_telm1, m->_right, n->_midle); - midle = new Tree23Node(TREE23_BI_NODE, m->_telm0, m->_left, m->_midle); - return new Tree23Node(TREE23_TRI_NODE, node->_telm0, m->_telm1, l, midle, right); - default: - break; - } - } - return node; - } - - - Tree23Node* _root; + Tree23Node* _root; }; /*===================================== Class List =====================================*/ -template +template class ListElm { - template friend class List; + template friend class List; public: - ListElm() - { - _elm = nullptr; - _prev = _next = nullptr; - } - ListElm(T* elm) - { - _elm = elm; - _prev = _next = nullptr; - } - T* getContent(void) - { - return _elm; - } - ~ListElm(){} + ListElm() + { + _elm = nullptr; + _prev = _next = nullptr; + } + ListElm(T* elm) + { + _elm = elm; + _prev = _next = nullptr; + } + T* getContent(void) + { + return _elm; + } + ~ListElm() + { + } private: - ListElm* getNext(void){return _next;} - T* _elm; - ListElm* _prev; - ListElm* _next; + ListElm* getNext(void) + { + return _next; + } + T* _elm; + ListElm* _prev; + ListElm* _next; }; - -template -class List{ +template +class List +{ public: - List() - { - _head = _tail = nullptr; - _size = 0; - } - ~List() - { - clear(); - } + List() + { + _head = _tail = nullptr; + _size = 0; + } + ~List() + { + clear(); + } - int add(T* t) - { - ListElm* elm = new ListElm(t); - if ( elm == nullptr ) - { - return 0; - } - if ( _head == nullptr ) - { - _head = elm; - _tail = elm; - } - else - { - elm->_prev = _tail; - _tail->_next = elm; - _tail = elm; - } - _size++; - return 1; - } + int add(T* t) + { + ListElm* elm = new ListElm(t); + if (elm == nullptr) + { + return 0; + } + if (_head == nullptr) + { + _head = elm; + _tail = elm; + } + else + { + elm->_prev = _tail; + _tail->_next = elm; + _tail = elm; + } + _size++; + return 1; + } - void erase(ListElm* elm) - { - if ( _head == elm ) - { - _head = elm->_next; - _size--; - delete elm; - } - else if ( _tail == elm ) - { - _tail = elm->_prev; - elm->_prev->_next = nullptr; - _size--; - delete elm; - } - else - { - elm->_prev->_next = elm->_next; - elm->_next->_prev = elm->_prev; - _size--; - delete elm; - } - } - void clear(void) - { - ListElm* p = _head; - while ( p ) - { - ListElm* q = p->_next; - delete p; - p = q; - } - _head = nullptr; - _tail = nullptr; - _size = 0; - } + void erase(ListElm* elm) + { + if (_head == elm) + { + _head = elm->_next; + _size--; + delete elm; + } + else if (_tail == elm) + { + _tail = elm->_prev; + elm->_prev->_next = nullptr; + _size--; + delete elm; + } + else + { + elm->_prev->_next = elm->_next; + elm->_next->_prev = elm->_prev; + _size--; + delete elm; + } + } + void clear(void) + { + ListElm* p = _head; + while (p) + { + ListElm* q = p->_next; + delete p; + p = q; + } + _head = nullptr; + _tail = nullptr; + _size = 0; + } - ListElm* getElm(void) - { - return _head; - } + ListElm* getElm(void) + { + return _head; + } - ListElm* getNext(ListElm* elm) - { - return elm->getNext(); - } - - int getSize(void) - { - return _size; - } + ListElm* getNext(ListElm* elm) + { + return elm->getNext(); + } + int getSize(void) + { + return _size; + } private: - ListElm* _head; - ListElm* _tail; - int _size; + ListElm* _head; + ListElm* _tail; + int _size; }; - extern Process* theProcess; extern MultiTaskProcess* theMultiTaskProcess; diff --git a/MQTTSNGateway/src/MQTTSNGWPublishHandler.cpp b/MQTTSNGateway/src/MQTTSNGWPublishHandler.cpp index 5ef8d5b..8b79935 100644 --- a/MQTTSNGateway/src/MQTTSNGWPublishHandler.cpp +++ b/MQTTSNGateway/src/MQTTSNGWPublishHandler.cpp @@ -27,7 +27,7 @@ using namespace MQTTSNGW; MQTTSNPublishHandler::MQTTSNPublishHandler(Gateway* gateway) { - _gateway = gateway; + _gateway = gateway; } MQTTSNPublishHandler::~MQTTSNPublishHandler() @@ -35,265 +35,280 @@ MQTTSNPublishHandler::~MQTTSNPublishHandler() } -MQTTGWPacket* MQTTSNPublishHandler::handlePublish(Client* client, MQTTSNPacket* packet) +MQTTGWPacket* MQTTSNPublishHandler::handlePublish(Client* client, + MQTTSNPacket* packet) { - uint8_t dup; - int qos; - uint8_t retained; - uint16_t msgId; - uint8_t* payload; + uint8_t dup; + int qos; + uint8_t retained; + uint16_t msgId; + uint8_t* payload; MQTTSN_topicid topicid; - int payloadlen; - Publish pub = MQTTPacket_Publish_Initializer; + int payloadlen; + Publish pub = MQTTPacket_Publish_Initializer; - char shortTopic[2]; + char shortTopic[2]; - if ( !_gateway->getAdapterManager()->getQoSm1Proxy()->isActive() ) - { - if ( client->isQoSm1() ) - { - _gateway->getAdapterManager()->getQoSm1Proxy()->savePacket(client, packet); + if (!_gateway->getAdapterManager()->getQoSm1Proxy()->isActive()) + { + if (client->isQoSm1()) + { + _gateway->getAdapterManager()->getQoSm1Proxy()->savePacket(client, + packet); - return nullptr; - } - } + return nullptr; + } + } - if ( packet->getPUBLISH(&dup, &qos, &retained, &msgId, &topicid, &payload, &payloadlen) ==0 ) - { - return nullptr; - } - pub.msgId = msgId; - pub.header.bits.dup = dup; - pub.header.bits.qos = ( qos == 3 ? 0 : qos ); - pub.header.bits.retain = retained; + if (packet->getPUBLISH(&dup, &qos, &retained, &msgId, &topicid, &payload, + &payloadlen) == 0) + { + return nullptr; + } + pub.msgId = msgId; + pub.header.bits.dup = dup; + pub.header.bits.qos = (qos == 3 ? 0 : qos); + pub.header.bits.retain = retained; - Topic* topic = nullptr; + Topic* topic = nullptr; - if( topicid.type == MQTTSN_TOPIC_TYPE_SHORT ) - { - shortTopic[0] = topicid.data.short_name[0]; - shortTopic[1] = topicid.data.short_name[1]; - pub.topic = shortTopic; - pub.topiclen = 2; - } - else - { - topic = client->getTopics()->getTopicById(&topicid); - if ( !topic ) - { - topic = _gateway->getTopics()->getTopicById(&topicid); - if ( topic ) - { - topic = client->getTopics()->add(topic->getTopicName()->c_str(), topic->getTopicId()); - } - } + if (topicid.type == MQTTSN_TOPIC_TYPE_SHORT) + { + shortTopic[0] = topicid.data.short_name[0]; + shortTopic[1] = topicid.data.short_name[1]; + pub.topic = shortTopic; + pub.topiclen = 2; + } + else + { + topic = client->getTopics()->getTopicById(&topicid); + if (!topic) + { + topic = _gateway->getTopics()->getTopicById(&topicid); + if (topic) + { + topic = client->getTopics()->add(topic->getTopicName()->c_str(), + topic->getTopicId()); + } + } - if( !topic && qos == 3 ) - { - WRITELOG("%s Invalid TopicId.%s %s\n", ERRMSG_HEADER, client->getClientId(), ERRMSG_FOOTER); - return nullptr; - } + if (!topic && qos == 3) + { + WRITELOG("%s Invalid TopicId.%s %s\n", ERRMSG_HEADER, + client->getClientId(), ERRMSG_FOOTER); + return nullptr; + } - if ( ( qos == 0 || qos == 3 ) && msgId > 0 ) - { - WRITELOG("%s Invalid MsgId.%s %s\n", ERRMSG_HEADER, client->getClientId(), ERRMSG_FOOTER); - return nullptr; - } + if ((qos == 0 || qos == 3) && msgId > 0) + { + WRITELOG("%s Invalid MsgId.%s %s\n", ERRMSG_HEADER, + client->getClientId(), ERRMSG_FOOTER); + return nullptr; + } - if( !topic && msgId && qos > 0 && qos < 3 ) - { - /* Reply PubAck with INVALID_TOPIC_ID to the client */ - MQTTSNPacket* pubAck = new MQTTSNPacket(); - pubAck->setPUBACK( topicid.data.id, msgId, MQTTSN_RC_REJECTED_INVALID_TOPIC_ID); - Event* ev1 = new Event(); - ev1->setClientSendEvent(client, pubAck); - _gateway->getClientSendQue()->post(ev1); - return nullptr; - } - if ( topic ) - { - pub.topic = (char*)topic->getTopicName()->data(); - pub.topiclen = topic->getTopicName()->length(); - } - } - /* Save a msgId & a TopicId pare for PUBACK */ - if( msgId && qos > 0 && qos < 3) - { - client->setWaitedPubTopicId(msgId, topicid.data.id, topicid.type); - } + if (!topic && msgId && qos > 0 && qos < 3) + { + /* Reply PubAck with INVALID_TOPIC_ID to the client */ + MQTTSNPacket* pubAck = new MQTTSNPacket(); + pubAck->setPUBACK(topicid.data.id, msgId, + MQTTSN_RC_REJECTED_INVALID_TOPIC_ID); + Event* ev1 = new Event(); + ev1->setClientSendEvent(client, pubAck); + _gateway->getClientSendQue()->post(ev1); + return nullptr; + } + if (topic) + { + pub.topic = (char*) topic->getTopicName()->data(); + pub.topiclen = topic->getTopicName()->length(); + } + } + /* Save a msgId & a TopicId pare for PUBACK */ + if (msgId && qos > 0 && qos < 3) + { + client->setWaitedPubTopicId(msgId, topicid.data.id, topicid.type); + } - pub.payload = (char*)payload; - pub.payloadlen = payloadlen; + pub.payload = (char*) payload; + pub.payloadlen = payloadlen; - MQTTGWPacket* publish = new MQTTGWPacket(); - publish->setPUBLISH(&pub); + MQTTGWPacket* publish = new MQTTGWPacket(); + publish->setPUBLISH(&pub); - if ( _gateway->getAdapterManager()->isAggregaterActive() && client->isAggregated() ) - { - return publish; - } - else - { - Event* ev1 = new Event(); - ev1->setBrokerSendEvent(client, publish); - _gateway->getBrokerSendQue()->post(ev1); - return nullptr; - } + if (_gateway->getAdapterManager()->isAggregaterActive() + && client->isAggregated()) + { + return publish; + } + else + { + Event* ev1 = new Event(); + ev1->setBrokerSendEvent(client, publish); + _gateway->getBrokerSendQue()->post(ev1); + return nullptr; + } } void MQTTSNPublishHandler::handlePuback(Client* client, MQTTSNPacket* packet) { - uint16_t topicId; - uint16_t msgId; - uint8_t rc; - - if ( client->isActive() ) - { - if ( packet->getPUBACK(&topicId, &msgId, &rc) == 0 ) - { - return; - } - - if ( rc == MQTTSN_RC_ACCEPTED) - { - if ( !_gateway->getAdapterManager()->getAggregater()->isActive() ) - { - MQTTGWPacket* pubAck = new MQTTGWPacket(); - pubAck->setAck(PUBACK, msgId); - Event* ev1 = new Event(); - ev1->setBrokerSendEvent(client, pubAck); - _gateway->getBrokerSendQue()->post(ev1); - } - } - else if ( rc == MQTTSN_RC_REJECTED_INVALID_TOPIC_ID) - { - WRITELOG(" PUBACK %d : Invalid Topic ID\n", msgId); - } - } -} - -void MQTTSNPublishHandler::handleAck(Client* client, MQTTSNPacket* packet, uint8_t packetType) -{ - uint16_t msgId; - - if ( client->isActive() ) - { - if ( packet->getACK(&msgId) == 0 ) - { - return; - } - MQTTGWPacket* ackPacket = new MQTTGWPacket(); - ackPacket->setAck(packetType, msgId); - Event* ev1 = new Event(); - ev1->setBrokerSendEvent(client, ackPacket); - _gateway->getBrokerSendQue()->post(ev1); - } -} - -void MQTTSNPublishHandler::handleRegister(Client* client, MQTTSNPacket* packet) -{ - uint16_t id; - uint16_t msgId; - MQTTSNString topicName = MQTTSNString_initializer;; - MQTTSN_topicid topicid; - - if ( client->isActive() || client->isAwake()) - { - if ( packet->getREGISTER(&id, &msgId, &topicName) == 0 ) - { - return; - } - - topicid.type = MQTTSN_TOPIC_TYPE_NORMAL; - topicid.data.long_.len = topicName.lenstring.len; - topicid.data.long_.name = topicName.lenstring.data; - - id = client->getTopics()->add(&topicid)->getTopicId(); - - MQTTSNPacket* regAck = new MQTTSNPacket(); - regAck->setREGACK(id, msgId, MQTTSN_RC_ACCEPTED); - Event* ev = new Event(); - ev->setClientSendEvent(client, regAck); - _gateway->getClientSendQue()->post(ev); - } -} - -void MQTTSNPublishHandler::handleRegAck( Client* client, MQTTSNPacket* packet) -{ - uint16_t id; + uint16_t topicId; uint16_t msgId; uint8_t rc; - if ( client->isActive() || client->isAwake()) + + if (client->isActive()) { - if ( packet->getREGACK(&id, &msgId, &rc) == 0 ) + if (packet->getPUBACK(&topicId, &msgId, &rc) == 0) { return; } - MQTTSNPacket* regAck = client->getWaitREGACKPacketList()->getPacket(msgId); + if (rc == MQTTSN_RC_ACCEPTED) + { + if (!_gateway->getAdapterManager()->getAggregater()->isActive()) + { + MQTTGWPacket* pubAck = new MQTTGWPacket(); + pubAck->setAck(PUBACK, msgId); + Event* ev1 = new Event(); + ev1->setBrokerSendEvent(client, pubAck); + _gateway->getBrokerSendQue()->post(ev1); + } + } + else if (rc == MQTTSN_RC_REJECTED_INVALID_TOPIC_ID) + { + WRITELOG(" PUBACK %d : Invalid Topic ID\n", msgId); + } + } +} - if ( regAck != nullptr ) +void MQTTSNPublishHandler::handleAck(Client* client, MQTTSNPacket* packet, + uint8_t packetType) +{ + uint16_t msgId; + + if (client->isActive()) + { + if (packet->getACK(&msgId) == 0) + { + return; + } + MQTTGWPacket* ackPacket = new MQTTGWPacket(); + ackPacket->setAck(packetType, msgId); + Event* ev1 = new Event(); + ev1->setBrokerSendEvent(client, ackPacket); + _gateway->getBrokerSendQue()->post(ev1); + } +} + +void MQTTSNPublishHandler::handleRegister(Client* client, MQTTSNPacket* packet) +{ + uint16_t id; + uint16_t msgId; + MQTTSNString topicName = MQTTSNString_initializer; + ; + MQTTSN_topicid topicid; + + if (client->isActive() || client->isAwake()) + { + if (packet->getREGISTER(&id, &msgId, &topicName) == 0) + { + return; + } + + topicid.type = MQTTSN_TOPIC_TYPE_NORMAL; + topicid.data.long_.len = topicName.lenstring.len; + topicid.data.long_.name = topicName.lenstring.data; + + id = client->getTopics()->add(&topicid)->getTopicId(); + + MQTTSNPacket* regAck = new MQTTSNPacket(); + regAck->setREGACK(id, msgId, MQTTSN_RC_ACCEPTED); + Event* ev = new Event(); + ev->setClientSendEvent(client, regAck); + _gateway->getClientSendQue()->post(ev); + } +} + +void MQTTSNPublishHandler::handleRegAck(Client* client, MQTTSNPacket* packet) +{ + uint16_t id; + uint16_t msgId; + uint8_t rc; + if (client->isActive() || client->isAwake()) + { + if (packet->getREGACK(&id, &msgId, &rc) == 0) + { + return; + } + + MQTTSNPacket* regAck = client->getWaitREGACKPacketList()->getPacket( + msgId); + + if (regAck != nullptr) { client->getWaitREGACKPacketList()->erase(msgId); Event* ev = new Event(); ev->setClientSendEvent(client, regAck); _gateway->getClientSendQue()->post(ev); } - if (client->isHoldPingReqest() && client->getWaitREGACKPacketList()->getCount() == 0 ) + if (client->isHoldPingReqest() + && client->getWaitREGACKPacketList()->getCount() == 0) { /* send PINGREQ to the broker */ - client->resetPingRequest(); - MQTTGWPacket* pingreq = new MQTTGWPacket(); - pingreq->setHeader(PINGREQ); - Event* evt = new Event(); - evt->setBrokerSendEvent(client, pingreq); - _gateway->getBrokerSendQue()->post(evt); + client->resetPingRequest(); + MQTTGWPacket* pingreq = new MQTTGWPacket(); + pingreq->setHeader(PINGREQ); + Event* evt = new Event(); + evt->setBrokerSendEvent(client, pingreq); + _gateway->getBrokerSendQue()->post(evt); } } } - - - -void MQTTSNPublishHandler::handleAggregatePublish(Client* client, MQTTSNPacket* packet) +void MQTTSNPublishHandler::handleAggregatePublish(Client* client, + MQTTSNPacket* packet) { - int msgId = 0; - MQTTGWPacket* publish = handlePublish(client, packet); - if ( publish != nullptr ) - { - if ( publish->getMsgId() > 0 ) - { - if ( packet->isDuplicate() ) - { - msgId = _gateway->getAdapterManager()->getAggregater()->getMsgId(client, packet->getMsgId()); - } - else - { - msgId = _gateway->getAdapterManager()->getAggregater()->addMessageIdTable(client, packet->getMsgId()); - } - publish->setMsgId(msgId); - } - Event* ev1 = new Event(); - ev1->setBrokerSendEvent(client, publish); - _gateway->getBrokerSendQue()->post(ev1); - } + int msgId = 0; + MQTTGWPacket* publish = handlePublish(client, packet); + if (publish != nullptr) + { + if (publish->getMsgId() > 0) + { + if (packet->isDuplicate()) + { + msgId = + _gateway->getAdapterManager()->getAggregater()->getMsgId( + client, packet->getMsgId()); + } + else + { + msgId = + _gateway->getAdapterManager()->getAggregater()->addMessageIdTable( + client, packet->getMsgId()); + } + publish->setMsgId(msgId); + } + Event* ev1 = new Event(); + ev1->setBrokerSendEvent(client, publish); + _gateway->getBrokerSendQue()->post(ev1); + } } -void MQTTSNPublishHandler::handleAggregateAck(Client* client, MQTTSNPacket* packet, int type) +void MQTTSNPublishHandler::handleAggregateAck(Client* client, + MQTTSNPacket* packet, int type) { - if ( type == MQTTSN_PUBREC ) - { - uint16_t msgId; + if (type == MQTTSN_PUBREC) + { + uint16_t msgId; - if ( packet->getACK(&msgId) == 0 ) - { - return; - } - MQTTSNPacket* ackPacket = new MQTTSNPacket(); - ackPacket->setPUBREL(msgId); - Event* ev = new Event(); - ev->setClientSendEvent(client, ackPacket); - _gateway->getClientSendQue()->post(ev); - } + if (packet->getACK(&msgId) == 0) + { + return; + } + MQTTSNPacket* ackPacket = new MQTTSNPacket(); + ackPacket->setPUBREL(msgId); + Event* ev = new Event(); + ev->setClientSendEvent(client, ackPacket); + _gateway->getClientSendQue()->post(ev); + } } diff --git a/MQTTSNGateway/src/MQTTSNGWPublishHandler.h b/MQTTSNGateway/src/MQTTSNGWPublishHandler.h index 85efeb8..d34b333 100644 --- a/MQTTSNGateway/src/MQTTSNGWPublishHandler.h +++ b/MQTTSNGateway/src/MQTTSNGWPublishHandler.h @@ -25,19 +25,19 @@ namespace MQTTSNGW class MQTTSNPublishHandler { public: - MQTTSNPublishHandler(Gateway* gateway); - ~MQTTSNPublishHandler(); - MQTTGWPacket* handlePublish(Client* client, MQTTSNPacket* packet); - void handlePuback(Client* client, MQTTSNPacket* packet); - void handleAck(Client* client, MQTTSNPacket* packet, uint8_t packetType); - void handleRegister(Client* client, MQTTSNPacket* packet); - void handleRegAck( Client* client, MQTTSNPacket* packet); + MQTTSNPublishHandler(Gateway* gateway); + ~MQTTSNPublishHandler(); + MQTTGWPacket* handlePublish(Client* client, MQTTSNPacket* packet); + void handlePuback(Client* client, MQTTSNPacket* packet); + void handleAck(Client* client, MQTTSNPacket* packet, uint8_t packetType); + void handleRegister(Client* client, MQTTSNPacket* packet); + void handleRegAck(Client* client, MQTTSNPacket* packet); - void handleAggregatePublish(Client* client, MQTTSNPacket* packet); - void handleAggregateAck(Client* client, MQTTSNPacket* packet, int type); + void handleAggregatePublish(Client* client, MQTTSNPacket* packet); + void handleAggregateAck(Client* client, MQTTSNPacket* packet, int type); private: - Gateway* _gateway; + Gateway* _gateway; }; } diff --git a/MQTTSNGateway/src/MQTTSNGWQoSm1Proxy.cpp b/MQTTSNGateway/src/MQTTSNGWQoSm1Proxy.cpp index 349996f..91b05f9 100644 --- a/MQTTSNGateway/src/MQTTSNGWQoSm1Proxy.cpp +++ b/MQTTSNGateway/src/MQTTSNGWQoSm1Proxy.cpp @@ -21,13 +21,13 @@ #include #include - using namespace MQTTSNGW; /*===================================== - Class QoSm1Proxy + Class QoSm1Proxy =====================================*/ -QoSm1Proxy:: QoSm1Proxy(Gateway* gw) : Adapter(gw) +QoSm1Proxy::QoSm1Proxy(Gateway* gw) : + Adapter(gw) { _gateway = gw; } @@ -37,24 +37,22 @@ QoSm1Proxy::~QoSm1Proxy(void) } - void QoSm1Proxy::initialize(char* gwName) { - if ( _gateway->hasSecureConnection() ) + if (_gateway->hasSecureConnection()) { - _isSecure = true; + _isSecure = true; } - /* Create QoS-1 Clients from clients.conf */ - _gateway->getClientList()->setClientList(QOSM1PROXY_TYPE); + /* Create QoS-1 Clients from clients.conf */ + _gateway->getClientList()->setClientList(QOSM1PROXY_TYPE); - /* Create a client for QoS-1 proxy */ - string name = string(gwName) + string("_QoS-1"); - setup(name.c_str(), Atype_QoSm1Proxy); - _isActive = true; + /* Create a client for QoS-1 proxy */ + string name = string(gwName) + string("_QoS-1"); + setup(name.c_str(), Atype_QoSm1Proxy); + _isActive = true; } - bool QoSm1Proxy::isActive(void) { return _isActive; diff --git a/MQTTSNGateway/src/MQTTSNGWQoSm1Proxy.h b/MQTTSNGateway/src/MQTTSNGWQoSm1Proxy.h index 82e5f2a..125b1b9 100644 --- a/MQTTSNGateway/src/MQTTSNGWQoSm1Proxy.h +++ b/MQTTSNGateway/src/MQTTSNGWQoSm1Proxy.h @@ -27,12 +27,12 @@ class SensorNetAddress; class MQTTSNPacket; /*===================================== - Class QoSm1Proxy + Class QoSm1Proxy =====================================*/ -class QoSm1Proxy : public Adapter +class QoSm1Proxy: public Adapter { public: - QoSm1Proxy(Gateway* gw); + QoSm1Proxy(Gateway* gw); ~QoSm1Proxy(void); void initialize(char* GWnAME); @@ -41,13 +41,10 @@ public: private: Gateway* _gateway; - bool _isActive {false}; - bool _isSecure {false}; + bool _isActive { false }; + bool _isSecure { false }; }; - } - - #endif /* MQTTSNGATEWAY_SRC_MQTTSNGWQOSM1PROXY_H_ */ diff --git a/MQTTSNGateway/src/MQTTSNGWSubscribeHandler.cpp b/MQTTSNGateway/src/MQTTSNGWSubscribeHandler.cpp index a08bf49..3f0d5f0 100644 --- a/MQTTSNGateway/src/MQTTSNGWSubscribeHandler.cpp +++ b/MQTTSNGateway/src/MQTTSNGWSubscribeHandler.cpp @@ -26,7 +26,7 @@ using namespace MQTTSNGW; MQTTSNSubscribeHandler::MQTTSNSubscribeHandler(Gateway* gateway) { - _gateway = gateway; + _gateway = gateway; } MQTTSNSubscribeHandler::~MQTTSNSubscribeHandler() @@ -34,65 +34,70 @@ MQTTSNSubscribeHandler::~MQTTSNSubscribeHandler() } -MQTTGWPacket* MQTTSNSubscribeHandler::handleSubscribe(Client* client, MQTTSNPacket* packet) +MQTTGWPacket* MQTTSNSubscribeHandler::handleSubscribe(Client* client, + MQTTSNPacket* packet) { - uint8_t dup; - int qos; - uint16_t msgId; - MQTTSN_topicid topicFilter; - Topic* topic = nullptr; + uint8_t dup; + int qos; + uint16_t msgId; + MQTTSN_topicid topicFilter; + Topic* topic = nullptr; uint16_t topicId = 0; MQTTGWPacket* subscribe; Event* ev1; Event* evsuback; - if ( packet->getSUBSCRIBE(&dup, &qos, &msgId, &topicFilter) == 0 ) - { - return nullptr; - } + if (packet->getSUBSCRIBE(&dup, &qos, &msgId, &topicFilter) == 0) + { + return nullptr; + } - if ( msgId == 0 ) - { - return nullptr; - } + if (msgId == 0) + { + return nullptr; + } - if ( topicFilter.type == MQTTSN_TOPIC_TYPE_PREDEFINED ) + if (topicFilter.type == MQTTSN_TOPIC_TYPE_PREDEFINED) { topic = client->getTopics()->getTopicById(&topicFilter); - if ( !topic ) + if (!topic) { - topic = _gateway->getTopics()->getTopicById(&topicFilter); - if ( topic ) - { - topic = client->getTopics()->add(topic->getTopicName()->c_str(), topic->getTopicId()); - } - else - { - goto RespExit; - } + topic = _gateway->getTopics()->getTopicById(&topicFilter); + if (topic) + { + topic = client->getTopics()->add(topic->getTopicName()->c_str(), + topic->getTopicId()); + } + else + { + goto RespExit; + } } topicId = topic->getTopicId(); subscribe = new MQTTGWPacket(); - subscribe->setSUBSCRIBE((char*)topic->getTopicName()->c_str(), (uint8_t)qos, (uint16_t)msgId); + subscribe->setSUBSCRIBE((char*) topic->getTopicName()->c_str(), + (uint8_t) qos, (uint16_t) msgId); } else if (topicFilter.type == MQTTSN_TOPIC_TYPE_NORMAL) { topic = client->getTopics()->getTopicByName(&topicFilter); - if ( topic == nullptr ) + if (topic == nullptr) { topic = client->getTopics()->add(&topicFilter); - if ( topic == nullptr ) + if (topic == nullptr) { - WRITELOG("%s Client(%s) can't add the Topic.%s\n", ERRMSG_HEADER, client->getClientId(), ERRMSG_FOOTER); + WRITELOG("%s Client(%s) can't add the Topic.%s\n", + ERRMSG_HEADER, client->getClientId(), ERRMSG_FOOTER); return nullptr; } } topicId = topic->getTopicId(); subscribe = new MQTTGWPacket(); - subscribe->setSUBSCRIBE((char*)topic->getTopicName()->c_str(), (uint8_t)qos, (uint16_t)msgId); + subscribe->setSUBSCRIBE((char*) topic->getTopicName()->c_str(), + (uint8_t) qos, (uint16_t) msgId); } else //MQTTSN_TOPIC_TYPE_SHORT { @@ -103,73 +108,72 @@ MQTTGWPacket* MQTTSNSubscribeHandler::handleSubscribe(Client* client, MQTTSNPack topicId = topicFilter.data.short_name[0] << 8; topicId |= topicFilter.data.short_name[1]; subscribe = new MQTTGWPacket(); - subscribe->setSUBSCRIBE(topicstr, (uint8_t)qos, (uint16_t)msgId); + subscribe->setSUBSCRIBE(topicstr, (uint8_t) qos, (uint16_t) msgId); } client->setWaitedSubTopicId(msgId, topicId, topicFilter.type); - if ( !client->isAggregated() ) + if (!client->isAggregated()) { - ev1 = new Event(); - ev1->setBrokerSendEvent(client, subscribe); - _gateway->getBrokerSendQue()->post(ev1); - return nullptr; + ev1 = new Event(); + ev1->setBrokerSendEvent(client, subscribe); + _gateway->getBrokerSendQue()->post(ev1); + return nullptr; } else { - return subscribe; + return subscribe; } - -RespExit: - MQTTSNPacket* sSuback = new MQTTSNPacket(); - sSuback->setSUBACK(qos, topicFilter.data.id, msgId, MQTTSN_RC_NOT_SUPPORTED); - evsuback = new Event(); - evsuback->setClientSendEvent(client, sSuback); - _gateway->getClientSendQue()->post(evsuback); - return nullptr; + RespExit: MQTTSNPacket* sSuback = new MQTTSNPacket(); + sSuback->setSUBACK(qos, topicFilter.data.id, msgId, + MQTTSN_RC_NOT_SUPPORTED); + evsuback = new Event(); + evsuback->setClientSendEvent(client, sSuback); + _gateway->getClientSendQue()->post(evsuback); + return nullptr; } -MQTTGWPacket* MQTTSNSubscribeHandler::handleUnsubscribe(Client* client, MQTTSNPacket* packet) +MQTTGWPacket* MQTTSNSubscribeHandler::handleUnsubscribe(Client* client, + MQTTSNPacket* packet) { - uint16_t msgId; - MQTTSN_topicid topicFilter; + uint16_t msgId; + MQTTSN_topicid topicFilter; MQTTGWPacket* unsubscribe = nullptr; - if ( packet->getUNSUBSCRIBE(&msgId, &topicFilter) == 0 ) - { - return nullptr; - } - - if ( msgId == 0 ) + if (packet->getUNSUBSCRIBE(&msgId, &topicFilter) == 0) { - return nullptr; + return nullptr; } + if (msgId == 0) + { + return nullptr; + } - if (topicFilter.type == MQTTSN_TOPIC_TYPE_SHORT) - { - char shortTopic[3]; + if (topicFilter.type == MQTTSN_TOPIC_TYPE_SHORT) + { + char shortTopic[3]; shortTopic[0] = topicFilter.data.short_name[0]; shortTopic[1] = topicFilter.data.short_name[1]; shortTopic[2] = 0; unsubscribe = new MQTTGWPacket(); unsubscribe->setUNSUBSCRIBE(shortTopic, msgId); - } - else - { - Topic* topic = nullptr; + } + else + { + Topic* topic = nullptr; - if (topicFilter.type == MQTTSN_TOPIC_TYPE_PREDEFINED) - { - topic = client->getTopics()->getTopicById(&topicFilter); - } - else - { - topic = client->getTopics()->getTopicByName(&topicFilter); - } + if (topicFilter.type == MQTTSN_TOPIC_TYPE_PREDEFINED) + { + topic = client->getTopics()->getTopicById(&topicFilter); + } + else + { + topic = client->getTopics()->getTopicByName(&topicFilter); + } - if ( topic == nullptr ) + if (topic == nullptr) { MQTTSNPacket* sUnsuback = new MQTTSNPacket(); sUnsuback->setUNSUBACK(msgId); @@ -183,85 +187,99 @@ MQTTGWPacket* MQTTSNSubscribeHandler::handleUnsubscribe(Client* client, MQTTSNPa unsubscribe = new MQTTGWPacket(); unsubscribe->setUNSUBSCRIBE(topic->getTopicName()->c_str(), msgId); } - } + } - if ( !client->isAggregated() ) + if (!client->isAggregated()) { - Event* ev1 = new Event(); - ev1->setBrokerSendEvent(client, unsubscribe); - _gateway->getBrokerSendQue()->post(ev1); - return nullptr; + Event* ev1 = new Event(); + ev1->setBrokerSendEvent(client, unsubscribe); + _gateway->getBrokerSendQue()->post(ev1); + return nullptr; } else { - return unsubscribe; + return unsubscribe; } } -void MQTTSNSubscribeHandler::handleAggregateSubscribe(Client* client, MQTTSNPacket* packet) +void MQTTSNSubscribeHandler::handleAggregateSubscribe(Client* client, + MQTTSNPacket* packet) { - MQTTGWPacket* subscribe = handleSubscribe(client, packet); + MQTTGWPacket* subscribe = handleSubscribe(client, packet); - if ( subscribe != nullptr ) - { - int msgId = 0; - if ( packet->isDuplicate() ) - { - msgId = _gateway->getAdapterManager()->getAggregater()->getMsgId(client, packet->getMsgId()); - } - else - { - msgId = _gateway->getAdapterManager()->getAggregater()->addMessageIdTable(client, packet->getMsgId()); - } + if (subscribe != nullptr) + { + int msgId = 0; + if (packet->isDuplicate()) + { + msgId = _gateway->getAdapterManager()->getAggregater()->getMsgId( + client, packet->getMsgId()); + } + else + { + msgId = + _gateway->getAdapterManager()->getAggregater()->addMessageIdTable( + client, packet->getMsgId()); + } - if ( msgId == 0 ) - { - WRITELOG("%s MQTTSNSubscribeHandler can't create MessageIdTableElement %s%s\n", ERRMSG_HEADER, client->getClientId(), ERRMSG_FOOTER); - return; - } + if (msgId == 0) + { + WRITELOG( + "%s MQTTSNSubscribeHandler can't create MessageIdTableElement %s%s\n", + ERRMSG_HEADER, client->getClientId(), ERRMSG_FOOTER); + return; + } - UTF8String str = subscribe->getTopic(); - string* topicName = new string(str.data, str.len); // topicName is delete by topic - Topic topic = Topic(topicName, MQTTSN_TOPIC_TYPE_NORMAL); + UTF8String str = subscribe->getTopic(); + string* topicName = new string(str.data, str.len); // topicName is delete by topic + Topic topic = Topic(topicName, MQTTSN_TOPIC_TYPE_NORMAL); - _gateway->getAdapterManager()->getAggregater()->addAggregateTopic(&topic, client); + _gateway->getAdapterManager()->getAggregater()->addAggregateTopic( + &topic, client); - subscribe->setMsgId(msgId); - Event* ev = new Event(); - ev->setBrokerSendEvent(client, subscribe); - _gateway->getBrokerSendQue()->post(ev); - } + subscribe->setMsgId(msgId); + Event* ev = new Event(); + ev->setBrokerSendEvent(client, subscribe); + _gateway->getBrokerSendQue()->post(ev); + } } -void MQTTSNSubscribeHandler::handleAggregateUnsubscribe(Client* client, MQTTSNPacket* packet) +void MQTTSNSubscribeHandler::handleAggregateUnsubscribe(Client* client, + MQTTSNPacket* packet) { - MQTTGWPacket* unsubscribe = handleUnsubscribe(client, packet); - if ( unsubscribe != nullptr ) - { - int msgId = 0; - if ( packet->isDuplicate() ) - { - msgId = _gateway->getAdapterManager()->getAggregater()->getMsgId(client, packet->getMsgId()); - } - else - { - msgId = _gateway->getAdapterManager()->getAggregater()->addMessageIdTable(client, packet->getMsgId()); - } + MQTTGWPacket* unsubscribe = handleUnsubscribe(client, packet); + if (unsubscribe != nullptr) + { + int msgId = 0; + if (packet->isDuplicate()) + { + msgId = _gateway->getAdapterManager()->getAggregater()->getMsgId( + client, packet->getMsgId()); + } + else + { + msgId = + _gateway->getAdapterManager()->getAggregater()->addMessageIdTable( + client, packet->getMsgId()); + } - if ( msgId == 0 ) - { - WRITELOG("%s MQTTSNUnsubscribeHandler can't create MessageIdTableElement %s%s\n", ERRMSG_HEADER, client->getClientId(), ERRMSG_FOOTER); - return; - } + if (msgId == 0) + { + WRITELOG( + "%s MQTTSNUnsubscribeHandler can't create MessageIdTableElement %s%s\n", + ERRMSG_HEADER, client->getClientId(), ERRMSG_FOOTER); + return; + } - UTF8String str = unsubscribe->getTopic(); - string* topicName = new string(str.data, str.len); // topicName is delete by topic - Topic topic = Topic(topicName, MQTTSN_TOPIC_TYPE_NORMAL); - _gateway->getAdapterManager()->getAggregater()->removeAggregateTopic(&topic, client); + UTF8String str = unsubscribe->getTopic(); + string* topicName = new string(str.data, str.len); // topicName is delete by topic + Topic topic = Topic(topicName, MQTTSN_TOPIC_TYPE_NORMAL); + _gateway->getAdapterManager()->getAggregater()->removeAggregateTopic( + &topic, client); - unsubscribe->setMsgId(msgId); - Event* ev = new Event(); - ev->setBrokerSendEvent(client, unsubscribe); - _gateway->getBrokerSendQue()->post(ev); - } + unsubscribe->setMsgId(msgId); + Event* ev = new Event(); + ev->setBrokerSendEvent(client, unsubscribe); + _gateway->getBrokerSendQue()->post(ev); + } } diff --git a/MQTTSNGateway/src/MQTTSNGWSubscribeHandler.h b/MQTTSNGateway/src/MQTTSNGWSubscribeHandler.h index 5b2202a..dd21e3e 100644 --- a/MQTTSNGateway/src/MQTTSNGWSubscribeHandler.h +++ b/MQTTSNGateway/src/MQTTSNGWSubscribeHandler.h @@ -24,23 +24,22 @@ namespace MQTTSNGW { /*===================================== - Class MQTTSNSubscribeHandler + Class MQTTSNSubscribeHandler =====================================*/ class MQTTSNSubscribeHandler { public: - MQTTSNSubscribeHandler(Gateway* gateway); - ~MQTTSNSubscribeHandler(); - MQTTGWPacket* handleSubscribe(Client* client, MQTTSNPacket* packet); - MQTTGWPacket* handleUnsubscribe(Client* client, MQTTSNPacket* packet); - void handleAggregateSubscribe(Client* client, MQTTSNPacket* packet); - void handleAggregateUnsubscribe(Client* client, MQTTSNPacket* packet); + MQTTSNSubscribeHandler(Gateway* gateway); + ~MQTTSNSubscribeHandler(); + MQTTGWPacket* handleSubscribe(Client* client, MQTTSNPacket* packet); + MQTTGWPacket* handleUnsubscribe(Client* client, MQTTSNPacket* packet); + void handleAggregateSubscribe(Client* client, MQTTSNPacket* packet); + void handleAggregateUnsubscribe(Client* client, MQTTSNPacket* packet); private: - Gateway* _gateway; + Gateway* _gateway; }; } - #endif /* MQTTSNGWSUBSCRIBEHANDLER_H_ */ diff --git a/MQTTSNGateway/src/MQTTSNGWTopic.cpp b/MQTTSNGateway/src/MQTTSNGWTopic.cpp index 8f56a4c..43bf82e 100644 --- a/MQTTSNGateway/src/MQTTSNGWTopic.cpp +++ b/MQTTSNGateway/src/MQTTSNGWTopic.cpp @@ -27,35 +27,35 @@ using namespace MQTTSNGW; Topic::Topic() { _type = MQTTSN_TOPIC_TYPE_NORMAL; - _topicName = nullptr; - _topicId = 0; - _next = nullptr; + _topicName = nullptr; + _topicId = 0; + _next = nullptr; } Topic::Topic(string* topic, MQTTSN_topicTypes type) { _type = type; - _topicName = topic; - _topicId = 0; - _next = nullptr; + _topicName = topic; + _topicId = 0; + _next = nullptr; } Topic::~Topic() { - if ( _topicName ) - { - delete _topicName; - } + if (_topicName) + { + delete _topicName; + } } string* Topic::getTopicName(void) { - return _topicName; + return _topicName; } uint16_t Topic::getTopicId(void) { - return _topicId; + return _topicId; } MQTTSN_topicTypes Topic::getType(void) @@ -65,108 +65,109 @@ MQTTSN_topicTypes Topic::getType(void) Topic* Topic::duplicate(void) { - Topic* newTopic = new Topic(); - newTopic->_type = _type; - newTopic->_topicId = _topicId; - newTopic->_topicName = new string(_topicName->c_str()); - return newTopic; + Topic* newTopic = new Topic(); + newTopic->_type = _type; + newTopic->_topicId = _topicId; + newTopic->_topicName = new string(_topicName->c_str()); + return newTopic; } bool Topic::isMatch(string* topicName) { - string::size_type tlen = _topicName->size(); + string::size_type tlen = _topicName->size(); - string::size_type tpos = 0; - string::size_type tloc = 0; - string::size_type pos = 0; - string::size_type loc = 0; - string wildcard = "#"; - string wildcards = "+"; + string::size_type tpos = 0; + string::size_type tloc = 0; + string::size_type pos = 0; + string::size_type loc = 0; + string wildcard = "#"; + string wildcards = "+"; - while(true) - { - loc = topicName->find('/', pos); - tloc = _topicName->find('/', tpos); + while (true) + { + loc = topicName->find('/', pos); + tloc = _topicName->find('/', tpos); - if ( loc != string::npos && tloc != string::npos ) - { - string subtopic = topicName->substr(pos, loc - pos); - string subtopict = _topicName->substr(tpos, tloc - tpos); - if (subtopict == wildcard) - { - return true; - } - else if (subtopict == wildcards) - { - if ( (tpos = tloc + 1 ) > tlen ) - { - pos = loc + 1; - loc = topicName->find('/', pos); - if ( loc == string::npos ) - { - return true; - } - else - { - return false; - } - } - pos = loc + 1; - } - else if ( subtopic != subtopict ) - { - return false; - } - else - { - if ( (tpos = tloc + 1) > tlen ) - { - return false; - } + if (loc != string::npos && tloc != string::npos) + { + string subtopic = topicName->substr(pos, loc - pos); + string subtopict = _topicName->substr(tpos, tloc - tpos); + if (subtopict == wildcard) + { + return true; + } + else if (subtopict == wildcards) + { + if ((tpos = tloc + 1) > tlen) + { + pos = loc + 1; + loc = topicName->find('/', pos); + if (loc == string::npos) + { + return true; + } + else + { + return false; + } + } + pos = loc + 1; + } + else if (subtopic != subtopict) + { + return false; + } + else + { + if ((tpos = tloc + 1) > tlen) + { + return false; + } - pos = loc + 1; - } - } - else if ( loc == string::npos && tloc == string::npos ) - { - string subtopic = topicName->substr(pos); - string subtopict = _topicName->substr(tpos); - if ( subtopict == wildcard || subtopict == wildcards) - { - return true; - } - else if ( subtopic == subtopict ) - { - return true; - } - else - { - return false; - } - } - else if ( loc == string::npos && tloc != string::npos ) - { - string subtopic = topicName->substr(pos); - string subtopict = _topicName->substr(tpos, tloc - tpos); - if ( subtopic != subtopict) - { - return false; - } + pos = loc + 1; + } + } + else if (loc == string::npos && tloc == string::npos) + { + string subtopic = topicName->substr(pos); + string subtopict = _topicName->substr(tpos); + if (subtopict == wildcard || subtopict == wildcards) + { + return true; + } + else if (subtopic == subtopict) + { + return true; + } + else + { + return false; + } + } + else if (loc == string::npos && tloc != string::npos) + { + string subtopic = topicName->substr(pos); + string subtopict = _topicName->substr(tpos, tloc - tpos); + if (subtopic != subtopict) + { + return false; + } - tpos = tloc + 1; + tpos = tloc + 1; - return _topicName->substr(tpos) == wildcard; - } - else if ( loc != string::npos && tloc == string::npos ) - { - return _topicName->substr(tpos) == wildcard; - } - } + return _topicName->substr(tpos) == wildcard; + } + else if (loc != string::npos && tloc == string::npos) + { + return _topicName->substr(tpos) == wildcard; + } + } } void Topic::print(void) { - WRITELOG("TopicName=%s ID=%d Type=%d\n", _topicName->c_str(), _topicId, _type); + WRITELOG("TopicName=%s ID=%d Type=%d\n", _topicName->c_str(), _topicId, + _type); } /*===================================== @@ -198,11 +199,11 @@ Topic* Topics::getTopicByName(const MQTTSN_topicid* topicid) string sname = string(ch, ch + topicid->data.long_.len); while (p) { - if ( p->_topicName->compare(sname) == 0 ) - { - return p; - } - p = p->_next; + if (p->_topicName->compare(sname) == 0) + { + return p; + } + p = p->_next; } return 0; } @@ -213,7 +214,7 @@ Topic* Topics::getTopicById(const MQTTSN_topicid* topicid) while (p) { - if ( p->_type == topicid->type && p->_topicId == topicid->data.id ) + if (p->_type == topicid->type && p->_topicId == topicid->data.id) { return p; } @@ -225,14 +226,14 @@ Topic* Topics::getTopicById(const MQTTSN_topicid* topicid) // For MQTTSN_TOPIC_TYPE_NORMAL */ Topic* Topics::add(const MQTTSN_topicid* topicid) { - if (topicid->type != MQTTSN_TOPIC_TYPE_NORMAL ) + if (topicid->type != MQTTSN_TOPIC_TYPE_NORMAL) { return 0; } Topic* topic = getTopicByName(topicid); - if ( topic ) + if (topic) { return topic; } @@ -244,18 +245,17 @@ Topic* Topics::add(const char* topicName, uint16_t id) { MQTTSN_topicid topicId; - if ( _cnt >= MAX_TOPIC_PAR_CLIENT ) + if (_cnt >= MAX_TOPIC_PAR_CLIENT) { return 0; } - topicId.data.long_.name = (char*)const_cast(topicName); + topicId.data.long_.name = (char*) const_cast(topicName); topicId.data.long_.len = strlen(topicName); - Topic* topic = getTopicByName(&topicId); - if ( topic ) + if (topic) { return topic; } @@ -270,7 +270,7 @@ Topic* Topics::add(const char* topicName, uint16_t id) string* name = new string(topicName); topic->_topicName = name; - if ( id == 0 ) + if (id == 0) { topic->_type = MQTTSN_TOPIC_TYPE_NORMAL; topic->_topicId = getNextTopicId(); @@ -278,12 +278,12 @@ Topic* Topics::add(const char* topicName, uint16_t id) else { topic->_type = MQTTSN_TOPIC_TYPE_PREDEFINED; - topic->_topicId = id; + topic->_topicId = id; } _cnt++; - if ( _first == nullptr) + if (_first == nullptr) { _first = topic; } @@ -331,7 +331,6 @@ Topic* Topics::match(const MQTTSN_topicid* topicid) return 0; } - void Topics::eraseNormal(void) { Topic* topic = _first; @@ -340,14 +339,14 @@ void Topics::eraseNormal(void) while (topic) { - if ( topic->_type == MQTTSN_TOPIC_TYPE_NORMAL ) + if (topic->_type == MQTTSN_TOPIC_TYPE_NORMAL) { next = topic->_next; - if ( _first == topic ) + if (_first == topic) { _first = next; } - if ( prev ) + if (prev) { prev->_next = next; } @@ -365,18 +364,18 @@ void Topics::eraseNormal(void) Topic* Topics::getFirstTopic(void) { - return _first; + return _first; } Topic* Topics::getNextTopic(Topic* topic) { - return topic->_next; + return topic->_next; } void Topics::print(void) { Topic* topic = _first; - if (topic == nullptr ) + if (topic == nullptr) { WRITELOG("No Topic.\n"); } @@ -398,7 +397,8 @@ uint8_t Topics::getCount(void) /*===================================== Class TopicIdMap =====================================*/ -TopicIdMapElement::TopicIdMapElement(uint16_t msgId, uint16_t topicId, MQTTSN_topicTypes type) +TopicIdMapElement::TopicIdMapElement(uint16_t msgId, uint16_t topicId, + MQTTSN_topicTypes type) { _msgId = msgId; _topicId = topicId; @@ -419,7 +419,7 @@ MQTTSN_topicTypes TopicIdMapElement::getTopicType(void) uint16_t TopicIdMapElement::getTopicId(void) { - return _topicId; + return _topicId; } TopicIdMap::TopicIdMap() @@ -434,7 +434,7 @@ TopicIdMap::TopicIdMap() TopicIdMap::~TopicIdMap() { TopicIdMapElement* p = _first; - while ( p ) + while (p) { TopicIdMapElement* q = p->_next; delete p; @@ -445,9 +445,9 @@ TopicIdMap::~TopicIdMap() TopicIdMapElement* TopicIdMap::getElement(uint16_t msgId) { TopicIdMapElement* p = _first; - while ( p ) + while (p) { - if ( p->_msgId == msgId ) + if (p->_msgId == msgId) { return p; } @@ -456,23 +456,25 @@ TopicIdMapElement* TopicIdMap::getElement(uint16_t msgId) return 0; } -TopicIdMapElement* TopicIdMap::add(uint16_t msgId, uint16_t topicId, MQTTSN_topicTypes type) +TopicIdMapElement* TopicIdMap::add(uint16_t msgId, uint16_t topicId, + MQTTSN_topicTypes type) { - if ( _cnt > _maxInflight * 2 || ( topicId == 0 && type != MQTTSN_TOPIC_TYPE_SHORT ) ) + if (_cnt > _maxInflight * 2 + || (topicId == 0 && type != MQTTSN_TOPIC_TYPE_SHORT)) { return 0; } - if ( getElement(msgId) ) + if (getElement(msgId)) { erase(msgId); } TopicIdMapElement* elm = new TopicIdMapElement(msgId, topicId, type); - if ( elm == 0 ) + if (elm == 0) { return 0; } - if ( _first == nullptr ) + if (_first == nullptr) { _first = elm; _end = elm; @@ -490,11 +492,11 @@ TopicIdMapElement* TopicIdMap::add(uint16_t msgId, uint16_t topicId, MQTTSN_topi void TopicIdMap::erase(uint16_t msgId) { TopicIdMapElement* p = _first; - while ( p ) + while (p) { - if ( p->_msgId == msgId ) + if (p->_msgId == msgId) { - if ( p->_prev == nullptr ) + if (p->_prev == nullptr) { _first = p->_next; } @@ -503,7 +505,7 @@ void TopicIdMap::erase(uint16_t msgId) p->_prev->_next = p->_next; } - if ( p->_next == nullptr ) + if (p->_next == nullptr) { _end = p->_prev; } @@ -523,7 +525,7 @@ void TopicIdMap::erase(uint16_t msgId) void TopicIdMap::clear(void) { TopicIdMapElement* p = _first; - while ( p ) + while (p) { TopicIdMapElement* q = p->_next; delete p; @@ -534,5 +536,3 @@ void TopicIdMap::clear(void) _cnt = 0; } - - diff --git a/MQTTSNGateway/src/MQTTSNGWTopic.h b/MQTTSNGateway/src/MQTTSNGWTopic.h index 4d7b0c3..6946b1c 100644 --- a/MQTTSNGateway/src/MQTTSNGWTopic.h +++ b/MQTTSNGateway/src/MQTTSNGWTopic.h @@ -24,7 +24,6 @@ namespace MQTTSNGW { - /*===================================== Class Topic ======================================*/ @@ -46,7 +45,7 @@ public: private: MQTTSN_topicTypes _type; uint16_t _topicId; - string* _topicName; + string* _topicName; Topic* _next; }; @@ -72,7 +71,7 @@ public: private: uint16_t _nextTopicId; Topic* _first; - uint8_t _cnt; + uint8_t _cnt; }; /*===================================== @@ -101,7 +100,8 @@ public: TopicIdMap(); ~TopicIdMap(); TopicIdMapElement* getElement(uint16_t msgId); - TopicIdMapElement* add(uint16_t msgId, uint16_t topicId, MQTTSN_topicTypes type); + TopicIdMapElement* add(uint16_t msgId, uint16_t topicId, + MQTTSN_topicTypes type); void erase(uint16_t msgId); void clear(void); private: @@ -112,9 +112,6 @@ private: int _maxInflight; }; - } - - #endif /* MQTTSNGATEWAY_SRC_MQTTSNGWTOPIC_H_ */ diff --git a/MQTTSNGateway/src/MQTTSNGWVersion.h b/MQTTSNGateway/src/MQTTSNGWVersion.h index 251e5af..e0e6186 100644 --- a/MQTTSNGateway/src/MQTTSNGWVersion.h +++ b/MQTTSNGateway/src/MQTTSNGWVersion.h @@ -17,6 +17,6 @@ #ifndef MQTTSNGWVERSION_H_IN_ #define MQTTSNGWVERSION_H_IN_ -#define PAHO_GATEWAY_VERSION "1.4.0" +#define PAHO_GATEWAY_VERSION "1.5.0" #endif /* MQTTSNGWVERSION_H_IN_ */ diff --git a/MQTTSNGateway/src/MQTTSNGateway.cpp b/MQTTSNGateway/src/MQTTSNGateway.cpp index 6ed0c04..83821e2 100644 --- a/MQTTSNGateway/src/MQTTSNGateway.cpp +++ b/MQTTSNGateway/src/MQTTSNGateway.cpp @@ -43,77 +43,77 @@ Gateway::Gateway(void) Gateway::~Gateway() { - if ( _params.loginId ) - { - free(_params.loginId); - } - if ( _params.password ) - { - free(_params.password); - } - if ( _params.gatewayName ) - { - free(_params.gatewayName); - } - if ( _params.brokerName ) - { - free(_params.brokerName); - } - if ( _params.port ) - { - free(_params.port); - } - if ( _params.portSecure ) - { - free(_params.portSecure); - } - if ( _params.certKey ) - { - free(_params.certKey); - } - if ( _params.privateKey ) - { - free(_params.privateKey); - } - if ( _params.rootCApath ) - { - free(_params.rootCApath); - } - if ( _params.rootCAfile ) - { - free(_params.rootCAfile); - } - if ( _params.clientListName ) - { - free(_params.clientListName); - } - if ( _params.predefinedTopicFileName ) - { - free( _params.predefinedTopicFileName); - } - if ( _params.configName ) - { - free(_params.configName); - } + if (_params.loginId) + { + free(_params.loginId); + } + if (_params.password) + { + free(_params.password); + } + if (_params.gatewayName) + { + free(_params.gatewayName); + } + if (_params.brokerName) + { + free(_params.brokerName); + } + if (_params.port) + { + free(_params.port); + } + if (_params.portSecure) + { + free(_params.portSecure); + } + if (_params.certKey) + { + free(_params.certKey); + } + if (_params.privateKey) + { + free(_params.privateKey); + } + if (_params.rootCApath) + { + free(_params.rootCApath); + } + if (_params.rootCAfile) + { + free(_params.rootCAfile); + } + if (_params.clientListName) + { + free(_params.clientListName); + } + if (_params.predefinedTopicFileName) + { + free(_params.predefinedTopicFileName); + } + if (_params.configName) + { + free(_params.configName); + } - if ( _params.qosMinusClientListName ) + if (_params.qosMinusClientListName) { free(_params.qosMinusClientListName); } - if ( _adapterManager ) + if (_adapterManager) { delete _adapterManager; } - if ( _clientList ) + if (_clientList) { delete _clientList; } - if ( _topics ) - { - delete _topics; - } + if (_topics) + { + delete _topics; + } // WRITELOG("Gateway is deleted normally.\r\n"); } @@ -124,256 +124,258 @@ int Gateway::getParam(const char* parameter, char* value) char* Gateway::getClientListFileName(void) { - return _params.clientListName; + return _params.clientListName; } char* Gateway::getPredefinedTopicFileName(void) { - return _params.predefinedTopicFileName; + return _params.predefinedTopicFileName; } void Gateway::initialize(int argc, char** argv) { - char param[MQTTSNGW_PARAM_MAX]; - string fileName; + char param[MQTTSNGW_PARAM_MAX]; + string fileName; theGateway = this; - MultiTaskProcess::initialize(argc, argv); - resetRingBuffer(); + MultiTaskProcess::initialize(argc, argv); + resetRingBuffer(); - _params.configDir = *getConfigDirName(); + _params.configDir = *getConfigDirName(); fileName = _params.configDir + *getConfigFileName(); _params.configName = strdup(fileName.c_str()); - if (getParam("BrokerName", param) == 0) - { - _params.brokerName = strdup(param); - } - if (getParam("BrokerPortNo", param) == 0) - { - _params.port = strdup(param); - } - if (getParam("BrokerSecurePortNo", param) == 0) - { - _params.portSecure = strdup(param); - } + if (getParam("BrokerName", param) == 0) + { + _params.brokerName = strdup(param); + } + if (getParam("BrokerPortNo", param) == 0) + { + _params.port = strdup(param); + } + if (getParam("BrokerSecurePortNo", param) == 0) + { + _params.portSecure = strdup(param); + } - if (getParam("CertKey", param) == 0) - { - _params.certKey = strdup(param); - } - if (getParam("PrivateKey", param) == 0) - { - _params.privateKey = strdup(param); - } - if (getParam("RootCApath", param) == 0) - { - _params.rootCApath = strdup(param); - } - if (getParam("RootCAfile", param) == 0) - { - _params.rootCAfile = strdup(param); - } + if (getParam("CertKey", param) == 0) + { + _params.certKey = strdup(param); + } + if (getParam("PrivateKey", param) == 0) + { + _params.privateKey = strdup(param); + } + if (getParam("RootCApath", param) == 0) + { + _params.rootCApath = strdup(param); + } + if (getParam("RootCAfile", param) == 0) + { + _params.rootCAfile = strdup(param); + } - if (getParam("GatewayID", param) == 0) - { - _params.gatewayId = atoi(param); - } + if (getParam("GatewayID", param) == 0) + { + _params.gatewayId = atoi(param); + } - if (_params.gatewayId == 0 || _params.gatewayId > 255) - { - throw Exception( "Gateway::initialize: invalid Gateway Id"); - } + if (_params.gatewayId == 0 || _params.gatewayId > 255) + { + throw Exception("Gateway::initialize: invalid Gateway Id"); + } - if (getParam("GatewayName", param) == 0) - { - _params.gatewayName = strdup(param); - } + if (getParam("GatewayName", param) == 0) + { + _params.gatewayName = strdup(param); + } - if (_params.gatewayName == 0 ) - { - throw Exception( "Gateway::initialize: Gateway Name is missing."); - } + if (_params.gatewayName == 0) + { + throw Exception("Gateway::initialize: Gateway Name is missing."); + } - _params.mqttVersion = DEFAULT_MQTT_VERSION; - if (getParam("MQTTVersion", param) == 0) - { - _params.mqttVersion = atoi(param); - } + _params.mqttVersion = DEFAULT_MQTT_VERSION; + if (getParam("MQTTVersion", param) == 0) + { + _params.mqttVersion = atoi(param); + } - _params.maxInflightMsgs = DEFAULT_MQTT_VERSION; - if (getParam("MaxInflightMsgs", param) == 0) - { - _params.maxInflightMsgs = atoi(param); - } + _params.maxInflightMsgs = DEFAULT_MQTT_VERSION; + if (getParam("MaxInflightMsgs", param) == 0) + { + _params.maxInflightMsgs = atoi(param); + } - _params.keepAlive = DEFAULT_KEEP_ALIVE_TIME; - if (getParam("KeepAlive", param) == 0) - { - _params.keepAlive = atoi(param); - } + _params.keepAlive = DEFAULT_KEEP_ALIVE_TIME; + if (getParam("KeepAlive", param) == 0) + { + _params.keepAlive = atoi(param); + } - if (getParam("LoginID", param) == 0) - { - _params.loginId = strdup(param); - } + if (getParam("LoginID", param) == 0) + { + _params.loginId = strdup(param); + } - if (getParam("Password", param) == 0) - { - _params.password = strdup(param); - } + if (getParam("Password", param) == 0) + { + _params.password = strdup(param); + } - if (getParam("ClientAuthentication", param) == 0) - { - if (!strcasecmp(param, "YES")) - { - _params.clientAuthentication = true; - } - } + if (getParam("ClientAuthentication", param) == 0) + { + if (!strcasecmp(param, "YES")) + { + _params.clientAuthentication = true; + } + } - if (getParam("ClientsList", param) == 0) - { - _params.clientListName = strdup(param); - } + if (getParam("ClientsList", param) == 0) + { + _params.clientListName = strdup(param); + } - if (getParam("PredefinedTopic", param) == 0) - { - if ( !strcasecmp(param, "YES") ) - { - _params.predefinedTopic = true; - if (getParam("PredefinedTopicList", param) == 0) - { - _params.predefinedTopicFileName = strdup(param); - } - } - } + if (getParam("PredefinedTopic", param) == 0) + { + if (!strcasecmp(param, "YES")) + { + _params.predefinedTopic = true; + if (getParam("PredefinedTopicList", param) == 0) + { + _params.predefinedTopicFileName = strdup(param); + } + } + } - if (getParam("AggregatingGateway", param) == 0) - { - if ( !strcasecmp(param, "YES") ) - { - _params.aggregatingGw = true; - } - } + if (getParam("AggregatingGateway", param) == 0) + { + if (!strcasecmp(param, "YES")) + { + _params.aggregatingGw = true; + } + } - if (getParam("Forwarder", param) == 0) - { - if ( !strcasecmp(param, "YES") ) - { - _params.forwarder = true; - } - } + if (getParam("Forwarder", param) == 0) + { + if (!strcasecmp(param, "YES")) + { + _params.forwarder = true; + } + } - if (getParam("QoS-1", param) == 0) - { - if ( !strcasecmp(param, "YES") ) - { - _params.qosMinus1 = true; - } - } + if (getParam("QoS-1", param) == 0) + { + if (!strcasecmp(param, "YES")) + { + _params.qosMinus1 = true; + } + } + /* Initialize adapters */ + _adapterManager->initialize(_params.gatewayName, _params.aggregatingGw, + _params.forwarder, _params.qosMinus1); - /* Initialize adapters */ - _adapterManager->initialize( _params.gatewayName, _params.aggregatingGw, _params.forwarder, _params.qosMinus1); - - /* Setup ClientList and Predefined topics */ - _clientList->initialize(_params.aggregatingGw); + /* Setup ClientList and Predefined topics */ + _clientList->initialize(_params.aggregatingGw); } void Gateway::run(void) { /* write prompts */ - _lightIndicator.redLight(true); - WRITELOG("\n%s", PAHO_COPYRIGHT4); - WRITELOG("\n%s\n", PAHO_COPYRIGHT0); - WRITELOG("%s\n", PAHO_COPYRIGHT1); - WRITELOG("%s\n", PAHO_COPYRIGHT2); - WRITELOG(" *\n%s\n", PAHO_COPYRIGHT3); - WRITELOG(" * Version: %s\n", PAHO_GATEWAY_VERSION); - WRITELOG("%s\n", PAHO_COPYRIGHT4); - WRITELOG("\n%s %s has been started.\n\n", currentDateTime(), _params.gatewayName); - WRITELOG(" ConfigFile: %s\n", _params.configName); + _lightIndicator.redLight(true); + WRITELOG("\n%s", PAHO_COPYRIGHT4); + WRITELOG("\n%s\n", PAHO_COPYRIGHT0); + WRITELOG("%s\n", PAHO_COPYRIGHT1); + WRITELOG("%s\n", PAHO_COPYRIGHT2); + WRITELOG(" *\n%s\n", PAHO_COPYRIGHT3); + WRITELOG(" * Version: %s\n", PAHO_GATEWAY_VERSION); + WRITELOG("%s\n", PAHO_COPYRIGHT4); + WRITELOG("\n%s %s has been started.\n\n", currentDateTime(), + _params.gatewayName); + WRITELOG(" ConfigFile: %s\n", _params.configName); - if ( _params.clientListName ) - { - WRITELOG(" ClientList: %s\n", _params.clientListName); - } + if (_params.clientListName) + { + WRITELOG(" ClientList: %s\n", _params.clientListName); + } - if ( _params.predefinedTopicFileName ) + if (_params.predefinedTopicFileName) { WRITELOG(" PreDefFile: %s\n", _params.predefinedTopicFileName); } - WRITELOG(" SensorN/W: %s\n", _sensorNetwork.getDescription()); - WRITELOG(" Broker: %s : %s, %s\n", _params.brokerName, _params.port, _params.portSecure); - WRITELOG(" RootCApath: %s\n", _params.rootCApath); - WRITELOG(" RootCAfile: %s\n", _params.rootCAfile); - WRITELOG(" CertKey: %s\n", _params.certKey); - WRITELOG(" PrivateKey: %s\n\n\n", _params.privateKey); + WRITELOG(" SensorN/W: %s\n", _sensorNetwork.getDescription()); + WRITELOG(" Broker: %s : %s, %s\n", _params.brokerName, _params.port, + _params.portSecure); + WRITELOG(" RootCApath: %s\n", _params.rootCApath); + WRITELOG(" RootCAfile: %s\n", _params.rootCAfile); + WRITELOG(" CertKey: %s\n", _params.certKey); + WRITELOG(" PrivateKey: %s\n\n\n", _params.privateKey); - _stopFlg = false; + _stopFlg = false; - /* Run Tasks until CTRL+C entred */ - MultiTaskProcess::run(); + /* Run Tasks until CTRL+C entred */ + MultiTaskProcess::run(); - _stopFlg = true; + _stopFlg = true; - /* stop Tasks */ - Event* ev = new Event(); - ev->setStop(); - _packetEventQue.post(ev); - ev = new Event(); - ev->setStop(); - _brokerSendQue.post(ev); - ev = new Event(); - ev->setStop(); - _clientSendQue.post(ev); + /* stop Tasks */ + Event* ev = new Event(); + ev->setStop(); + _packetEventQue.post(ev); + ev = new Event(); + ev->setStop(); + _brokerSendQue.post(ev); + ev = new Event(); + ev->setStop(); + _clientSendQue.post(ev); - /* wait until all Task stop */ - MultiTaskProcess::waitStop(); + /* wait until all Task stop */ + MultiTaskProcess::waitStop(); - WRITELOG("\n\n%s MQTT-SN Gateway stopped.\n\n", currentDateTime()); - _lightIndicator.allLightOff(); + WRITELOG("\n\n%s MQTT-SN Gateway stopped.\n\n", currentDateTime()); + _lightIndicator.allLightOff(); } bool Gateway::IsStopping(void) { - return _stopFlg; + return _stopFlg; } EventQue* Gateway::getPacketEventQue() { - return &_packetEventQue; + return &_packetEventQue; } EventQue* Gateway::getClientSendQue() { - return &_clientSendQue; + return &_clientSendQue; } EventQue* Gateway::getBrokerSendQue() { - return &_brokerSendQue; + return &_brokerSendQue; } ClientList* Gateway::getClientList() { - return _clientList; + return _clientList; } SensorNetwork* Gateway::getSensorNetwork() { - return &_sensorNetwork; + return &_sensorNetwork; } LightIndicator* Gateway::getLightIndicator() { - return &_lightIndicator; + return &_lightIndicator; } GatewayParams* Gateway::getGWParams(void) { - return &_params; + return &_params; } AdapterManager* Gateway::getAdapterManager(void) @@ -388,10 +390,8 @@ Topics* Gateway::getTopics(void) bool Gateway::hasSecureConnection(void) { - return ( _params.certKey - && _params.privateKey - && _params.rootCApath - && _params.rootCAfile ); + return (_params.certKey && _params.privateKey && _params.rootCApath + && _params.rootCAfile); } /*===================================== Class EventQue @@ -403,87 +403,86 @@ EventQue::EventQue() EventQue::~EventQue() { - _mutex.lock(); - while (_que.size() > 0) - { - delete _que.front(); - _que.pop(); - } - _mutex.unlock(); + _mutex.lock(); + while (_que.size() > 0) + { + delete _que.front(); + _que.pop(); + } + _mutex.unlock(); } -void EventQue::setMaxSize(uint16_t maxSize) +void EventQue::setMaxSize(uint16_t maxSize) { - _que.setMaxSize((int)maxSize); + _que.setMaxSize((int) maxSize); } Event* EventQue::wait(void) { - Event* ev = nullptr; + Event* ev = nullptr; - while(ev == nullptr) - { - if ( _que.size() == 0 ) - { - _sem.wait(); - } - _mutex.lock(); - ev = _que.front(); - _que.pop(); - _mutex.unlock(); - } - return ev; + while (ev == nullptr) + { + if (_que.size() == 0) + { + _sem.wait(); + } + _mutex.lock(); + ev = _que.front(); + _que.pop(); + _mutex.unlock(); + } + return ev; } Event* EventQue::timedwait(uint16_t millsec) { - Event* ev; - if ( _que.size() == 0 ) - { - _sem.timedwait(millsec); - } - _mutex.lock(); + Event* ev; + if (_que.size() == 0) + { + _sem.timedwait(millsec); + } + _mutex.lock(); - if (_que.size() == 0) - { - ev = new Event(); - ev->setTimeout(); - } - else - { - ev = _que.front(); - _que.pop(); - } - _mutex.unlock(); - return ev; + if (_que.size() == 0) + { + ev = new Event(); + ev->setTimeout(); + } + else + { + ev = _que.front(); + _que.pop(); + } + _mutex.unlock(); + return ev; } void EventQue::post(Event* ev) { - if ( ev ) - { - _mutex.lock(); - if ( _que.post(ev) ) - { - _sem.post(); - } - else - { - delete ev; - } - _mutex.unlock(); - } + if (ev) + { + _mutex.lock(); + if (_que.post(ev)) + { + _sem.post(); + } + else + { + delete ev; + } + _mutex.unlock(); + } } int EventQue::size() { - _mutex.lock(); - int sz = _que.size(); - _mutex.unlock(); - return sz; + _mutex.lock(); + int sz = _que.size(); + _mutex.unlock(); + return sz; } - /*===================================== Class Event =====================================*/ @@ -494,96 +493,95 @@ Event::Event() Event::~Event() { - if (_sensorNetAddr) - { - delete _sensorNetAddr; - } + if (_sensorNetAddr) + { + delete _sensorNetAddr; + } - if (_mqttSNPacket) - { - delete _mqttSNPacket; - } + if (_mqttSNPacket) + { + delete _mqttSNPacket; + } - if (_mqttGWPacket) - { - delete _mqttGWPacket; - } + if (_mqttGWPacket) + { + delete _mqttGWPacket; + } } EventType Event::getEventType() { - return _eventType; + return _eventType; } void Event::setClientSendEvent(Client* client, MQTTSNPacket* packet) { - _client = client; - _eventType = EtClientSend; - _mqttSNPacket = packet; + _client = client; + _eventType = EtClientSend; + _mqttSNPacket = packet; } void Event::setBrokerSendEvent(Client* client, MQTTGWPacket* packet) { - _client = client; - _eventType = EtBrokerSend; - _mqttGWPacket = packet; + _client = client; + _eventType = EtBrokerSend; + _mqttGWPacket = packet; } void Event::setClientRecvEvent(Client* client, MQTTSNPacket* packet) { - _client = client; - _eventType = EtClientRecv; - _mqttSNPacket = packet; + _client = client; + _eventType = EtClientRecv; + _mqttSNPacket = packet; } void Event::setBrokerRecvEvent(Client* client, MQTTGWPacket* packet) { - _client = client; - _eventType = EtBrokerRecv; - _mqttGWPacket = packet; + _client = client; + _eventType = EtBrokerRecv; + _mqttGWPacket = packet; } void Event::setTimeout(void) { - _eventType = EtTimeout; + _eventType = EtTimeout; } void Event::setStop(void) { - _eventType = EtStop; + _eventType = EtStop; } void Event::setBrodcastEvent(MQTTSNPacket* msg) { - _mqttSNPacket = msg; - _eventType = EtBroadcast; + _mqttSNPacket = msg; + _eventType = EtBroadcast; } void Event::setClientSendEvent(SensorNetAddress* addr, MQTTSNPacket* msg) { - _eventType = EtSensornetSend; - _sensorNetAddr = addr; - _mqttSNPacket = msg; + _eventType = EtSensornetSend; + _sensorNetAddr = addr; + _mqttSNPacket = msg; } Client* Event::getClient(void) { - return _client; + return _client; } SensorNetAddress* Event::getSensorNetAddress(void) { - return _sensorNetAddr; + return _sensorNetAddr; } MQTTSNPacket* Event::getMQTTSNPacket() { - return _mqttSNPacket; + return _mqttSNPacket; } MQTTGWPacket* Event::getMQTTGWPacket(void) { - return _mqttGWPacket; + return _mqttGWPacket; } - diff --git a/MQTTSNGateway/src/MQTTSNGateway.h b/MQTTSNGateway/src/MQTTSNGateway.h index 86c7952..10c6c2a 100644 --- a/MQTTSNGateway/src/MQTTSNGateway.h +++ b/MQTTSNGateway/src/MQTTSNGateway.h @@ -46,8 +46,8 @@ namespace MQTTSNGW #define LEFTARROW "<---" #define RIGHTARROW "--->" -#define LEFTARROWB "<===" -#define RIGHTARROWB "===>" +#define LEFTARROWB "<===" +#define RIGHTARROWB "===>" #define FORMAT_Y_G_G_NL "\n%s \033[0m\033[0;33m%-18s\033[0m\033[0;32m%-6s%-34.32s \033[0m\033[0;34m%s\033[0m\033[0;37m\n" #define FORMAT_Y_G_G "%s \033[0m\033[0;33m%-18s\033[0m\033[0;32m%-6s%-34.32s \033[0m\033[0;34m%s\033[0m\033[0;37m\n" @@ -68,150 +68,147 @@ namespace MQTTSNGW #define FORMAT_BL_NL "\n%s \033[0m\033[0;34m%-18s%-6s%-34.32s %s\033[0m\033[0;37m\n" #define FORMAT_W_NL "\n%s %-18s%-6s%-34.32s %s\n" -#define ERRMSG_HEADER "\033[0m\033[0;31mError:" -#define ERRMSG_FOOTER "\033[0m\033[0;37m" +#define ERRMSG_HEADER "\033[0m\033[0;31mError:" +#define ERRMSG_FOOTER "\033[0m\033[0;37m" /*===================================== - Class Event - ====================================*/ + Class Event + ====================================*/ class Client; -enum EventType{ - Et_NA = 0, - EtStop, - EtTimeout, - EtBrokerRecv, - EtBrokerSend, - EtClientRecv, - EtClientSend, - EtBroadcast, - EtSensornetSend +enum EventType +{ + Et_NA = 0, + EtStop, + EtTimeout, + EtBrokerRecv, + EtBrokerSend, + EtClientRecv, + EtClientSend, + EtBroadcast, + EtSensornetSend }; - -class Event{ +class Event +{ public: - Event(); - ~Event(); - EventType getEventType(void); - void setClientRecvEvent(Client*, MQTTSNPacket*); - void setClientSendEvent(Client*, MQTTSNPacket*); - void setBrokerRecvEvent(Client*, MQTTGWPacket*); - void setBrokerSendEvent(Client*, MQTTGWPacket*); - void setBrodcastEvent(MQTTSNPacket*); // ADVERTISE and GWINFO - void setTimeout(void); // Required by EventQue.timedwait() - void setStop(void); - void setClientSendEvent(SensorNetAddress*, MQTTSNPacket*); - Client* getClient(void); - SensorNetAddress* getSensorNetAddress(void); - MQTTSNPacket* getMQTTSNPacket(void); - MQTTGWPacket* getMQTTGWPacket(void); + Event(); + ~Event(); + EventType getEventType(void); + void setClientRecvEvent(Client*, MQTTSNPacket*); + void setClientSendEvent(Client*, MQTTSNPacket*); + void setBrokerRecvEvent(Client*, MQTTGWPacket*); + void setBrokerSendEvent(Client*, MQTTGWPacket*); + void setBrodcastEvent(MQTTSNPacket*); // ADVERTISE and GWINFO + void setTimeout(void); // Required by EventQue.timedwait() + void setStop(void); + void setClientSendEvent(SensorNetAddress*, MQTTSNPacket*); + Client* getClient(void); + SensorNetAddress* getSensorNetAddress(void); + MQTTSNPacket* getMQTTSNPacket(void); + MQTTGWPacket* getMQTTGWPacket(void); private: - EventType _eventType {Et_NA}; - Client* _client {nullptr}; - SensorNetAddress* _sensorNetAddr {nullptr}; - MQTTSNPacket* _mqttSNPacket {nullptr}; - MQTTGWPacket* _mqttGWPacket {nullptr}; + EventType _eventType { Et_NA }; + Client* _client { nullptr }; + SensorNetAddress* _sensorNetAddr { nullptr }; + MQTTSNPacket* _mqttSNPacket { nullptr }; + MQTTGWPacket* _mqttGWPacket { nullptr }; }; - /*===================================== Class EventQue ====================================*/ class EventQue { public: - EventQue(); - ~EventQue(); - Event* wait(void); - Event* timedwait(uint16_t millsec); - void setMaxSize(uint16_t maxSize); - void post(Event*); - int size(); + EventQue(); + ~EventQue(); + Event* wait(void); + Event* timedwait(uint16_t millsec); + void setMaxSize(uint16_t maxSize); + void post(Event*); + int size(); private: - Que _que; - Mutex _mutex; - Semaphore _sem; + Que _que; + Mutex _mutex; + Semaphore _sem; }; - - /*===================================== Class GatewayParams ====================================*/ class GatewayParams { public: - string configDir; - char* configName {nullptr}; - char* clientListName {nullptr}; - char* loginId {nullptr}; - char* password {nullptr}; - uint16_t keepAlive {0}; - uint8_t gatewayId {0}; - uint8_t mqttVersion {0}; - uint16_t maxInflightMsgs {0}; - char* gatewayName {nullptr}; - char* brokerName {nullptr}; - char* port {nullptr}; - char* portSecure {nullptr}; - char* rootCApath {nullptr}; - char* rootCAfile {nullptr}; - char* certKey {nullptr}; - char* predefinedTopicFileName {nullptr}; - char* privateKey {nullptr}; - char* qosMinusClientListName {nullptr}; - bool clientAuthentication {false}; - bool predefinedTopic {false}; - bool aggregatingGw {false}; - bool qosMinus1 {false}; - bool forwarder {false}; + string configDir; + char* configName { nullptr }; + char* clientListName { nullptr }; + char* loginId { nullptr }; + char* password { nullptr }; + uint16_t keepAlive { 0 }; + uint8_t gatewayId { 0 }; + uint8_t mqttVersion { 0 }; + uint16_t maxInflightMsgs { 0 }; + char* gatewayName { nullptr }; + char* brokerName { nullptr }; + char* port { nullptr }; + char* portSecure{ nullptr }; + char* rootCApath { nullptr }; + char* rootCAfile { nullptr }; + char* certKey { nullptr }; + char* predefinedTopicFileName { nullptr }; + char* privateKey { nullptr }; + char* qosMinusClientListName { nullptr }; + bool clientAuthentication { false }; + bool predefinedTopic { false }; + bool aggregatingGw { false }; + bool qosMinus1 { false }; + bool forwarder { false }; }; - - /*===================================== - Class Gateway + Class Gateway =====================================*/ class AdapterManager; class ClientList; -class Gateway: public MultiTaskProcess{ +class Gateway: public MultiTaskProcess +{ public: Gateway(void); - ~Gateway(); - virtual void initialize(int argc, char** argv); - void run(void); + ~Gateway(); + virtual void initialize(int argc, char** argv); + void run(void); - EventQue* getPacketEventQue(void); - EventQue* getClientSendQue(void); - EventQue* getBrokerSendQue(void); - ClientList* getClientList(void); - SensorNetwork* getSensorNetwork(void); - LightIndicator* getLightIndicator(void); - GatewayParams* getGWParams(void); - AdapterManager* getAdapterManager(void); - int getParam(const char* parameter, char* value); - char* getClientListFileName(void); - char* getPredefinedTopicFileName(void); + EventQue* getPacketEventQue(void); + EventQue* getClientSendQue(void); + EventQue* getBrokerSendQue(void); + ClientList* getClientList(void); + SensorNetwork* getSensorNetwork(void); + LightIndicator* getLightIndicator(void); + GatewayParams* getGWParams(void); + AdapterManager* getAdapterManager(void); + int getParam(const char* parameter, char* value); + char* getClientListFileName(void); + char* getPredefinedTopicFileName(void); - bool hasSecureConnection(void); - Topics* getTopics(void); - bool IsStopping(void); + bool hasSecureConnection(void); + Topics* getTopics(void); + bool IsStopping(void); private: - GatewayParams _params; - ClientList* _clientList {nullptr}; - EventQue _packetEventQue; - EventQue _brokerSendQue; - EventQue _clientSendQue; - LightIndicator _lightIndicator; - SensorNetwork _sensorNetwork; - AdapterManager* _adapterManager {nullptr}; - Topics* _topics; - bool _stopFlg; + GatewayParams _params; + ClientList* _clientList { nullptr }; + EventQue _packetEventQue; + EventQue _brokerSendQue; + EventQue _clientSendQue; + LightIndicator _lightIndicator; + SensorNetwork _sensorNetwork; + AdapterManager* _adapterManager { nullptr }; + Topics* _topics; + bool _stopFlg; }; } diff --git a/MQTTSNGateway/src/mainGateway.cpp b/MQTTSNGateway/src/mainGateway.cpp index 4c6657c..d657deb 100644 --- a/MQTTSNGateway/src/mainGateway.cpp +++ b/MQTTSNGateway/src/mainGateway.cpp @@ -26,11 +26,11 @@ using namespace MQTTSNGW; * Gateway Application */ Gateway gateway; -PacketHandleTask task1(&gateway); -ClientRecvTask task2(&gateway); -ClientSendTask task3(&gateway); -BrokerRecvTask task4(&gateway); -BrokerSendTask task5(&gateway); +PacketHandleTask task1(&gateway); +ClientRecvTask task2(&gateway); +ClientSendTask task3(&gateway); +BrokerRecvTask task4(&gateway); +BrokerSendTask task5(&gateway); int main(int argc, char** argv) { @@ -38,13 +38,12 @@ int main(int argc, char** argv) gateway.run(); try { - gateway.initialize(argc, argv); - gateway.run(); - } - catch (const std::exception &ex) + gateway.initialize(argc, argv); + gateway.run(); + } catch (const std::exception &ex) { - WRITELOG("\nEclipse Paho MQTT-SN Gateway exception: %s\n", ex.what()); - WRITELOG("MQTT-SNGateway [-f Config file name]\n"); - } - return 0; + WRITELOG("\nEclipse Paho MQTT-SN Gateway exception: %s\n", ex.what()); + WRITELOG("MQTT-SNGateway [-f Config file name]\n"); + } + return 0; } diff --git a/MQTTSNGateway/src/mainLogmonitor.cpp b/MQTTSNGateway/src/mainLogmonitor.cpp index f73a2a9..da66757 100644 --- a/MQTTSNGateway/src/mainLogmonitor.cpp +++ b/MQTTSNGateway/src/mainLogmonitor.cpp @@ -19,15 +19,14 @@ using namespace MQTTSNGW; - /* * Logmonitor process */ int main(int argc, char** argv) { - Logmonitor monitor = Logmonitor(); - monitor.initialize(argc, argv); - monitor.run(); - return 0; + Logmonitor monitor = Logmonitor(); + monitor.initialize(argc, argv); + monitor.run(); + return 0; }