Add Bluetooth classic as a sensor network #69, #195, #90

I think the architecture of the ble sensor network, which does not use
threads per socket, can be applied to DTLS.

Known bug:
Occasionally a timeout error occurs when connecting to RFCOMM.
BLE is not supported yet. I need help to do it.


Signed-off-by: tomoaki <tomoaki@tomy-tech.com>
This commit is contained in:
tomoaki
2021-06-02 20:15:52 +09:00
parent 982e6d4884
commit 55128f0f0e
54 changed files with 1764 additions and 934 deletions

View File

@@ -87,12 +87,27 @@ TARGET_INCLUDE_DIRECTORIES(mqtt-sngateway_common
/usr/local/opt/openssl/include
)
IF(SENSORNET MATCHES "ble")
TARGET_LINK_LIBRARIES(mqtt-sngateway_common
PRIVATE
MQTTSNPacket
pthread
ssl
crypto)
crypto
bluetooth
)
ELSE()
TARGET_LINK_LIBRARIES(mqtt-sngateway_common
PRIVATE
MQTTSNPacket
pthread
ssl
crypto
)
ENDIF()
ADD_EXECUTABLE(MQTT-SNGateway
mainGateway.cpp

View File

@@ -30,8 +30,7 @@ MQTTGWConnectionHandler::~MQTTGWConnectionHandler()
}
void MQTTGWConnectionHandler::handleConnack(Client* client,
MQTTGWPacket* packet)
void MQTTGWConnectionHandler::handleConnack(Client* client, MQTTGWPacket* packet)
{
uint8_t rc = MQTT_SERVER_UNAVAILABLE;
Connack resp;
@@ -45,35 +44,28 @@ void MQTTGWConnectionHandler::handleConnack(Client* client,
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());
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());
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",
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");
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");
WRITELOG(" Gateway Configuration Error: The Client is not authorized to connect.\n");
}
MQTTSNPacket* snPacket = new MQTTSNPacket();
@@ -85,8 +77,7 @@ void MQTTGWConnectionHandler::handleConnack(Client* client,
_gateway->getClientSendQue()->post(ev1);
}
void MQTTGWConnectionHandler::handlePingresp(Client* client,
MQTTGWPacket* packet)
void MQTTGWConnectionHandler::handlePingresp(Client* client, MQTTGWPacket* packet)
{
MQTTSNPacket* snPacket = new MQTTSNPacket();
snPacket->setPINGRESP();
@@ -96,8 +87,7 @@ void MQTTGWConnectionHandler::handlePingresp(Client* client,
_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);

View File

@@ -28,10 +28,8 @@ 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" };
static const char* mqtt_packet_names[] = { "RESERVED", "CONNECT", "CONNACK", "PUBLISH", "PUBACK", "PUBREC", "PUBREL", "PUBCOMP",
"SUBSCRIBE", "SUBACK", "UNSUBSCRIBE", "UNSUBACK", "PINGREQ", "PINGRESP", "DISCONNECT" };
/**
* Encodes the message length according to the MQTT algorithm
@@ -50,7 +48,8 @@ int MQTTPacket_encode(char* buf, int length)
if (length > 0)
d |= 0x80;
buf[rc++] = d;
} while (length > 0);
}
while (length > 0);
return rc;
}
@@ -206,7 +205,8 @@ int MQTTGWPacket::recv(Network* network)
}
_remainingLength += (c & 127) * multiplier;
multiplier *= 128;
} while ((c & 128) != 0);
}
while ((c & 128) != 0);
if (_remainingLength > 0)
{
@@ -243,9 +243,8 @@ int MQTTGWPacket::send(Network* network)
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)
if (PUBACK != _header.bits.type && PUBREC != _header.bits.type && PUBREL != _header.bits.type
&& PUBCOMP != _header.bits.type && UNSUBACK != _header.bits.type)
{
return 0;
}
@@ -305,18 +304,15 @@ int MQTTGWPacket::getPUBLISH(Publish* pub)
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;
_remainingLength = ((connect->version == 3) ? 12 : 10)
+ (int) strlen(connect->clientID) + 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;
_remainingLength += (int) strlen(connect->willTopic) + 2 + (int) strlen(connect->willMsg) + 2;
}
if (connect->flags.bits.username)
{
@@ -365,8 +361,7 @@ int MQTTGWPacket::setCONNECT(Connect* connect, unsigned char* username,
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;
@@ -640,8 +635,7 @@ MQTTGWPacket& MQTTGWPacket::operator =(MQTTGWPacket& packet)
UTF8String MQTTGWPacket::getTopic(void)
{
UTF8String str =
{ 0, nullptr };
UTF8String str = { 0, nullptr };
if (_header.bits.type == SUBSCRIBE || _header.bits.type == UNSUBSCRIBE)
{
char* ptr = (char*) (_data + 2);

View File

@@ -40,7 +40,7 @@ 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);
ERRMSG_HEADER, client->getStatus(), ERRMSG_FOOTER);
return;
}
@@ -66,9 +66,8 @@ void MQTTGWPublishHandler::handlePublish(Client* client, MQTTGWPacket* packet)
*msg = *packet;
if (msg->getType() == 0)
{
WRITELOG(
"%s MQTTGWPublishHandler::handlePublish can't allocate memories for Packet.%s\n",
ERRMSG_HEADER, ERRMSG_FOOTER);
WRITELOG("%s MQTTGWPublishHandler::handlePublish can't allocate memories for Packet.%s\n",
ERRMSG_HEADER, ERRMSG_FOOTER);
delete msg;
return;
}
@@ -105,15 +104,14 @@ void MQTTGWPublishHandler::handlePublish(Client* client, MQTTGWPacket* packet)
}
else
{
/* This message might be subscribed with wild card or not cleanSession*/
/* This message might be subscribed with wild card or not cleanSession*/
topicId.type = MQTTSN_TOPIC_TYPE_NORMAL;
Topic* topic = client->getTopics()->match(&topicId);
if (topic == nullptr && client->isCleanSession())
if (topic == nullptr && client->isCleanSession())
{
WRITELOG(
"%sMQTTGWPublishHandler Invalid Topic. PUBLISH message is discarded.%s\n",
ERRMSG_HEADER, ERRMSG_FOOTER);
WRITELOG("%sMQTTGWPublishHandler Invalid Topic. PUBLISH message is discarded.%s\n",
ERRMSG_HEADER, ERRMSG_FOOTER);
if (pub.header.bits.qos == 1)
{
replyACK(client, &pub, PUBACK);
@@ -127,20 +125,20 @@ void MQTTGWPublishHandler::handlePublish(Client* client, MQTTGWPacket* packet)
return;
}
if (topic == nullptr)
{
topicId.type = MQTTSN_TOPIC_TYPE_NORMAL;
topicId.data.long_.len = pub.topiclen;
topicId.data.long_.name = pub.topic;
topicId.data.id = 0;
}
if (topic == nullptr)
{
topicId.type = MQTTSN_TOPIC_TYPE_NORMAL;
topicId.data.long_.len = pub.topiclen;
topicId.data.long_.name = pub.topic;
topicId.data.id = 0;
}
/* add the Topic and get a TopicId */
topic = client->getTopics()->add(&topicId);
if (topic == nullptr)
{
WRITELOG(
"%sMQTTGWPublishHandler Can't Add a Topic. MAX_TOPIC_PAR_CLIENT is exceeded. PUBLISH message is discarded.%s\n",
WRITELOG(
"%sMQTTGWPublishHandler Can't Add a Topic. MAX_TOPIC_PAR_CLIENT is exceeded. PUBLISH message is discarded.%s\n",
ERRMSG_HEADER, ERRMSG_FOOTER);
delete snPacket;
return;
@@ -165,29 +163,23 @@ void MQTTGWPublishHandler::handlePublish(Client* client, MQTTGWPacket* packet)
/* 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);
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. PUBLISH message is discarded.%s\n",
ERRMSG_HEADER, ERRMSG_FOOTER);
WRITELOG("%sMQTTGWPublishHandler Can't create a Topic. PUBLISH message is discarded.%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);
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);
@@ -207,8 +199,7 @@ void MQTTGWPublishHandler::handlePuback(Client* client, MQTTGWPacket* packet)
{
Ack ack;
packet->getAck(&ack);
TopicIdMapElement* topicId = client->getWaitedPubTopicId(
(uint16_t) ack.msgId);
TopicIdMapElement* topicId = client->getWaitedPubTopicId((uint16_t) ack.msgId);
if (topicId)
{
MQTTSNPacket* mqttsnPacket = new MQTTSNPacket();
@@ -220,13 +211,11 @@ void MQTTGWPublishHandler::handlePuback(Client* client, MQTTGWPacket* packet)
_gateway->getClientSendQue()->post(ev1);
return;
}
WRITELOG(
" PUBACK from the Broker is invalid. PacketID : %04X ClientID : %s \n",
(uint16_t) ack.msgId, client->getClientId());
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);
@@ -264,13 +253,11 @@ void MQTTGWPublishHandler::handleAck(Client* client, MQTTGWPacket* packet,
}
}
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);
Client* newClient = _gateway->getAdapterManager()->convertClient(msgId, &clientMsgId);
if (newClient != nullptr)
{
packet->setMsgId((int) clientMsgId);
@@ -278,13 +265,11 @@ void MQTTGWPublishHandler::handleAggregatePuback(Client* client,
}
}
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);
Client* newClient = _gateway->getAdapterManager()->convertClient(msgId, &clientMsgId);
if (newClient != nullptr)
{
packet->setMsgId((int) clientMsgId);
@@ -292,16 +277,14 @@ void MQTTGWPublishHandler::handleAggregateAck(Client* client,
}
}
void MQTTGWPublishHandler::handleAggregatePubrel(Client* client,
MQTTGWPacket* packet)
void MQTTGWPublishHandler::handleAggregatePubrel(Client* client, MQTTGWPacket* packet)
{
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);
@@ -310,9 +293,7 @@ void MQTTGWPublishHandler::handleAggregatePublish(Client* client,
Topic topic = Topic(topicName, MQTTSN_TOPIC_TYPE_NORMAL);
// ToDo: need to refactor
ClientTopicElement* elm =
_gateway->getAdapterManager()->getAggregater()->getClientElement(
&topic);
ClientTopicElement* elm = _gateway->getAdapterManager()->getAggregater()->getClientElement(&topic);
while (elm != nullptr)
{
@@ -322,9 +303,8 @@ void MQTTGWPublishHandler::handleAggregatePublish(Client* client,
if (msg->getType() == 0)
{
WRITELOG(
"%s MQTTGWPublishHandler::handleAggregatePublish can't allocate memories for Packet.%s\n",
ERRMSG_HEADER, ERRMSG_FOOTER);
WRITELOG("%s MQTTGWPublishHandler::handleAggregatePublish can't allocate memories for Packet.%s\n",
ERRMSG_HEADER, ERRMSG_FOOTER);
delete msg;
break;
}

View File

@@ -61,8 +61,7 @@ void MQTTGWSubscribeHandler::handleSuback(Client* client, MQTTGWPacket* packet)
}
}
void MQTTGWSubscribeHandler::handleUnsuback(Client* client,
MQTTGWPacket* packet)
void MQTTGWSubscribeHandler::handleUnsuback(Client* client, MQTTGWPacket* packet)
{
Ack ack;
packet->getAck(&ack);
@@ -73,14 +72,11 @@ void MQTTGWSubscribeHandler::handleUnsuback(Client* client,
_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);
Client* newClient = _gateway->getAdapterManager()->getAggregater()->convertClient(msgId, &clientMsgId);
if (newClient != nullptr)
{
packet->setMsgId((int) clientMsgId);
@@ -88,14 +84,11 @@ void MQTTGWSubscribeHandler::handleAggregateSuback(Client* client,
}
}
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);
Client* newClient = _gateway->getAdapterManager()->getAggregater()->convertClient(msgId, &clientMsgId);
if (newClient != nullptr)
{
packet->setMsgId((int) clientMsgId);

View File

@@ -26,8 +26,7 @@ using namespace MQTTSNGW;
/*=====================================
Class MQTTSNAggregateConnectionHandler
=====================================*/
MQTTSNAggregateConnectionHandler::MQTTSNAggregateConnectionHandler(
Gateway* gateway)
MQTTSNAggregateConnectionHandler::MQTTSNAggregateConnectionHandler(Gateway* gateway)
{
_gateway = gateway;
}
@@ -40,8 +39,7 @@ 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)
@@ -86,8 +84,7 @@ void MQTTSNAggregateConnectionHandler::handleConnect(Client* client,
{
if (tp->getType() == MQTTSN_TOPIC_TYPE_NORMAL)
{
_gateway->getAdapterManager()->getAggregater()->removeAggregateTopic(
tp, client);
_gateway->getAdapterManager()->getAggregater()->removeAggregateTopic(tp, client);
}
tp = topics->getNextTopic(tp);
}
@@ -124,8 +121,7 @@ void MQTTSNAggregateConnectionHandler::handleConnect(Client* client,
/*
* WILLMSG
*/
void MQTTSNAggregateConnectionHandler::handleWillmsg(Client* client,
MQTTSNPacket* packet)
void MQTTSNAggregateConnectionHandler::handleWillmsg(Client* client, MQTTSNPacket* packet)
{
if (!client->isWaitWillMsg())
{
@@ -160,8 +156,7 @@ void MQTTSNAggregateConnectionHandler::handleWillmsg(Client* client,
/*
* DISCONNECT
*/
void MQTTSNAggregateConnectionHandler::handleDisconnect(Client* client,
MQTTSNPacket* packet)
void MQTTSNAggregateConnectionHandler::handleDisconnect(Client* client, MQTTSNPacket* packet)
{
MQTTSNPacket* snMsg = new MQTTSNPacket();
snMsg->setDISCONNECT(0);
@@ -173,11 +168,9 @@ void MQTTSNAggregateConnectionHandler::handleDisconnect(Client* client,
/*
* PINGREQ
*/
void MQTTSNAggregateConnectionHandler::handlePingreq(Client* client,
MQTTSNPacket* packet)
void MQTTSNAggregateConnectionHandler::handlePingreq(Client* client, MQTTSNPacket* packet)
{
if ((client->isSleep() || client->isAwake())
&& client->getClientSleepPacket())
if ((client->isSleep() || client->isAwake()) && client->getClientSleepPacket())
{
sendStoredPublish(client);
client->holdPingRequest();

View File

@@ -63,13 +63,12 @@ void Adapter::setup(const char* adpterName, AdapterType adapterType)
string nameSecure = string(adpterName) + "-S";
idSecure.cstring = const_cast<char*>(nameSecure.c_str());
Client* client = _gateway->getClientList()->createClient(0, &id, true,
false, TRANSPEARENT_TYPE);
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);
TRANSPEARENT_TYPE);
setClient(client, true);
client->setAdapterType(adapterType);
}
@@ -173,9 +172,8 @@ void Adapter::send(MQTTSNPacket* packet, Client* client)
}
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;
}
}
@@ -243,8 +241,7 @@ Proxy::~Proxy(void)
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);
@@ -258,8 +255,7 @@ 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;

View File

@@ -39,8 +39,7 @@ AdapterManager::AdapterManager(Gateway* 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)
{
@@ -91,8 +90,7 @@ Aggregater* AdapterManager::getAggregater(void)
bool AdapterManager::isAggregatedClient(Client* client)
{
if (!_aggregater->isActive() || client->isQoSm1() || client->isAggregater()
|| client->isQoSm1Proxy())
if (!_aggregater->isActive() || client->isQoSm1() || client->isAggregater() || client->isQoSm1Proxy())
{
return false;
}
@@ -128,8 +126,7 @@ Client* AdapterManager::getClient(Client* client)
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();
@@ -141,10 +138,8 @@ int AdapterManager::unicastToClient(Client* client, MQTTSNPacket* 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());
WRITELOG(FORMAT_Y_W_G, currentDateTime(), encap.getName(), RIGHTARROW, fwd->getId(), encap.print(pbuf));
rc = encap.unicast(_gateway->getSensorNetwork(), fwd->getSensorNetAddr());
}
else
{
@@ -159,8 +154,7 @@ int AdapterManager::unicastToClient(Client* client, MQTTSNPacket* packet,
}
else
{
rc = packet->unicast(_gateway->getSensorNetwork(),
client->getSensorNetAddress());
rc = packet->unicast(_gateway->getSensorNetwork(), client->getSensorNetAddress());
}
}
return rc;

View File

@@ -129,8 +129,7 @@ ClientTopicElement* AggregateTopicElement::getFirstClientTopicElement(void)
return _head;
}
ClientTopicElement* AggregateTopicElement::getNextClientTopicElement(
ClientTopicElement* elmClient)
ClientTopicElement* AggregateTopicElement::getNextClientTopicElement(ClientTopicElement* elmClient)
{
return elmClient->_next;
}
@@ -262,8 +261,7 @@ void AggregateTopicTable::erase(AggregateTopicElement* elmTopic)
}
}
AggregateTopicElement* AggregateTopicTable::getAggregateTopicElement(
Topic* topic)
AggregateTopicElement* AggregateTopicTable::getAggregateTopicElement(Topic* topic)
{
AggregateTopicElement* elm = _head;

View File

@@ -84,8 +84,7 @@ uint16_t Aggregater::getMsgId(Client* client, uint16_t 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);
}

View File

@@ -54,7 +54,7 @@ void BrokerRecvTask::run(void)
{
struct timeval timeout;
MQTTGWPacket* packet = nullptr;
int rc;
int rc;
Event* ev = nullptr;
fd_set rset;
fd_set wset;
@@ -135,53 +135,43 @@ void BrokerRecvTask::run(void)
{
if (rc == 0) // Disconnected
{
WRITELOG(
"%s BrokerRecvTask %s is disconnected by the broker.%s\n",
ERRMSG_HEADER,
client->getClientId(),
ERRMSG_FOOTER);
client->getNetwork()->close();
client->disconnected();
WRITELOG("%s BrokerRecvTask %s is disconnected by the broker.%s\n",
ERRMSG_HEADER, client->getClientId(),
ERRMSG_FOOTER);
client->getNetwork()->close();
client->disconnected();
}
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);
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_HEADER, client->getClientId(),
ERRMSG_FOOTER);
}
else if (rc == -3)
{
WRITELOG(
"%s BrokerRecvTask can't allocate memories for the packet %s%s\n",
ERRMSG_HEADER,
client->getClientId(),
ERRMSG_FOOTER);
WRITELOG("%s BrokerRecvTask can't allocate memories for the packet %s%s\n",
ERRMSG_HEADER, client->getClientId(),
ERRMSG_FOOTER);
}
delete packet;
if ((rc == -1 || rc == -2)
&& (client->isActive()
|| client->isSleep()
|| client->isAwake()))
if ((rc == -1 || rc == -2) && (client->isActive() || client->isSleep() || client->isAwake()))
{
client->getNetwork()->close();
client->disconnected();
client->getNetwork()->close();
client->disconnected();
}
}
}
}
nextClient: client = client->getNextClient();
}
nextClient: client = client->getNextClient();
}
}
}
@@ -200,31 +190,26 @@ int BrokerRecvTask::log(Client* client, MQTTGWPacket* packet)
switch (packet->getType())
{
case CONNACK:
WRITELOG(FORMAT_Y_Y_W, currentDateTime(), packet->getName(), LEFTARROWB,
client->getClientId(), packet->print(pbuf));
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));
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));
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));
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));
WRITELOG(FORMAT_Y_Y_W, currentDateTime(), packet->getName(), LEFTARROWB, client->getClientId(), packet->print(pbuf));
break;
default:
WRITELOG("Type=%x\n", packet->getType());

View File

@@ -94,28 +94,20 @@ void BrokerSendTask::run()
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);
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);
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);
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;
@@ -139,10 +131,8 @@ void BrokerSendTask::run()
}
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);
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();
@@ -174,12 +164,11 @@ void BrokerSendTask::log(Client* client, MQTTGWPacket* packet)
{
case CONNECT:
WRITELOG(FORMAT_Y_Y_W, currentDateTime(), packet->getName(),
RIGHTARROWB, client->getClientId(), packet->print(pbuf));
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));
WRITELOG(FORMAT_W_MSGID_Y_W, currentDateTime(), packet->getName(), packet->getMsgId(msgId), RIGHTARROWB,
client->getClientId(), packet->print(pbuf));
break;
case SUBSCRIBE:
case UNSUBSCRIBE:
@@ -187,17 +176,16 @@ void BrokerSendTask::log(Client* client, MQTTGWPacket* packet)
case PUBREC:
case PUBREL:
case PUBCOMP:
WRITELOG(FORMAT_W_MSGID_Y_W, currentDateTime(), packet->getName(),
packet->getMsgId(msgId), RIGHTARROWB, client->getClientId(),
packet->print(pbuf));
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));
RIGHTARROWB, client->getClientId(), packet->print(pbuf));
break;
case DISCONNECT:
WRITELOG(FORMAT_Y_Y_W, currentDateTime(), packet->getName(),
RIGHTARROWB, client->getClientId(), packet->print(pbuf));
RIGHTARROWB, client->getClientId(), packet->print(pbuf));
break;
default:
break;

View File

@@ -31,16 +31,14 @@ char* currentDateTime(void);
/*=====================================
Class Client
=====================================*/
static const char* theClientStatus[] =
{ "InPool", "Disconnected", "TryConnecting", "Connecting", "Active", "Asleep",
"Awake",
static const char* theClientStatus[] = { "InPool", "Disconnected", "TryConnecting", "Connecting", "Active", "Asleep", "Awake",
"Lost" };
Client::Client(bool secure)
{
_packetId = 0;
_snMsgId = 0;
_status = Cstat_Free;
_status = Cstat_Free;
_keepAliveMsec = 0;
_topics = new Topics();
_clientId = nullptr;
@@ -121,13 +119,11 @@ int Client::setClientSleepPacket(MQTTGWPacket* packet)
int rc = _clientSleepPacketQue.post(packet);
if (rc)
{
WRITELOG("%s %s is sleeping. the packet was saved.\n",
currentDateTime(), _clientId);
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);
WRITELOG("%s %s is sleeping but discard the packet.\n", currentDateTime(), _clientId);
}
return rc;
}
@@ -147,13 +143,11 @@ int Client::setProxyPacket(MQTTSNPacket* packet)
int rc = _proxyPacketQue.post(packet);
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;
}
@@ -231,8 +225,7 @@ bool Client::erasable(void)
void Client::updateStatus(MQTTSNPacket* packet)
{
if (((_status == Cstat_Disconnected) || (_status == Cstat_Lost))
&& packet->getType() == MQTTSN_CONNECT)
if (((_status == Cstat_Disconnected) || (_status == Cstat_Lost)) && packet->getType() == MQTTSN_CONNECT)
{
setKeepAlive(packet);
}
@@ -288,7 +281,7 @@ void Client::updateStatus(MQTTSNPacket* packet)
default:
break;
}
} DEBUGLOG("Client Status = %s\n", theClientStatus[_status]);
}DEBUGLOG("Client Status = %s\n", theClientStatus[_status]);
}
void Client::updateStatus(ClientStatus stat)
@@ -326,7 +319,7 @@ void Client::tryConnect(void)
bool Client::isCleanSession(void)
{
return _sessionStatus;
return _sessionStatus;
}
bool Client::isConnectSendable(void)

View File

@@ -32,8 +32,8 @@ ClientList::ClientList(Gateway* gw)
_authorize = false;
_firstClient = nullptr;
_endClient = nullptr;
_clientsPool = new ClientsPool();
_gateway = gw;
_clientsPool = new ClientsPool();
_gateway = gw;
}
ClientList::~ClientList()
@@ -49,18 +49,18 @@ ClientList::~ClientList()
cl = ncl;
};
if (_clientsPool)
{
delete _clientsPool;
}
if (_clientsPool)
{
delete _clientsPool;
}
_mutex.unlock();
}
void ClientList::initialize(bool aggregate)
{
_clientsPool->allocate(_gateway->getGWParams()->maxClients);
_clientsPool->allocate(_gateway->getGWParams()->maxClients);
if (_gateway->getGWParams()->clientAuthentication)
if (_gateway->getGWParams()->clientAuthentication)
{
int type = TRANSPEARENT_TYPE;
if (aggregate)
@@ -71,7 +71,7 @@ void ClientList::initialize(bool aggregate)
_authorize = true;
}
if (_gateway->getGWParams()->predefinedTopic)
if (_gateway->getGWParams()->predefinedTopic)
{
setPredefinedTopics(aggregate);
}
@@ -79,21 +79,17 @@ void ClientList::initialize(bool aggregate)
void ClientList::setClientList(int type)
{
if (!createList(_gateway->getGWParams()->clientListName, type))
if (!createList(_gateway->getGWParams()->clientListName, type))
{
throw EXCEPTION(
"ClientList::setClientList Client list not found!", 0);
throw EXCEPTION("ClientList::setClientList Client list not found!", 0);
}
}
void ClientList::setPredefinedTopics(bool aggrecate)
{
if (!readPredefinedList(_gateway->getGWParams()->predefinedTopicFileName,
aggrecate))
if (!readPredefinedList(_gateway->getGWParams()->predefinedTopicFileName, aggrecate))
{
throw EXCEPTION(
"ClientList::setPredefinedTopics PredefindTopic list not found!",
0);
throw EXCEPTION("ClientList::setPredefinedTopics PredefindTopic list not found!", 0);
}
}
@@ -161,15 +157,13 @@ 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);
}
else if (forwarder && type == FORWARDER_TYPE)
{
_gateway->getAdapterManager()->getForwarderList()->addForwarder(
&netAddr, &clientId);
_gateway->getAdapterManager()->getForwarderList()->addForwarder(&netAddr, &clientId);
}
else if (type == TRANSPEARENT_TYPE)
{
@@ -230,8 +224,7 @@ 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;
@@ -327,8 +320,7 @@ Client* ClientList::getClient(MQTTSNString* clientId)
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;
@@ -339,14 +331,12 @@ 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);
}
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 = getClient(addr);
if (client)
@@ -355,16 +345,16 @@ Client* ClientList::createClient(SensorNetAddress* addr, MQTTSNString* clientId,
}
/* acquire a free client */
client = _clientsPool->getClient();
client = _clientsPool->getClient();
if (!client)
{
WRITELOG("%s%sMax number of Clients%s\n", currentDateTime(),
ERRMSG_HEADER, ERRMSG_FOOTER);
return nullptr;
WRITELOG("%s%sMax number of Clients%s\n", currentDateTime(),
ERRMSG_HEADER, ERRMSG_FOOTER);
return nullptr;
}
client->disconnected();
client->disconnected();
if (addr)
{
client->setClientAddress(addr);
@@ -410,19 +400,17 @@ 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());
WRITELOG("Invalid TopicId. Predefined Topic %s, TopicId is 0. \n", topicName.c_str());
return nullptr;
}
if (strcmp(clientId->cstring, common_topic) == 0)
{
_gateway->getTopics()->add((const char*) topicName.c_str(), topicId);
_gateway->getTopics()->add((const char*) topicName.c_str(), topicId);
return nullptr;
}
else
@@ -490,63 +478,62 @@ bool ClientList::isAuthorized()
ClientsPool::ClientsPool()
{
_clientCnt = 0;
_firstClient = nullptr;
_endClient = nullptr;
_clientCnt = 0;
_firstClient = nullptr;
_endClient = nullptr;
}
ClientsPool::~ClientsPool()
{
Client* cl = _firstClient;
Client* ncl;
Client* cl = _firstClient;
Client* ncl;
while (cl != nullptr)
{
ncl = cl->_nextClient;
delete cl;
cl = ncl;
};
while (cl != nullptr)
{
ncl = cl->_nextClient;
delete cl;
cl = ncl;
};
}
void ClientsPool::allocate(int maxClients)
{
Client* cl = nullptr;
Client* cl = nullptr;
_firstClient = new Client();
_firstClient = new Client();
for (int i = 0; i < maxClients; i++)
{
if ((cl = new Client()) == nullptr)
{
throw Exception(
"ClientsPool::Can't allocate max number of clients\n", 0);
}
cl->_nextClient = _firstClient;
_firstClient = cl;
_clientCnt++;
}
for (int i = 0; i < maxClients; i++)
{
if ((cl = new Client()) == nullptr)
{
throw Exception("ClientsPool::Can't allocate max number of clients\n", 0);
}
cl->_nextClient = _firstClient;
_firstClient = cl;
_clientCnt++;
}
}
Client* ClientsPool::getClient(void)
{
while (_firstClient != nullptr)
{
Client* cl = _firstClient;
_firstClient = cl->_nextClient;
cl->_nextClient = nullptr;
_clientCnt--;
return cl;
}
return nullptr;
while (_firstClient != nullptr)
{
Client* cl = _firstClient;
_firstClient = cl->_nextClient;
cl->_nextClient = nullptr;
_clientCnt--;
return cl;
}
return nullptr;
}
void ClientsPool::setClient(Client* client)
{
if (client)
{
client->_nextClient = _firstClient;
_firstClient = client;
_clientCnt++;
}
if (client)
{
client->_nextClient = _firstClient;
_firstClient = client;
_clientCnt++;
}
}

View File

@@ -29,23 +29,18 @@ char* currentDateTime(void);
=====================================*/
ClientRecvTask::ClientRecvTask(Gateway* gateway)
{
_gateway = gateway;
_gateway->attach((Thread*) this);
_sensorNetwork = _gateway->getSensorNetwork();
setTaskName("ClientRecvTask");
_gateway = gateway;
_gateway->attach((Thread*) this);
_sensorNetwork = _gateway->getSensorNetwork();
setTaskName("ClientRecvTask");
}
ClientRecvTask::~ClientRecvTask()
{
}
/**
* Initialize SensorNetwork
*/
void ClientRecvTask::initialize(int argc, char** argv)
{
_sensorNetwork->initialize();
}
/*
@@ -55,305 +50,286 @@ 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();
EventQue* clientsendQue = _gateway->getClientSendQue();
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();
EventQue* clientsendQue = _gateway->getClientSendQue();
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("%s %s stopped.\n", currentDateTime(), getTaskName());
delete packet;
return;
}
if (CHK_SIGINT)
{
WRITELOG("%s %s stopped.\n", currentDateTime(), getTaskName());
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<char *>(fwd->getName());
log(0, packet, &fwdName);
if (fwd != nullptr)
{
MQTTSNString fwdName = MQTTSNString_initializer;
fwdName.cstring = const_cast<char *>(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)
{
log(client, packet, 0);
if (client != nullptr)
{
log(client, packet, 0);
if (client->isDisconnect() && packet->getType() != MQTTSN_CONNECT)
{
WRITELOG("%s MQTTSNGWClientRecvTask %s is not connecting.%s\n",
ERRMSG_HEADER, client->getClientId(), ERRMSG_FOOTER);
if (client->isDisconnect() && packet->getType() != MQTTSN_CONNECT)
{
WRITELOG("%s MQTTSNGWClientRecvTask %s is not connecting.%s\n",
ERRMSG_HEADER, client->getClientId(), ERRMSG_FOOTER);
/* send DISCONNECT to the client, if it is not connected */
MQTTSNPacket* snPacket = new MQTTSNPacket();
snPacket->setDISCONNECT(0);
ev = new Event();
ev->setClientSendEvent(client, snPacket);
clientsendQue->post(ev);
delete packet;
continue;
}
else
{
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;
}
/* send DISCONNECT to the client, if it is not connected */
MQTTSNPacket* snPacket = new MQTTSNPacket();
snPacket->setDISCONNECT(0);
ev = new Event();
ev->setClientSendEvent(client, snPacket);
clientsendQue->post(ev);
delete packet;
continue;
}
else
{
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. */
fwd->addClient(client, &nodeId);
}
else
{
if (client)
{
/* Authentication is not required */
if (_gateway->getGWParams()->clientAuthentication
== false)
{
client->setClientAddress(senderAddr);
}
}
else
{
/* create a new client */
client = clientList->createClient(senderAddr,
&data.clientID, clientType);
}
}
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)
{
/* Authentication is not required */
if (_gateway->getGWParams()->clientAuthentication == false)
{
client->setClientAddress(senderAddr);
}
}
else
{
/* create a new client */
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);
clientId = cstr;
}
}
else if (client)
{
clientId = client->getClientId();
}
else
{
clientId = UNKNOWNCL;
}
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);
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)
{
char pbuf[ SIZE_OF_LOG_PACKET * 3 + 1];
char msgId[6];
char pbuf[ SIZE_OF_LOG_PACKET * 3 + 1];
char msgId[6];
switch (packet->getType())
{
case MQTTSN_SEARCHGW:
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));
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));
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));
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));
break;
case MQTTSN_ENCAPSULATED:
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));
break;
}
switch (packet->getType())
{
case MQTTSN_SEARCHGW:
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));
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));
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));
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));
break;
case MQTTSN_ENCAPSULATED:
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));
break;
}
}

View File

@@ -63,9 +63,8 @@ void ClientSendTask::run()
if (packet->broadcast(_sensorNetwork) < 0)
{
WRITELOG(
"%s ClientSendTask can't multicast a packet Error=%d%s\n",
ERRMSG_HEADER, errno, ERRMSG_FOOTER);
WRITELOG("%s ClientSendTask can't multicast a packet Error=%d%s\n",
ERRMSG_HEADER, errno, ERRMSG_FOOTER);
}
}
else
@@ -85,12 +84,9 @@ void ClientSendTask::run()
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);
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;
@@ -101,15 +97,14 @@ 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;
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));
CLIENTS, packet->print(pbuf));
break;
case MQTTSN_CONNACK:
case MQTTSN_DISCONNECT:
@@ -118,13 +113,11 @@ void ClientSendTask::log(Client* client, MQTTSNPacket* packet)
case MQTTSN_WILLTOPICRESP:
case MQTTSN_WILLMSGRESP:
case MQTTSN_PINGRESP:
WRITELOG(FORMAT_Y_W_G, currentDateTime(), packet->getName(), RIGHTARROW,
clientId, packet->print(pbuf));
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,
WRITELOG(FORMAT_W_MSGID_W_G, currentDateTime(), packet->getName(), packet->getMsgId(msgId), RIGHTARROW, clientId,
packet->print(pbuf));
break;
case MQTTSN_REGACK:
@@ -134,8 +127,7 @@ void ClientSendTask::log(Client* client, MQTTSNPacket* packet)
case MQTTSN_PUBCOMP:
case MQTTSN_SUBACK:
case MQTTSN_UNSUBACK:
WRITELOG(FORMAT_W_MSGID_W_G, currentDateTime(), packet->getName(),
packet->getMsgId(msgId), RIGHTARROW, clientId,
WRITELOG(FORMAT_W_MSGID_W_G, currentDateTime(), packet->getName(), packet->getMsgId(msgId), RIGHTARROW, clientId,
packet->print(pbuf));
break;
default:

View File

@@ -42,8 +42,7 @@ MQTTSNConnectionHandler::~MQTTSNConnectionHandler()
void MQTTSNConnectionHandler::sendADVERTISE()
{
MQTTSNPacket* adv = new MQTTSNPacket();
adv->setADVERTISE(_gateway->getGWParams()->gatewayId,
_gateway->getGWParams()->keepAlive);
adv->setADVERTISE(_gateway->getGWParams()->gatewayId, _gateway->getGWParams()->keepAlive);
Event* ev1 = new Event();
ev1->setBrodcastEvent(adv); //broadcast
_gateway->getClientSendQue()->post(ev1);
@@ -67,8 +66,7 @@ void MQTTSNConnectionHandler::handleSearchgw(MQTTSNPacket* packet)
/*
* CONNECT
*/
void MQTTSNConnectionHandler::handleConnect(Client* client,
MQTTSNPacket* packet)
void MQTTSNConnectionHandler::handleConnect(Client* client, MQTTSNPacket* packet)
{
MQTTSNPacket_connectData data;
if (packet->getCONNECT(&data) == 0)
@@ -149,8 +147,7 @@ void MQTTSNConnectionHandler::handleConnect(Client* client,
/* 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,
mqMsg->setCONNECT(client->getConnectData(), (unsigned char*) _gateway->getGWParams()->loginId,
(unsigned char*) _gateway->getGWParams()->password);
Event* ev1 = new Event();
ev1->setBrokerSendEvent(client, mqMsg);
@@ -161,8 +158,7 @@ void MQTTSNConnectionHandler::handleConnect(Client* client,
/*
* WILLTOPIC
*/
void MQTTSNConnectionHandler::handleWilltopic(Client* client,
MQTTSNPacket* packet)
void MQTTSNConnectionHandler::handleWilltopic(Client* client, MQTTSNPacket* packet)
{
int willQos;
uint8_t willRetain;
@@ -192,8 +188,7 @@ void MQTTSNConnectionHandler::handleWilltopic(Client* client,
/*
* WILLMSG
*/
void MQTTSNConnectionHandler::handleWillmsg(Client* client,
MQTTSNPacket* packet)
void MQTTSNConnectionHandler::handleWillmsg(Client* client, MQTTSNPacket* packet)
{
if (!client->isWaitWillMsg())
{
@@ -216,8 +211,7 @@ void MQTTSNConnectionHandler::handleWillmsg(Client* client,
/* create CONNECT message */
MQTTGWPacket* mqttPacket = new MQTTGWPacket();
connectData->willMsg = client->getWillMsg();
mqttPacket->setCONNECT(connectData,
(unsigned char*) _gateway->getGWParams()->loginId,
mqttPacket->setCONNECT(connectData, (unsigned char*) _gateway->getGWParams()->loginId,
(unsigned char*) _gateway->getGWParams()->password);
/* Send CONNECT to the broker */
@@ -231,8 +225,7 @@ void MQTTSNConnectionHandler::handleWillmsg(Client* client,
/*
* DISCONNECT
*/
void MQTTSNConnectionHandler::handleDisconnect(Client* client,
MQTTSNPacket* packet)
void MQTTSNConnectionHandler::handleDisconnect(Client* client, MQTTSNPacket* packet)
{
uint16_t duration = 0;
@@ -258,8 +251,7 @@ void MQTTSNConnectionHandler::handleDisconnect(Client* client,
/*
* 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();
@@ -272,8 +264,7 @@ void MQTTSNConnectionHandler::handleWilltopicupd(Client* client,
/*
* 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();
@@ -286,11 +277,9 @@ void MQTTSNConnectionHandler::handleWillmsgupd(Client* client,
/*
* PINGREQ
*/
void MQTTSNConnectionHandler::handlePingreq(Client* client,
MQTTSNPacket* packet)
void MQTTSNConnectionHandler::handlePingreq(Client* client, MQTTSNPacket* packet)
{
if ((client->isSleep() || client->isAwake())
&& client->getClientSleepPacket())
if ((client->isSleep() || client->isAwake()) && client->getClientSleepPacket())
{
sendStoredPublish(client);
client->holdPingRequest();

View File

@@ -22,9 +22,7 @@ using namespace MQTTSNGW;
using namespace std;
WirelessNodeId::WirelessNodeId() :
_len
{ 0 }, _nodeId
{ 0 }
_len { 0 }, _nodeId { 0 }
{
}
@@ -78,17 +76,13 @@ bool WirelessNodeId::operator ==(WirelessNodeId& id)
* Class MQTTSNGWEncapsulatedPacket
*/
MQTTSNGWEncapsulatedPacket::MQTTSNGWEncapsulatedPacket() :
_mqttsn
{ 0 }, _ctrl
{ 0 }
_mqttsn { 0 }, _ctrl { 0 }
{
}
MQTTSNGWEncapsulatedPacket::MQTTSNGWEncapsulatedPacket(MQTTSNPacket* packet) :
_mqttsn
{ packet }, _ctrl
{ 0 }
_mqttsn { packet }, _ctrl { 0 }
{
}
@@ -98,8 +92,7 @@ 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);
@@ -121,8 +114,7 @@ int MQTTSNGWEncapsulatedPacket::serialize(uint8_t* buf)
return buf[0] + len;
}
int MQTTSNGWEncapsulatedPacket::desirialize(unsigned char* buf,
unsigned short len)
int MQTTSNGWEncapsulatedPacket::desirialize(unsigned char* buf, unsigned short len)
{
if (_mqttsn)
{

View File

@@ -64,8 +64,7 @@ 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)
@@ -251,10 +250,7 @@ SensorNetAddress* Forwarder::getSensorNetAddr(void)
*/
ForwarderElement::ForwarderElement() :
_client
{ 0 }, _wirelessNodeId
{ 0 }, _next
{ 0 }
_client { 0 }, _wirelessNodeId { 0 }, _next { 0 }
{
}

View File

@@ -45,8 +45,7 @@ MessageIdTable::~MessageIdTable()
_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)
{
@@ -194,18 +193,12 @@ uint16_t MessageIdTable::getMsgId(Client* client, uint16_t clientMsgId)
* Class MessageIdElement
===============================*/
MessageIdElement::MessageIdElement(void) :
_msgId
{ 0 }, _clientMsgId
{ 0 }, _client
{ nullptr }, _next
{ nullptr }, _prev
{ nullptr }
_msgId { 0 }, _clientMsgId { 0 }, _client { nullptr }, _next { nullptr }, _prev { nullptr }
{
}
MessageIdElement::MessageIdElement(uint16_t msgId, Client* client,
uint16_t clientMsgId) :
MessageIdElement::MessageIdElement(uint16_t msgId, Client* client, uint16_t clientMsgId) :
MessageIdElement()
{
_msgId = msgId;

View File

@@ -149,8 +149,7 @@ 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);
int len = MQTTSNSerialize_advertise(buf, buflen, (unsigned char) gatewayid, (unsigned short) duration);
return desirialize(buf, len);
}
@@ -158,8 +157,7 @@ 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);
int len = MQTTSNSerialize_gwinfo(buf, buflen, (unsigned char) gatewayId, 0, 0);
return desirialize(buf, len);
}
@@ -202,45 +200,37 @@ int MQTTSNPacket::setWILLMSGREQ(void)
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);
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);
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,
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);
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);
int len = MQTTSNSerialize_puback(buf, buflen, (unsigned short) topicId, (unsigned short) msgId, (unsigned char) returnCode);
return desirialize(buf, len);
}
@@ -268,13 +258,12 @@ int MQTTSNPacket::setPUBCOMP(uint16_t 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);
int len = MQTTSNSerialize_suback(buf, buflen, qos, (unsigned short) topicId, (unsigned short) msgId,
(unsigned char) returnCode);
return desirialize(buf, len);
}
@@ -336,8 +325,7 @@ int MQTTSNPacket::setPINGREQ(MQTTSNString* clientId)
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)
@@ -350,11 +338,9 @@ int MQTTSNPacket::getCONNACK(uint8_t* 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)
@@ -362,34 +348,28 @@ int MQTTSNPacket::getWILLMSG(MQTTSNString* willmsg)
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,
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)
@@ -398,17 +378,14 @@ int MQTTSNPacket::getACK(uint16_t* msgId)
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)
@@ -428,11 +405,9 @@ int MQTTSNPacket::getDISCONNECT(uint16_t* duration)
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)

View File

@@ -125,8 +125,7 @@ void PacketHandleTask::run()
if (_advertiseTimer.isTimeup())
{
_mqttsnConnection->sendADVERTISE();
_advertiseTimer.start(
_gateway->getGWParams()->keepAlive * 1000UL);
_advertiseTimer.start(_gateway->getGWParams()->keepAlive * 1000UL);
}
/*------ Check Adapters Connect or PINGREQ ------*/
@@ -180,8 +179,7 @@ void PacketHandleTask::run()
}
}
void PacketHandleTask::aggregatePacketHandler(Client*client,
MQTTSNPacket* packet)
void PacketHandleTask::aggregatePacketHandler(Client*client, MQTTSNPacket* packet)
{
switch (packet->getType())
{
@@ -238,8 +236,7 @@ void PacketHandleTask::aggregatePacketHandler(Client*client,
}
}
void PacketHandleTask::aggregatePacketHandler(Client*client,
MQTTGWPacket* packet)
void PacketHandleTask::aggregatePacketHandler(Client*client, MQTTGWPacket* packet)
{
switch (packet->getType())
{
@@ -275,8 +272,7 @@ void PacketHandleTask::aggregatePacketHandler(Client*client,
}
}
void PacketHandleTask::transparentPacketHandler(Client*client,
MQTTSNPacket* packet)
void PacketHandleTask::transparentPacketHandler(Client*client, MQTTSNPacket* packet)
{
switch (packet->getType())
{
@@ -333,8 +329,7 @@ void PacketHandleTask::transparentPacketHandler(Client*client,
}
}
void PacketHandleTask::transparentPacketHandler(Client*client,
MQTTGWPacket* packet)
void PacketHandleTask::transparentPacketHandler(Client*client, MQTTGWPacket* packet)
{
switch (packet->getType())
{

View File

@@ -163,7 +163,7 @@ int Process::getParam(const char* parameter, char* value)
if ((fp = fopen(configPath.c_str(), "r")) == NULL)
{
throw Exception("No config file:\n\nUsage: Command -f path/config_file_name\n", 0);
throw Exception("Config file not found:\n\nUsage: Command -f path/config_file_name\n", 0);
}
while (true)
@@ -257,7 +257,7 @@ MultiTaskProcess::~MultiTaskProcess()
{
for (int i = 0; i < _threadCount; i++)
{
_threadList[i]->stop();
_threadList[i]->stop();
}
}
@@ -338,18 +338,18 @@ int MultiTaskProcess::getParam(const char* parameter, char* value)
======================================*/
Exception::Exception(const char* message, const int errNo)
{
_message = message;
_message = message;
_errNo = errNo;
_fileName = nullptr;
_functionName = nullptr;
_line = 0;
}
Exception::Exception(const char* message, const int errNo, const char* file,
const char* function, const int line)
Exception::Exception(const char* message, const int errNo, const char* file, const char* function, const int line)
{
_message = message;
_message = message;
_errNo = errNo;
_fileName = getFileName(file);;
_fileName = getFileName(file);
;
_functionName = function;
_line = line;
}
@@ -388,39 +388,40 @@ void Exception::writeMessage()
{
if (_fileName == nullptr)
{
if (_errNo == 0)
{
WRITELOG("%s%s %s%s\n", currentDateTime(), RED_HDR, _message, CLR_HDR);
}
else
{
WRITELOG("%s%s %s.\n errno=%d : %s%s\n", currentDateTime(), RED_HDR,_message, _errNo, strerror(_errNo), CLR_HDR);
}
if (_errNo == 0)
{
WRITELOG("%s%s %s%s\n", currentDateTime(), RED_HDR, _message, CLR_HDR);
}
else
{
WRITELOG("%s%s %s.\n errno=%d : %s%s\n", currentDateTime(), RED_HDR, _message, _errNo,
strerror(_errNo), CLR_HDR);
}
}
else
{
if (_errNo == 0)
{
WRITELOG("%s%s %s. %s line %-4d %s()%s\n",
currentDateTime(), RED_HDR, _message, _fileName, _line, _functionName, CLR_HDR);
}
else
{
WRITELOG("%s%s %s. %s line %-4d %s()\n errno=%d : %s%s\n",
currentDateTime(), RED_HDR, _message, _fileName, _line, _functionName, _errNo, strerror(_errNo), CLR_HDR);
}
if (_errNo == 0)
{
WRITELOG("%s%s %s. %s line %-4d %s()%s\n", currentDateTime(), RED_HDR, _message, _fileName, _line, _functionName,
CLR_HDR);
}
else
{
WRITELOG("%s%s %s. %s line %-4d %s()\n errno=%d : %s%s\n", currentDateTime(), RED_HDR, _message,
_fileName, _line, _functionName, _errNo, strerror(_errNo), CLR_HDR);
}
}
}
const char* Exception::getFileName(const char* file)
{
for ( int len = strlen(file); len > 0; len-- )
{
if (*(file + len) == '/')
{
return file + len + 1;
}
}
return file;
for (int len = strlen(file); len > 0; len--)
{
if (*(file + len) == '/')
{
return file + len + 1;
}
}
return file;
}

View File

@@ -35,14 +35,13 @@ 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;
uint16_t tid;
uint16_t tid;
uint8_t* payload;
MQTTSN_topicid topicid;
int payloadlen;
@@ -54,15 +53,13 @@ MQTTGWPacket* MQTTSNPublishHandler::handlePublish(Client* client,
{
if (client->isQoSm1())
{
_gateway->getAdapterManager()->getQoSm1Proxy()->savePacket(client,
packet);
_gateway->getAdapterManager()->getQoSm1Proxy()->savePacket(client, packet);
return nullptr;
}
}
if (packet->getPUBLISH(&dup, &qos, &retained, &msgId, &topicid, &payload,
&payloadlen) == 0)
if (packet->getPUBLISH(&dup, &qos, &retained, &msgId, &topicid, &payload, &payloadlen) == 0)
{
return nullptr;
}
@@ -70,7 +67,7 @@ MQTTGWPacket* MQTTSNPublishHandler::handlePublish(Client* client,
pub.header.bits.dup = dup;
pub.header.bits.qos = (qos == 3 ? 0 : qos);
pub.header.bits.retain = retained;
tid = topicid.data.id;
tid = topicid.data.id;
Topic* topic = nullptr;
@@ -89,22 +86,19 @@ MQTTGWPacket* MQTTSNPublishHandler::handlePublish(Client* client,
topic = _gateway->getTopics()->getTopicById(&topicid);
if (topic)
{
topic = client->getTopics()->add(topic->getTopicName()->c_str(),
topic->getTopicId());
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);
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);
WRITELOG("%s Invalid MsgId.%s %s\n", ERRMSG_HEADER, client->getClientId(), ERRMSG_FOOTER);
return nullptr;
}
@@ -112,8 +106,7 @@ MQTTGWPacket* MQTTSNPublishHandler::handlePublish(Client* client,
{
/* 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);
pubAck->setPUBACK(topicid.data.id, msgId, MQTTSN_RC_REJECTED_INVALID_TOPIC_ID);
Event* ev1 = new Event();
ev1->setClientSendEvent(client, pubAck);
_gateway->getClientSendQue()->post(ev1);
@@ -123,14 +116,14 @@ MQTTGWPacket* MQTTSNPublishHandler::handlePublish(Client* client,
{
pub.topic = (char*) topic->getTopicName()->data();
pub.topiclen = topic->getTopicName()->length();
topicid.data.long_.name = pub.topic;
topicid.data.long_.len = pub.topiclen;
topicid.data.long_.name = pub.topic;
topicid.data.long_.len = pub.topiclen;
}
}
/* Save a msgId & a TopicId pare for PUBACK */
if (msgId && qos > 0 && qos < 3)
{
client->setWaitedPubTopicId(msgId, tid, &topicid);
client->setWaitedPubTopicId(msgId, tid, &topicid);
}
pub.payload = (char*) payload;
@@ -139,8 +132,7 @@ MQTTGWPacket* MQTTSNPublishHandler::handlePublish(Client* client,
MQTTGWPacket* publish = new MQTTGWPacket();
publish->setPUBLISH(&pub);
if (_gateway->getAdapterManager()->isAggregaterActive()
&& client->isAggregated())
if (_gateway->getAdapterManager()->isAggregaterActive() && client->isAggregated())
{
return publish;
}
@@ -184,8 +176,7 @@ void MQTTSNPublishHandler::handlePuback(Client* client, MQTTSNPacket* packet)
}
}
void MQTTSNPublishHandler::handleAck(Client* client, MQTTSNPacket* packet,
uint8_t packetType)
void MQTTSNPublishHandler::handleAck(Client* client, MQTTSNPacket* packet, uint8_t packetType)
{
uint16_t msgId;
@@ -245,19 +236,17 @@ void MQTTSNPublishHandler::handleRegAck(Client* client, MQTTSNPacket* packet)
}
/* get PUBLISH message */
MQTTSNPacket* regAck = client->getWaitREGACKPacketList()->getPacket(
msgId);
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);
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();
@@ -271,8 +260,7 @@ void MQTTSNPublishHandler::handleRegAck(Client* client, MQTTSNPacket* packet)
}
void MQTTSNPublishHandler::handleAggregatePublish(Client* client,
MQTTSNPacket* packet)
void MQTTSNPublishHandler::handleAggregatePublish(Client* client, MQTTSNPacket* packet)
{
int msgId = 0;
MQTTGWPacket* publish = handlePublish(client, packet);
@@ -282,15 +270,11 @@ void MQTTSNPublishHandler::handleAggregatePublish(Client* client,
{
if (packet->isDuplicate())
{
msgId =
_gateway->getAdapterManager()->getAggregater()->getMsgId(
client, packet->getMsgId());
msgId = _gateway->getAdapterManager()->getAggregater()->getMsgId(client, packet->getMsgId());
}
else
{
msgId =
_gateway->getAdapterManager()->getAggregater()->addMessageIdTable(
client, packet->getMsgId());
msgId = _gateway->getAdapterManager()->getAggregater()->addMessageIdTable(client, packet->getMsgId());
}
publish->setMsgId(msgId);
}
@@ -300,8 +284,7 @@ void MQTTSNPublishHandler::handleAggregatePublish(Client* client,
}
}
void MQTTSNPublishHandler::handleAggregateAck(Client* client,
MQTTSNPacket* packet, int type)
void MQTTSNPublishHandler::handleAggregateAck(Client* client, MQTTSNPacket* packet, int type)
{
if (type == MQTTSN_PUBREC)
{

View File

@@ -34,8 +34,7 @@ MQTTSNSubscribeHandler::~MQTTSNSubscribeHandler()
}
MQTTGWPacket* MQTTSNSubscribeHandler::handleSubscribe(Client* client,
MQTTSNPacket* packet)
MQTTGWPacket* MQTTSNSubscribeHandler::handleSubscribe(Client* client, MQTTSNPacket* packet)
{
uint8_t dup;
int qos;
@@ -63,16 +62,15 @@ MQTTGWPacket* MQTTSNSubscribeHandler::handleSubscribe(Client* client,
if (!topic)
{
/* Search the topic in Client common topic table */
/* Search the topic in Client common topic table */
topic = _gateway->getTopics()->getTopicById(&topicFilter);
if (topic)
{
topic = client->getTopics()->add(topic->getTopicName()->c_str(),
topic->getTopicId());
topic = client->getTopics()->add(topic->getTopicName()->c_str(), topic->getTopicId());
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);
goto RespExit;
}
}
@@ -83,8 +81,7 @@ MQTTGWPacket* MQTTSNSubscribeHandler::handleSubscribe(Client* client,
}
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)
@@ -96,15 +93,14 @@ MQTTGWPacket* MQTTSNSubscribeHandler::handleSubscribe(Client* client,
if (topic == nullptr)
{
WRITELOG("%s Client(%s) can't add the Topic.%s\n",
ERRMSG_HEADER, client->getClientId(), ERRMSG_FOOTER);
ERRMSG_HEADER, client->getClientId(), ERRMSG_FOOTER);
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 //MQTTSN_TOPIC_TYPE_SHORT
{
@@ -133,16 +129,14 @@ MQTTGWPacket* MQTTSNSubscribeHandler::handleSubscribe(Client* client,
}
RespExit: MQTTSNPacket* sSuback = new MQTTSNPacket();
sSuback->setSUBACK(qos, topicFilter.data.id, msgId,
MQTTSN_RC_REJECTED_INVALID_TOPIC_ID);
sSuback->setSUBACK(qos, topicFilter.data.id, msgId, MQTTSN_RC_REJECTED_INVALID_TOPIC_ID);
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;
@@ -209,8 +203,7 @@ MQTTGWPacket* MQTTSNSubscribeHandler::handleUnsubscribe(Client* client,
}
}
void MQTTSNSubscribeHandler::handleAggregateSubscribe(Client* client,
MQTTSNPacket* packet)
void MQTTSNSubscribeHandler::handleAggregateSubscribe(Client* client, MQTTSNPacket* packet)
{
MQTTGWPacket* subscribe = handleSubscribe(client, packet);
@@ -219,21 +212,17 @@ void MQTTSNSubscribeHandler::handleAggregateSubscribe(Client* client,
int msgId = 0;
if (packet->isDuplicate())
{
msgId = _gateway->getAdapterManager()->getAggregater()->getMsgId(
client, packet->getMsgId());
msgId = _gateway->getAdapterManager()->getAggregater()->getMsgId(client, packet->getMsgId());
}
else
{
msgId =
_gateway->getAdapterManager()->getAggregater()->addMessageIdTable(
client, packet->getMsgId());
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);
WRITELOG("%s MQTTSNSubscribeHandler can't create MessageIdTableElement %s%s\n",
ERRMSG_HEADER, client->getClientId(), ERRMSG_FOOTER);
return;
}
@@ -241,8 +230,7 @@ void MQTTSNSubscribeHandler::handleAggregateSubscribe(Client* client,
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();
@@ -251,8 +239,7 @@ void MQTTSNSubscribeHandler::handleAggregateSubscribe(Client* client,
}
}
void MQTTSNSubscribeHandler::handleAggregateUnsubscribe(Client* client,
MQTTSNPacket* packet)
void MQTTSNSubscribeHandler::handleAggregateUnsubscribe(Client* client, MQTTSNPacket* packet)
{
MQTTGWPacket* unsubscribe = handleUnsubscribe(client, packet);
if (unsubscribe != nullptr)
@@ -260,29 +247,24 @@ void MQTTSNSubscribeHandler::handleAggregateUnsubscribe(Client* client,
int msgId = 0;
if (packet->isDuplicate())
{
msgId = _gateway->getAdapterManager()->getAggregater()->getMsgId(
client, packet->getMsgId());
msgId = _gateway->getAdapterManager()->getAggregater()->getMsgId(client, packet->getMsgId());
}
else
{
msgId =
_gateway->getAdapterManager()->getAggregater()->addMessageIdTable(
client, packet->getMsgId());
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);
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);
_gateway->getAdapterManager()->getAggregater()->removeAggregateTopic(&topic, client);
unsubscribe->setMsgId(msgId);
Event* ev = new Event();

View File

@@ -166,8 +166,7 @@ bool Topic::isMatch(string* topicName)
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);
}
/*=====================================
@@ -402,16 +401,16 @@ TopicIdMapElement::TopicIdMapElement(uint16_t msgId, uint16_t topicId, MQTTSN_to
_msgId = msgId;
_topicId = topicId;
_type = topic->type;
_wildcard = 0;
_wildcard = 0;
_next = nullptr;
_prev = nullptr;
if (_type == MQTTSN_TOPIC_TYPE_NORMAL)
{
if ( strchr(topic->data.long_.name, '#') != 0 || strchr(topic->data.long_.name, '+') != 0 )
{
_wildcard = 1;
}
if (strchr(topic->data.long_.name, '#') != 0 || strchr(topic->data.long_.name, '+') != 0)
{
_wildcard = 1;
}
}
}
@@ -427,14 +426,14 @@ MQTTSN_topicTypes TopicIdMapElement::getTopicType(void)
uint16_t TopicIdMapElement::getTopicId(void)
{
if (_wildcard > 0)
{
return 0;
}
else
{
return _topicId;
}
if (_wildcard > 0)
{
return 0;
}
else
{
return _topicId;
}
}
TopicIdMap::TopicIdMap()
@@ -473,8 +472,7 @@ TopicIdMapElement* TopicIdMap::getElement(uint16_t msgId)
TopicIdMapElement* TopicIdMap::add(uint16_t msgId, uint16_t topicId, MQTTSN_topicid* topic)
{
if (_cnt > _maxInflight * 2
|| (topicId == 0 && topic->type != MQTTSN_TOPIC_TYPE_SHORT))
if (_cnt > _maxInflight * 2 || (topicId == 0 && topic->type != MQTTSN_TOPIC_TYPE_SHORT))
{
return 0;
}

View File

@@ -101,7 +101,7 @@ public:
TopicIdMap();
~TopicIdMap();
TopicIdMapElement* getElement(uint16_t msgId);
TopicIdMapElement* add(uint16_t msgId, uint16_t topicId, MQTTSN_topicid* topic);
TopicIdMapElement* add(uint16_t msgId, uint16_t topicId, MQTTSN_topicid* topic);
void erase(uint16_t msgId);
void clear(void);
private:

View File

@@ -35,7 +35,7 @@ Gateway::Gateway(void)
theMultiTaskProcess = this;
theProcess = this;
_packetEventQue.setMaxSize(MAX_INFLIGHTMESSAGES * MAX_CLIENTS);
_clientList = new ClientList();
_clientList = new ClientList(this);
_adapterManager = new AdapterManager(this);
_topics = new Topics();
_stopFlg = false;
@@ -101,6 +101,11 @@ Gateway::~Gateway()
free(_params.qosMinusClientListName);
}
if (_params.bleAddress)
{
free(_params.bleAddress);
}
if (_adapterManager)
{
delete _adapterManager;
@@ -114,7 +119,6 @@ Gateway::~Gateway()
{
delete _topics;
}
// WRITELOG("Gateway is deleted normally.\r\n");
}
int Gateway::getParam(const char* parameter, char* value)
@@ -201,7 +205,7 @@ void Gateway::initialize(int argc, char** argv)
_params.mqttVersion = atoi(param);
}
_params.maxInflightMsgs = DEFAULT_MQTT_VERSION;
_params.maxInflightMsgs = MAX_INFLIGHTMESSAGES;
if (getParam("MaxInflightMsgs", param) == 0)
{
_params.maxInflightMsgs = atoi(param);
@@ -272,12 +276,25 @@ void Gateway::initialize(int argc, char** argv)
}
}
_params.maxClients = MAX_CLIENTS;
if (getParam("MaxNumberOfClients", param) == 0)
{
_params.maxClients = atoi(param);
}
if (getParam("BleAddress", param) == 0)
{
_params.bleAddress = strdup(param);
}
/* Initialize adapters */
_adapterManager->initialize(_params.gatewayName, _params.aggregatingGw,
_params.forwarder, _params.qosMinus1);
_adapterManager->initialize(_params.gatewayName, _params.aggregatingGw, _params.forwarder, _params.qosMinus1);
/* Setup ClientList and Predefined topics */
_clientList->initialize(_params.aggregatingGw);
/* SensorNetwork initialize */
_sensorNetwork.initialize();
}
void Gateway::run(void)
@@ -291,8 +308,7 @@ void Gateway::run(void)
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("\n%s %s has been started.\n\n", currentDateTime(), _params.gatewayName);
WRITELOG(" ConfigFile: %s\n", _params.configName);
if (_params.clientListName)
@@ -306,8 +322,8 @@ void Gateway::run(void)
}
WRITELOG(" SensorN/W: %s\n", _sensorNetwork.getDescription());
WRITELOG(" Broker: %s : %s, %s\n", _params.brokerName, _params.port,
_params.portSecure);
WRITELOG(" Broker: %s : %s, %s\n", _params.brokerName, _params.port, _params.portSecure);
WRITELOG(" Max number of Clients: %d\n", _params.maxClients);
WRITELOG(" RootCApath: %s\n", _params.rootCApath);
WRITELOG(" RootCAfile: %s\n", _params.rootCAfile);
WRITELOG(" CertKey: %s\n", _params.certKey);
@@ -390,8 +406,7 @@ 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

View File

@@ -167,6 +167,8 @@ public:
bool aggregatingGw { false };
bool qosMinus1 { false };
bool forwarder { false };
int maxClients {0};
char* bleAddress { nullptr };
};
/*=====================================
@@ -174,6 +176,7 @@ public:
=====================================*/
class AdapterManager;
class ClientList;
class ClientsPool;
class Gateway: public MultiTaskProcess
{
@@ -201,13 +204,13 @@ public:
private:
GatewayParams _params;
ClientList* _clientList { nullptr };
ClientList* _clientList;
EventQue _packetEventQue;
EventQue _brokerSendQue;
EventQue _clientSendQue;
LightIndicator _lightIndicator;
SensorNetwork _sensorNetwork;
AdapterManager* _adapterManager { nullptr };
AdapterManager* _adapterManager;
Topics* _topics;
bool _stopFlg;
};

View File

@@ -524,7 +524,7 @@ bool Thread::equals(pthread_t *t1, pthread_t *t2)
int Thread::start(void)
{
Runnable* runnable = this;
Runnable* runnable = this;
return pthread_create(&_threadID, 0, _run, runnable);
}

View File

@@ -95,7 +95,7 @@ private:
class RingBuffer
{
public:
RingBuffer(const char* keyDirctory = MQTTSNGW_KEY_DIRECTORY);
RingBuffer(const char* keyDirctory = MQTTSNGW_KEY_DIRECTORY);
~RingBuffer();
void put(char* buffer);
int get(char* buffer, int bufferLength);

View File

@@ -0,0 +1,425 @@
/**************************************************************************************
* Copyright (c) 2016, Tomoaki Yamaguchi
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Tomoaki Yamaguchi - initial API and implementation and/or initial documentation
**************************************************************************************/
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
#include <string.h>
#include <regex>
#include <string>
#include <stdlib.h>
#include "SensorNetwork.h"
#include "MQTTSNGWProcess.h"
using namespace std;
using namespace MQTTSNGW;
/*===========================================
* Class SensorNetAddreess
* These 4 methods are minimum requirements for the SensorNetAddress class.
* isMatch(SensorNetAddress* )
* operator =(SensorNetAddress& )
* setAddress(string* )
* sprint(char* )
* BlePort class requires these 3 methods.
* getIpAddress(void)
* getPortNo(void)
* setAddress(uint32_t BtAddr, uint16_t channel)
============================================*/
bdaddr_t NullAddr = { 0, 0, 0, 0, 0, 0 };
SensorNetAddress::SensorNetAddress()
{
_channel = 0;
bacpy(&_bdAddr, &NullAddr);
}
SensorNetAddress::~SensorNetAddress()
{
}
bdaddr_t* SensorNetAddress::getAddress(void)
{
return &_bdAddr;
}
uint16_t SensorNetAddress::getPortNo(void)
{
return _channel;
}
void SensorNetAddress::setAddress(bdaddr_t BdAddr, uint16_t channel)
{
bacpy(&_bdAddr, &BdAddr);
_channel = channel;
}
/**
* Set Address data to SensorNetAddress
*
* @param *dev_channel is "Device_Address.Channel" format string
* @return success = 0, Invalid format = -1
*
* Valid channels are 1 to 30.
*
* Client01,XX:XX:XX:XX:XX:XX.1
*
*/
int SensorNetAddress::setAddress(string* dev_channel)
{
int rc = -1;
size_t pos = dev_channel->find_first_of(".");
if (pos == string::npos)
{
_channel = 0;
memset(&_bdAddr, 0, sizeof(bdaddr_t));
return rc;
}
string dvAddr = dev_channel->substr(0, pos);
string strchannel = dev_channel->substr(pos + 1);
if (strchannel == "*")
{
_channel = 0;
}
else
{
_channel = atoi(strchannel.c_str());
}
str2ba(dvAddr.c_str(), &_bdAddr);
if ((_channel < 0 && _channel > 30) || bacmp(&_bdAddr, &NullAddr) == 0)
{
return rc;
}
return 0;
}
bool SensorNetAddress::isMatch(SensorNetAddress* addr)
{
return ((this->_channel == addr->_channel) && bacmp(&this->_bdAddr, &addr->_bdAddr) == 0);
}
SensorNetAddress& SensorNetAddress::operator =(SensorNetAddress& addr)
{
this->_channel = addr._channel;
this->_bdAddr = addr._bdAddr;
return *this;
}
char* SensorNetAddress::sprint(char* buf)
{
ba2str(const_cast<bdaddr_t*>(&_bdAddr), buf);
sprintf(buf + strlen(buf), ".%d", _channel);
return buf;
}
/*================================================================
Class SensorNetwork
getDescpription( ) is used by Gateway::initialize( )
initialize( ) is used by Gateway::initialize( )
getSenderAddress( ) is used by ClientRecvTask::run( )
broadcast( ) is used by MQTTSNPacket::broadcast( )
unicast( ) is used by MQTTSNPacket::unicast( )
read( ) is used by MQTTSNPacket::recv( )
================================================================*/
SensorNetwork::SensorNetwork()
{
}
SensorNetwork::~SensorNetwork()
{
}
int SensorNetwork::unicast(const uint8_t* payload, uint16_t payloadLength, SensorNetAddress* sendToAddr)
{
uint16_t ch = sendToAddr->getPortNo();
BlePort* blep = &_rfPorts[ch - 1];
int rc = 0;
errno = 0;
if ((rc = blep->send(payload, (uint32_t) payloadLength)) < 0)
{
D_NWSTACK("errno == %d in BlePort::sendto %d\n", errno, ch);
} D_NWSTACK("sendto %u length = %d\n", ch, rc);
return rc;
}
int SensorNetwork::broadcast(const uint8_t* payload, uint16_t payloadLength)
{
int rc = 0;
for (int i = 0; i < MAX_RFCOMM_CH; i++)
{
errno = 0;
if (_rfPorts[i].getSock() > 0)
{
if ((rc = _rfPorts[i].send(payload, (uint32_t) payloadLength)) < 0)
{
D_NWSTACK("errno == %d in BlePort::sendto %d\n", errno, i + 1);
}D_NWSTACK("sendto %u length = %d\n", i + 1, rc);
}
}
return rc;
}
int SensorNetwork::read(uint8_t* buf, uint16_t bufLen)
{
struct timeval timeout;
fd_set recvfds;
int maxSock = 0;
timeout.tv_sec = 1;
timeout.tv_usec = 0; // 1 sec
FD_ZERO(&recvfds);
for (int i = 0; i < MAX_RFCOMM_CH; i++)
{
if (_rfPorts[i]._rfCommSock > 0)
{
if (maxSock < _rfPorts[i]._rfCommSock)
{
maxSock = _rfPorts[i]._rfCommSock;
}
FD_SET(_rfPorts[i]._rfCommSock, &recvfds);
}
else if (_rfPorts[i]._listenSock > 0)
{
if (maxSock < _rfPorts[i]._listenSock)
{
maxSock = _rfPorts[i]._listenSock;
}
FD_SET(_rfPorts[i]._listenSock, &recvfds);
}
}
int rc = 0;
if (select(maxSock + 1, &recvfds, 0, 0, &timeout) > 0)
{
WRITELOG("RECV\n");
for (int i = 0; i < MAX_RFCOMM_CH; i++)
{
if (_rfPorts[i]._rfCommSock > 0)
{
if (FD_ISSET(_rfPorts[i]._rfCommSock, &recvfds))
{
rc = _rfPorts[i].recv(buf, bufLen);
if (rc == -1)
{
_rfPorts[i].close();
}
}
}
else if (_rfPorts[i]._listenSock > 0)
{
if (FD_ISSET(_rfPorts[i]._listenSock, &recvfds))
{
int sock = _rfPorts[i].accept(&_senderAddr);
if (sock > 0)
{
_rfPorts[i]._rfCommSock = sock;
}
WRITELOG("accept sock= %d CH = %d\n", sock, i + 1);
}
}
}
}
return rc;
}
/**
* Prepare UDP sockets and description of SensorNetwork like
* "UDP Multicast 225.1.1.1:1883 Gateway Port 10000".
* The description is for a start up prompt.
*/
void SensorNetwork::initialize(void)
{
char param[MQTTSNGW_PARAM_MAX];
string devAddr;
SensorNetAddress sa;
/*
* theProcess->getParam( ) copies
* a text specified by "Key" into param[] from the Gateway.conf
*
* in Gateway.conf e.g.
*
* # BLE
* BleAddress=XX:XX:XX:XX:XX:XX.0
*
*/
if (theProcess->getParam("BleAddress", param) == 0)
{
devAddr = param;
_description = "BLE RFCOMM ";
_description += param;
}
errno = 0;
if (sa.setAddress(&devAddr) == -1)
{
throw EXCEPTION("Invalid BLE Address", errno);
}
/* Prepare BLE sockets */
WRITELOG("Initialize ble\n");
int rc = MAX_RFCOMM_CH;
for (uint16_t i = 0; i < MAX_RFCOMM_CH; i++)
{
rc += _rfPorts[i].open(sa.getAddress(), i + 1);
}
if (rc == 0)
{
throw EXCEPTION("Can't open BLE RFComms", errno);
}
}
const char* SensorNetwork::getDescription(void)
{
return _description.c_str();
}
SensorNetAddress* SensorNetwork::getSenderAddress(void)
{
return &_senderAddr;
}
/*=========================================
Class BleStack
=========================================*/
BlePort::BlePort()
{
_disconReq = false;
_rfCommSock = 0;
_listenSock = 0;
_channel = 0;
}
BlePort::~BlePort()
{
close();
if (_listenSock > 0)
{
::close(_listenSock);
}
}
void BlePort::close(void)
{
if (_rfCommSock > 0)
{
::close(_rfCommSock);
_rfCommSock = 0;
}
}
int BlePort::open(bdaddr_t* devAddr, uint16_t channel)
{
const int reuse = 1;
if (channel < 1 || channel > 30)
{
D_NWSTACK("error Channel undefined in BlePort::open\n");
return 0;
}
/*------ Create unicast socket --------*/
_listenSock = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
if (_listenSock < 0)
{
D_NWSTACK("error can't create Rfcomm socket in BlePort::open\n");
return 0;
}
sockaddr_rc addru;
addru.rc_family = AF_BLUETOOTH;
addru.rc_channel = channel;
bacpy(&addru.rc_bdaddr, devAddr);
uint8_t buf[20];
ba2str(devAddr, (char*) buf);
setsockopt(_listenSock, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
errno = 0;
if (::bind(_listenSock, (sockaddr*) &addru, sizeof(addru)) < 0)
{
WRITELOG("\033[0m\033[0;31mCan't bind RFCOMM CH = %d %s\033[0m\033[0;37m\n", channel, strerror(errno));
::close(_listenSock);
return 0;
}
_channel = channel;
::listen(_listenSock, 1);
WRITELOG("Listen RFCOMM CH = %d\n", channel);
return 1;
}
int BlePort::send(const uint8_t* buf, uint32_t length)
{
WRITELOG("sock = %d\n", _rfCommSock);
return ::send(_rfCommSock, buf, length, 0);
}
int BlePort::recv(uint8_t* buf, uint16_t len)
{
int rc = 0;
errno = 0;
rc = ::read(_rfCommSock, buf, len);
if (rc < 0 && errno != EAGAIN)
{
D_NWSTACK("errno = %d in BlePort::recv\n", errno);
return -1;
}
return rc;
}
int BlePort::accept(SensorNetAddress* addr)
{
struct sockaddr_rc devAddr = { 0 };
socklen_t opt = sizeof(devAddr);
int sock = 0;
errno = 0;
sock = ::accept(_listenSock, (sockaddr *) &devAddr, &opt);
if (sock < 0 && errno != EAGAIN)
{
D_NWSTACK("errno == %d in BlePort::recv\n", errno);
return -1;
}
bdaddr_t bdAddr = devAddr.rc_bdaddr;
addr->setAddress(bdAddr, _channel);
return sock;
}
int BlePort::getSock(void)
{
return _rfCommSock;
}

View File

@@ -0,0 +1,104 @@
/**************************************************************************************
* Copyright (c) 2016, Tomoaki Yamaguchi
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Eclipse Distribution License v1.0 which accompany this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
* and the Eclipse Distribution License is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* Contributors:
* Tomoaki Yamaguchi - initial API and implementation and/or initial documentation
**************************************************************************************/
#ifndef SENSORNETWORK_H_
#define SENSORNETWORK_H_
#include "MQTTSNGWDefines.h"
#include <string>
#include <bluetooth/bluetooth.h>
using namespace std;
namespace MQTTSNGW
{
#ifdef DEBUG_NWSTACK
#define D_NWSTACK(...) printf(__VA_ARGS__)
#else
#define D_NWSTACK(...)
#endif
#define MAX_RFCOMM_CH 30
/*===========================================
Class SensorNetAddreess
============================================*/
class SensorNetAddress
{
public:
SensorNetAddress();
~SensorNetAddress();
void setAddress(bdaddr_t bdAddr, uint16_t channel);
int setAddress(string* data);
uint16_t getPortNo(void);
bdaddr_t* getAddress(void);
bool isMatch(SensorNetAddress* addr);
SensorNetAddress& operator =(SensorNetAddress& addr);
char* sprint(char* buf);
private:
uint16_t _channel;
bdaddr_t _bdAddr;
};
/*========================================
Class BlePort
=======================================*/
class BlePort
{
friend class SensorNetwork;
public:
BlePort();
virtual ~BlePort();
int open(bdaddr_t* devAddress, uint16_t channel);
void close(void);
int send(const uint8_t* buf, uint32_t length);
int recv(uint8_t* buf, uint16_t len);
int getSock(void);
int accept(SensorNetAddress* addr);
private:
int _rfCommSock;
int _listenSock;
uint16_t _channel;
bool _disconReq;
};
/*===========================================
Class SensorNetwork
============================================*/
class SensorNetwork
{
public:
SensorNetwork();
~SensorNetwork();
int unicast(const uint8_t* payload, uint16_t payloadLength, SensorNetAddress* sendto);
int broadcast(const uint8_t* payload, uint16_t payloadLength);
int read(uint8_t* buf, uint16_t bufLen);
void initialize(void);
const char* getDescription(void);
SensorNetAddress* getSenderAddress(void);
private:
// sockets for RFCOMM
BlePort _rfPorts[MAX_RFCOMM_CH];
SensorNetAddress _senderAddr;
string _description;
};
}
#endif /* SENSORNETWORK_H_ */

View File

@@ -142,7 +142,7 @@ char* SensorNetAddress::sprint(char* buf)
In Gateway version 1.0
getDescpription( ) is used by Gateway::initialize( )
initialize( ) is used by ClientSendTask::initialize( )
initialize( ) is used by Gateway::initialize( )
getSenderAddress( ) is used by ClientRecvTask::run( )
broadcast( ) is used by MQTTSNPacket::broadcast( )
unicast( ) is used by MQTTSNPacket::unicast( )