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

@@ -97,11 +97,13 @@
<option IS_BUILTIN_EMPTY="false" IS_VALUE_EMPTY="false" id="gnu.cpp.link.option.libs.1848275182" name="Libraries (-l)" superClass="gnu.cpp.link.option.libs" useByScannerDiscovery="false" valueType="libs">
<listOptionValue builtIn="false" srcPrefixMapping="" srcRootPath="" value="pthread"/>
<listOptionValue builtIn="false" value="pthread"/>
<listOptionValue builtIn="false" srcPrefixMapping="" srcRootPath="" value="ssl"/>
<listOptionValue builtIn="false" value="ssl"/>
<listOptionValue builtIn="false" srcPrefixMapping="" srcRootPath="" value="crypto"/>
<listOptionValue builtIn="false" value="crypto"/>
<listOptionValue builtIn="false" value="bluetooth"/>
</option>
@@ -133,7 +135,11 @@
<sourceEntries>
<entry excluding="MQTTSNGateway/GatewayTester|MQTTSNGateway/GatewayTester/samples/ClientPubQoS-1|MQTTSNGateway/GatewayTester/samples/ClientSub|MQTTSNGateway/GatewayTester/samples/ClientPub|MQTTSNGateway/src/linux/udp6|MQTTSNGateway/src/linux/loralink|MQTTSNClient|MQTTSNGateway/src/MQTTSNGWProxy.cpp|MQTTSNPacket/test|MQTTSNPacket/samples|MQTTSNGateway/src/mainLogmonitor.cpp|MQTTSNGateway/src/linux/xbee|MQTTSNGateway/GatewayTester/samples/mainTemplate.cpp|MQTTSNGateway/src/tests|MQTTSNGateway/src/tests/mainTestProcessFramework.cpp|ClientPubQoS-1|MQTTSNGateway/GatewayTester/samples/mainOTA.cpp" flags="VALUE_WORKSPACE_PATH" kind="sourcePath" name=""/>
<entry excluding="src/linux/ble|src/mainLogmonitor.cpp|src/linux/xbee|src/linux/udp6|src/linux/loralink|src/tests|GatewayTester|GatewayTester/samples|GatewayTester/src" flags="VALUE_WORKSPACE_PATH" kind="sourcePath" name="MQTTSNGateway"/>
<entry excluding="samples|src" flags="VALUE_WORKSPACE_PATH" kind="sourcePath" name="MQTTSNGateway/GatewayTester"/>
<entry excluding="samples|test" flags="VALUE_WORKSPACE_PATH" kind="sourcePath" name="MQTTSNPacket"/>
</sourceEntries>
@@ -273,9 +279,9 @@
<sourceEntries>
<entry excluding="MQTTSNGateway/GatewayTester|MQTTSNGateway/GatewayTester/samples/ClientPubQoS-1|MQTTSNGateway/GatewayTester/samples/ClientSub|MQTTSNGateway/GatewayTester/samples/ClientPub|MQTTSNGateway/src/tests/mainTestProcess.cpp|MQTTSNGateway/src/linux|MQTTSNPacket/src|MQTTSNClient|MQTTSNPacket/test|MQTTSNPacket/samples|MQTTSNGateway/GatewayTester/samples/mainOTA.cpp|MQTTSNGateway/src/mainLogmonitor.cpp|MQTTSNGateway/GatewayTester/samples/mainTemplate.cpp|ClientPubQoS-1" flags="VALUE_WORKSPACE_PATH" kind="sourcePath" name=""/>
<entry excluding="MQTTSNGateway|MQTTSNGateway/GatewayTester|MQTTSNGateway/src|MQTTSNGateway/GatewayTester/samples/ClientPubQoS-1|MQTTSNGateway/GatewayTester/samples/ClientSub|MQTTSNGateway/GatewayTester/samples/ClientPub|MQTTSNGateway/src/tests/mainTestProcess.cpp|MQTTSNGateway/src/linux|MQTTSNPacket/src|MQTTSNClient|MQTTSNPacket/test|MQTTSNPacket/samples|MQTTSNGateway/GatewayTester/samples/mainOTA.cpp|MQTTSNGateway/src/mainLogmonitor.cpp|MQTTSNGateway/GatewayTester/samples/mainTemplate.cpp|ClientPubQoS-1" flags="VALUE_WORKSPACE_PATH" kind="sourcePath" name=""/>
<entry excluding="udp6|xbee|loralink" flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="MQTTSNGateway/src/linux"/>
<entry excluding="linux/ble" flags="VALUE_WORKSPACE_PATH|RESOLVED" kind="sourcePath" name="MQTTSNGateway/src"/>
<entry flags="VALUE_WORKSPACE_PATH" kind="sourcePath" name="MQTTSNPacket/src"/>

View File

@@ -11,7 +11,7 @@
<provider-reference id="org.eclipse.cdt.managedbuilder.core.MBSLanguageSettingsProvider" ref="shared-provider"/>
<provider class="org.eclipse.cdt.managedbuilder.language.settings.providers.GCCBuiltinSpecsDetector" console="false" env-hash="-152861151764916298" id="org.eclipse.cdt.managedbuilder.core.GCCBuiltinSpecsDetector" keep-relative-paths="false" name="CDT GCC Built-in Compiler Settings" parameter="${COMMAND} ${FLAGS} -E -P -v -dD &quot;${INPUTS}&quot;" prefer-non-shared="true">
<provider class="org.eclipse.cdt.managedbuilder.language.settings.providers.GCCBuiltinSpecsDetector" console="false" env-hash="-152611677936340298" id="org.eclipse.cdt.managedbuilder.core.GCCBuiltinSpecsDetector" keep-relative-paths="false" name="CDT GCC Built-in Compiler Settings" parameter="${COMMAND} ${FLAGS} -E -P -v -dD &quot;${INPUTS}&quot;" prefer-non-shared="true">
<language-scope id="org.eclipse.cdt.core.gcc"/>
@@ -33,7 +33,7 @@
<provider-reference id="org.eclipse.cdt.managedbuilder.core.MBSLanguageSettingsProvider" ref="shared-provider"/>
<provider class="org.eclipse.cdt.managedbuilder.language.settings.providers.GCCBuiltinSpecsDetector" console="false" env-hash="-152861151764916298" id="org.eclipse.cdt.managedbuilder.core.GCCBuiltinSpecsDetector" keep-relative-paths="false" name="CDT GCC Built-in Compiler Settings" parameter="${COMMAND} ${FLAGS} -E -P -v -dD &quot;${INPUTS}&quot;" prefer-non-shared="true">
<provider class="org.eclipse.cdt.managedbuilder.language.settings.providers.GCCBuiltinSpecsDetector" console="false" env-hash="-152611677936340298" id="org.eclipse.cdt.managedbuilder.core.GCCBuiltinSpecsDetector" keep-relative-paths="false" name="CDT GCC Built-in Compiler Settings" parameter="${COMMAND} ${FLAGS} -E -P -v -dD &quot;${INPUTS}&quot;" prefer-non-shared="true">
<language-scope id="org.eclipse.cdt.core.gcc"/>

View File

@@ -20,6 +20,7 @@ CPPSRCS := \
$(SUBDIR)/LGwProxy.cpp \
$(SUBDIR)/LMqttsnClient.cpp \
$(SUBDIR)/LNetworkUdp.cpp \
$(SUBDIR)/LNetworkBle.cpp \
$(SUBDIR)/LPublishManager.cpp \
$(SUBDIR)/LRegisterManager.cpp \
$(SUBDIR)/LSubscribeManager.cpp \
@@ -41,7 +42,7 @@ DEFS :=
LIBS +=
LDFLAGS :=
CXXFLAGS := -Wall -O3 -std=c++11
LDADD :=
LDADD := -lbluetooth
OUTDIR := Build
PROG := $(OUTDIR)/$(PROGTEST)

View File

@@ -1,7 +1,7 @@
###Gateway Test Program.
# Gateway Test Program.
**sample/mainTest.cpp** is a Test sample coading.
Each test is described as one function. test1(), test2()...
````
```
/*------------------------------------------------------
* Test functions
*
@@ -36,9 +36,9 @@ void test2(void)
uint8_t qos = 1;
SUBSCRIBE(topic2, on_publish02, qos);
}
````
```
**TEST_LIST** is a test senario. Test functions are executed one by one.
````
```
/*------------------------------------------------------
* A List of Test Tasks
*------------------------------------------------------*/
@@ -52,10 +52,24 @@ TEST_LIST = {// e.g. TEST( Label, Test),
TEST("Disconnect", test5),
END_OF_TEST_LIST
};
````
### **step1. Build **
````
```
## step1. Define a sensor network
**UDP** or **Bluetooth** is available as a sensor network.
Uncomment a line \#define UDP or BLE in LMqttsnClientApp.h file.
```
/*======================================
* Program mode Flag
======================================*/
//#define CLIENT_MODE
#define UDP
//#define BLE
```
## step2. Build
```
$ git clone https://github.com/eclipse/paho.mqtt-sn.embedded-c
$ cd paho.mqtt-sn.embedded-c/MQTTSNGateway/GatewayTester
$ make
@@ -65,9 +79,9 @@ $ make clean
MQTT-SNGatewayTester program is copied into ../../../ directory.
### **step2. Execute Gateway Tester.**
## **step3. Execute Gateway Tester.**
````
```
$ cd ../../..
$ ./MQTT-SNGatewayTester
@@ -116,4 +130,4 @@ recved 192.168.11.17 :10000 08 13 20 00 01 00 01 00
Execute Publish topic1 Test ? ( Y/N ) :
````
```

View File

@@ -58,6 +58,14 @@ UDPCONF = {
20010, // Local PortNo
};
/*------------------------------------------------------
* BLE Configuration (theNetcon)
*------------------------------------------------------*/
BLECONF = { "GatewayTestClient", // ClientId
{ 0x60, 0x57, 0x18, 0x06, 0x8b, 0x72 }, // GW Address
1, // Rfcomm channel
};
/*------------------------------------------------------
* Client Configuration (theMqcon)
*------------------------------------------------------*/

View File

@@ -58,6 +58,14 @@ UDPCONF = {
20001, // Local PortNo
};
/*------------------------------------------------------
* BLE Configuration (theNetcon)
*------------------------------------------------------*/
BLECONF = { "GatewayTestClient", // ClientId
{ 0x60, 0x57, 0x18, 0x06, 0x8b, 0x72 }, // GW Address
1, // Rfcomm channel
};
/*------------------------------------------------------
* Client Configuration (theMqcon)
*------------------------------------------------------*/

View File

@@ -58,6 +58,14 @@ UDPCONF = {
20011, // Local PortNo
};
/*------------------------------------------------------
* BLE Configuration (theNetcon)
*------------------------------------------------------*/
BLECONF = { "GatewayTestClient", // ClientId
{ 0x44, 0x1C, 0xA8, 0x16, 0x94, 0x94 }, // GW Address
1, // Rfcomm channel
};
/*------------------------------------------------------
* Client Configuration (theMqcon)
*------------------------------------------------------*/

View File

@@ -51,18 +51,24 @@ extern LScreen* theScreen;
/*------------------------------------------------------
* UDP Configuration (theNetcon)
*------------------------------------------------------*/
UDPCONF =
{ "GatewayTestClient", // ClientId
UDPCONF = { "GatewayTestClient", // ClientId
{ 225, 1, 1, 1 }, // Multicast group IP
1883, // Multicast group Port
20020, // Local PortNo
};
/*------------------------------------------------------
* BLE Configuration (theNetcon)
*------------------------------------------------------*/
BLECONF = { "GatewayTestClient", // ClientId
{ 0x60, 0x57, 0x18, 0x06, 0x8b, 0x72 }, // GW Address
1, // Rfcomm channel
};
/*------------------------------------------------------
* Client Configuration (theMqcon)
*------------------------------------------------------*/
MQTTSNCONF =
{ 60, //KeepAlive [seconds]
MQTTSNCONF = { 60, //KeepAlive [seconds]
true, //Clean session
300, //Sleep duration [seconds]
"", //WillTopic

View File

@@ -66,7 +66,7 @@ LGwProxy::~LGwProxy()
_topicTbl.clearTopic();
}
void LGwProxy::initialize(LUdpConfig netconf, LMqttsnConfig mqconf)
void LGwProxy::initialize(SENSORNET_CONFIG_t netconf, LMqttsnConfig mqconf)
{
_network.initialize(netconf);
_clientId = netconf.clientId;
@@ -87,6 +87,12 @@ void LGwProxy::connect()
{
pos = _msg;
if (!_network.isBroadcastable() && _status == GW_LOST)
{
_status = GW_CONNECTING;
continue;
}
if (_status == GW_LOST)
{

View File

@@ -23,6 +23,7 @@
#include "LMqttsnClientApp.h"
#include "LNetworkUdp.h"
#include "LNetworkBle.h"
#include "LRegisterManager.h"
#include "LTimer.h"
#include "LTopicTable.h"
@@ -54,7 +55,7 @@ public:
LGwProxy();
~LGwProxy();
void initialize(LUdpConfig netconf, LMqttsnConfig mqconf);
void initialize(SENSORNET_CONFIG_t netconf, LMqttsnConfig mqconf);
void connect(void);
void disconnect(uint16_t sec = 0);
int getMessage(void);

View File

@@ -29,7 +29,7 @@ extern TaskList theTaskList[];
extern TestList theTestList[];
extern OnPublishList theOnPublishList[];
extern MQTTSNCONF;
extern UDPCONF;
extern SENSORNET_CONFIG_t theNetcon;
extern void setup(void);
/*=====================================
@@ -50,7 +50,14 @@ int main(int argc, char** argv)
#ifndef CLIENT_MODE
char c = 0;
printf("\n%s", PAHO_COPYRIGHT4);
printf("\n%s\n", PAHO_COPYRIGHT0);
printf("\n%s", PAHO_COPYRIGHT0);
#if defined(UDP)
printf(" UDP\n");
#elif defined(BLE)
printf(" BLE\n");
#else
printf("\n");
#endif
printf("%s\n", PAHO_COPYRIGHT1);
printf("%s\n", PAHO_COPYRIGHT2);
printf(" *\n%s\n", PAHO_COPYRIGHT3);
@@ -108,7 +115,7 @@ LMqttsnClient::~LMqttsnClient()
}
void LMqttsnClient::initialize(LUdpConfig netconf, LMqttsnConfig mqconf)
void LMqttsnClient::initialize(SENSORNET_CONFIG_t netconf, LMqttsnConfig mqconf)
{
_gwProxy.initialize(netconf, mqconf);
setSleepDuration(mqconf.sleepDuration);

View File

@@ -58,7 +58,7 @@ public:
void unsubscribe(const char* topicName);
void unsubscribe(const uint16_t topicId);
void disconnect(uint16_t sleepInSecs);
void initialize(LUdpConfig netconf, LMqttsnConfig mqconf);
void initialize(SENSORNET_CONFIG_t netconf, LMqttsnConfig mqconf);
void run(void);
void addTask(bool test);
void setSleepDuration(uint32_t duration);

View File

@@ -21,11 +21,12 @@
* Program mode Flag
======================================*/
//#define CLIENT_MODE
#define UDP
//#define BLE
/*======================================
* Debug Flag
======================================*/
//#define DEBUG_NW
#define DEBUG_NW
//#define DEBUG_MQTTSN
/****************************************
@@ -55,7 +56,8 @@ typedef signed int int32_t;
Application config structures
*****************************************/
struct LMqttsnConfig{
struct LMqttsnConfig
{
uint16_t keepAlive;
bool cleanSession;
uint32_t sleepDuration;
@@ -65,13 +67,21 @@ struct LMqttsnConfig{
bool willRetain;
};
struct LUdpConfig{
struct LUdpConfig
{
const char* clientId;
uint8_t ipAddress[4];
uint16_t gPortNo;
uint16_t uPortNo;
};
struct LBleConfig
{
const char* clientId;
uint8_t gwAddress[6];
uint8_t channel;
};
typedef enum
{
@@ -85,7 +95,19 @@ typedef enum
MACROs for Application
=======================================*/
#define MQTTSN_CONFIG MqttsnConfig theMqttsnConfig
#define MQTTSNCONF LMqttsnConfig theMqcon
#ifdef UDP
#define NETWORK_CONFIG UdpConfig theNetworkConfig
#define UDPCONF LUdpConfig theNetcon
#define BLECONF LBleConfig theConf
#define SENSORNET_CONFIG_t LUdpConfig
#else
#define NETWORK_CONFIG BleConfig theNetworkConfig
#define BLECONF LBleConfig theNetcon
#define UDPCONF LUdpConfig theConf
#define SENSORNET_CONFIG_t LBleConfig
#endif
#define CONNECT(...) theClient->getGwProxy()->connect(__VA_ARGS__)
#define PUBLISH(...) theClient->publish(__VA_ARGS__)
@@ -104,8 +126,7 @@ typedef enum
#define SUBSCRIBE_LIST OnPublishList theOnPublishList[]
#define SUB(...) {__VA_ARGS__}
#define END_OF_SUBSCRIBE_LIST {MQTTSN_TOPIC_TYPE_NORMAL,0,0,0, 0}
#define UDPCONF LUdpConfig theNetcon
#define MQTTSNCONF LMqttsnConfig theMqcon
#define SetForwarderMode(...) theClient->getGwProxy()->setForwarderMode(__VA_ARGS__)
#define SetQoSMinus1Mode(...) theClient->getGwProxy()->setQoSMinus1Mode(__VA_ARGS__)

View File

@@ -0,0 +1,295 @@
/**************************************************************************************
* Copyright (c) 2021, 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 "LMqttsnClientApp.h"
#ifdef BLE
#include <stdio.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <termios.h>
#include <bluetooth/bluetooth.h>
#include <bluetooth/rfcomm.h>
#include "LNetworkBle.h"
#include "LTimer.h"
#include "LScreen.h"
using namespace std;
using namespace linuxAsyncClient;
extern uint16_t getUint16(const uint8_t* pos);
extern uint32_t getUint32(const uint8_t* pos);
extern LScreen* theScreen;
extern bool theClientMode;
extern LBleConfig theNetcon;
/*=========================================
Class LNetwork
=========================================*/
LNetwork::LNetwork()
{
_sleepflg = false;
_returnCode = 0;
}
LNetwork::~LNetwork()
{
}
int LNetwork::broadcast(const uint8_t* xmitData, uint16_t dataLen)
{
return LBlePort::unicast(xmitData, dataLen);
}
int LNetwork::unicast(const uint8_t* xmitData, uint16_t dataLen)
{
return LBlePort::unicast(xmitData, dataLen);
}
uint8_t* LNetwork::getMessage(int* len)
{
*len = 0;
if (checkRecvBuf())
{
uint16_t recvLen = LBlePort::recv(_rxDataBuf, MQTTSN_MAX_PACKET_SIZE, false);
if (recvLen < 0)
{
*len = recvLen;
return 0;
}
else
{
if (_rxDataBuf[0] == 0x01)
{
*len = getUint16(_rxDataBuf + 1);
}
else
{
*len = _rxDataBuf[0];
}
//if(recvLen != *len){
// *len = 0;
// return 0;
//}else{
return _rxDataBuf;
//}
}
}
return 0;
}
void LNetwork::setGwAddress(void)
{
}
void LNetwork::setFixedGwAddress(void)
{
_channel = LBlePort::_channel;
memcpy(_gwAddress, theNetcon.gwAddress, 6);
}
bool LNetwork::initialize(LBleConfig config)
{
return LBlePort::open(config);
}
void LNetwork::setSleep()
{
_sleepflg = true;
}
bool LNetwork::isBroadcastable()
{
return false;
}
/*=========================================
Class BleStack
=========================================*/
LBlePort::LBlePort()
{
_disconReq = false;
_sockBle = 0;
_channel = 0;
}
LBlePort::~LBlePort()
{
close();
}
void LBlePort::close()
{
if (_sockBle > 0)
{
::close(_sockBle);
_sockBle = 0;
}
}
bool LBlePort::open(LBleConfig config)
{
const int reuse = 1;
uint8_t* gw = config.gwAddress + 5;
for (int i = 0; i < 6; i++)
{
*(_gwAddress + i) = *gw--;
}
_channel = config.channel;
if (_channel == 0 || _gwAddress == 0 || _devAddress == 0)
{
D_NWLOG("\033[0m\033[0;31merror BLE Address in BlePort::open\033[0m\033[0;37m\n");
DISPLAY("\033[0m\033[0;31m\nerror BLE Address in BlePort::open\033[0m\033[0;37m\n");
return false;
}
_sockBle = socket(AF_BLUETOOTH, SOCK_STREAM, BTPROTO_RFCOMM);
if (_sockBle < 0)
{
D_NWLOG("\033[0m\033[0;31merror Can't create socket in BlePort::open\033[0m\033[0;37m\n");
DISPLAY("\033[0m\033[0;31m\nerror Can't create socket in BlePort::open\033[0m\033[0;37m\n");
return false;
}
setsockopt(_sockBle, SOL_SOCKET, SO_REUSEADDR, &reuse, sizeof(reuse));
struct sockaddr_rc addru = { 0 };
addru.rc_family = AF_BLUETOOTH;
addru.rc_channel = _channel;
memcpy(&addru.rc_bdaddr, _gwAddress, 6);
char bufgw[30];
ba2str(&addru.rc_bdaddr, bufgw);
DISPLAY("GW MAC = %s RFCOMM CH = %d\n", bufgw, addru.rc_channel);
// connect to server
errno = 0;
int status = connect(_sockBle, (struct sockaddr *) &addru, sizeof(addru));
if (status < 0)
{
D_NWLOG("\033[0m\033[0;31merror = %d Can't connect to GW in BlePort::open\033[0m\033[0;37m\n", errno);
DISPLAY("\033[0m\033[0;31mCan't connect to GW Ble socket in BlePort::open\033[0m\033[0;37m\n");
close();
return false;
}
return true;
}
int LBlePort::unicast(const uint8_t* buf, uint32_t length)
{
int status = ::write(_sockBle, buf, length);
if (status < 0)
{
D_NWLOG("errno == %d in LBlePort::unicast\n", errno);
DISPLAY("errno == %d in LBlePort::unicast\n", errno);
}
else
{
D_NWLOG("sendto %-2d", _channel);
for (uint16_t i = 0; i < length; i++)
{
D_NWLOG(" %02x", *(buf + i));
}
D_NWLOG("\n");
if (!theClientMode)
{
char sbuf[SCREEN_BUFF_SIZE];
int pos = 0;
sprintf(sbuf, "\033[0;34msendto %-2dch", _channel);
pos = strlen(sbuf);
for (uint16_t i = 0; i < length; i++)
{
sprintf(sbuf + pos, " %02x", *(buf + i));
if (strlen(sbuf) > SCREEN_BUFF_SIZE - 20) // -20 for Escape sequence
{
break;
}
pos += 3;
}
sprintf(sbuf + strlen(sbuf), "\033[0;37m\n");
theScreen->display(sbuf);
}
}
return status;
}
bool LBlePort::checkRecvBuf()
{
uint8_t buf[2];
if (::recv(_sockBle, buf, 1, MSG_DONTWAIT | MSG_PEEK) > 0)
{
return true;
}
return false;
}
int LBlePort::recv(uint8_t* buf, uint16_t length, bool flg)
{
int flags = flg ? MSG_DONTWAIT : 0;
int status = ::recv(_sockBle, buf, length, flags);
if (status < 0 && errno != EAGAIN)
{
D_NWLOG("\033[0m\033[0;31merrno == %d in BlePort::recv \033[0m\033[0;37m\n", errno);
DISPLAY("\033[0m\033[0;31merrno == %d in BlePort::recv \033[0m\033[0;37m\n", errno);
}
else if (status > 0)
{
D_NWLOG("\nrecved ");
for (uint16_t i = 0; i < status; i++)
{
D_NWLOG(" %02x", *(buf + i));
}
D_NWLOG("\n");
if (!theClientMode)
{
char sbuf[SCREEN_BUFF_SIZE];
int pos = 0;
sprintf(sbuf, "\033[0;34mrecved ");
pos = strlen(sbuf);
for (uint16_t i = 0; i < status; i++)
{
sprintf(sbuf + pos, " %02x", *(buf + i));
if (strlen(sbuf) > SCREEN_BUFF_SIZE - 20)
{
break;
}
pos += 3;
}
sprintf(sbuf + strlen(sbuf), "\033[0;37m\n");
theScreen->display(sbuf);
}
return status;
}
else
{
return 0;
}
return status;
}
#endif

View File

@@ -0,0 +1,106 @@
/**************************************************************************************
* Copyright (c) 2021, 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 NETWORKBLE_H_
#define NETWORKBLE_H_
#include "LMqttsnClientApp.h"
#ifdef BLE
#include <sys/time.h>
#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <string>
#include <bluetooth/bluetooth.h>
#define SOCKET_MAXHOSTNAME 200
#define SOCKET_MAXCONNECTIONS 5
#define SOCKET_MAXRECV 500
#define SOCKET_MAXBUFFER_LENGTH 500 // buffer size
#define STAT_UNICAST 1
#define STAT_MULTICAST 2
using namespace std;
namespace linuxAsyncClient
{
/*========================================
Class LBlePort
=======================================*/
class LBlePort
{
friend class LNetwork;
public:
LBlePort();
virtual ~LBlePort();
bool open(LBleConfig config);
int unicast(const uint8_t* buf, uint32_t length);
int recv(uint8_t* buf, uint16_t len, bool nonblock);
bool checkRecvBuf();
bool isUnicast();
private:
void close();
int _sockBle;
uint8_t _devAddress[6];
uint8_t _gwAddress[6];
uint8_t _channel;
bool _disconReq;
};
#define NO_ERROR 0
#define PACKET_EXCEEDS_LENGTH 1
/*===========================================
Class Network
============================================*/
class LNetwork: public LBlePort
{
public:
LNetwork();
~LNetwork();
int broadcast(const uint8_t* payload, uint16_t payloadLen);
int unicast(const uint8_t* payload, uint16_t payloadLen);
void setGwAddress(void);
void resetGwAddress(void);
void setFixedGwAddress(void);
bool initialize(LBleConfig config);
uint8_t* getMessage(int* len);
bool isBroadcastable();
private:
void setSleep();
int readApiFrame(void);
int _returnCode;
bool _sleepflg;
uint8_t _rxDataBuf[MQTTSN_MAX_PACKET_SIZE + 1]; // defined in MqttsnClientApp.h
};
} /* end of namespace */
#endif /* BLE */
#endif /* NETWORKBLE_H_ */

View File

@@ -13,6 +13,8 @@
* Contributors:
* Tomoaki Yamaguchi - initial API and implementation and/or initial documentation
**************************************************************************************/
#include "LMqttsnClientApp.h"
#ifdef UDP
#include <stdio.h>
#include <sys/time.h>
@@ -29,7 +31,6 @@
#include "LTimer.h"
#include "LScreen.h"
#include "LMqttsnClientApp.h"
using namespace std;
using namespace linuxAsyncClient;
@@ -111,6 +112,10 @@ void LNetwork::setSleep(){
_sleepflg = true;
}
bool LNetwork::isBroadcastable()
{
return true;
}
/*=========================================
Class udpStack
=========================================*/
@@ -385,5 +390,5 @@ int LUdpPort::recvfrom (uint8_t* buf, uint16_t length, int flags, uint32_t* ipAd
return status;
}
#endif

View File

@@ -17,6 +17,9 @@
#ifndef NETWORKUDP_H_
#define NETWORKUDP_H_
#include "LMqttsnClientApp.h"
#ifdef UDP
#include <sys/time.h>
#include <iostream>
#include <sys/types.h>
@@ -27,7 +30,6 @@
#include <string>
#include <arpa/inet.h>
#include "LMqttsnClientApp.h"
#define SOCKET_MAXHOSTNAME 200
#define SOCKET_MAXCONNECTIONS 5
@@ -89,6 +91,7 @@ public:
void setFixedGwAddress(void);
bool initialize(LUdpConfig config);
uint8_t* getMessage(int* len);
bool isBroadcastable();
private:
void setSleep();
int readApiFrame(void);
@@ -103,6 +106,6 @@ private:
};
} /* end of namespace */
#endif /* UDP */
#endif /* NETWORKUDP_H_ */

View File

@@ -7,7 +7,7 @@ This Gateway can run as a transparent or aggregating Gateway by specifying the g
````
$ git clone -b develop https://github.com/eclipse/paho.mqtt-sn.embedded-c
$ cd paho.mqtt-sn.embedded-c/MQTTSNGateway
$ ./build.sh {udp|udp6|xbee|loralink}
$ ./build.sh [udp|udp6|xbee|loralink | ble]
````
In order to build a gateway, an argument is required.
@@ -50,6 +50,7 @@ ClientAuthentication=NO
AggregatingGateway=NO
QoS-1=NO
Forwarder=NO
MaxNumberOfClients=30;
#ClientsList=/path/to/your_clients.conf
@@ -91,6 +92,9 @@ BaudrateLoRaLink=115200
DeviceRxLoRaLink=/dev/ttyLoRaLinkRx
DeviceTxLoRaLink=/dev/ttyLoRaLinkTx
# BLE RFCOMM
BleAddress=60:57:18:06:8B:72.*
# LOG
ShearedMemory=NO;
@@ -106,6 +110,7 @@ Format of the file is ClientId and SensorNetwork Address. e.g. IP address and Po
When **QoS-1** is **YES**, QoS-1 PUBLISH is available. All clients which send QoS-1 PUBLISH must be specified by Client.conf file.
When **PredefinedTopic** is **YES**, **Pre-definedTopicId**s specified by **PredefinedTopicList** are effective. This file defines Pre-definedTopics of the clients. In this file, ClientID,TopicName and TopicID are declared in CSV format.
When **Forwarder** is **YES**, Forwarder Encapsulation Message is available. Connectable Forwarders must be declared by a **ClientsList** file.
**MaxNumberOfClients** Maximum number of clients allocated.
### ** How to monitor the gateway from remote. **
Change gateway.conf as follows:

View File

@@ -27,6 +27,7 @@ ClientAuthentication=NO
AggregatingGateway=NO
QoS-1=NO
Forwarder=NO
MaxNumberOfClients=30;
#ClientsList=/path/to/your_clients.conf
@@ -68,6 +69,9 @@ BaudrateLoRaLink=115200
DeviceRxLoRaLink=/dev/loralinkRx
DeviceTxLoRaLink=/dev/loralinkTx
# BLE RFCOMM
BleAddress=60:57:18:06:8B:72.*
# LOG
ShearedMemory=NO;

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

@@ -66,8 +66,7 @@ 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",
WRITELOG("%s MQTTGWPublishHandler::handlePublish can't allocate memories for Packet.%s\n",
ERRMSG_HEADER, ERRMSG_FOOTER);
delete msg;
return;
@@ -111,8 +110,7 @@ void MQTTGWPublishHandler::handlePublish(Client* client, MQTTGWPacket* packet)
if (topic == nullptr && client->isCleanSession())
{
WRITELOG(
"%sMQTTGWPublishHandler Invalid Topic. PUBLISH message is discarded.%s\n",
WRITELOG("%sMQTTGWPublishHandler Invalid Topic. PUBLISH message is discarded.%s\n",
ERRMSG_HEADER, ERRMSG_FOOTER);
if (pub.header.bits.qos == 1)
{
@@ -165,18 +163,14 @@ 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",
WRITELOG("%sMQTTGWPublishHandler Can't create a Topic. PUBLISH message is discarded.%s\n",
ERRMSG_HEADER, ERRMSG_FOOTER);
delete snPacket;
return;
@@ -184,10 +178,8 @@ void MQTTGWPublishHandler::handlePublish(Client* client, MQTTGWPacket* packet)
}
}
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,8 +303,7 @@ void MQTTGWPublishHandler::handleAggregatePublish(Client* client,
if (msg->getType() == 0)
{
WRITELOG(
"%s MQTTGWPublishHandler::handleAggregatePublish can't allocate memories for Packet.%s\n",
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,8 +63,7 @@ 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);
@@ -173,8 +172,7 @@ void Adapter::send(MQTTSNPacket* packet, Client* client)
}
else
{
WRITELOG(
"%s %s No Secure connections %s 's packet is discarded.%s\n",
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

@@ -135,45 +135,35 @@ void BrokerRecvTask::run(void)
{
if (rc == 0) // Disconnected
{
WRITELOG(
"%s BrokerRecvTask %s is disconnected by the broker.%s\n",
ERRMSG_HEADER,
client->getClientId(),
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(),
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(),
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();
@@ -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();
@@ -177,9 +167,8 @@ void BrokerSendTask::log(Client* client, MQTTGWPacket* packet)
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,9 +176,8 @@ 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(),

View File

@@ -31,9 +31,7 @@ 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)
@@ -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)

View File

@@ -81,19 +81,15 @@ void ClientList::setClientList(int 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)
@@ -410,13 +400,11 @@ 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;
}
@@ -518,8 +506,7 @@ void ClientsPool::allocate(int maxClients)
{
if ((cl = new Client()) == nullptr)
{
throw Exception(
"ClientsPool::Can't allocate max number of clients\n", 0);
throw Exception("ClientsPool::Can't allocate max number of clients\n", 0);
}
cl->_nextClient = _firstClient;
_firstClient = cl;

View File

@@ -37,15 +37,10 @@ ClientRecvTask::ClientRecvTask(Gateway* gateway)
ClientRecvTask::~ClientRecvTask()
{
}
/**
* Initialize SensorNetwork
*/
void ClientRecvTask::initialize(int argc, char** argv)
{
_sensorNetwork->initialize();
}
/*
@@ -58,8 +53,7 @@ void ClientRecvTask::run()
Event* ev = nullptr;
AdapterManager* adpMgr = _gateway->getAdapterManager();
QoSm1Proxy* qosm1Proxy = adpMgr->getQoSm1Proxy();
int clientType =
adpMgr->isAggregaterActive() ? AGGREGATER_TYPE : TRANSPEARENT_TYPE;
int clientType = adpMgr->isAggregaterActive() ? AGGREGATER_TYPE : TRANSPEARENT_TYPE;
ClientList* clientList = _gateway->getClientList();
EventQue* packetEventQue = _gateway->getPacketEventQue();
EventQue* clientsendQue = _gateway->getClientSendQue();
@@ -88,8 +82,7 @@ void ClientRecvTask::run()
continue;
}
if (packet->getType() <= MQTTSN_ADVERTISE
|| packet->getType() == MQTTSN_GWINFO)
if (packet->getType() <= MQTTSN_ADVERTISE || packet->getType() == MQTTSN_GWINFO)
{
delete packet;
continue;
@@ -105,14 +98,11 @@ void ClientRecvTask::run()
continue;
}
SensorNetAddress* senderAddr =
_gateway->getSensorNetwork()->getSenderAddress();
SensorNetAddress* senderAddr = _gateway->getSensorNetwork()->getSenderAddress();
if (packet->getType() == MQTTSN_ENCAPSULATED)
{
fwd =
_gateway->getAdapterManager()->getForwarderList()->getForwarder(
senderAddr);
fwd = _gateway->getAdapterManager()->getForwarderList()->getForwarder(senderAddr);
if (fwd != nullptr)
{
@@ -122,8 +112,7 @@ void ClientRecvTask::run()
/* get the packet from the encapsulation message */
MQTTSNGWEncapsulatedPacket encap;
encap.desirialize(packet->getPacketData(),
packet->getPacketLength());
encap.desirialize(packet->getPacketData(), packet->getPacketLength());
nodeId.setId(encap.getWirelessNodeId());
client = fwd->getClient(&nodeId);
packet = encap.getMQTTSNPacket();
@@ -144,10 +133,8 @@ void ClientRecvTask::run()
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);
WRITELOG("%s %s %s can send only PUBLISH with QoS-1.%s\n",
ERRMSG_HEADER, clientName, senderAddr->sprint(buf), ERRMSG_FOOTER);
delete packet;
continue;
}
@@ -209,8 +196,7 @@ void ClientRecvTask::run()
if (client == nullptr)
{
/* create a new client */
client = clientList->createClient(0, &data.clientID,
clientType);
client = clientList->createClient(0, &data.clientID, clientType);
}
/* Add to a forwarded client list of forwarder. */
fwd->addClient(client, &nodeId);
@@ -220,8 +206,7 @@ void ClientRecvTask::run()
if (client)
{
/* Authentication is not required */
if (_gateway->getGWParams()->clientAuthentication
== false)
if (_gateway->getGWParams()->clientAuthentication == false)
{
client->setClientAddress(senderAddr);
}
@@ -229,8 +214,7 @@ void ClientRecvTask::run()
else
{
/* create a new client */
client = clientList->createClient(senderAddr,
&data.clientID, clientType);
client = clientList->createClient(senderAddr, &data.clientID, clientType);
}
}
@@ -238,8 +222,7 @@ void ClientRecvTask::run()
if (client == nullptr)
{
WRITELOG(
"%s Client(%s) was rejected. CONNECT message has been discarded.%s\n",
WRITELOG("%s Client(%s) was rejected. CONNECT message has been discarded.%s\n",
ERRMSG_HEADER, senderAddr->sprint(buf),
ERRMSG_FOOTER);
delete packet;
@@ -258,14 +241,12 @@ void ClientRecvTask::run()
{
WRITELOG(
"%s MQTTSNGWClientRecvTask Forwarder(%s) is not declared by ClientList file. message has been discarded.%s\n",
ERRMSG_HEADER,
_sensorNetwork->getSenderAddress()->sprint(buf),
ERRMSG_HEADER, _sensorNetwork->getSenderAddress()->sprint(buf),
ERRMSG_FOOTER);
}
else
{
WRITELOG(
"%s MQTTSNGWClientRecvTask Client(%s) is not connecting. message has been discarded.%s\n",
WRITELOG("%s MQTTSNGWClientRecvTask Client(%s) is not connecting. message has been discarded.%s\n",
ERRMSG_HEADER, senderAddr->sprint(buf),
ERRMSG_FOOTER);
}
@@ -327,15 +308,13 @@ void ClientRecvTask::log(const char* clientId, MQTTSNPacket* packet)
case MQTTSN_WILLMSGUPD:
case MQTTSN_WILLTOPIC:
case MQTTSN_WILLMSG:
WRITELOG(FORMAT_Y_G_G, currentDateTime(), packet->getName(), LEFTARROW,
clientId, packet->print(pbuf));
WRITELOG(FORMAT_Y_G_G, currentDateTime(), packet->getName(), LEFTARROW, clientId, packet->print(pbuf));
break;
case MQTTSN_PUBLISH:
case MQTTSN_REGISTER:
case MQTTSN_SUBSCRIBE:
case MQTTSN_UNSUBSCRIBE:
WRITELOG(FORMAT_G_MSGID_G_G_NL, currentDateTime(), packet->getName(),
packet->getMsgId(msgId), LEFTARROW, clientId,
WRITELOG(FORMAT_G_MSGID_G_G_NL, currentDateTime(), packet->getName(), packet->getMsgId(msgId), LEFTARROW, clientId,
packet->print(pbuf));
break;
case MQTTSN_REGACK:
@@ -343,17 +322,14 @@ void ClientRecvTask::log(const char* clientId, MQTTSNPacket* packet)
case MQTTSN_PUBREC:
case MQTTSN_PUBREL:
case MQTTSN_PUBCOMP:
WRITELOG(FORMAT_G_MSGID_G_G, currentDateTime(), packet->getName(),
packet->getMsgId(msgId), LEFTARROW, clientId,
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));
WRITELOG(FORMAT_Y_G_G, currentDateTime(), packet->getName(), LEFTARROW, clientId, packet->print(pbuf));
break;
default:
WRITELOG(FORMAT_W_NL, currentDateTime(), packet->getName(), LEFTARROW,
clientId, packet->print(pbuf));
WRITELOG(FORMAT_W_NL, currentDateTime(), packet->getName(), LEFTARROW, clientId, packet->print(pbuf));
break;
}
}

View File

@@ -63,8 +63,7 @@ void ClientSendTask::run()
if (packet->broadcast(_sensorNetwork) < 0)
{
WRITELOG(
"%s ClientSendTask can't multicast a packet Error=%d%s\n",
WRITELOG("%s ClientSendTask can't multicast a packet Error=%d%s\n",
ERRMSG_HEADER, errno, ERRMSG_FOOTER);
}
}
@@ -85,11 +84,8 @@ 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),
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);
}
}
@@ -101,8 +97,7 @@ 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())
{
@@ -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)
@@ -344,12 +344,12 @@ Exception::Exception(const char* message, const int errNo)
_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;
_errNo = errNo;
_fileName = getFileName(file);;
_fileName = getFileName(file);
;
_functionName = function;
_line = line;
}
@@ -394,27 +394,28 @@ void Exception::writeMessage()
}
else
{
WRITELOG("%s%s %s.\n errno=%d : %s%s\n", currentDateTime(), RED_HDR,_message, _errNo, strerror(_errNo), CLR_HDR);
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);
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);
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-- )
for (int len = strlen(file); len > 0; len--)
{
if (*(file + len) == '/')
{

View File

@@ -35,8 +35,7 @@ MQTTSNPublishHandler::~MQTTSNPublishHandler()
}
MQTTGWPacket* MQTTSNPublishHandler::handlePublish(Client* client,
MQTTSNPacket* packet)
MQTTGWPacket* MQTTSNPublishHandler::handlePublish(Client* client, MQTTSNPacket* packet)
{
uint8_t dup;
int qos;
@@ -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;
}
@@ -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);
@@ -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,8 +236,7 @@ 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)
{
@@ -256,8 +246,7 @@ void MQTTSNPublishHandler::handleRegAck(Client* client, MQTTSNPacket* packet)
_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;
@@ -67,8 +66,7 @@ MQTTGWPacket* MQTTSNSubscribeHandler::handleSubscribe(Client* client,
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",
@@ -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)
@@ -103,8 +100,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 //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,20 +212,16 @@ 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",
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,20 +247,16 @@ 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",
WRITELOG("%s MQTTSNUnsubscribeHandler can't create MessageIdTableElement %s%s\n",
ERRMSG_HEADER, client->getClientId(), ERRMSG_FOOTER);
return;
}
@@ -281,8 +264,7 @@ void MQTTSNSubscribeHandler::handleAggregateUnsubscribe(Client* client,
UTF8String str = unsubscribe->getTopic();
string* topicName = new string(str.data, str.len); // topicName is delete by topic
Topic topic = Topic(topicName, MQTTSN_TOPIC_TYPE_NORMAL);
_gateway->getAdapterManager()->getAggregater()->removeAggregateTopic(
&topic, client);
_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);
}
/*=====================================
@@ -408,7 +407,7 @@ TopicIdMapElement::TopicIdMapElement(uint16_t msgId, uint16_t topicId, MQTTSN_to
if (_type == MQTTSN_TOPIC_TYPE_NORMAL)
{
if ( strchr(topic->data.long_.name, '#') != 0 || strchr(topic->data.long_.name, '+') != 0 )
if (strchr(topic->data.long_.name, '#') != 0 || strchr(topic->data.long_.name, '+') != 0)
{
_wildcard = 1;
}
@@ -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

@@ -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

@@ -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( )

View File

@@ -9,6 +9,8 @@ echo "travis build dir $TRAVIS_BUILD_DIR pwd $PWD"
cmake .. -DSENSORNET=loralink
make
ctest -VV --timeout 600
cmake .. -DSENSORNET=ble
make MQTT-SNGateway
cmake .. -DSENSORNET=xbee
make MQTT-SNGateway
cmake .. -DSENSORNET=udp6