├── Client ├── Client program structure.pdf ├── Makefile ├── README.md └── src │ ├── LinuxClientSample.cpp │ ├── SoilMoistureClientSample.ino │ ├── lib │ ├── MQTTSN_Application.h │ ├── Network.h │ ├── mqUtil.cpp │ ├── mqUtil.h │ ├── mqttsn.cpp │ ├── mqttsn.h │ ├── mqttsnClient.cpp │ ├── mqttsnClient.h │ ├── mqttsnClientAppFw4Arduino.cpp │ ├── mqttsnClientAppFw4Arduino.h │ ├── mqttsnClientAppFw4Linux.cpp │ ├── mqttsnClientAppFw4Linux.h │ ├── mqttsnClientAppFw4mbed.cpp │ ├── mqttsnClientAppFw4mbed.h │ ├── udpStack.cpp │ ├── udpStack.h │ ├── zbeeStack.cpp │ └── zbeeStack.h │ └── mbedClientSample.cpp ├── Gateway ├── Makefile ├── README.md └── src │ ├── BrokerRecvTask.cpp │ ├── BrokerRecvTask.h │ ├── BrokerSendTask.cpp │ ├── BrokerSendTask.h │ ├── ClientRecvTask.cpp │ ├── ClientRecvTask.h │ ├── ClientSendTask.cpp │ ├── ClientSendTask.h │ ├── ErrorMessage.h │ ├── GatewayControlTask.cpp │ ├── GatewayControlTask.h │ ├── GatewayDefines.h │ ├── GatewayResourcesProvider.cpp │ ├── GatewayResourcesProvider.h │ ├── TomyGateway.cpp │ └── lib │ ├── Defines.h │ ├── Messages.cpp │ ├── Messages.h │ ├── ProcessFramework.cpp │ ├── ProcessFramework.h │ ├── TCPStack.cpp │ ├── TCPStack.h │ ├── TLSStack.cpp │ ├── TLSStack.h │ ├── Topics.cpp │ ├── Topics.h │ ├── UDPStack.cpp │ ├── UDPStack.h │ ├── XXXXXStack.cpp │ ├── XXXXXStack.h │ ├── ZBStack.cpp │ └── ZBStack.h ├── LogMonitor ├── Makefile └── src │ ├── LogMonitor.cpp │ ├── LogMonitor.h │ ├── LogMonitorApp.cpp │ └── lib │ ├── Defines.h │ ├── ProcessFramework.cpp │ └── ProcessFramework.h └── README.md /Client/Client program structure.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ty4tw/MQTT-SN/6f471e2252211ee8217a02723f5137285f69a3b1/Client/Client program structure.pdf -------------------------------------------------------------------------------- /Client/Makefile: -------------------------------------------------------------------------------- 1 | PROGNAME := TomyClient 2 | SRCDIR := src 3 | SUBDIR := src/lib 4 | 5 | SRCS := $(SRCDIR)/LinuxClientSample.cpp \ 6 | $(SUBDIR)/mqttsnClientAppFw4Linux.cpp \ 7 | $(SUBDIR)/mqttsn.cpp \ 8 | $(SUBDIR)/mqttsnClient.cpp \ 9 | $(SUBDIR)/zbeeStack.cpp \ 10 | $(SUBDIR)/udpStack.cpp \ 11 | $(SUBDIR)/mqUtil.cpp 12 | 13 | CXX := g++ 14 | CPPFLAGS += 15 | DEFS := 16 | LDFLAGS += 17 | LIBS += 18 | 19 | CXXFLAGS := -Wall -O3 20 | 21 | OUTDIR := Build 22 | 23 | PROG := $(OUTDIR)/$(PROGNAME) 24 | OBJS := $(SRCS:%.cpp=$(OUTDIR)/%.o) 25 | DEPS := $(SRCS:%.cpp=$(OUTDIR)/%.d) 26 | 27 | .PHONY: install clean distclean 28 | 29 | all: $(PROG) 30 | 31 | -include $(DEPS) 32 | 33 | $(PROG): $(OBJS) 34 | $(CXX) $(LDFLAGS) -o $@ $^ $(LIBS) 35 | 36 | $(OUTDIR)/%.o:%.cpp 37 | @if [ ! -e `dirname $@` ]; then mkdir -p `dirname $@`; fi 38 | $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(DEFS) -o $@ -c -MMD -MP -MF $(@:%.o=%.d) $< 39 | 40 | clean: 41 | rm -rf $(OUTDIR) 42 | 43 | distclean: 44 | rm -rf Build 45 | 46 | install: 47 | cp -p $(PROG) ../../ 48 | 49 | -------------------------------------------------------------------------------- /Client/README.md: -------------------------------------------------------------------------------- 1 | MQTT-SN Client 2 | ====== 3 | MQTT-SN Client over XBee (running on linux, Arduino and mbed) 4 | MQTT-SN Client over UDP (running on linux and Arduino) 5 | 6 | 7 | Supported functions 8 | ------------------- 9 | 10 | QOS Level 0 and 1 11 | * SEARCHGW, GWINFO 12 | * CONNECT, WILLTOPICREQ, WILLTOPIC, WILLMSGREQ, WILLMSG 13 | * PINGREQ, PINGRESP 14 | * CONNACK, REGISTER, REGACK, SUBACK, PUBACK, UNSUBACK 15 | * SUBSCRIBE, PUBLISH, UNSUBSCRIBE, DISCONNECT 16 | 17 | Implemented control flows: 18 | Application program executes publish() function, 19 | Message flow as berrow is conducted automaticaly. 20 | 21 | 22 | Client Gateway Broker 23 | | | | 24 | PUBLISH() -->| --- SERCHGW ----> | | 25 | | <-- GWINFO ----- | | 26 | | --- CONNECT ----> | | 27 | | <--WILLTOPICREQ-- | | 28 | | --- WILLTOPIC --> | | 29 | | <-- WILLMSGREQ -- | | 30 | | --- WILLMSG ----> | ---- CONNECT ----> |(accepted) 31 | | <-- CONNACK ----- | <--- CONNACK ----- | 32 | | --- PUBLISH ----> | | 33 | | <-- PUBACK ----- | (invalid TopicId) | 34 | | --- REGISTER ---> | | 35 | | <-- REGACK ----- | | 36 | | --- PUBLISH ----> | ---- PUBLISH ----> |(accepted) 37 | | <-- PUBACK ----- | <---- PUBACK ----- | 38 | | | | 39 | // // // 40 | | | | 41 | SUBSCRIBE() -->| --- SUBSCRIBE --> | ---- SUBSCRIBE --> | 42 | [set Callback] | <-- SUBACK ------ | <--- SUBACK ------ | 43 | | | | 44 | // // // 45 | | | | 46 | | <-- REGISTER ---- | <--- PUBLISH ----- |<-- PUBLISH 47 | [exec Callback] | <-- PUBLISH ---- | | 48 | | --- PUBACK ---> | ---- PUBACK ----> |--> PUBACK 49 | | | | 50 | 51 | 52 | Usage 53 | ------ 54 | ####Minimum requirements 55 | Over XBee 56 | Three XBee S2 devices, a coordinator, a gateway and a client. 57 | or two XBee S1 with digimesh firmware, gateway and client. 58 | 59 | Over UDP 60 | Arduino with Ethernet shield or Arduino Ether. 61 | or linux client. 62 | 63 | MQTT Broker 64 | TomyGateway 65 | 66 | ####1) Start Gateway 67 | 68 | see MQTT-SN/Gateway 69 | 70 | 71 | 72 | ####2) Start Client (-d parameter is a device which XBee dongle connected.) 73 | 74 | 1. XBee client 75 | 76 | $ TomyClient -i ClientID -d /dev/ttyUSB0 -b 9600 77 | 78 | 2. UDP Client (Linux only, Arduino is embeded parameters defined by UDP_APP_CONFIG) 79 | 80 | $ TomyClient -i ClientID -g 225.1.1.1 -p 1883 -c -t WillTopic -m WillMessage -k 300 81 | 82 | -g : Multicast address 83 | -p : Multicast port 84 | -c : Clean session 85 | -k : Keep alive 86 | 87 | 88 | ####3) XBee configurations 89 | 90 | Serial interfacing of Clients and gateway. 91 | Coordinator is default setting. 92 | XBee Firmware version is 2xA7. 93 | 94 | [BD] 0-7 Arduino Clients : 3 (9600bps) Linux Clients : 5 (38400bps) 95 | [D7] 1 96 | [D6] 0 or 1 97 | [AP] 2 98 | [SP] Coordinator, Router Device : AF0 End device :20 99 | 100 | Other values are defaults. Baudrate is used by mqtts.begin(device, _baudrate_) or mqtts.begin(_baudrate_) function. 101 | In case of LINUX, if you set D6 to 1, uncomment a line //#define XBEE_FLOWCTL_CRTSCTS in Mqtts_Defines.h 102 | 103 | 104 | How to Build (Requiered source code list) 105 | ----------- 106 | ####1) Linux Client 107 | _copy src/lib/* and src/LinuxClientSample.cpp_ 108 | 109 | $ make 110 | $ make install 111 | 112 | ####2) Arduino Client 113 | _Copy src/lib into Aruino Librally directory._ 114 | _Copy SoilMoistureClientSample.ino into Aruino sketch directory._ 115 | 116 | 117 | _in IPAddress.h, change raw_address() tp public from private._ 118 | _Add beginMulticast() to EthernetUDP.cpp_ 119 | see http://forum.arduino.cc/index.php?topic=150006.0 120 | 121 | ####3) mbed Client 122 | _copy src/lib/* and src/mbedClientSample.cpp_ 123 | 124 | Module descriptions 125 | ------------------- 126 | ####1) MqttsClientApp.cpp 127 | Client application sample which is used for debug. 128 | 129 | 130 | ####2) MqttsClientFwApp.ino 131 | MqttsClient sample application for Arduino. 132 | 133 | ###Modules in mqttslib 134 | 135 | ####1) MqttsClient.cpp 136 | MQTT-S Client Engine class. This Class is used by a application. 137 | Usages are shown as follows. 138 | 139 | MqttsClient mqtts = MqttsClient(); // Declare the client object 140 | mqtts.begin(argv[1], B9600); // argv[1] is a serial device for XBee. ex) /dev/ttyUSB0 141 | mqtts.init("Node-02"); // Get XBee's address64, short address and set XBee Node ID, 142 | mqtts.setWillTopic(willtopic); // set WILLTOPIC. 143 | mqtts.setWillMessage(willmsg); // set WILLMSG those are sent automatically. 144 | mqtts.setKeepAlive(60000); // PINGREQ interval time 145 | 146 | mqtts.subscribe(topic, callback,qos); // Execute the callback, when the subscribed topic's data is published. 147 | mqtts.publish(topic, payload, payload_length,qos); // publish the data, topic is converted into ID automatically. 148 | mqtts.publish(topic, MQString* payload,qos); 149 | mqtts.unsubscribe(topic); 150 | mqtts.disconnect(); 151 | 152 | above APIs are primitive one. 153 | In the Application, use PUBLISE(), SUBSCRIBE(), UNSUBSCRIBE(), DISCONNECT(). 154 | see Sample.cpp 155 | 156 | 157 | ####2) MqttsClientAppFw4Arduino.cpp 158 | Application framework for Arduino. 159 | Interupt and watch dog timer are supported. 160 | set MAC address of your Ethernet sheild to the UDP_APP_CONFIG structure. 161 | 162 | ####3) MqttsClientAppFw4Linux.cpp 163 | Application framework for Linux. 164 | watch dog timer are supported. 165 | 166 | ####4) MqttsClientAppFw4mbed.cpp 167 | Application framework for mbed. 168 | watch dog timer are supported. 169 | UDP is not supported. 170 | 171 | ####5) MQTTS.cpp 172 | MQTT-S messages classes and some classes for client and Gateway. 173 | 174 | ####6) ZBeeStack.cpp 175 | XBee control classes 176 | 177 | ####7) udpStack.cpp 178 | UDP control classes 179 | 180 | ####8) MQTTSN_Application.h 181 | Default setting is Linux and UDP. 182 | select the system and uncoment it. 183 | 184 | //#define LINUX 185 | //#define MBED 186 | 187 | select the NetworkStack and uncomment it. 188 | 189 | //#define NETWORK_XBEE 190 | //#define NETWORK_UDP 191 | 192 | 193 | 194 | -------------------------------------------------------------------------------- /Client/src/LinuxClientSample.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * LinuxClientSample.cpp 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 2014/09/05 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 1.0.0 34 | */ 35 | 36 | #include "lib/MQTTSN_Application.h" 37 | 38 | #ifdef LINUX 39 | #include "lib/mqttsnClientAppFw4Linux.h" 40 | #include 41 | #include 42 | 43 | using namespace std; 44 | using namespace tomyClient; 45 | 46 | /*============================================ 47 | * 48 | * MQTT-SN Client Application for Linux 49 | * 50 | *===========================================*/ 51 | 52 | /*------------------------------------------------------ 53 | * Create Topic 54 | *------------------------------------------------------*/ 55 | 56 | MQString* tp1 = new MQString("topic/01"); 57 | MQString* tp2 = new MQString("topic/02"); 58 | MQString* tp3 = new MQString("topic/03"); 59 | MQString* tp4 = new MQString("topic/04"); 60 | MQString* tp5 = new MQString("topic/05"); 61 | 62 | MQString* tp_request_01 = new MQString("topic/req/01"); 63 | MQString* tp_response_01 = new MQString("topic/rsp/01"); 64 | 65 | MQString* tp_request_02 = new MQString("topic/req/02"); 66 | MQString* tp_response_02 = new MQString("topic/rsp/02"); 67 | 68 | /*------------------------------------------------------ 69 | * Tasks invoked by Timer 70 | *------------------------------------------------------*/ 71 | 72 | int f_publish_all(){ 73 | PUBLISH(tp1,"topic/01", 8,QOS1); 74 | PUBLISH(tp2,"topic/02", 8,QOS1); 75 | PUBLISH(tp3,"topic/03", 8,QOS1); 76 | PUBLISH(tp4,"topic/04", 8,QOS1); 77 | PUBLISH(tp5,"topic/05", 8,QOS1); 78 | 79 | Payload pl = Payload(40); 80 | pl.set_uint32( 200); 81 | pl.set_uint32( 10); 82 | pl.set_uint32( 50000); 83 | pl.set_uint32( 70000); 84 | pl.set_int32( -300); 85 | pl.set_int32(-70000); 86 | pl.set_float((float)1000.01); 87 | pl.set_str("abcdef"); 88 | PUBLISH(tp_request_01,&pl,1); 89 | 90 | return 0; 91 | } 92 | 93 | 94 | /*--------------- List of task invoked by Timer ------------*/ 95 | 96 | TASK_LIST = { //{ MQString* topic, executing duration in second}, 97 | {f_publish_all, 10}, 98 | END_OF_TASK_LIST 99 | }; 100 | 101 | 102 | /*------------------------------------------------------ 103 | * Tasks invoked by PUBLISH command Packet 104 | *------------------------------------------------------*/ 105 | /*----- Topic list used in callback functions -----*/ 106 | TOPICS_IN_CALLBACK = { 107 | tp_response_01, 108 | tp_response_02, 109 | END_OF_TOPICS 110 | }; 111 | 112 | int f_onRequest_01(MqttsnPublish* msg){ 113 | printf("inside f_onRequest_01()\n"); 114 | Payload pl; 115 | pl.getPayload(msg); 116 | pl.print(); 117 | printf("uint8: %d\n",pl.get_uint32(0)); 118 | printf("uint16: %d\n",pl.get_uint32(1)); 119 | printf("uint32: %d\n",pl.get_uint32(2)); 120 | printf("int8: %d\n",pl.get_uint32(3)); 121 | printf("int16: %d\n",pl.get_int32(4)); 122 | printf("int32: %d\n",pl.get_int32(5)); 123 | printf("float: %g \n",pl.get_float(6)); 124 | uint16_t len; 125 | printf("str: %s \n",pl.get_str(7,&len)); 126 | 127 | PUBLISH(tp_response_01,&pl,QOS1); 128 | return 0; 129 | } 130 | 131 | int f_onRequest_02(MqttsnPublish* msg){ 132 | printf("inside f_onRequest_02()\n"); 133 | PUBLISH(tp_response_02,"topic/rsp/02", 12,1); 134 | return 0; 135 | } 136 | 137 | /*-------------- List of Task invoked by PUBLISH -----------*/ 138 | 139 | SUBSCRIBE_LIST = { //{ MQString* topic, on_publish1, QOS }, 140 | {tp_request_01, f_onRequest_01, QOS1}, 141 | {tp_request_02, f_onRequest_02, QOS1}, 142 | END_OF_SUBSCRIBE_LIST 143 | }; 144 | 145 | 146 | /*================================================== 147 | * Application setup 148 | *=================================================*/ 149 | void setup(){ 150 | printf("Client start\n"); 151 | } 152 | /*============== End of Program ==============*/ 153 | 154 | #endif // LINUX 155 | -------------------------------------------------------------------------------- /Client/src/SoilMoistureClientSample.ino: -------------------------------------------------------------------------------- 1 | /* 2 | * SoilMoisture.ino 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 2014/09/05 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 1.0.0 34 | */ 35 | 36 | #include 37 | #include 38 | #include 39 | #include 40 | #include 41 | 42 | /*============================================ 43 | * 44 | * MQTT-SN Client Application for Arduino 45 | * 46 | *===========================================*/ 47 | #ifdef NETWORK_XBEE 48 | XBEE_APP_CONFIG = { 49 | { 50 | 9600, //Baudrate 51 | 0, //Serial PortNo (for Arduino App) 52 | 0 //Device (for linux App) 53 | }, 54 | { 55 | "ARD02", //ClientId 56 | 300, //KeepAlive 57 | true, //Clean session 58 | false, //EndDevice 59 | "willTopic", //WillTopic or 0 DO NOT USE NULL STRING "" ! 60 | "willMessage" //WillMessage or 0 DO NOT USE NULL STRING "" ! 61 | } 62 | }; 63 | #endif 64 | 65 | #ifdef NETWORK_UDP 66 | UDP_APP_CONFIG = { 67 | { 68 | {225,1,1,1}, // Multicast group IP 69 | 1883, // Multicast group Port 70 | {192,168,11,18}, // Local IP (for Arduino App) 71 | 12001, // Local PortNo 72 | {0x90,0xa2,0xda,0x0f,0x53,0xa5} // MAC address (for Arduino App) 73 | }, 74 | { 75 | "ARD02", //ClientId 76 | 300, //KeepAlive 77 | true, //Clean session 78 | false, //EndDevice 79 | "willTopic", //WillTopic or 0 DO NOT USE NULL STRING "" ! 80 | "willMessage" //WillMessage or 0 DO NOT USE NULL STRING "" ! 81 | } 82 | }; 83 | #endif 84 | 85 | /*------------------------------------------------------ 86 | * Create Topic 87 | *------------------------------------------------------*/ 88 | MQString* topic1 = new MQString("ty4tw/tp1"); 89 | MQString* topic2 = new MQString("ty4tw/tp2"); 90 | MQString* tpMeasure = new MQString("ty4tw/soilReg"); 91 | /*------------------------------------------------------ 92 | * Tasks invoked by Timer 93 | *------------------------------------------------------*/ 94 | #define PIN5 5 // 3.3V supply port 95 | #define MCOUNT 10 // measurement count 96 | #define PIN0 0 // measurement port 97 | #define RP 20 // resistance [K ohom] 98 | 99 | int measure(){ 100 | int val = 0; 101 | pinMode(PIN5,OUTPUT); 102 | digitalWrite(PIN5,1); 103 | 104 | for(uint8_t cnt = 0; cnt < MCOUNT; cnt++){ 105 | delay(50); 106 | val += analogRead(PIN0); 107 | } 108 | digitalWrite(PIN5,0); 109 | int soilR = 1023 * RP / (val /MCOUNT) - RP; 110 | if(soilR < 0){ 111 | soilR = 9999; 112 | } 113 | Payload pl(30); 114 | pl.set_array(3); 115 | pl.set_uint32(GETUTC()); 116 | pl.set_int32(soilR); 117 | pl.set_str("Kohom"); 118 | return PUBLISH(tpMeasure,&pl,QOS1); 119 | } 120 | 121 | 122 | int task1(){ 123 | Payload pl = Payload(36); 124 | pl.set_array(9); 125 | pl.set_int32(30); 126 | pl.set_int32(255); 127 | pl.set_int32(70000); 128 | pl.set_str("abcdef"); 129 | pl.set_int32(-16); 130 | pl.set_int32(-60); 131 | pl.set_int32(-300); 132 | pl.set_int32(-70000); 133 | pl.set_float(1000.01); 134 | return PUBLISH(topic1,&pl,QOS1); 135 | } 136 | 137 | /*--------------- List of task invoked by Timer ------------*/ 138 | 139 | TASK_LIST = { //{ MQString* topic, executing duration in second}, 140 | {measure, 40}, 141 | {task1,6}, 142 | //{task2,6}, 143 | END_OF_TASK_LIST}; 144 | 145 | 146 | /*------------------------------------------------------ 147 | * Tasks invoked by PUBLISH command Packet 148 | *------------------------------------------------------*/ 149 | TOPICS_IN_CALLBACK = { 150 | 151 | END_OF_TOPICS 152 | }; 153 | 154 | 155 | int on_publish2(MqttsnPublish* msg){ 156 | theApplication->indicatorOff(); 157 | return 0; 158 | } 159 | 160 | /*------------ Link Callback to Topic -------------*/ 161 | 162 | SUBSCRIBE_LIST = { 163 | //{topic1, on_publish1, QOS1}, 164 | //{topic2, on_publish2, QOS1}, 165 | 166 | END_OF_SUBSCRIBE_LIST}; 167 | 168 | /*------------------------------------------------------ 169 | * Tasks invoked by INT0 interuption 170 | *------------------------------------------------------*/ 171 | void interruptCallback(){ 172 | //NOP 173 | } 174 | 175 | /*------------------------------------------------------ 176 | * Arduino setup() function 177 | *------------------------------------------------------*/ 178 | void setup(){ 179 | 180 | } 181 | 182 | 183 | -------------------------------------------------------------------------------- /Client/src/lib/MQTTSN_Application.h: -------------------------------------------------------------------------------- 1 | /* 2 | * MQTTSN_Application.h 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 2014/09/05 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 1.0.0 34 | */ 35 | 36 | #ifndef MATTSNAPPLICATION_H_ 37 | #define MATTSNAPPLICATION_H_ 38 | 39 | /**************************************** 40 | Select Platform and Network 41 | *****************************************/ 42 | 43 | /*----------- Select Platform ---------*/ 44 | #ifndef ARDUINO 45 | #define LINUX 46 | //#define MBED 47 | #endif 48 | 49 | /*--------- Select byte order ----------*/ 50 | #define CPU_LITTLEENDIANN 51 | //#define CPU_BIGENDIANN 52 | 53 | 54 | /*-------- Select Network -------------*/ 55 | #define NETWORK_XBEE 56 | //#define NETWORK_UDP 57 | 58 | 59 | /*--- XBee Buffer Flow Control --*/ 60 | #ifdef NETWORK_XBEE 61 | //#define XBEE_FLOWCTL_CRTSCTS 62 | #endif 63 | 64 | /*====================================== 65 | * Debug Flag 66 | ======================================*/ 67 | //#define NW_DEBUG 68 | //#define MQTTSN_DEBUG 69 | #define DEBUG 70 | 71 | 72 | /**************************************** 73 | MQTT-SN Packet length 74 | *****************************************/ 75 | #ifdef ARDUINO 76 | #define MQTTSN_MAX_FRAME_SIZE 70 77 | #else 78 | #ifdef NETWORK_XBEE 79 | #define MQTTSN_MAX_FRAME_SIZE 70 80 | #else 81 | #ifdef NETWORK_UDP 82 | #define MQTTSN_MAX_FRAME_SIZE 1024 83 | #endif 84 | #endif 85 | #endif 86 | /**************************************** 87 | Application config structures 88 | *****************************************/ 89 | #ifdef LINUX 90 | typedef unsigned char uint8_t; 91 | typedef unsigned short uint16_t; 92 | typedef unsigned int uint32_t; 93 | typedef signed char int8_t; 94 | typedef signed short int16_t; 95 | typedef signed int int32_t; 96 | #endif 97 | 98 | #ifdef MBED 99 | #include "mbed.h" 100 | #endif 101 | 102 | #ifdef ARDUINO 103 | #include 104 | #endif 105 | 106 | typedef struct { 107 | const char* nodeId; 108 | uint16_t keepAlive; 109 | bool cleanSession; 110 | bool endDevice; 111 | const char* willTopic; 112 | const char* willMsg; 113 | }MqttsnConfig; 114 | 115 | typedef struct { 116 | long baudrate; 117 | uint8_t portNo; 118 | char* device; 119 | }XBeeConfig; 120 | 121 | typedef struct { 122 | XBeeConfig netCfg; 123 | MqttsnConfig mqttsnCfg; 124 | }XBeeAppConfig; 125 | 126 | typedef struct { 127 | uint8_t ipAddress[4]; 128 | uint16_t gPortNo; 129 | uint8_t ipLocal[4]; 130 | uint16_t uPortNo; 131 | uint8_t macAddr[6]; 132 | }UdpConfig; 133 | 134 | typedef struct { 135 | UdpConfig netCfg; 136 | MqttsnConfig mqttsnCfg; 137 | }UdpAppConfig; 138 | 139 | /*====================================== 140 | MACROs for Application 141 | =======================================*/ 142 | #ifdef NETWORK_XBEE 143 | #define XBEE_APP_CONFIG XBeeAppConfig theAppConfig 144 | #define APP_CONFIG XBeeAppConfig 145 | #define NETWORK_CONFIG XBeeConfig 146 | #endif 147 | 148 | #ifdef NETWORK_UDP 149 | #define UDP_APP_CONFIG UdpAppConfig theAppConfig 150 | #define APP_CONFIG UdpAppConfig 151 | #define NETWORK_CONFIG UdpConfig 152 | #endif 153 | 154 | #define TASK_LIST TaskList theTaskList[] 155 | #define END_OF_TASK_LIST {0,0} 156 | #define SUBSCRIBE_LIST OnPublishList theOnPublishList[] 157 | #define END_OF_SUBSCRIBE_LIST {0,0,0} 158 | #define TOPICS_IN_CALLBACK MQString* theTopics[] 159 | #define END_OF_TOPICS 0 160 | 161 | #define PUBLISH(...) theApplication->publish(__VA_ARGS__) 162 | #define SUBSCRIBE(...) theApplication->subscribe(__VA_ARGS__) 163 | #define UNSUBSCRIBE(...) theApplication->unsubscribe(__VA_ARGS__) 164 | #define DISCONNECT() theApplication->disconnect() 165 | #define SETRETAIN(...) theApplication->setRetain(__VA_ARGS__) 166 | 167 | /*====================================== 168 | MACROs for debugging 169 | ========================================*/ 170 | #ifdef ARDUINO 171 | #ifdef NW_DEBUG 172 | #define D_NWSTACK(...) debug.print(__VA_ARGS__) 173 | #define D_NWSTACKLN(... ) debug.println(__VA_ARGS__) 174 | #define D_NWSTACKW(...) debug.print(__VA_ARGS__) 175 | #define D_NWSTACKF(...) 176 | #else 177 | #define D_NWSTACK(...) 178 | #define D_NWSTACKLN(...) 179 | #define D_NWSTACKW(...) 180 | #define D_NWSTACKF(...) 181 | #endif 182 | 183 | #ifdef MQTTSN_DEBUG 184 | #define D_MQTT(...) debug.print(__VA_ARGS__) 185 | #define D_MQTTW(...) debug.print(__VA_ARGS__) 186 | #define D_MQTTLN(...) debug.println(__VA_ARGS__) 187 | #define D_MQTTF(...) 188 | #else 189 | #define D_MQTT(...) 190 | #define D_MQTTLN(...) 191 | #define D_MQTTW(...) 192 | #define D_MQTTF(...) 193 | #endif 194 | #else 195 | #ifdef NW_DEBUG 196 | #define D_NWSTACKF(...) printf(__VA_ARGS__) 197 | #define D_NWSTACKW(...) printf(__VA_ARGS__) 198 | #define D_NWSTACKLN(...) 199 | #define D_NWSTACK(...) 200 | #else 201 | #define D_NWSTACK(...) 202 | #define D_NWSTACKLN(...) 203 | #define D_NWSTACKW(...) 204 | #define D_NWSTACKF(...) 205 | #endif 206 | #ifdef MQTTSN_DEBUG 207 | #define D_MQTTF(...) printf(__VA_ARGS__) 208 | #define D_MQTTW(...) printf("%s",__VA_ARGS__) 209 | #define D_MQTTLN(...) 210 | #define D_MQTT(...) 211 | #else 212 | #define D_MQTT(...) 213 | #define D_MQTTLN(...) 214 | #define D_MQTTW(...) 215 | #define D_MQTTF(...) 216 | #endif 217 | #endif 218 | 219 | #endif /* MATTSNAPPLICATION_H_ */ 220 | 221 | -------------------------------------------------------------------------------- /Client/src/lib/Network.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Network.cpp 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 2014/09/05 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 1.0.0 34 | */ 35 | 36 | #ifndef NEWORK_H_ 37 | #define NEWORK_H_ 38 | 39 | #ifndef ARDUINO 40 | #include "MQTTSN_Application.h" 41 | #else 42 | #include 43 | #endif 44 | 45 | /*********************************** 46 | * Send Request Type 47 | ***********************************/ 48 | enum SendReqType{ 49 | NoReq = 0, 50 | UcastReq, 51 | BcastReq 52 | }; 53 | 54 | /*================================= 55 | * Network stacks 56 | ==================================*/ 57 | #ifdef NETWORK_XBEE 58 | #ifdef ARDUINO 59 | #include 60 | #else 61 | #include "zbeeStack.h" 62 | #endif 63 | #endif 64 | 65 | #ifdef NETWORK_UDP 66 | #ifdef ARDUINO 67 | #include 68 | #else 69 | #include "udpStack.h" 70 | #endif 71 | #endif 72 | 73 | 74 | namespace tomyClient { 75 | /*********************************** 76 | * MQTT-SN Client's state 77 | ***********************************/ 78 | enum NodeStatus { 79 | NdDisconnected = 0, 80 | NdActive, 81 | NdAsleep, 82 | NdAwaik, 83 | NdLost 84 | }; 85 | 86 | #define PACKET_SENDED 0 87 | #define PACKET_ERROR_RESPONSE -1 88 | #define PACKET_ERROR_UNKOWN -2 89 | #define PACKET_ERROR_NODATA -3 90 | #define PACKET_MODEM_STATUS -4 91 | 92 | } /* end of namespace */ 93 | 94 | #endif /* NEWORK_H_ */ 95 | -------------------------------------------------------------------------------- /Client/src/lib/mqUtil.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * mqUtil.cpp 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 2014/09/05 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 1.0.0 34 | */ 35 | 36 | #ifndef ARDUINO 37 | #include "MQTTSN_Application.h" 38 | #include "mqUtil.h" 39 | #include "stdio.h" 40 | #include "string.h" 41 | #else 42 | #include 43 | #include 44 | #include 45 | #include 46 | #endif /* ARDUINO */ 47 | 48 | #ifdef MBED 49 | #include "mbed.h" 50 | #endif /* MBED */ 51 | 52 | 53 | using namespace std; 54 | using namespace tomyClient; 55 | 56 | /*===================================== 57 | Global functions 58 | ======================================*/ 59 | 60 | #ifdef CPU_LITTLEENDIANN 61 | 62 | /*--- For Little endianness ---*/ 63 | 64 | uint16_t getUint16(uint8_t* pos){ 65 | uint16_t val = ((uint16_t)*pos++ << 8); 66 | return val += *pos; 67 | } 68 | 69 | void setUint16(uint8_t* pos, uint16_t val){ 70 | *pos++ = (val >> 8) & 0xff; 71 | *pos = val & 0xff; 72 | } 73 | 74 | uint32_t getUint32(uint8_t* pos){ 75 | uint32_t val = uint32_t(*pos++) << 24; 76 | val += uint32_t(*pos++) << 16; 77 | val += uint32_t(*pos++) << 8; 78 | return val += *pos++; 79 | } 80 | 81 | void setUint32(uint8_t* pos, uint32_t val){ 82 | *pos++ = (val >> 24) & 0xff; 83 | *pos++ = (val >> 16) & 0xff; 84 | *pos++ = (val >> 8) & 0xff; 85 | *pos = val & 0xff; 86 | } 87 | 88 | float getFloat32(uint8_t* pos){ 89 | union{ 90 | float flt; 91 | uint8_t d[4]; 92 | }val; 93 | val.d[3] = *pos++; 94 | val.d[2] = *pos++; 95 | val.d[1] = *pos++; 96 | val.d[0] = *pos; 97 | return val.flt; 98 | } 99 | 100 | void setFloat32(uint8_t* pos, float flt){ 101 | union{ 102 | float flt; 103 | uint8_t d[4]; 104 | }val; 105 | val.flt = flt; 106 | *pos++ = val.d[3]; 107 | *pos++ = val.d[2]; 108 | *pos++ = val.d[1]; 109 | *pos = val.d[0]; 110 | } 111 | 112 | #endif // CPU_LITTLEENDIANN 113 | 114 | /*--- For Big endianness ---*/ 115 | #ifdef CPU_BIGENDIANN 116 | 117 | uint16_t getUint16(uint8_t* pos){ 118 | uint16_t val = *pos++; 119 | return val += ((uint16_t)*pos++ << 8); 120 | } 121 | 122 | void setUint16(uint8_t* pos, uint16_t val){ 123 | *pos++ = val & 0xff; 124 | *pos = (val >> 8) & 0xff; 125 | } 126 | 127 | uint32_t getUint32(uint8_t* pos){ 128 | long val = uint32_t(*(pos + 3)) << 24; 129 | val += uint32_t(*(pos + 2)) << 16; 130 | val += uint32_t(*(pos + 1)) << 8; 131 | return val += *pos; 132 | } 133 | 134 | void setUint32(uint8_t* pos, uint32_t val){ 135 | *pos++ = val & 0xff; 136 | *pos++ = (val >> 8) & 0xff; 137 | *pos++ = (val >> 16) & 0xff; 138 | *pos = (val >> 24) & 0xff; 139 | } 140 | 141 | float getFloat32(uint8_t* pos){ 142 | union{ 143 | float flt; 144 | uint8_t d[4]; 145 | }val; 146 | 147 | val.d[0] = *pos++; 148 | val.d[1] = *pos++; 149 | val.d[2] = *pos++; 150 | val.d[3] = *pos; 151 | return val.flt; 152 | } 153 | 154 | void setFloat32(uint8_t* pos, float flt){ 155 | union{ 156 | float flt; 157 | uint8_t d[4]; 158 | }val; 159 | val.flt = flt; 160 | *pos++ = val.d[0]; 161 | *pos++ = val.d[1]; 162 | *pos++ = val.d[2]; 163 | *pos = val.d[3]; 164 | } 165 | 166 | #endif // CPU_BIGENDIANN 167 | 168 | /*========================================= 169 | Class XBeeTimer 170 | =========================================*/ 171 | 172 | #ifdef ARDUINO 173 | /** 174 | * for Arduino 175 | */ 176 | uint32_t XTimer::_unixTime; 177 | uint32_t XTimer::_epochTime; 178 | uint32_t XTimer::_timerStopTimeAccum; 179 | bool XTimer::_utcFlag; 180 | 181 | 182 | XTimer::XTimer(){ 183 | stop(); 184 | } 185 | 186 | void XTimer::initialize(){ 187 | _unixTime = 0; 188 | _epochTime = 0; 189 | _timerStopTimeAccum = 0; 190 | _utcFlag = false; 191 | } 192 | 193 | void XTimer::start(uint32_t msec){ 194 | _startTime = millis(); 195 | _millis = msec; 196 | _currentTime = 0; 197 | _timeupUnixTime = getUnixTime() + msec / 1000; 198 | } 199 | 200 | bool XTimer::isTimeUp(){ 201 | return isTimeUp(_millis); 202 | } 203 | 204 | bool XTimer::isTimeUp(uint32_t msec){ 205 | if(_utcFlag){ 206 | _utcFlag = false; 207 | if(_timeupUnixTime > 1000000000 && _unixTime){ 208 | return (getUnixTime() >= _timeupUnixTime); 209 | }else{ 210 | return false; 211 | } 212 | }else{ 213 | if ( _startTime){ 214 | _currentTime = millis(); 215 | if ( _currentTime < _startTime){ 216 | return (0xffffffff - _startTime + _currentTime > msec); 217 | }else{ 218 | return (_currentTime - _startTime > msec); 219 | } 220 | }else{ 221 | return false; 222 | } 223 | } 224 | } 225 | 226 | void XTimer::stop(){ 227 | _startTime = 0; 228 | _millis = 0; 229 | _currentTime = 0; 230 | _timeupUnixTime = 0; 231 | } 232 | 233 | void XTimer::setUnixTime(uint32_t utc){ 234 | _epochTime = millis(); 235 | _timerStopTimeAccum = 0; 236 | _unixTime = utc; 237 | } 238 | 239 | uint32_t XTimer::getUnixTime(){ 240 | uint32_t tm = _timerStopTimeAccum + millis(); 241 | if (_epochTime > tm ){ 242 | return _unixTime + (uint32_t)((0xffffffff - tm - _epochTime) / 1000); 243 | }else{ 244 | return _unixTime + (uint32_t)((tm - _epochTime) / 1000); 245 | } 246 | } 247 | 248 | void XTimer::setStopTimeDuration(uint32_t msec){ 249 | _timerStopTimeAccum += msec; 250 | } 251 | 252 | void XTimer::changeUTC(){ 253 | _utcFlag = true; 254 | } 255 | 256 | #endif 257 | 258 | 259 | #ifdef MBED 260 | /** 261 | * for MBED 262 | */ 263 | XTimer::XTimer(){ 264 | stop(); 265 | } 266 | 267 | void XTimer::start(uint32_t msec){ 268 | _timer.start(); 269 | _millis = msec; 270 | _timeupTime = time(0) + (uint32_t)(msec/1000UL); 271 | } 272 | 273 | bool XTimer::isTimeUp(){ 274 | return isTimeUp(_millis); 275 | } 276 | 277 | bool XTimer::isTimeUp(uint32_t msec){ 278 | if(_utcFlg){ 279 | if(_timeupTime > 100000000){ 280 | return( time(0) > _timeupTime); 281 | }else{ 282 | return false; 283 | } 284 | }else{ 285 | return _timer.read_ms() > msec; 286 | } 287 | } 288 | 289 | void XTimer::stop(){ 290 | _timer.stop(); 291 | _millis = 0; 292 | _timeupTime = 0; 293 | } 294 | 295 | void XTimer::changeUTC(){ 296 | _utcFlg = true; 297 | } 298 | 299 | #endif 300 | 301 | #ifdef LINUX 302 | /** 303 | * for LINUX 304 | */ 305 | XTimer::XTimer(){ 306 | _startTime.tv_sec = 0; 307 | _millis = 0; 308 | } 309 | 310 | XTimer::~XTimer(){ 311 | 312 | } 313 | 314 | void XTimer::start(uint32_t msec){ 315 | gettimeofday(&_startTime, 0); 316 | _millis = msec; 317 | } 318 | 319 | bool XTimer::isTimeUp(void){ 320 | return isTimeUp(_millis); 321 | } 322 | 323 | bool XTimer::isTimeUp(uint32_t msec){ 324 | struct timeval curTime; 325 | uint32_t secs, usecs; 326 | if (_startTime.tv_sec == 0){ 327 | return false; 328 | }else{ 329 | gettimeofday(&curTime, 0); 330 | secs = (curTime.tv_sec - _startTime.tv_sec) * 1000; 331 | usecs = (curTime.tv_usec - _startTime.tv_usec) / 1000.0; 332 | return ((secs + usecs) > (uint32_t)msec); 333 | } 334 | } 335 | 336 | void XTimer::stop(){ 337 | _startTime.tv_sec = 0; 338 | _millis = 0; 339 | } 340 | 341 | #endif 342 | -------------------------------------------------------------------------------- /Client/src/lib/mqUtil.h: -------------------------------------------------------------------------------- 1 | /* 2 | * mqUtil.h 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 2014/09/05 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 1.0.0 34 | */ 35 | 36 | #ifndef XTIMER_H_ 37 | #define XTIMER_H_ 38 | 39 | 40 | #if defined(ARDUINO) 41 | #include 42 | #if ARDUINO >= 100 43 | #include "Arduino.h" 44 | #include 45 | #else 46 | #if ARDUINO < 100 47 | #include "WProgram.h" 48 | #include 49 | #endif 50 | #endif 51 | 52 | #define XB_CTS_PIN 3 // XBee CTS 53 | #define XB_SLEEP_PIN 4 // XBee Pinhybernate 54 | #else 55 | #include "MQTTSN_Application.h" 56 | #endif /* ARDUINO */ 57 | 58 | 59 | #ifdef LINUX 60 | #include 61 | #endif 62 | 63 | #ifdef MBED 64 | #include "mbed.h" 65 | #endif 66 | 67 | namespace tomyClient { 68 | 69 | 70 | #ifdef ARDUINO 71 | /*============================================ 72 | XBeeTimer for Arduino 73 | ============================================*/ 74 | class XTimer{ 75 | public: 76 | XTimer(); 77 | ~XTimer(){}; 78 | void start(uint32_t msec = 0); 79 | bool isTimeUp(uint32_t msec); 80 | bool isTimeUp(void); 81 | void stop(); 82 | static uint32_t getUnixTime(); 83 | static void setUnixTime(uint32_t utc); 84 | static void setStopTimeDuration(uint32_t msec); 85 | static void initialize(); 86 | static void changeUTC(); 87 | 88 | private: 89 | uint32_t _startTime; 90 | uint32_t _currentTime; 91 | uint32_t _millis; 92 | uint32_t _timeupUnixTime; 93 | static uint32_t _unixTime; 94 | static uint32_t _epochTime; 95 | static uint32_t _timerStopTimeAccum; 96 | static bool _utcFlag; 97 | 98 | }; 99 | 100 | 101 | #endif 102 | 103 | #ifdef MBED 104 | /*============================================ 105 | XBeeTimer for MBED 106 | ============================================*/ 107 | class XTimer{ 108 | public: 109 | XTimer(); 110 | ~XTimer(){}; 111 | void start(uint32_t msec = 0); 112 | bool isTimeUp(uint32_t msec); 113 | bool isTimeUp(void); 114 | void stop(void); 115 | void changeUTC(void); 116 | 117 | private: 118 | Timer _timer; 119 | time_t _startTime; 120 | uint32_t _millis; 121 | time_t _timeupTime; 122 | bool _utcFlg; 123 | }; 124 | 125 | #endif 126 | 127 | 128 | #ifdef LINUX 129 | /*============================================ 130 | XBeeTimer 131 | ============================================*/ 132 | class XTimer{ 133 | public: 134 | XTimer(); 135 | ~XTimer(); 136 | void start(uint32_t msec = 0); 137 | bool isTimeUp(uint32_t msec); 138 | bool isTimeUp(void); 139 | void stop(void); 140 | void changeUTC(void){}; 141 | private: 142 | struct timeval _startTime; 143 | uint32_t _millis; 144 | }; 145 | 146 | #endif 147 | } 148 | 149 | #endif /* XTIMER_H_ */ 150 | -------------------------------------------------------------------------------- /Client/src/lib/mqttsnClient.h: -------------------------------------------------------------------------------- 1 | /* 2 | * mqttsnClient.h 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 2014/09/05 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 1.0.0 34 | */ 35 | 36 | #ifndef MQTTSCLIENT_H_ 37 | #define MQTTSCLIENT_H_ 38 | 39 | #ifdef LINUX 40 | #define SENDQ_SIZE 20 41 | #else 42 | #define SENDQ_SIZE 5 43 | #endif 44 | 45 | #if defined(ARDUINO) && ARDUINO >= 100 46 | #include "Arduino.h" 47 | #include 48 | #include 49 | #include 50 | #include 51 | #include 52 | #else 53 | #if defined(ARDUINO) && ARDUINO < 100 54 | #include "WProgram.h" 55 | #include 56 | #include 57 | #include 58 | #include 59 | #else 60 | #ifdef LINUX 61 | #include 62 | #endif 63 | #include 64 | #include "MQTTSN_Application.h" 65 | #include "Network.h" 66 | #include "mqUtil.h" 67 | #include "mqttsn.h" 68 | #endif 69 | #endif 70 | 71 | 72 | #define GW_LOST 0 73 | #define GW_SEARCHING 1 74 | #define GW_FIND 2 75 | 76 | #define CL_DISCONNECTED 0 77 | #define CL_ACTIVE 1 78 | #define CL_ASLEEP 2 79 | #define CL_AWAKE 3 80 | 81 | 82 | using namespace tomyClient; 83 | 84 | typedef struct { 85 | int (*callback)(void); 86 | uint32_t sec; 87 | }TaskList; 88 | 89 | typedef struct { 90 | MQString* topic; 91 | int (*pubCallback)(MqttsnPublish*); 92 | uint8_t qos; 93 | }OnPublishList; 94 | 95 | typedef struct { 96 | uint32_t prevTime; 97 | uint32_t interval; 98 | int (*callback)(void); 99 | }MQ_TimerTbl; 100 | 101 | /*===================================== 102 | Class ClientStatus 103 | ======================================*/ 104 | class ClientStatus{ 105 | public: 106 | ClientStatus(); 107 | ~ClientStatus(); 108 | 109 | bool isLost(); 110 | bool isSearching(); 111 | bool isConnected(); 112 | bool isOnConnected(); 113 | bool isSubscribing(); 114 | bool isAvailableToSend(); 115 | bool isPINGREQRequired(); 116 | bool isGatewayAlive(); 117 | 118 | uint16_t getKeepAlive(); 119 | void setKeepAlive(uint16_t sec); 120 | void sendSEARCHGW(); 121 | bool recvGWINFO(MqttsnGwInfo* gwi); 122 | void recvADVERTISE(MqttsnAdvertise* adv); 123 | void recvCONNACK(); 124 | void recvDISCONNECT(); 125 | void recvPINGRESP(); 126 | void setAvailableToSend(); 127 | void setSubscribing(bool); 128 | void setLastSendTime(); 129 | void setModeSleep(); 130 | void init(); 131 | 132 | 133 | private: 134 | void changeUTC(); 135 | 136 | uint8_t _gwId; 137 | uint8_t _gwStat; 138 | uint8_t _clStat; 139 | bool _onConnectFlg; 140 | bool _subscribingFlg; 141 | uint16_t _keepAliveDuration; // PINGREQ interval 142 | uint16_t _advertiseDuration; // Gateway heart beat 143 | XTimer _keepAliveTimer; 144 | XTimer _advertiseTimer; 145 | bool _sleepModeFlg; 146 | }; 147 | 148 | /*===================================== 149 | Class SendQue (FIFO) 150 | ======================================*/ 151 | class SendQue { 152 | public: 153 | SendQue(); 154 | ~SendQue(); 155 | int addRequest(MqttsnMessage* msg); 156 | int addPriorityRequest(MqttsnMessage* msg); 157 | void setStatus(uint8_t index, uint8_t status); 158 | MqttsnMessage* getMessage(uint8_t index); 159 | int getStatus(uint8_t index); 160 | uint8_t getCount(); 161 | int deleteRequest(uint8_t index); 162 | void deleteAllRequest(); 163 | void setQueSize(uint8_t sz); 164 | private: 165 | uint8_t _queSize; 166 | uint8_t _queCnt; 167 | MqttsnMessage* _msg[SENDQ_SIZE]; 168 | }; 169 | 170 | 171 | /*===================================== 172 | Class MqttsnClient 173 | ======================================*/ 174 | class MqttsnClient { 175 | public: 176 | MqttsnClient(); 177 | ~MqttsnClient(); 178 | 179 | Topics* getTopics(); 180 | 181 | int initialize(APP_CONFIG config); 182 | void subscribe(); 183 | void setSubscribing(bool); 184 | void setKeepAlive(uint16_t sec); 185 | void setWillTopic(MQString* topic); 186 | void setWillMessage(MQString* msg); 187 | void setSleepMode(void); 188 | void setRetain(bool retain); 189 | void setClean(bool clean); 190 | void setRetryMax(uint8_t cnt); 191 | void setGwAddress(); 192 | MQString* getClientId(); 193 | ClientStatus* getClientStatus(); 194 | bool isCleanSession(); 195 | 196 | 197 | int publish(MQString* topic, const char* data, int dataLength, uint8_t qos = 1); 198 | int publish(MQString* topic, MQString* data, uint8_t qos = 1); 199 | int publish(uint16_t predifinedId, const char* data, int dataLength, uint8_t qos = 1); 200 | int publish(MQString* topic, Payload* payload, uint8_t qos = 1); 201 | int registerTopic(MQString* topic); 202 | int subscribe(MQString* topic, TopicCallback callback, uint8_t qos = 1); 203 | int subscribe(uint16_t predefinedId, TopicCallback callback, uint8_t qos); 204 | int unsubscribe(MQString* topic); 205 | int unsubscribe(uint16_t predefinedId); 206 | int disconnect(uint16_t duration = 0); 207 | void createTopics(); 208 | 209 | void recieveMessageHandler(NWResponse* msg, int* returnCode); 210 | void publishHdl(MqttsnPublish* msg); 211 | void recvMsg(uint16_t msec); 212 | int exec(); 213 | int readPacket(); 214 | uint8_t getMsgRequestCount(); 215 | 216 | private: 217 | int sendRecvMsg(); 218 | void clearMsgRequest(); 219 | int requestSendMsg(MqttsnMessage* msg); 220 | int requestPrioritySendMsg(MqttsnMessage* mqttsMsgPtr); 221 | int broadcast(uint16_t packetReadTimeout); 222 | int unicast(uint16_t packetReadTimeout); 223 | 224 | int searchGw(uint8_t radius); 225 | int connect(); 226 | int pingReq(MQString* clietnId); 227 | int willTopic(); 228 | int willMsg(); 229 | int pubAck(uint16_t topicId, uint16_t msgId, uint8_t rc); 230 | int pubRec(uint16_t msgId); 231 | int pubRel(uint16_t msgId); 232 | int regAck(uint16_t topicId, uint16_t msgId, uint8_t rc); 233 | int pubComp(uint16_t msgId); 234 | 235 | uint8_t getMsgRequestType(); 236 | uint8_t getMsgRequestStatus(); 237 | void setMsgRequestStatus(uint8_t stat); 238 | void createTopic(MQString* topic, TopicCallback callback); 239 | 240 | void delayTime(uint16_t baseTime); 241 | void copyMsg(MqttsnMessage* msg, NWResponse* recvMsg); 242 | uint16_t getNextMsgId(); 243 | 244 | Network* _network; 245 | Topics _topics; 246 | SendQue* _sendQ; 247 | XTimer _respTimer; 248 | PublishHandller _pubHdl; 249 | 250 | uint16_t _duration; 251 | MQString* _clientId; 252 | uint8_t _clientFlg; 253 | uint8_t _nRetry; 254 | uint8_t _nRetryCnt; 255 | uint16_t _tRetry; 256 | MQString* _willTopic; 257 | MQString* _willMessage; 258 | uint16_t _msgId; 259 | ClientStatus _clientStatus; 260 | bool _sendFlg; 261 | bool _subscribingFlg; 262 | }; 263 | 264 | 265 | 266 | #endif /* MQTTSCLIENT_H_ */ 267 | -------------------------------------------------------------------------------- /Client/src/lib/mqttsnClientAppFw4Arduino.h: -------------------------------------------------------------------------------- 1 | /* 2 | * mqttsnClientAppFw4Arduino.h 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 2014/09/05 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 1.0.0 34 | */ 35 | 36 | #ifdef ARDUINO 37 | 38 | #ifndef MQTTSNCLIENTAPPLICATION_H_ 39 | #define MQTTSNCLIENTAPPLICATION_H_ 40 | 41 | #include 42 | #include 43 | #include 44 | #include 45 | #include 46 | #include 47 | #include 48 | #include 49 | #include 50 | #include 51 | 52 | #define MQ_LED_PIN 13 53 | #define MQ_INT0_PIN 2 54 | #define MQ_SLEEP_PIN 4 // Connect to XBee DTR for hibernation mode 55 | #define MQ_ERROR_RECOVERY_DURATION_ON 8 56 | #define MQ_ON 1 57 | #define MQ_OFF 0 58 | 59 | #define ZB_ROUTER_DEVICE 0 60 | #define ZB_PIN_HIBERNATE 1 61 | 62 | 63 | #define MQ_WDT_ERR (B01100000) // Error Indication time 64 | 65 | #define MQ_WDT_TIME (B01000110) // 1 Sec 66 | #define MQ_WDT_TIME_MSEC 1000 67 | 68 | //#define MQ_WDT_TIME (B01000111) // 2 Secs 69 | //#define MQ_WDT_TIME_MSEC 2000 70 | 71 | //#define MQ_WDT_TIME (B01100000) // 4 Secs 72 | //#define MQ_WDT_TIME_MSEC 4000 73 | 74 | //#define MQ_WDT_TIME (B01100001) // 8 Secs 75 | //#define MQ_WDT_TIME_MSEC 8000 76 | 77 | 78 | enum MQ_INT_STATUS{ WAIT, INT0_LL, INT0_WAIT_HL, INT_WDT}; 79 | 80 | 81 | #define INDICATOR_ON() theApplication->indicatorOn() 82 | #define INDICATOR_OFF() theApplication->indicatorOff() 83 | #define BLINK_INDICATOR(...) theApplication->blinkIndicator(__VA_ARGS__) 84 | #define GETUTC() theApplication->getUnixTime() 85 | //#define GET_DATETIME(...) theApplication->getDateTime(__VA_ARGS__) 86 | 87 | 88 | extern void setUint32(uint8_t*, uint32_t); 89 | extern uint32_t getUint32(uint8_t*); 90 | extern void setUint16(uint8_t*, uint16_t); 91 | extern uint16_t getUint16(uint8_t*); 92 | 93 | 94 | /*====================================== 95 | Class WdTimer 96 | ========================================*/ 97 | class WdTimer:public XTimer { 98 | public: 99 | WdTimer(void); 100 | int registerCallback(uint32_t sec, int (*proc)(void)); 101 | void refleshRegisterTable(); 102 | void start(void); 103 | void stop(void); 104 | bool wakeUp(void); 105 | 106 | private: 107 | MQ_TimerTbl *_timerTbls; 108 | uint8_t _timerCnt; 109 | bool _initFlg; 110 | }; 111 | 112 | 113 | /*====================================== 114 | Class MqttsnClientApplication 115 | ========================================*/ 116 | class MqttsnClientApplication{ 117 | public: 118 | MqttsnClientApplication(); 119 | ~MqttsnClientApplication(); 120 | void registerInt0Callback(void (*callback)()); 121 | void registerWdtCallback(long sec, int (*callback)(void)); 122 | void refleshWdtCallbackTable(); 123 | int initialize(APP_CONFIG config); 124 | int setSubscribe(); 125 | void setKeepAlive(uint16_t msec); 126 | void setWillTopic(MQString* willTopic); 127 | void setWillMessage(MQString* willMsg); 128 | void setRetain(bool retain); 129 | void setClean(bool clean); 130 | void setClientId(MQString* id); 131 | void setZBPinHibernate(); 132 | void blinkIndicator(int msec); 133 | void startSleepMode(); 134 | void subscribe(void); 135 | void addTask(void); 136 | 137 | int registerTopic(MQString* topic); 138 | int publish(MQString* topic, const char* data, int dataLength, uint8_t qos = 1); 139 | int publish(uint16_t predefinedId, const char* data, int dataLength, uint8_t qos = 1); 140 | int publish(MQString* topic, Payload* payload, uint8_t qos); 141 | int subscribe(MQString* topic, TopicCallback callback, uint8_t qos = 1); 142 | int subscribe(uint16_t predefinedId, TopicCallback callback, uint8_t qos = 1); 143 | int unsubscribe(MQString* topic); 144 | int disconnect(uint16_t duration); 145 | 146 | void startWdt(); 147 | void stopWdt(); 148 | int run(); 149 | void setUnixTime(MqttsnPublish* msg); 150 | uint32_t getUnixTime(); 151 | void getDateTime(char* buf); 152 | void reboot(); 153 | void indicatorOn(); 154 | void indicatorOff(); 155 | 156 | private: 157 | void checkInterupt(); 158 | void interruptHandler(); 159 | void setInterrupt(); 160 | void sleepXB(); 161 | void wakeupXB(); 162 | void sleepApp(); 163 | 164 | MqttsnClient _mqttsn; 165 | bool _txFlag; 166 | bool _sleepFlg; 167 | uint8_t _deviceType; 168 | 169 | WdTimer _wdTimer; 170 | XTimer _keepAliveTimer; 171 | XTimer _advertiseTimer; 172 | 173 | void (*_intHandler)(void); 174 | 175 | }; 176 | 177 | extern MqttsnClientApplication* theApplication; 178 | 179 | #else 180 | 181 | #endif /*ARDUINO*/ 182 | 183 | 184 | 185 | 186 | #endif /* MQTTSNCLIENTAPPLICATION_H_ */ 187 | -------------------------------------------------------------------------------- /Client/src/lib/mqttsnClientAppFw4Linux.h: -------------------------------------------------------------------------------- 1 | /* 2 | * mqttsnClientAppFw4Linux.h 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 2014/09/05 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 1.0.0 34 | */ 35 | 36 | #ifdef LINUX 37 | 38 | #ifndef MQTTSNCLIENTAPPLICATION_H_ 39 | #define MQTTSNCLIENTAPPLICATION_H_ 40 | 41 | #include "MQTTSN_Application.h" 42 | #include "mqttsnClient.h" 43 | #include "mqUtil.h" 44 | 45 | 46 | /*====================================== 47 | Class WdTimer 48 | ========================================*/ 49 | class WdTimer:public XTimer { 50 | public: 51 | WdTimer(void); 52 | int registerCallback(uint32_t sec, int (*proc)(void)); 53 | void refleshRegisterTable(); 54 | void start(void); 55 | void stop(void); 56 | bool wakeUp(void); 57 | 58 | private: 59 | MQ_TimerTbl *_timerTbls; 60 | uint8_t _timerCnt; 61 | bool _initFlg; 62 | }; 63 | 64 | 65 | /*====================================== 66 | Class MqttsnClientApplication 67 | ========================================*/ 68 | class MqttsnClientApplication{ 69 | public: 70 | MqttsnClientApplication(); 71 | ~MqttsnClientApplication(); 72 | void refleshWdtCallbackTable(); 73 | void initialize(int argc, char** argv); 74 | void setSubscribe(); 75 | 76 | int publish(MQString* topic, const char* data, int dataLength, uint8_t qos = 1); 77 | int publish(uint16_t predefinedId, const char* data, int dataLength, uint8_t qos = 1); 78 | int publish(MQString* topic, Payload* payload, uint8_t qos); 79 | int subscribe(MQString* topic, TopicCallback callback, uint8_t qos = 1); 80 | int subscribe(uint16_t predefinedId, TopicCallback callback, uint8_t qos = 1); 81 | int unsubscribe(MQString* topic); 82 | int disconnect(uint16_t duration); 83 | void setRetain(bool flag); 84 | 85 | void addTask(); 86 | void startWdt(); 87 | void stopWdt(); 88 | int run(); 89 | 90 | 91 | private: 92 | MqttsnClient _mqttsn; 93 | WdTimer _wdTimer; 94 | XTimer _keepAliveTimer; 95 | XTimer _advertiseTimer; 96 | 97 | }; 98 | 99 | extern MqttsnClientApplication* theApplication; 100 | 101 | 102 | 103 | #else 104 | 105 | #endif /*LINUX*/ 106 | 107 | 108 | 109 | 110 | #endif /* MQTTSCLIENTAPPLICATION_H_ */ 111 | -------------------------------------------------------------------------------- /Client/src/lib/mqttsnClientAppFw4mbed.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * mqttsnClientAppAppFwmbed.cpp 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 2014/09/05 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 1.0.0 34 | */ 35 | 36 | #ifndef ARDUINO 37 | 38 | #include "MQTTSN_Application.h" 39 | #ifdef MBED 40 | #include "mqttsnClientAppFw4mbed.h" 41 | #include 42 | #include 43 | #include 44 | #include 45 | 46 | using namespace std; 47 | using namespace tomyClient; 48 | 49 | MqttsnClientApplication* theApplication = new MqttsnClientApplication(); 50 | 51 | extern TaskList theTaskList[]; 52 | extern OnPublishList theOnPublishList[]; 53 | extern APP_CONFIG theAppConfig; 54 | extern void setup(); 55 | 56 | /*======================================== 57 | main function 58 | =========================================*/ 59 | int main(){ 60 | theApplication->setKeepAlive(theAppConfig.mqttsnCfg.keepAlive); 61 | theApplication->setClean(theAppConfig.mqttsnCfg.cleanSession); 62 | if(theAppConfig.mqttsnCfg.willTopic){ 63 | MQString* willTpc = new MQString(theAppConfig.mqttsnCfg.willTopic); 64 | theApplication->setWillTopic(willTpc); 65 | } 66 | if(theAppConfig.mqttsnCfg.willMsg){ 67 | MQString* willMsg = new MQString(theAppConfig.mqttsnCfg.willMsg); 68 | theApplication->setWillMessage(willMsg); 69 | } 70 | 71 | theApplication->addTask(); 72 | setup(); 73 | theApplication->initialize(theAppConfig); 74 | theApplication->run(); 75 | return 0; 76 | } 77 | 78 | /*======================================== 79 | Class MqttsnClientApplication 80 | =========================================*/ 81 | /*-------------------------------- 82 | set UnixTime 83 | ---------------------------------*/ 84 | int setUTC(MqttsnPublish* msg){ 85 | set_time(getUint32(msg->getData())); 86 | return 0; 87 | } 88 | 89 | MqttsnClientApplication::MqttsnClientApplication(){ 90 | 91 | } 92 | 93 | MqttsnClientApplication::~MqttsnClientApplication(){ 94 | 95 | } 96 | 97 | 98 | void MqttsnClientApplication::startWdt(){ 99 | _wdTimer.start(); 100 | } 101 | 102 | void MqttsnClientApplication::stopWdt(){ 103 | _wdTimer.stop(); 104 | } 105 | 106 | /*------------ Client execution forever --------------*/ 107 | int MqttsnClientApplication::run(){ 108 | while(true){ 109 | _wdTimer.wakeUp(); 110 | _mqttsn.readPacket(); 111 | int rc = _mqttsn.exec(); 112 | if(rc == MQTTSN_ERR_REBOOT_REQUIRED){ 113 | _mqttsn.subscribe(); 114 | } 115 | } 116 | } 117 | 118 | 119 | void MqttsnClientApplication::initialize(APP_CONFIG config){ 120 | _mqttsn.initialize(config); 121 | setSubscribe(); 122 | } 123 | 124 | void MqttsnClientApplication::setSubscribe(){ 125 | _mqttsn.setSubscribing(true); // re-entrant control 126 | _mqttsn.subscribe(); 127 | _mqttsn.subscribe(MQTTSN_TOPICID_PREDEFINED_TIME, setUTC,1); 128 | _mqttsn.setSubscribing(false); 129 | } 130 | 131 | void MqttsnClientApplication::addTask(){ 132 | for(int i = 0; theTaskList[i].sec; i++){ 133 | _wdTimer.registerCallback(theTaskList[i].sec, theTaskList[i].callback); 134 | } 135 | } 136 | 137 | void MqttsnClientApplication::setKeepAlive(uint16_t sec){ 138 | _mqttsn.setKeepAlive(sec); 139 | } 140 | 141 | 142 | void MqttsnClientApplication::setWillTopic(MQString* willTopic){ 143 | _mqttsn.setWillTopic(willTopic); 144 | } 145 | 146 | void MqttsnClientApplication::setWillMessage(MQString* willMsg){ 147 | _mqttsn.setWillMessage(willMsg); 148 | } 149 | 150 | void MqttsnClientApplication::setRetain(bool retain){ 151 | _mqttsn.setRetain(retain); 152 | } 153 | 154 | void MqttsnClientApplication::setClean(bool clean){ 155 | _mqttsn.setClean(clean); 156 | } 157 | 158 | int MqttsnClientApplication::publish(MQString* topic, const char* data, int dataLength, uint8_t qos){ 159 | return _mqttsn.publish(topic, data, dataLength, qos); 160 | } 161 | 162 | int MqttsnClientApplication::publish(uint16_t predefinedId, const char* data, int dataLength, uint8_t qos){ 163 | return _mqttsn.publish(predefinedId, data, dataLength, qos); 164 | } 165 | 166 | int MqttsnClientApplication::publish(MQString* topic, Payload* payload, uint8_t qos){ 167 | return _mqttsn.publish(topic, payload, qos); 168 | } 169 | 170 | 171 | int MqttsnClientApplication::subscribe(MQString* topic, TopicCallback callback, uint8_t qos){ 172 | return _mqttsn.subscribe(topic, callback,qos); 173 | } 174 | 175 | int MqttsnClientApplication::subscribe(uint16_t predefinedId, TopicCallback callback, uint8_t qos){ 176 | return _mqttsn.subscribe(predefinedId, callback, qos); 177 | } 178 | 179 | 180 | int MqttsnClientApplication::unsubscribe(MQString* topic){ 181 | return _mqttsn.unsubscribe(topic); 182 | } 183 | 184 | int MqttsnClientApplication::disconnect(uint16_t duration){ 185 | return _mqttsn.disconnect(duration); 186 | } 187 | 188 | /*-------------- Callback related functions ---------------*/ 189 | 190 | 191 | void MqttsnClientApplication::refleshWdtCallbackTable(){ 192 | _wdTimer.refleshRegisterTable(); 193 | } 194 | 195 | /*====================================== 196 | Class WdTimer 197 | ========================================*/ 198 | WdTimer::WdTimer(void) { 199 | _timerTbls = 0; 200 | _timerCnt = 0; 201 | _initFlg = true; 202 | 203 | } 204 | 205 | void WdTimer::start(void) { 206 | //MQwatchdogEnable(); 207 | } 208 | 209 | 210 | void WdTimer::stop(void){ 211 | // 212 | } 213 | 214 | 215 | bool WdTimer::wakeUp(void){ 216 | bool rcflg = false; 217 | int rc; 218 | for(uint8_t i = 0; i < _timerCnt; i++) { 219 | if ((_timerTbls[i].prevTime + _timerTbls[i].interval < (uint32_t)time(0)) || _initFlg){ 220 | rc = (_timerTbls[i].callback)(); 221 | if(rc == MQTTSN_ERR_REBOOT_REQUIRED){ 222 | theApplication->initialize(theAppConfig); 223 | } 224 | _timerTbls[i].prevTime = time(0); 225 | rcflg = true; 226 | } 227 | } 228 | _initFlg = false; 229 | return rcflg; 230 | } 231 | 232 | int WdTimer::registerCallback(uint32_t sec, int (*callback)(void)){ 233 | MQ_TimerTbl *savTbl = _timerTbls; 234 | MQ_TimerTbl *newTbl = (MQ_TimerTbl*)calloc(_timerCnt + 1,sizeof(MQ_TimerTbl)); 235 | 236 | if ( newTbl != 0 ) { 237 | _timerTbls = newTbl; 238 | for(uint8_t i = 0; i < _timerCnt; i++ ){ 239 | _timerTbls[i].prevTime = savTbl[i].prevTime; 240 | _timerTbls[i].interval = savTbl[i].interval; 241 | _timerTbls[i].callback = savTbl[i].callback; 242 | } 243 | free(savTbl); 244 | 245 | _timerTbls[_timerCnt].prevTime = time(0); 246 | _timerTbls[_timerCnt].interval = sec; 247 | _timerTbls[_timerCnt].callback = callback; 248 | _timerCnt++; 249 | return MQTTSN_ERR_NO_ERROR; 250 | } 251 | return MQTTSN_ERR_OUT_OF_MEMORY; 252 | } 253 | 254 | void WdTimer::refleshRegisterTable(){ 255 | for(uint8_t i = 0; i < _timerCnt; i++) { 256 | _timerTbls[i].prevTime = time(0); 257 | } 258 | } 259 | 260 | 261 | #endif 262 | #endif 263 | 264 | 265 | 266 | -------------------------------------------------------------------------------- /Client/src/lib/mqttsnClientAppFw4mbed.h: -------------------------------------------------------------------------------- 1 | /* 2 | * mqttsnClientAppFw4mbed.h 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 2014/09/05 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 1.0.0 34 | */ 35 | 36 | #ifdef MBED 37 | 38 | #ifndef MQTTSNCLIENTAPPLICATION_H_ 39 | #define MQTTSNCLIENTAPPLICATION_H_ 40 | 41 | #include "mqttsnClient.h" 42 | 43 | 44 | extern uint16_t getUint16(uint8_t* pos); 45 | extern uint32_t getUint32(uint8_t* pos); 46 | extern void setUint16(uint8_t* pos, uint16_t val); 47 | extern void setUint32(uint8_t* pos, uint32_t val); 48 | 49 | /*====================================== 50 | Class WdTimer 51 | ========================================*/ 52 | class WdTimer:public XTimer { 53 | public: 54 | WdTimer(void); 55 | int registerCallback(uint32_t sec, int (*proc)(void)); 56 | void refleshRegisterTable(); 57 | void start(void); 58 | void stop(void); 59 | bool wakeUp(void); 60 | 61 | private: 62 | MQ_TimerTbl *_timerTbls; 63 | uint8_t _timerCnt; 64 | bool _initFlg; 65 | }; 66 | 67 | 68 | /*====================================== 69 | Class MqttsnClientApplication 70 | ========================================*/ 71 | class MqttsnClientApplication{ 72 | public: 73 | MqttsnClientApplication(); 74 | ~MqttsnClientApplication(); 75 | void refleshWdtCallbackTable(); 76 | void initialize(APP_CONFIG config); 77 | void setSubscribe(); 78 | void setKeepAlive(uint16_t msec); 79 | void setWillTopic(MQString* willTopic); 80 | void setWillMessage(MQString* willMsg); 81 | void setRetain(bool retain); 82 | void setClean(bool clean); 83 | void setClientId(MQString* id); 84 | 85 | int publish(MQString* topic, const char* data, int dataLength, uint8_t qos = 1); 86 | int publish(uint16_t predefinedId, const char* data, int dataLength, uint8_t qos = 1); 87 | int publish(MQString* topic, Payload* payload, uint8_t qos); 88 | int subscribe(MQString* topic, TopicCallback callback, uint8_t qos = 1); 89 | int subscribe(uint16_t predefinedId, TopicCallback callback, uint8_t qos = 1); 90 | int unsubscribe(MQString* topic); 91 | int disconnect(uint16_t duration); 92 | 93 | void addTask(); 94 | void startWdt(); 95 | void stopWdt(); 96 | int run(); 97 | 98 | 99 | private: 100 | MqttsnClient _mqttsn; 101 | WdTimer _wdTimer; 102 | XTimer _keepAliveTimer; 103 | XTimer _advertiseTimer; 104 | 105 | }; 106 | 107 | extern MqttsnClientApplication* theApplication; 108 | 109 | 110 | 111 | #else 112 | 113 | #endif /*LINUX*/ 114 | 115 | 116 | 117 | 118 | #endif /* MQTTSCLIENTAPPLICATION_H_ */ 119 | 120 | 121 | -------------------------------------------------------------------------------- /Client/src/lib/udpStack.h: -------------------------------------------------------------------------------- 1 | /* 2 | * udpStack.h 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 2014/09/05 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 1.0.0 34 | */ 35 | 36 | #ifndef UDPSTACK_H_ 37 | #define UDPSTACK_H_ 38 | 39 | #ifdef ARDUINO 40 | #include 41 | #include 42 | #include 43 | #else 44 | #include "MQTTSN_Application.h" 45 | #include "mqUtil.h" 46 | #include "Network.h" 47 | #endif 48 | 49 | #ifdef NETWORK_UDP 50 | 51 | #ifdef ARDUINO 52 | #include 53 | #include 54 | #include 55 | #if ARDUINO >= 100 56 | #include "Arduino.h" 57 | #include 58 | #else 59 | #if ARDUINO < 100 60 | #include "WProgram.h" 61 | #include 62 | #endif 63 | #endif 64 | #endif /* ARDUINO */ 65 | 66 | 67 | #ifdef MBED 68 | #include "mbed.h" 69 | #endif 70 | 71 | #ifdef LINUX 72 | #include 73 | #include 74 | #include 75 | #include 76 | #include 77 | #include 78 | #include 79 | #include 80 | #include 81 | #endif 82 | 83 | #define STAT_UNICAST 1 84 | #define STAT_MULTICAST 2 85 | 86 | #define SOCKET_MAXHOSTNAME 200 87 | #define SOCKET_MAXCONNECTIONS 5 88 | #define SOCKET_MAXRECV 500 89 | #define SOCKET_MAXBUFFER_LENGTH 500 // buffer size 90 | 91 | #define PACKET_TIMEOUT_CHECK 200 // msec 92 | 93 | using namespace std; 94 | 95 | namespace tomyClient { 96 | 97 | /*============================================ 98 | NWAddress64 99 | =============================================*/ 100 | class NWAddress64 { 101 | public: 102 | NWAddress64(uint32_t msb, uint32_t lsb); 103 | NWAddress64(void); 104 | uint32_t getMsb(); 105 | uint32_t getLsb(); 106 | void setMsb(uint32_t msb); 107 | void setLsb(uint32_t lsb); 108 | private: 109 | uint32_t _msb; 110 | uint32_t _lsb; 111 | }; 112 | 113 | /*============================================ 114 | NWResponse 115 | =============================================*/ 116 | 117 | class NWResponse { 118 | public: 119 | NWResponse(); 120 | bool isAvailable(); 121 | uint8_t isError(); 122 | uint8_t getType(); 123 | uint8_t getFrameLength(); 124 | uint8_t getPayload(uint8_t index); 125 | uint8_t* getPayload(); 126 | uint8_t* getBody(); 127 | uint16_t getBodyLength(); 128 | uint8_t getPayloadLength(); 129 | uint16_t getAddress16(); 130 | NWAddress64& getAddress64(); 131 | void setLength(uint16_t len); 132 | // void setType(uint8_t type); 133 | void setFrame(uint8_t* framePtr); 134 | void setAddress64(uint32_t msb, uint32_t ipAddress); 135 | void setAddress16(uint16_t portNo); 136 | void setErrorCode(uint8_t); 137 | void setAvailable(bool); 138 | void resetResponse(); 139 | private: 140 | NWAddress64 _addr64; 141 | uint16_t _addr16; 142 | uint16_t _len; 143 | uint8_t* _frameDataPtr; 144 | uint8_t _type; 145 | uint8_t _errorCode; 146 | bool _complete; 147 | }; 148 | 149 | 150 | /*======================================== 151 | Class UpdPort 152 | =======================================*/ 153 | class UdpPort{ 154 | public: 155 | UdpPort(); 156 | virtual ~UdpPort(); 157 | 158 | bool open(NETWORK_CONFIG config); 159 | 160 | int unicast(const uint8_t* buf, uint32_t length, uint32_t ipaddress, uint16_t port ); 161 | int multicast( const uint8_t* buf, uint32_t length ); 162 | int recv(uint8_t* buf, uint16_t len, bool nonblock, uint32_t* ipaddress, uint16_t* port ); 163 | int recv(uint8_t* buf, uint16_t len, int flags); 164 | bool checkRecvBuf(); 165 | bool isUnicast(); 166 | 167 | private: 168 | void close(); 169 | int recvfrom ( uint8_t* buf, uint16_t len, int flags, uint32_t* ipaddress, uint16_t* port ); 170 | 171 | #ifdef LINUX 172 | int _sockfdUcast; 173 | int _sockfdMcast; 174 | uint16_t _gPortNo; 175 | uint16_t _uPortNo; 176 | uint32_t _gIpAddr; 177 | uint8_t _castStat; 178 | #endif 179 | #ifdef ARDUINO 180 | EthernetUDP _udpUnicast; 181 | EthernetUDP _udpMulticast; 182 | IPAddress _gIpAddr; 183 | IPAddress _cIpAddr; 184 | uint16_t _gPortNo; 185 | uint16_t _uPortNo; 186 | uint8_t* _macAddr; 187 | uint8_t _castStat; 188 | #endif 189 | 190 | bool _disconReq; 191 | 192 | }; 193 | 194 | #define NO_ERROR 0 195 | #define PACKET_EXCEEDS_LENGTH 1 196 | /*=========================================== 197 | Class Network 198 | ============================================*/ 199 | class Network : public UdpPort { 200 | public: 201 | Network(); 202 | ~Network(); 203 | 204 | void send(uint8_t* xmitData, uint8_t dataLen, SendReqType type); 205 | int readPacket(uint8_t type = 0); 206 | void setGwAddress(); 207 | void resetGwAddress(void); 208 | void setRxHandler(void (*callbackPtr)(NWResponse* data, int* returnCode)); 209 | void setSleep(); 210 | int initialize(UdpConfig config); 211 | private: 212 | int readApiFrame(); 213 | 214 | NWResponse _nlResp; 215 | uint32_t _gwIpAddress; 216 | uint16_t _gwPortNo; 217 | int _returnCode; 218 | bool _sleepflg; 219 | void (*_rxCallbackPtr)(NWResponse* data, int* returnCode); 220 | uint8_t _rxFrameDataBuf[MQTTSN_MAX_FRAME_SIZE]; 221 | 222 | }; 223 | 224 | 225 | } /* end of namespace */ 226 | 227 | #endif 228 | #endif /* UDPSTACK_H__ */ 229 | -------------------------------------------------------------------------------- /Client/src/mbedClientSample.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * mbedClientSample.cpp 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | 36 | #include "lib/MQTTSN_Application.h" 37 | 38 | #ifdef MBED 39 | #include "lib/mqttsnClientAppFw4mbed.h" 40 | 41 | using namespace std; 42 | using namespace tomyClient; 43 | 44 | /*============================================ 45 | * 46 | * MQTT-SN Client Application for mbed 47 | * 48 | *===========================================*/ 49 | XBEE_APP_CONFIG = { 50 | { 51 | 9600, //Baudrate (bps) 52 | 0, //Serial PortNo 53 | 0 //Device (for linux App) 54 | }, 55 | { 56 | "Node01", //NodeId 57 | 300, //KeepAlive (sec) 58 | false, //Clean session 59 | false, //EndDevice 60 | "willTopic", //WillTopic or 0 DO NOT USE 0 STRING! 61 | "willMessage" //WillMessage or 0 DO NOT USE 0 STRING! 62 | } 63 | }; 64 | /*------------------------------------------------------ 65 | * Create Topic 66 | *------------------------------------------------------*/ 67 | MQString* topic1 = new MQString("dev/indicator"); 68 | 69 | 70 | /*------------------------------------------------------ 71 | * Tasks invoked by Timer 72 | *------------------------------------------------------*/ 73 | bool led_flg = false; 74 | 75 | int task1(){ 76 | if(led_flg){ 77 | PUBLISH(topic1, "off", 3, QOS1); 78 | led_flg = false; 79 | }else{ 80 | PUBLISH(topic1, "on", 2, QOS1); 81 | led_flg = true; 82 | } 83 | return 0; 84 | } 85 | 86 | /*--------- Link Tasks to the Application ----------*/ 87 | TASK_LIST = { 88 | {task1, 60}, 89 | END_OF_TASK_LIST}; 90 | 91 | /*------------------------------------------------------ 92 | * Tasks invoked by PUBLISH command Packet 93 | *------------------------------------------------------*/ 94 | DigitalOut indicator(LED1); 95 | 96 | int blinkIndicator(MqttsnPublish* msg){ 97 | 98 | if( !strncmp("on", (const char*)msg->getData(),2)){ 99 | indicator = 1; 100 | }else if( !strncmp("off", (const char*)msg->getData(),3)){ 101 | indicator = 0; 102 | } 103 | return 0; 104 | } 105 | /*-------------- Link Tasks to Topic -------------------*/ 106 | SUBSCRIBE_LIST = { 107 | {topic1, blinkIndicator, QOS1}, 108 | END_OF_SUBSCRIBE_LIST}; 109 | 110 | /*================================================== 111 | * Application setup 112 | *=================================================*/ 113 | void setup(){ 114 | // nop 115 | } 116 | 117 | #endif 118 | 119 | 120 | -------------------------------------------------------------------------------- /Gateway/Makefile: -------------------------------------------------------------------------------- 1 | PROGNAME := TomyGateway 2 | SRCDIR := src 3 | SUBDIR := src/lib 4 | 5 | SRCS := $(SRCDIR)/TomyGateway.cpp \ 6 | $(SRCDIR)/BrokerRecvTask.cpp \ 7 | $(SRCDIR)/BrokerSendTask.cpp \ 8 | $(SRCDIR)/ClientRecvTask.cpp \ 9 | $(SRCDIR)/ClientSendTask.cpp \ 10 | $(SRCDIR)/GatewayControlTask.cpp \ 11 | $(SRCDIR)/GatewayResourcesProvider.cpp \ 12 | $(SUBDIR)/ProcessFramework.cpp \ 13 | $(SUBDIR)/Messages.cpp \ 14 | $(SUBDIR)/TCPStack.cpp \ 15 | $(SUBDIR)/TLSStack.cpp \ 16 | $(SUBDIR)/Topics.cpp \ 17 | $(SUBDIR)/UDPStack.cpp \ 18 | $(SUBDIR)/XXXXXStack.cpp \ 19 | $(SUBDIR)/ZBStack.cpp 20 | 21 | CXX := g++ 22 | CPPFLAGS += 23 | DEFS := 24 | LDFLAGS += 25 | LIBS += 26 | #LDADD := -lpthread -lrt -lssl -lcrypto 27 | LDADD := -lpthread -lrt -lwiringPi -lssl -lcrypto 28 | 29 | CXXFLAGS := -Wall -O3 30 | 31 | OUTDIR := Build 32 | 33 | PROG := $(OUTDIR)/$(PROGNAME) 34 | OBJS := $(SRCS:%.cpp=$(OUTDIR)/%.o) 35 | DEPS := $(SRCS:%.cpp=$(OUTDIR)/%.d) 36 | 37 | .PHONY: install clean distclean 38 | 39 | all: $(PROG) 40 | 41 | -include $(DEPS) 42 | 43 | $(PROG): $(OBJS) 44 | $(CXX) $(LDFLAGS) -o $@ $^ $(LIBS) $(LDADD) 45 | 46 | $(OUTDIR)/%.o:%.cpp 47 | @if [ ! -e `dirname $@` ]; then mkdir -p `dirname $@`; fi 48 | $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(DEFS) -o $@ -c -MMD -MP -MF $(@:%.o=%.d) $< 49 | 50 | clean: 51 | rm -rf $(OUTDIR) 52 | 53 | install: 54 | cp -p $(PROG) ../../ 55 | -------------------------------------------------------------------------------- /Gateway/README.md: -------------------------------------------------------------------------------- 1 | MQTT-SN Gateway 2 | ====== 3 | This program is a Gateway over XBee and UDP. 4 | Select from the network layer in lib/Defines.h, shown in below. 5 | 6 | In case of UDP, Multicast is required for SEARCHGW and GWINFO messages. 7 | Client multicasts the SEARCHGW to find the gateway. 8 | Gateway multicasts the GWINFO from unicast port. 9 | Client can get the gateway IP and port using std::recvfrom() functions. 10 | 11 | If your client does not support SEARCHGW and GWINFO, you can skip the search gateway procedure. 12 | You can CONNECT to a portNo specified with -u parameter and Gateway's IP address directly. 13 | 14 | If you want to change to your own networkStack, i.e bluetooth, just modify the XXXXXXStack.cpp, .h 15 | and lib/Defines.h, ClientRecv.cpp, ClientSend.cpp files. Templates are built in already. 16 | 17 | Supported functions 18 | ------------------- 19 | 20 | * QOS Level 0, 1 and 2 21 | * CONNECT, WILLTOPICREQ, WILLTOPIC, WILLMSGREQ, WILLMSG 22 | * REGISTER, SUBSCRIBE, PUBLISH, UNSUBSCRIBE, DISCONNECT 23 | * CONNACK, REGACK, SUBACK, PUBACK, PUBREL, PUBCOMP, UNSUBACK 24 | * ADVERTIZE, GWINFO 25 | 26 | 27 | Usage 28 | ------ 29 | ####1) Minimum requirements 30 | * Linux ( Windows can not execute this program.) 31 | * pthread, rt liblaries to be linked. 32 | * wiringPi for Raspberry Pi (http://wiringpi.com/download-and-install/) 33 | * In case of XBee, Three XBee S2 (one coordinator, one gateway and one client.) 34 | * or two XBee S1 (Digimesh, one for gateway and another for client) 35 | 36 | ####2) How to Build 37 | for XBee DigiMesh 38 | $ make 39 | 40 | for UDP 41 | $ make DEFS=-DNETWORK_UDP 42 | 43 | Makefile is in Gateway directory. 44 | TomyGateway (Executable) is created in Build directory. 45 | 46 | $ make install 47 | TomyGateway is copied to the directory repo located. 48 | 49 | $ make clean 50 | remove the Build directory. 51 | 52 | ####3) Start Gateway 53 | Prepare parameter file /usr/local/etc/tomygateway/config/param.conf 54 | 55 | BrokerName=test.mosquitto.org 56 | BrokerPortNo=1883 57 | #LoginID= 58 | #Password= 59 | SerialDevice=/dev/ttyUSB0 60 | BaudRate=57600 61 | BroadcastIP=225.1.1.1 62 | GatewayPortNo=2000 63 | BroadcastPortNo=1883 64 | GatewayID=1 65 | KeepAlive=900 66 | 67 | Prepare Key files for semaphore and sheared memory. file's contents is emply. 68 | 69 | /usr/local/etc/tomygateway/config/rbmutex.key 70 | /usr/local/etc/tomygateway/config/ringbuffer.key 71 | /usr/local/etc/tomygateway/config/semaphore.key 72 | 73 | Execute 74 | $ TomyGateway 75 | 76 | 77 | 78 | XBee configurations 79 | ---------------------- 80 | Serial interfacing of gateway. 81 | Coordinator is default setting. 82 | 83 | [BD] 6 57600 bps 84 | [D7] 1 CTS-Flow Control 85 | [D6] 1 RTS-Flow Control 86 | [AP] 2 API Enable 87 | 88 | Other values are defaults. 89 | 90 | Gateway configurations 91 | ---------------------- 92 | lib/Defines.h 93 | 94 | /*================================= 95 | * CPU TYPE 96 | ==================================*/ 97 | #define CPU_LITTLEENDIANN 98 | //#define CPU_BIGENDIANN 99 | 100 | /*================================= 101 | * Debug LOG 102 | ==================================*/ 103 | //#define DEBUG_NWSTACK // show network layer transactions. 104 | 105 | Raspberry Pi SD card img file 106 | ---------------------- 107 | 108 | 1) Download from https://drive.google.com/a/tomy-tech.com/?tab=mo#folders/0ByWDD8Fur4QcMGpuRWd2RWVtMDA 109 | 2) unzip and copy to SD card 110 | 3) root's password is root 111 | 4) Login ID is "gw" and password is "gw". xxx.xxx... is IP address DHCP assigned. 112 | $ ssh xxx.xxx.xxx.xxx -l gw -p 22022 113 | 5) Download latest version from github & compile as follows 114 | 6) $ rm -rf MQTT-SN 115 | 7) $ git clone https://github.com/ty4tw/MQTT-SN.git 116 | 8) $ cd MQTT-SN/Gateway 117 | 9) $ make CXXFLAGS=-DRASPBERRY_PI 118 | or 119 | $ make CXXFLAGS=-DRASPBERRY_PI DEFS=-DNETWORK_UDP 120 | 10) $ make install 121 | 11) reboot 122 | 123 | 124 | 125 | How to connect XBee to Raspberry Pi 126 | ---------------------- 127 | XBee Vcc ---> Raspberry Pi Pin 1 128 | XBee Gnd ---> Raspberry Pi Pin 6 129 | XBee RX ---> Raspberry Pi Pin 8 130 | XBee TX ---> Raspberry Pi Pin 10 131 | 132 | 133 | How to connect Indicators and power off switch 134 | ---------------------- 135 | Green LED ---> Raspberry Pi Pin 16 (Broker connected) 136 | RED LED ---> Raspberry Pi Pin 18 (Broker disconnected) 137 | Blue LED ---> Raspberry Pi Pin 22 (Sending/Receiving) 138 | PWR Off SW ---> Raspberry Pi Pin 11 (shutdown safely) 139 | 140 | 141 | Pin 11 -----+-----/\/\/\/----- +Vcc 3.3V 142 | | 10K 143 | | 144 | |+ SW 145 | | 146 | | 147 | GND 148 | 149 | 150 | How to monitor the Gateway 151 | ---------------------- 152 | $ sudo /home/gw/LogMonitor 153 | 154 | 155 | 156 | 157 | 158 | 159 | 160 | 161 | 162 | -------------------------------------------------------------------------------- /Gateway/src/BrokerRecvTask.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * BrokerRecvTask.cpp 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | 36 | #include "BrokerRecvTask.h" 37 | #include "GatewayResourcesProvider.h" 38 | #include "GatewayDefines.h" 39 | #include "lib/ProcessFramework.h" 40 | #include "lib/Messages.h" 41 | #include 42 | #include 43 | #include 44 | #include 45 | 46 | extern char* currentDateTime(); 47 | 48 | 49 | BrokerRecvTask::BrokerRecvTask(GatewayResourcesProvider* res){ 50 | _res = res; 51 | _res->attach(this); 52 | _stableNetwork = true; 53 | } 54 | 55 | BrokerRecvTask::~BrokerRecvTask(){ 56 | 57 | } 58 | 59 | 60 | void BrokerRecvTask::run(){ 61 | char param[TOMYFRAME_PARAM_MAX]; 62 | if(_res->getParam("NetworkIsStable",param) == 0){ 63 | if(!strcasecmp(param, "NO")){ 64 | _stableNetwork = false; 65 | } 66 | } 67 | 68 | struct timeval timeout; 69 | 70 | LightIndicator* lightIndicator = _res->getLightIndicator(); 71 | ClientList* clist = _res->getClientList(); 72 | fd_set rset; 73 | fd_set wset; 74 | 75 | while(true){ 76 | timeout.tv_sec = 0; 77 | timeout.tv_usec = 500000; // 500 msec 78 | FD_ZERO(&rset); 79 | FD_ZERO(&wset); 80 | int maxSock = 0; 81 | int sockfd = 0; 82 | 83 | /*------- Prepare socket list to check -------*/ 84 | for( int i = 0; i < clist->getClientCount(); i++){ 85 | if((*clist)[i]){ 86 | if((*clist)[i]->getStack()->isValid()){ 87 | sockfd = (*clist)[i]->getStack()->getSock(); 88 | FD_SET(sockfd, &rset); 89 | FD_SET(sockfd, &wset); 90 | if(sockfd > maxSock){ 91 | maxSock = sockfd; 92 | } 93 | } 94 | }else{ 95 | break; 96 | } 97 | } 98 | 99 | if(maxSock == 0){ 100 | lightIndicator->greenLight(false); 101 | }else{ 102 | 103 | /*------- Check socket to receive -------*/ 104 | int activity = select( maxSock + 1 , &rset , 0 , 0 , &timeout); 105 | 106 | if (activity > 0){ 107 | for( int i = 0; i < clist->getClientCount(); i++){ 108 | if((*clist)[i]){ 109 | if((*clist)[i]->getStack()->isValid()){ 110 | int sockfd = (*clist)[i]->getStack()->getSock(); 111 | if(FD_ISSET(sockfd, &rset)){ 112 | recvAndFireEvent((*clist)[i]); 113 | lightIndicator->greenLight(true); 114 | } 115 | } 116 | }else{ 117 | break; 118 | } 119 | } 120 | } 121 | } 122 | } 123 | } 124 | 125 | 126 | /*----------------------------------------- 127 | Recv socket & Create MQTT Messages 128 | -----------------------------------------*/ 129 | void BrokerRecvTask::recvAndFireEvent(ClientNode* clnode){ 130 | 131 | uint8_t sbuff[SOCKET_MAXBUFFER_LENGTH * 5]; 132 | uint8_t buffer[SOCKET_MAXBUFFER_LENGTH]; 133 | memset(buffer, 0, SOCKET_MAXBUFFER_LENGTH); 134 | int recvLength = 0; 135 | uint8_t* packet = buffer; 136 | 137 | recvLength = clnode->getStack()->recv(packet,SOCKET_MAXBUFFER_LENGTH); 138 | 139 | if (recvLength == -1){ 140 | LOGWRITE(" Client : %s Error: BrokerRecvTask can't Receive data from Broker\n", clnode->getNodeId()->c_str()); 141 | clnode->disconnected(); 142 | } 143 | 144 | while(recvLength > 0){ 145 | 146 | if((*packet & 0xf0) == MQTT_TYPE_PUBACK){ 147 | MQTTPubAck* puback = new MQTTPubAck(); 148 | puback->deserialize(packet); 149 | puback->serialize(sbuff); 150 | LOGWRITE(BLUE_FORMAT1, currentDateTime(), "PUBACK", LEFTARROW, BROKER, msgPrint(sbuff, puback)); 151 | 152 | clnode->setBrokerRecvMessage(puback); 153 | }else if((*packet & 0xf0) == MQTT_TYPE_PUBREC){ 154 | MQTTPubRec* pubRec = new MQTTPubRec(); 155 | pubRec->deserialize(packet); 156 | pubRec->serialize(sbuff); 157 | LOGWRITE(BLUE_FORMAT1, currentDateTime(), "PUBREC", LEFTARROW, BROKER, msgPrint(sbuff, pubRec)); 158 | 159 | clnode->setBrokerRecvMessage(pubRec); 160 | 161 | }else if((*packet & 0xf0) == MQTT_TYPE_PUBREL){ 162 | MQTTPubRel* pubRel = new MQTTPubRel(); 163 | pubRel->deserialize(packet); 164 | pubRel->serialize(sbuff); 165 | LOGWRITE(BLUE_FORMAT1, currentDateTime(), "PUBREL", LEFTARROW, BROKER, msgPrint(sbuff, pubRel)); 166 | 167 | clnode->setBrokerRecvMessage(pubRel); 168 | 169 | }else if((*packet & 0xf0) == MQTT_TYPE_PUBCOMP){ 170 | MQTTPubComp* pubComp = new MQTTPubComp(); 171 | pubComp->deserialize(packet); 172 | pubComp->serialize(sbuff); 173 | LOGWRITE(BLUE_FORMAT1, currentDateTime(), "PUBCOMP", LEFTARROW, BROKER, msgPrint(sbuff, pubComp)); 174 | 175 | clnode->setBrokerRecvMessage(pubComp); 176 | 177 | }else if((*packet & 0xf0) == MQTT_TYPE_PUBLISH){ 178 | MQTTPublish* publish = new MQTTPublish(); 179 | if(!publish->deserialize(packet)){ 180 | clnode->disconnected(); 181 | clnode->getStack()->disconnect(); 182 | LOGWRITE("%s ill-formed UTF-8\n",currentDateTime()); 183 | } 184 | publish->serialize(sbuff); 185 | LOGWRITE(GREEN_FORMAT2, currentDateTime(), "PUBLISH", LEFTARROW, BROKER, msgPrint(sbuff, publish)); 186 | 187 | clnode->setBrokerRecvMessage(publish); 188 | 189 | }else if((*packet & 0xf0) == MQTT_TYPE_SUBACK){ 190 | MQTTSubAck* suback = new MQTTSubAck(); 191 | suback->deserialize(packet); 192 | suback->serialize(sbuff); 193 | LOGWRITE(FORMAT1, currentDateTime(), "SUBACK", LEFTARROW, BROKER, msgPrint(sbuff, suback)); 194 | 195 | clnode->setBrokerRecvMessage(suback); 196 | 197 | }else if((*packet & 0xf0) == MQTT_TYPE_PINGRESP){ 198 | MQTTPingResp* pingresp = new MQTTPingResp(); 199 | pingresp->deserialize(packet); 200 | pingresp->serialize(sbuff); 201 | LOGWRITE(FORMAT1, currentDateTime(), "PINGRESP", LEFTARROW, BROKER, msgPrint(sbuff, pingresp)); 202 | 203 | clnode->setBrokerRecvMessage(pingresp); 204 | 205 | }else if((*packet & 0xf0) == MQTT_TYPE_UNSUBACK){ 206 | MQTTUnsubAck* unsuback = new MQTTUnsubAck(); 207 | unsuback->deserialize(packet); 208 | unsuback->serialize(sbuff); 209 | LOGWRITE(FORMAT1, currentDateTime(), "UNSUBACK", LEFTARROW, BROKER, msgPrint(sbuff, unsuback)); 210 | 211 | clnode->setBrokerRecvMessage(unsuback); 212 | 213 | }else if((*packet & 0xf0) == MQTT_TYPE_CONNACK){ 214 | MQTTConnAck* connack = new MQTTConnAck(); 215 | connack->deserialize(packet); 216 | connack->serialize(sbuff); 217 | LOGWRITE(CYAN_FORMAT1, currentDateTime(), "CONNACK", LEFTARROW, BROKER, msgPrint(sbuff, connack)); 218 | 219 | clnode->setBrokerRecvMessage(connack); 220 | 221 | }else{ 222 | LOGWRITE("%s UNKOWN_TYPE packetLength=%d\n",currentDateTime(), recvLength); 223 | return; 224 | } 225 | 226 | Event* ev = new Event(); 227 | ev->setBrokerRecvEvent(clnode); 228 | _res->getGatewayEventQue()->post(ev); 229 | 230 | RemainingLength rl; 231 | rl.deserialize(packet + 1); 232 | uint16_t packetLength = 1 + rl.getSize() + rl.decode(); 233 | recvLength -= packetLength; 234 | packet += packetLength; 235 | } 236 | } 237 | 238 | 239 | char* BrokerRecvTask::msgPrint(uint8_t* buffer, MQTTMessage* msg){ 240 | char* buf = _printBuf; 241 | 242 | _res->getLightIndicator()->blueLight(true); 243 | 244 | sprintf(buf, " %02X", *buffer); 245 | buf += 3; 246 | 247 | for(int i = 0; i < msg->getRemainLength() + msg->getRemainLengthSize(); i++){ 248 | sprintf(buf, " %02X", *( buffer + 1 + i)); 249 | buf += 3; 250 | } 251 | *buf = 0; 252 | _res->getLightIndicator()->blueLight(false); 253 | return _printBuf; 254 | } 255 | -------------------------------------------------------------------------------- /Gateway/src/BrokerRecvTask.h: -------------------------------------------------------------------------------- 1 | /* 2 | * BrokerRecvTask.h 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | 36 | #ifndef BROKERRECVTASK_H_ 37 | #define BROKERRECVTASK_H_ 38 | 39 | #include "lib/ProcessFramework.h" 40 | #include "lib/Messages.h" 41 | #include "GatewayResourcesProvider.h" 42 | 43 | 44 | class BrokerRecvTask : public Thread{ 45 | MAGIC_WORD_FOR_TASK; 46 | public: 47 | BrokerRecvTask(GatewayResourcesProvider* res); 48 | ~BrokerRecvTask(); 49 | void initialize(); 50 | void run(); 51 | char* msgPrint(uint8_t* buf, MQTTMessage* msg); 52 | 53 | private: 54 | void recvAndFireEvent(ClientNode*); 55 | GatewayResourcesProvider* _res; 56 | char _printBuf[SOCKET_MAXBUFFER_LENGTH * 5]; 57 | bool _stableNetwork; 58 | }; 59 | 60 | 61 | #endif /* BROKERRECVTASK_H_ */ 62 | -------------------------------------------------------------------------------- /Gateway/src/BrokerSendTask.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * BrokerSendTask.cpp 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | 36 | #include "BrokerSendTask.h" 37 | #include "GatewayResourcesProvider.h" 38 | #include "GatewayDefines.h" 39 | #include "lib/ProcessFramework.h" 40 | #include "lib/Messages.h" 41 | #include "lib/Defines.h" 42 | #include 43 | #include 44 | #include 45 | #include 46 | #include 47 | 48 | extern char* currentDateTime(); 49 | 50 | 51 | BrokerSendTask::BrokerSendTask(GatewayResourcesProvider* res){ 52 | _res = res; 53 | _res->attach(this); 54 | } 55 | 56 | BrokerSendTask::~BrokerSendTask(){ 57 | if(_host){ 58 | delete _host; 59 | } 60 | if(_service){ 61 | delete _service; 62 | } 63 | } 64 | 65 | void BrokerSendTask::run(){ 66 | Event* ev = 0; 67 | MQTTMessage* srcMsg = 0; 68 | ClientNode* clnode = 0; 69 | char param[TOMYFRAME_PARAM_MAX]; 70 | 71 | if(_res->getParam("BrokerName",param) == 0){ 72 | _host = strdup(param); 73 | } 74 | if(_res->getParam("BrokerPortNo",param) == 0){ 75 | _service =strdup( param); 76 | } 77 | _light = _res->getLightIndicator(); 78 | 79 | 80 | while(true){ 81 | 82 | uint16_t length = 0; 83 | memset(_buffer, 0, SOCKET_MAXBUFFER_LENGTH); 84 | 85 | ev = _res->getBrokerSendQue()->wait(); 86 | 87 | clnode = ev->getClientNode(); 88 | srcMsg = clnode->getBrokerSendMessage(); 89 | 90 | if(srcMsg->getType() == MQTT_TYPE_PUBLISH){ 91 | MQTTPublish* msg = static_cast(srcMsg); 92 | length = msg->serialize(_buffer); 93 | LOGWRITE(BLUE_FORMAT, currentDateTime(), "PUBLISH", RIGHTARROW, GREEN_BROKER, msgPrint(msg)); 94 | send(clnode, length); 95 | 96 | }else if(srcMsg->getType() == MQTT_TYPE_PUBACK){ 97 | MQTTPubAck* msg = static_cast(srcMsg); 98 | length = msg->serialize(_buffer); 99 | LOGWRITE(GREEN_FORMAT, currentDateTime(), "PUBACK", RIGHTARROW, GREEN_BROKER, msgPrint(msg)); 100 | send(clnode, length); 101 | 102 | }else if(srcMsg->getType() == MQTT_TYPE_PUBREL){ 103 | MQTTPubRel* msg = static_cast(srcMsg); 104 | length = msg->serialize(_buffer); 105 | LOGWRITE(GREEN_FORMAT, currentDateTime(), "PUBREL", RIGHTARROW, GREEN_BROKER, msgPrint(msg)); 106 | send(clnode, length); 107 | 108 | }else if(srcMsg->getType() == MQTT_TYPE_PINGREQ){ 109 | MQTTPingReq* msg = static_cast(srcMsg); 110 | length = msg->serialize(_buffer); 111 | LOGWRITE(FORMAT, currentDateTime(), "PINGREQ", RIGHTARROW, GREEN_BROKER, msgPrint(msg)); 112 | send(clnode, length); 113 | 114 | }else if(srcMsg->getType() == MQTT_TYPE_SUBSCRIBE){ 115 | MQTTSubscribe* msg = static_cast(srcMsg); 116 | length = msg->serialize(_buffer); 117 | LOGWRITE(FORMAT, currentDateTime(), "SUBSCRIBE", RIGHTARROW, GREEN_BROKER, msgPrint(msg)); 118 | send(clnode, length); 119 | 120 | }else if(srcMsg->getType() == MQTT_TYPE_UNSUBSCRIBE){ 121 | MQTTUnsubscribe* msg = static_cast(srcMsg); 122 | length = msg->serialize(_buffer); 123 | LOGWRITE(FORMAT, currentDateTime(), "UNSUBSCRIBE", RIGHTARROW, GREEN_BROKER, msgPrint(msg)); 124 | send(clnode, length); 125 | 126 | }else if(srcMsg->getType() == MQTT_TYPE_CONNECT){ 127 | MQTTConnect* msg = static_cast(srcMsg); 128 | length = msg->serialize(_buffer); 129 | LOGWRITE(FORMAT, currentDateTime(), "CONNECT", RIGHTARROW, GREEN_BROKER, msgPrint(msg)); 130 | clnode->connectSended(); 131 | send(clnode, length); 132 | 133 | }else if(srcMsg->getType() == MQTT_TYPE_DISCONNECT){ 134 | MQTTDisconnect* msg = static_cast(srcMsg); 135 | length = msg->serialize(_buffer); 136 | LOGWRITE(FORMAT, currentDateTime(), "DISCONNECT", RIGHTARROW, GREEN_BROKER, msgPrint(msg)); 137 | send(clnode, length); 138 | 139 | clnode->getStack()->disconnect(); 140 | } 141 | 142 | delete ev; 143 | } 144 | } 145 | 146 | 147 | int BrokerSendTask::send(ClientNode* clnode, int length){ 148 | int rc = -1; 149 | 150 | if(length <= 0){ 151 | return rc; 152 | } 153 | 154 | if( clnode->getStack()->isValid()){ 155 | rc = clnode->getStack()->send(_buffer, length); 156 | if(rc != length){ 157 | LOGWRITE("\n%s \x1b[0m\x1b[31merror:\x1b[0m\x1b[37m Can't Xmit to the Broker. errno=%d\n", currentDateTime(), rc == -1 ? errno : 0); 158 | clnode->getStack()->disconnect(); 159 | clnode->disconnected(); 160 | }else{ 161 | _light->greenLight(true); 162 | } 163 | }else{ 164 | if(clnode->getStack()->connect(_host, _service)){ 165 | rc = clnode->getStack()->send(_buffer, length); 166 | if(rc != length){ 167 | LOGWRITE("\n%s \x1b[0m\x1b[31merror:\x1b[0m\x1b[37m Can't Xmit to the Broker. errno=%d\n", currentDateTime(), rc == -1 ? errno : 0); 168 | clnode->getStack()->disconnect(); 169 | clnode->disconnected(); 170 | }else{ 171 | _light->greenLight(true); 172 | } 173 | }else{ 174 | LOGWRITE("\n%s \x1b[0m\x1b[31merror:\x1b[0m\x1b[37m Can't connect to the Broker.\n", currentDateTime()); 175 | clnode->getStack()->disconnect(); 176 | clnode->disconnected(); 177 | } 178 | } 179 | return rc; 180 | } 181 | 182 | char* BrokerSendTask::msgPrint(MQTTMessage* msg){ 183 | char* buf = _printBuf; 184 | _light->blueLight(true); 185 | 186 | sprintf(buf, " %02X", *_buffer); 187 | buf += 3; 188 | 189 | for(int i = 0; i < msg->getRemainLength() + msg->getRemainLengthSize(); i++){ 190 | sprintf(buf, " %02X", *( _buffer + 1 + i)); 191 | buf += 3; 192 | } 193 | *buf = 0; 194 | _light->blueLight(false); 195 | return _printBuf; 196 | } 197 | 198 | -------------------------------------------------------------------------------- /Gateway/src/BrokerSendTask.h: -------------------------------------------------------------------------------- 1 | /* 2 | * BrokerSendTask.h 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | 36 | #ifndef BROKERSENDTASK_H_ 37 | #define BROKERSENDTASK_H_ 38 | 39 | #include "lib/ProcessFramework.h" 40 | #include "lib/Messages.h" 41 | #include "GatewayResourcesProvider.h" 42 | 43 | class BrokerSendTask : public Thread{ 44 | MAGIC_WORD_FOR_TASK; 45 | public: 46 | BrokerSendTask(GatewayResourcesProvider* res); 47 | ~BrokerSendTask(); 48 | void run(); 49 | 50 | private: 51 | char* msgPrint(MQTTMessage* msg); 52 | int send(ClientNode* clnode, int length); 53 | 54 | GatewayResourcesProvider* _res; 55 | char _printBuf[SOCKET_MAXBUFFER_LENGTH * 5]; 56 | uint8_t _buffer[SOCKET_MAXBUFFER_LENGTH]; 57 | const char* _host; 58 | const char* _service; 59 | LightIndicator* _light; 60 | }; 61 | 62 | 63 | #endif /* BROKERSENDTASK_H_ */ 64 | -------------------------------------------------------------------------------- /Gateway/src/ClientRecvTask.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * ClientRecvTask.cpp 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | #include "ClientRecvTask.h" 36 | #include "GatewayResourcesProvider.h" 37 | #include "GatewayDefines.h" 38 | #include "lib/ProcessFramework.h" 39 | #include "lib/Messages.h" 40 | #include "lib/ZBStack.h" 41 | #include "ErrorMessage.h" 42 | 43 | 44 | #include 45 | #include 46 | #include 47 | #include 48 | #include 49 | #include 50 | 51 | extern char* currentDateTime(); 52 | 53 | ClientRecvTask::ClientRecvTask(GatewayResourcesProvider* res){ 54 | _res = res; 55 | _res->attach(this); 56 | } 57 | 58 | ClientRecvTask::~ClientRecvTask(){ 59 | 60 | } 61 | 62 | 63 | 64 | void ClientRecvTask::run(){ 65 | NETWORK_CONFIG config; 66 | char param[TOMYFRAME_PARAM_MAX]; 67 | bool secure = false; // TCP 68 | 69 | #ifdef NETWORK_XBEE 70 | 71 | if(_res->getParam("BaudRate",param) == 0){ 72 | 73 | int val = atoi(param); 74 | switch(val){ 75 | case 9600: 76 | config.baudrate = B9600; 77 | break; 78 | case 19200: 79 | config.baudrate =B19200; 80 | break; 81 | case 38400: 82 | config.baudrate =B38400; 83 | break; 84 | case 57600: 85 | config.baudrate =B57600; 86 | break; 87 | case 115200: 88 | config.baudrate = B115200; 89 | break; 90 | default: 91 | THROW_EXCEPTION(ExFatal, ERRNO_APL_01, "Invalid baud rate!"); // ABORT 92 | } 93 | }else{ 94 | config.baudrate = B57600; 95 | } 96 | config.flag = O_RDONLY; 97 | if(_res->getParam("SerialDevice",param) == 0){ 98 | config.device = strdup(param); 99 | } 100 | 101 | if(_res->getParam("SecureConnection",param) == 0){ 102 | if(!strcasecmp(param, "YES")){ 103 | secure = true; // TLS 104 | } 105 | } 106 | 107 | _res->getClientList()->authorize(FILE_NAME_CLIENT_LIST, secure); 108 | _network = new Network(); 109 | 110 | #endif 111 | 112 | #ifdef NETWORK_UDP 113 | if(_res->getParam("BroadcastIP", param) == 0){ 114 | config.ipAddress = strdup(param); 115 | } 116 | if(_res->getParam("BroadcastPortNo",param) == 0){ 117 | config.gPortNo = atoi(param); 118 | } 119 | if(_res->getParam("GatewayPortNo",param) == 0){ 120 | config.uPortNo = atoi(param); 121 | } 122 | _network = _res->getNetwork(); 123 | #endif 124 | 125 | #ifdef NETWORK_XXXXX 126 | _network = _res->getNetwork(); 127 | #endif 128 | if(_network->initialize(config) < 0){ 129 | THROW_EXCEPTION(ExFatal, ERRNO_APL_01, "can't open the client port."); // ABORT 130 | } 131 | 132 | while(true){ 133 | 134 | NWResponse* resp = new NWResponse(); 135 | bool eventSetFlg = true; 136 | 137 | if(_network->getResponse(resp)){ 138 | Event* ev = new Event(); 139 | ClientNode* clnode = _res->getClientList()->getClient(resp->getClientAddress64(), 140 | resp->getClientAddress16()); 141 | 142 | if(!clnode){ 143 | if(resp->getMsgType() == MQTTSN_TYPE_CONNECT){ 144 | 145 | #ifdef NETWORK_XBEE 146 | ClientNode* node = _res->getClientList()->createNode(secure, resp->getClientAddress64(),0); 147 | #endif 148 | #ifdef NETWORK_UDP 149 | ClientNode* node = _res->getClientList()->createNode(secure, resp->getClientAddress64(), 150 | resp->getClientAddress16()); 151 | #endif 152 | #ifdef NETWORK_XXXXX 153 | ClientNode* node = _res->getClientList()->createNode(secure, resp->getClientAddress64(), 154 | resp->getClientAddress16()); 155 | #endif 156 | 157 | if(!node){ 158 | delete ev; 159 | LOGWRITE("Client is not authorized.\n"); 160 | continue; 161 | } 162 | 163 | MQTTSnConnect* msg = new MQTTSnConnect(); 164 | msg->absorb(resp); 165 | node->setClientAddress16(resp->getClientAddress16()); 166 | if(msg->getClientId()->size() > 0){ 167 | node->setNodeId(msg->getClientId()); 168 | } 169 | node->setClientRecvMessage(msg); 170 | ev->setClientRecvEvent(node); 171 | }else if(resp->getMsgType() == MQTTSN_TYPE_SEARCHGW){ 172 | MQTTSnSearchGw* msg = new MQTTSnSearchGw(); 173 | msg->absorb(resp); 174 | ev->setEvent(msg); 175 | 176 | }else{ 177 | eventSetFlg = false; 178 | } 179 | }else{ 180 | if (resp->getMsgType() == MQTTSN_TYPE_CONNECT){ 181 | MQTTSnConnect* msg = new MQTTSnConnect(); 182 | msg->absorb(resp); 183 | clnode->setClientRecvMessage(msg); 184 | clnode->setClientAddress16(resp->getClientAddress16()); 185 | ev->setClientRecvEvent(clnode); 186 | 187 | }else if(resp->getMsgType() == MQTTSN_TYPE_PUBLISH){ 188 | MQTTSnPublish* msg = new MQTTSnPublish(); 189 | msg->absorb(resp); 190 | clnode->setClientRecvMessage(msg); 191 | ev->setClientRecvEvent(clnode); 192 | 193 | }else if(resp->getMsgType() == MQTTSN_TYPE_PUBACK){ 194 | MQTTSnPubAck* msg = new MQTTSnPubAck(); 195 | msg->absorb(resp); 196 | clnode->setClientRecvMessage(msg); 197 | ev->setClientRecvEvent(clnode); 198 | 199 | }else if(resp->getMsgType() == MQTTSN_TYPE_PUBREL){ 200 | MQTTSnPubRel* msg = new MQTTSnPubRel(); 201 | msg->absorb(resp); 202 | clnode->setClientRecvMessage(msg); 203 | ev->setClientRecvEvent(clnode); 204 | 205 | }else if (resp->getMsgType() == MQTTSN_TYPE_CONNECT){ 206 | MQTTSnConnect* msg = new MQTTSnConnect(); 207 | msg->absorb(resp); 208 | clnode->setClientRecvMessage(msg); 209 | ev->setClientRecvEvent(clnode); 210 | 211 | }else if (resp->getMsgType() == MQTTSN_TYPE_PINGREQ){ 212 | MQTTSnPingReq* msg = new MQTTSnPingReq(); 213 | msg->absorb(resp); 214 | clnode->setClientRecvMessage(msg); 215 | ev->setClientRecvEvent(clnode); 216 | 217 | }else if (resp->getMsgType() == MQTTSN_TYPE_DISCONNECT){ 218 | MQTTSnDisconnect* msg = new MQTTSnDisconnect(); 219 | msg->absorb(resp); 220 | clnode->setClientRecvMessage(msg); 221 | ev->setClientRecvEvent(clnode); 222 | 223 | }else if (resp->getMsgType() == MQTTSN_TYPE_REGISTER){ 224 | MQTTSnRegister* msg = new MQTTSnRegister(); 225 | msg->absorb(resp); 226 | clnode->setClientRecvMessage(msg); 227 | ev->setClientRecvEvent(clnode); 228 | 229 | }else if (resp->getMsgType() == MQTTSN_TYPE_REGACK){ 230 | MQTTSnRegAck* msg = new MQTTSnRegAck(); 231 | msg->absorb(resp); 232 | clnode->setClientRecvMessage(msg); 233 | ev->setClientRecvEvent(clnode); 234 | 235 | }else if (resp->getMsgType() == MQTTSN_TYPE_UNSUBSCRIBE){ 236 | MQTTSnUnsubscribe* msg = new MQTTSnUnsubscribe(); 237 | msg->absorb(resp); 238 | clnode->setClientRecvMessage(msg); 239 | ev->setClientRecvEvent(clnode); 240 | 241 | }else if (resp->getMsgType() == MQTTSN_TYPE_SUBSCRIBE){ 242 | MQTTSnSubscribe* msg = new MQTTSnSubscribe(); 243 | msg->absorb(resp); 244 | clnode->setClientRecvMessage(msg); 245 | ev->setClientRecvEvent(clnode); 246 | 247 | }else if (resp->getMsgType() == MQTTSN_TYPE_WILLTOPIC){ 248 | MQTTSnWillTopic* msg = new MQTTSnWillTopic(); 249 | msg->absorb(resp); 250 | clnode->setClientRecvMessage(msg); 251 | ev->setClientRecvEvent(clnode); 252 | 253 | }else if (resp->getMsgType() == MQTTSN_TYPE_WILLMSG){ 254 | MQTTSnWillMsg* msg = new MQTTSnWillMsg(); 255 | msg->absorb(resp); 256 | clnode->setClientRecvMessage(msg); 257 | ev->setClientRecvEvent(clnode); 258 | 259 | }else if(resp->getMsgType() == MQTTSN_TYPE_SEARCHGW){ 260 | MQTTSnSearchGw* msg = new MQTTSnSearchGw(); 261 | clnode->disconnected(); 262 | msg->absorb(resp); 263 | ev->setEvent(msg); 264 | }else{ 265 | eventSetFlg = false; 266 | } 267 | } 268 | if(eventSetFlg){ 269 | _res->getGatewayEventQue()->post(ev); 270 | }else{ 271 | delete ev; 272 | } 273 | } 274 | delete resp; 275 | } 276 | } 277 | 278 | 279 | 280 | 281 | 282 | -------------------------------------------------------------------------------- /Gateway/src/ClientRecvTask.h: -------------------------------------------------------------------------------- 1 | /* 2 | * ClientRecvTask.h 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | #ifndef CLIENTRECVTASK_H_ 36 | #define CLIENTRECVTASK_H_ 37 | 38 | #include "lib/ProcessFramework.h" 39 | #include "GatewayResourcesProvider.h" 40 | 41 | /*===================================== 42 | Class ClientRecvTask 43 | =====================================*/ 44 | class ClientRecvTask:public Thread{ 45 | MAGIC_WORD_FOR_TASK; 46 | public: 47 | ClientRecvTask(GatewayResourcesProvider*); 48 | ~ClientRecvTask(); 49 | void run(); 50 | 51 | private: 52 | GatewayResourcesProvider* _res; 53 | Network* _network; 54 | }; 55 | 56 | 57 | #endif /* CLIENTRECVTASK_H_ */ 58 | 59 | 60 | -------------------------------------------------------------------------------- /Gateway/src/ClientSendTask.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * ClientSendTask.cpp 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | #include "ClientSendTask.h" 36 | #include "GatewayResourcesProvider.h" 37 | #include "lib/ProcessFramework.h" 38 | #include "lib/Messages.h" 39 | #include "ErrorMessage.h" 40 | 41 | #include 42 | #include 43 | #include 44 | #include 45 | #include 46 | #include 47 | 48 | 49 | ClientSendTask::ClientSendTask(GatewayResourcesProvider* res){ 50 | _res = res; 51 | _res->attach(this); 52 | } 53 | 54 | ClientSendTask::~ClientSendTask(){ 55 | 56 | } 57 | 58 | 59 | void ClientSendTask::run(){ 60 | NETWORK_CONFIG config; 61 | #ifdef NETWORK_XBEE 62 | 63 | char param[TOMYFRAME_PARAM_MAX]; 64 | bool secure = true; 65 | 66 | if(_res->getParam("BaudRate",param) == 0){ 67 | 68 | int val = atoi(param); 69 | switch(val){ 70 | case 9600: 71 | config.baudrate = B9600; 72 | break; 73 | case 19200: 74 | config.baudrate =B19200; 75 | break; 76 | case 38400: 77 | config.baudrate =B38400; 78 | break; 79 | case 57600: 80 | config.baudrate =B57600; 81 | break; 82 | case 115200: 83 | config.baudrate = B115200; 84 | break; 85 | default: 86 | THROW_EXCEPTION(ExFatal, ERRNO_APL_01, "Invalid baud rate!"); // ABORT 87 | } 88 | }else{ 89 | config.baudrate = B57600; 90 | } 91 | config.flag = O_WRONLY; 92 | if(_res->getParam("SerialDevice", param) == 0){ 93 | config.device = strdup(param); 94 | } 95 | if(_res->getParam("SecureConnection",param) == 0){ 96 | if(strcmp(param, "YES")){ 97 | secure = false; // TCP 98 | } 99 | } 100 | _res->getClientList()->authorize(FILE_NAME_CLIENT_LIST, secure); 101 | _network = new Network(); 102 | 103 | if(_network->initialize(config) < 0){ 104 | THROW_EXCEPTION(ExFatal, ERRNO_APL_01, "can't open the client port."); // ABORT 105 | } 106 | 107 | #endif 108 | 109 | #ifdef NETWORK_UDP 110 | _network = _res->getNetwork(); 111 | 112 | #endif 113 | 114 | #ifdef NETWORK_XXXXX 115 | _network = _res->getNetwork(); 116 | #endif 117 | 118 | 119 | while(true){ 120 | Event* ev = _res->getClientSendQue()->wait(); 121 | 122 | if(ev->getEventType() == EtClientSend){ 123 | MQTTSnMessage msg = MQTTSnMessage(); 124 | ClientNode* clnode = ev->getClientNode(); 125 | msg.absorb( clnode->getClientSendMessage() ); 126 | 127 | _network->unicast(clnode->getAddress64Ptr(), clnode->getAddress16(), 128 | msg.getMessagePtr(), msg.getMessageLength()); 129 | }else if(ev->getEventType() == EtBroadcast){ 130 | MQTTSnMessage msg = MQTTSnMessage(); 131 | msg.absorb( ev->getMqttSnMessage() ); 132 | _network->broadcast(msg.getMessagePtr(), msg.getMessageLength()); 133 | } 134 | delete ev; 135 | } 136 | } 137 | 138 | 139 | -------------------------------------------------------------------------------- /Gateway/src/ClientSendTask.h: -------------------------------------------------------------------------------- 1 | /* 2 | * ClientSendTask.h 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | #ifndef CLIENTSENDTASK_H_ 36 | #define CLIENTSENDTASK_H_ 37 | 38 | #include "lib/ProcessFramework.h" 39 | #include "GatewayResourcesProvider.h" 40 | 41 | class ClientSendTask:public Thread{ 42 | MAGIC_WORD_FOR_TASK; 43 | public: 44 | ClientSendTask(GatewayResourcesProvider* res); 45 | ~ClientSendTask(); 46 | 47 | void run(); 48 | 49 | private: 50 | GatewayResourcesProvider* _res; 51 | Network* _network; 52 | }; 53 | 54 | 55 | #endif /* CLIENTSENDTASK_H_ */ 56 | 57 | 58 | -------------------------------------------------------------------------------- /Gateway/src/ErrorMessage.h: -------------------------------------------------------------------------------- 1 | /* 2 | * ErrorMessage.h 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | 36 | #ifndef ERRORMESSAGE_H_ 37 | #define ERRORMESSAGE_H_ 38 | 39 | 40 | #define ERRNO_APL_01 1001 // can't open device. 41 | #define ERRNO_APL_02 1002 // Socket error 42 | #define ERRNO_APL_03 1003 // can't create a clientNode. 43 | #define ERRNO_APL_04 1004 // invalid GatewayId 44 | #define ERRNO_APL_05 1005 // KeepAliveTime is grater than 65536 Secs 45 | 46 | #endif /* ERRORMESSAGE_H_ */ 47 | -------------------------------------------------------------------------------- /Gateway/src/GatewayControlTask.h: -------------------------------------------------------------------------------- 1 | /* 2 | * GatewayControlTask.h 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | 36 | #ifndef GATEWAYCONTROLTASK_H_ 37 | #define GATEWAYCONTROLTASK_H_ 38 | 39 | #include "lib/ZBStack.h" 40 | #include "lib/ProcessFramework.h" 41 | #include "GatewayResourcesProvider.h" 42 | 43 | /*===================================== 44 | Class GatewayControlTask 45 | =====================================*/ 46 | class GatewayControlTask : public Thread{ 47 | MAGIC_WORD_FOR_TASK; 48 | public: 49 | GatewayControlTask(GatewayResourcesProvider* res); 50 | ~GatewayControlTask(); 51 | 52 | void run(); 53 | private: 54 | EventQue* _eventQue; 55 | GatewayResourcesProvider* _res; 56 | char _printBuf[512]; 57 | uint8_t _protocol; 58 | uint8_t _gatewayId; 59 | string _loginId; 60 | string _password; 61 | bool _secure; 62 | bool _stableNetwork; 63 | 64 | void handleClientMessage(Event*); 65 | void handleBrokerMessage(Event*); 66 | 67 | void handleSnPublish(Event* ev, ClientNode* clnode, MQTTSnMessage* msg); 68 | void handleSnSubscribe(Event* ev, ClientNode* clnode, MQTTSnMessage* msg); 69 | void handleSnUnsubscribe(Event* ev, ClientNode* clnode, MQTTSnMessage* msg); 70 | void handleSnPingReq(Event* ev, ClientNode* clnode, MQTTSnMessage* msg); 71 | void handleSnPubAck(Event* ev, ClientNode* clnode, MQTTSnMessage* msg); 72 | void handleSnConnect(Event* ev, ClientNode* clnode, MQTTSnMessage* msg); 73 | void handleSnWillTopic(Event* ev, ClientNode* clnode, MQTTSnMessage* msg); 74 | void handleSnWillMsg(Event* ev, ClientNode* clnode, MQTTSnMessage* msg); 75 | void handleSnDisconnect(Event* ev, ClientNode* clnode, MQTTSnMessage* msg); 76 | void handleSnRegister(Event* ev, ClientNode* clnode, MQTTSnMessage* msg); 77 | void handleSnPubRec(Event* ev, ClientNode* clnode, MQTTSnMessage* msg); 78 | void handleSnPubRel(Event* ev, ClientNode* clnode, MQTTSnMessage* msg); 79 | void handleSnPubComp(Event* ev, ClientNode* clnode, MQTTSnMessage* msg); 80 | 81 | void handlePuback(Event* ev, ClientNode* clnode, MQTTMessage* msg); 82 | void handlePingresp(Event* ev, ClientNode* clnode, MQTTMessage* msg); 83 | void handleSuback(Event* ev, ClientNode* clnode, MQTTMessage* msg); 84 | void handleUnsuback(Event* ev, ClientNode* clnode, MQTTMessage* msg); 85 | void handleConnack(Event* ev, ClientNode* clnode, MQTTMessage* msg); 86 | void handlePublish(Event* ev, ClientNode* clnode, MQTTMessage* msg); 87 | void handleDisconnect(Event* ev, ClientNode* clnode, MQTTMessage* msg); 88 | void handlePubRec(Event* ev, ClientNode* clnode, MQTTMessage* msg); 89 | void handlePubRel(Event* ev, ClientNode* clnode, MQTTMessage* msg); 90 | void handlePubComp(Event* ev, ClientNode* clnode, MQTTMessage* msg); 91 | char* msgPrint(MQTTSnMessage* msg); 92 | char* msgPrint(MQTTMessage* msg); 93 | }; 94 | 95 | #endif /* GATEWAYCONTROLTASK_H_ */ 96 | -------------------------------------------------------------------------------- /Gateway/src/GatewayDefines.h: -------------------------------------------------------------------------------- 1 | /* 2 | * GatewayDefines.h 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | 36 | #ifndef GATEWAYDEFINES_H_ 37 | #define GATEWAYDEFINES_H_ 38 | 39 | #define GATEWAY_VERSION "(Ver 1.1.7)" 40 | 41 | #define BROKER "Broker" 42 | #define GREEN_BROKER "\x1b[0m\x1b[32mBroker\x1b[0m\x1b[37m" 43 | #define GATEWAY "Gateway" 44 | #define CLIENT "Client" 45 | #define LEFTARROW "<---" 46 | #define RIGHTARROW "--->" 47 | 48 | #define FORMAT "%s %-14s%-8s%-44s%s\n" 49 | #define FORMAT1 "%s %-14s%-8s%-26s%s\n" 50 | #define FORMAT2 "\n%s %-14s%-8s%-26s%s\n" 51 | 52 | #define RED_FORMAT1 "%s \x1b[0m\x1b[31m%-14s%-8s%-44s\x1b[0m\x1b[37m%s\n" 53 | #define RED_FORMAT2 "\n%s \x1b[0m\x1b[31m%-14s%-8s%-26s\x1b[0m\x1b[37m%s\n" 54 | 55 | #define GREEN_FORMAT "%s \x1b[0m\x1b[32m%-14s%-8s%-44s\x1b[0m\x1b[37m%s\n" 56 | #define GREEN_FORMAT1 "%s \x1b[0m\x1b[32m%-14s%-8s%-26s\x1b[0m\x1b[37m%s\n" 57 | #define GREEN_FORMAT2 "\n%s \x1b[0m\x1b[32m%-14s%-8s%-26s\x1b[0m\x1b[37m%s\n" 58 | 59 | #define YELLOW_FORMAT1 "%s \x1b[0m\x1b[33m%-14s%-8s%-26s\x1b[0m\x1b[37m%s\n" 60 | #define YELLOW_FORMAT2 "\n%s \x1b[0m\x1b[33m%-14s%-8s%-26s\x1b[0m\x1b[37m%s\n" 61 | 62 | #define BLUE_FORMAT "%s \x1b[0m\x1b[34m%-14s%-8s%-44s\x1b[0m\x1b[37m%s\n" 63 | #define BLUE_FORMAT1 "%s \x1b[0m\x1b[34m%-14s%-8s%-26s\x1b[0m\x1b[37m%s\n" 64 | #define BLUE_FORMAT2 "\n%s \x1b[0m\x1b[34m%-14s%-8s%-26s\x1b[0m\x1b[37m%s\n" 65 | 66 | #define CYAN_FORMAT1 "%s \x1b[0m\x1b[36m%-14s%-8s%-26s\x1b[0m\x1b[37m%s\n" 67 | #define SYAN_FORMAT2 "\n%s \x1b[0m\x1b[36m%-14s%-8s%-26s\x1b[0m\x1b[37m%s\n" 68 | 69 | /*=========================================== 70 | * Gateway Control Constants 71 | ===========================================*/ 72 | 73 | #define BROKER_HOST_NAME "localhost" 74 | #define BROKER_PORT "1883" 75 | 76 | 77 | #define KEEP_ALIVE_TIME 900 // 900 sec = 15 min 78 | 79 | #define TIMEOUT_PERIOD 10 // 10 sec = 10 sec 80 | 81 | #define SEND_UNIXTIME_TIME 30 // 30sec after KEEP_ALIVE_TIME 82 | 83 | 84 | 85 | #define MAX_CLIENT_NODES 500 86 | 87 | /*========================================================== 88 | * Light Indicators 89 | ===========================================================*/ 90 | 91 | #define LIGHT_INDICATOR_GREEN 4 // RPi connector 16 92 | #define LIGHT_INDICATOR_RED 5 // RPi connector 18 93 | #define LIGHT_INDICATOR_BLUE 6 // RPi connector 22 94 | 95 | #endif /* GATEWAYDEFINES_H_ */ 96 | -------------------------------------------------------------------------------- /Gateway/src/GatewayResourcesProvider.h: -------------------------------------------------------------------------------- 1 | /* 2 | * GatewayResourcesProvider.h 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | 36 | #ifndef GATEWAY_RESOURCES_PROVIDER_H_ 37 | #define GATEWAY_RESOURCES_PROVIDER_H_ 38 | 39 | #include "lib/ProcessFramework.h" 40 | #include "lib/Messages.h" 41 | #include "lib/Topics.h" 42 | #include "lib/TLSStack.h" 43 | 44 | #define FILE_NAME_CLIENT_LIST "/usr/local/etc/tomygateway/config/clientList.conf" 45 | 46 | /*===================================== 47 | Class MessageQue 48 | =====================================*/ 49 | template class MessageQue{ 50 | public: 51 | MessageQue(); 52 | ~MessageQue(); 53 | T* getMessage(); 54 | void push(T*); 55 | void pop(); 56 | void clear(); 57 | private: 58 | queue _que; 59 | Mutex _mutex; 60 | }; 61 | 62 | 63 | enum ClientStatus { 64 | Cstat_Disconnected = 0, 65 | Cstat_TryConnecting, 66 | Cstat_Connecting, 67 | Cstat_Active, 68 | Cstat_Asleep, 69 | Cstat_Awake, 70 | Cstat_Lost 71 | }; 72 | 73 | /*===================================== 74 | Class ClientNode 75 | =====================================*/ 76 | class ClientNode{ 77 | public: 78 | ClientNode(); 79 | ClientNode(bool secure); 80 | ~ClientNode(); 81 | 82 | MQTTMessage* getBrokerSendMessage(); 83 | MQTTMessage* getBrokerRecvMessage(); 84 | MQTTSnMessage* getClientSendMessage(); 85 | MQTTSnMessage* getClientRecvMessage(); 86 | MQTTConnect* getConnectMessage(); 87 | MQTTSnPubAck* getWaitedPubAck(); 88 | MQTTSnSubAck* getWaitedSubAck(); 89 | MQTTSnMessage* getClientSleepMessage(); 90 | 91 | void setBrokerSendMessage(MQTTMessage*); 92 | void setBrokerRecvMessage(MQTTMessage*); 93 | void setClientSendMessage(MQTTSnMessage*); 94 | void setClientRecvMessage(MQTTSnMessage*); 95 | void setConnectMessage(MQTTConnect*); 96 | void setWaitedPubAck(MQTTSnPubAck* msg); 97 | void setWaitedSubAck(MQTTSnSubAck* msg); 98 | void setClientSleepMessage(MQTTSnMessage*); 99 | 100 | void deleteBrokerSendMessage(); 101 | void deleteBrokerRecvMessage(); 102 | void deleteClientSendMessage(); 103 | void deleteClientRecvMessage(); 104 | 105 | void checkTimeover(); 106 | void updateStatus(MQTTSnMessage*); 107 | void updateStatus(ClientStatus); 108 | void connectSended(); 109 | void connackSended(int rc); 110 | void connectQued(); 111 | void disconnected(); 112 | bool isConnectSendable(); 113 | uint16_t getNextMessageId(); 114 | uint8_t getNextSnMsgId(); 115 | Topics* getTopics(); 116 | 117 | TLSStack* getStack(); 118 | NWAddress64* getAddress64Ptr(); 119 | uint16_t getAddress16(); 120 | string* getNodeId(); 121 | void setMsb(uint32_t); 122 | void setLsb(uint32_t); 123 | void setClientAddress16(uint16_t addr); 124 | void setClientAddress64(NWAddress64* addr); 125 | void setTopics(Topics* topics); 126 | void setNodeId(string* id); 127 | int checkConnAck(MQTTSnConnack* msg); 128 | MQTTSnConnack* checkGetConnAck(); 129 | void setConnAckSaveFlg(); 130 | void setWaitWillMsgFlg(); 131 | bool isDisconnect(); 132 | bool isActive(); 133 | bool isSleep(); 134 | 135 | private: 136 | void setKeepAlive(MQTTSnMessage* msg); 137 | 138 | MessageQue _brokerSendMessageQue; 139 | MessageQue _brokerRecvMessageQue; 140 | MessageQue _clientSendMessageQue; 141 | MessageQue _clientRecvMessageQue; 142 | MessageQue _clientSleepMessageQue; 143 | 144 | MQTTConnect* _mqttConnect; 145 | 146 | MQTTSnPubAck* _waitedPubAck; 147 | MQTTSnSubAck* _waitedSubAck; 148 | 149 | uint16_t _msgId; 150 | uint8_t _snMsgId; 151 | Topics* _topics; 152 | ClientStatus _status; 153 | uint32_t _keepAliveMsec; 154 | Timer _keepAliveTimer; 155 | 156 | TLSStack* _stack; 157 | 158 | NWAddress64 _address64; 159 | uint16_t _address16; 160 | string _nodeId; 161 | bool _connAckSaveFlg; 162 | bool _waitWillMsgFlg; 163 | MQTTSnConnack* _connAck; 164 | 165 | }; 166 | 167 | /*===================================== 168 | Class ClientList 169 | =====================================*/ 170 | class ClientList{ 171 | public: 172 | ClientList(); 173 | ~ClientList(); 174 | void authorize(const char* fileName, bool secure); 175 | void erase(ClientNode*); 176 | ClientNode* getClient(NWAddress64* addr64, uint16_t addr16); 177 | ClientNode* createNode(bool secure, NWAddress64* addr64, uint16_t addr16, string* nodeId = 0); 178 | uint16_t getClientCount(); 179 | ClientNode* operator[](int); 180 | bool isAuthorized(); 181 | private: 182 | vector* _clientVector; 183 | Mutex _mutex; 184 | uint16_t _clientCnt; 185 | bool _authorize; 186 | }; 187 | 188 | /*===================================== 189 | Class Event 190 | ====================================*/ 191 | enum EventType{ 192 | Et_NA = 0, 193 | EtTimeout, 194 | 195 | EtBrokerSend, 196 | EtBrokerRecv, 197 | EtClientSend, 198 | EtClientRecv, 199 | EtBroadcast, 200 | EtSocketAlive 201 | }; 202 | 203 | class Event{ 204 | public: 205 | Event(); 206 | Event(EventType); 207 | ~Event(); 208 | EventType getEventType(); 209 | void setClientSendEvent(ClientNode*); 210 | void setBrokerSendEvent(ClientNode*); 211 | void setClientRecvEvent(ClientNode*); 212 | void setBrokerRecvEvent(ClientNode*); 213 | void setEvent(MQTTSnMessage*); 214 | void setTimeout(); 215 | ClientNode* getClientNode(); 216 | MQTTSnMessage* getMqttSnMessage(); 217 | private: 218 | EventType _eventType; 219 | ClientNode* _clientNode; 220 | MQTTSnMessage* _mqttSnMessage; 221 | }; 222 | 223 | /*===================================== 224 | Class LightIndicator 225 | =====================================*/ 226 | class LightIndicator{ 227 | public: 228 | LightIndicator(); 229 | ~LightIndicator(); 230 | void greenLight(bool); 231 | void blueLight(bool); 232 | void redLightOff(); 233 | private: 234 | void init(); 235 | void lit(int gpioNo, int onoff); 236 | bool _greenStatus; 237 | bool _blueStatus; 238 | bool _gpioAvailable; 239 | }; 240 | 241 | /*===================================== 242 | Class GatewayResourcesProvider 243 | =====================================*/ 244 | class GatewayResourcesProvider: public MultiTaskProcess{ 245 | public: 246 | GatewayResourcesProvider(); 247 | ~GatewayResourcesProvider(); 248 | 249 | EventQue* getGatewayEventQue(); 250 | EventQue* getClientSendQue(); 251 | EventQue* getBrokerSendQue(); 252 | ClientList* getClientList(); 253 | Network* getNetwork(); 254 | LightIndicator* getLightIndicator(); 255 | private: 256 | ClientList _clientList; 257 | EventQue _gatewayEventQue; 258 | EventQue _brokerSendQue; 259 | EventQue _clientSendQue; 260 | Network _network; 261 | LightIndicator _lightIndicator; 262 | }; 263 | 264 | 265 | 266 | /*===================================== 267 | Class MessageQue Implementation 268 | =====================================*/ 269 | template MessageQue::MessageQue(){ 270 | 271 | } 272 | 273 | template MessageQue::~MessageQue(){ 274 | clear(); 275 | } 276 | 277 | template T* MessageQue::getMessage(){ 278 | T* msg; 279 | if(!_que.empty()){ 280 | _mutex.lock(); 281 | msg = _que.front(); 282 | _mutex.unlock(); 283 | return msg; 284 | }else{ 285 | return 0; 286 | } 287 | } 288 | 289 | template void MessageQue::push(T* msg){ 290 | _mutex.lock(); 291 | _que.push(msg); 292 | _mutex.unlock(); 293 | } 294 | 295 | template void MessageQue::pop(){ 296 | if(!_que.empty()){ 297 | _mutex.lock(); 298 | delete _que.front(); 299 | _que.pop(); 300 | _mutex.unlock(); 301 | } 302 | } 303 | 304 | template void MessageQue::clear(){ 305 | _mutex.lock(); 306 | while(!_que.empty()){ 307 | delete _que.front(); 308 | _que.pop(); 309 | } 310 | _mutex.unlock(); 311 | } 312 | 313 | #endif /* GATEWAY_RESOURCES_PROVIDER_H_ */ 314 | -------------------------------------------------------------------------------- /Gateway/src/TomyGateway.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * A_ProgramStructure.cpp 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | 36 | #include "GatewayResourcesProvider.h" 37 | #include "ClientRecvTask.h" 38 | #include "ClientSendTask.h" 39 | #include "BrokerRecvTask.h" 40 | #include "BrokerSendTask.h" 41 | #include "GatewayControlTask.h" 42 | #include "lib/ProcessFramework.h" 43 | 44 | const char* theCmdlineParameter = "b:d:i:h:p:g:u:l:w:k:"; 45 | 46 | /************************************** 47 | * Gateway Application 48 | **************************************/ 49 | 50 | GatewayResourcesProvider gwR = GatewayResourcesProvider(); 51 | 52 | GatewayControlTask th0 = GatewayControlTask(&gwR); 53 | ClientRecvTask th1 = ClientRecvTask(&gwR); 54 | ClientSendTask th2 = ClientSendTask(&gwR); 55 | BrokerRecvTask th3 = BrokerRecvTask(&gwR); 56 | BrokerSendTask th4 = BrokerSendTask(&gwR); 57 | -------------------------------------------------------------------------------- /Gateway/src/lib/Defines.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Defines.h 3 | * The BSD License 4 | * 5 | * Copyright (c) 2014, tomoaki@tomy-tech.com 6 | * All rights reserved. 7 | * 8 | * Redistribution and use in source and binary forms, with or without modification, 9 | * are permitted provided that the following conditions are met: 10 | * 11 | * 1. Redistributions of source code must retain the above copyright notice, 12 | * this list of conditions and the following disclaimer. 13 | * 14 | * 2. Redistributions in binary form must reproduce the above copyright notice, 15 | * this list of conditions and the following disclaimer in the documentation 16 | * and/or other materials provided with the distribution. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 21 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 22 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 23 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 24 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 25 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 26 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 27 | * THE POSSIBILITY OF SUCH DAMAGE. 28 | * 29 | * Created on: 2014/06/01 30 | * Modified: 31 | * Author: Tomoaki YAMAGUCHI 32 | * Version: 0.0.0 33 | */ 34 | #ifndef DEFINES_H_ 35 | #define DEFINES_H_ 36 | 37 | /*================================= 38 | * Network Selection 39 | =================================*/ 40 | 41 | #if ! defined(NETWORK_UDP) && ! defined (NETWORK_XXXXX) 42 | #define NETWORK_XBEE 43 | #define GATEWAY_NETWORK "Network is XBee." 44 | #endif 45 | 46 | #ifdef NETWORK_UDP 47 | #define GATEWAY_NETWORK "Network is UDP." 48 | #endif 49 | 50 | #ifdef NETWORK_XXXXX 51 | #define GATEWAY_NETWORK "Network is XXXXX." 52 | #endif 53 | /*================================= 54 | * CPU TYPE 55 | ==================================*/ 56 | #define CPU_LITTLEENDIANN 57 | //#define CPU_BIGENDIANN 58 | 59 | /*================================= 60 | * Debug LOG 61 | ==================================*/ 62 | //#define DEBUG_NWSTACK 63 | 64 | /*================================= 65 | Debug Print functions 66 | ==================================*/ 67 | #ifdef DEBUG_NWSTACK 68 | #define D_NWSTACK(...) printf(__VA_ARGS__) 69 | #else 70 | #define D_NWSTACK(...) 71 | #endif 72 | 73 | /*================================= 74 | * Data Type 75 | ==================================*/ 76 | typedef unsigned char uint8_t; 77 | typedef unsigned short uint16_t; 78 | typedef unsigned int uint32_t; 79 | 80 | 81 | typedef struct { 82 | long baudrate; 83 | char* device; 84 | unsigned int flag; 85 | }XBeeConfig; 86 | 87 | typedef struct { 88 | char* ipAddress; 89 | uint16_t gPortNo; 90 | uint16_t uPortNo; 91 | }UdpConfig; 92 | 93 | typedef struct { 94 | uint8_t param1; 95 | uint16_t param2; 96 | uint16_t param3; 97 | }XXXXXConfig; 98 | 99 | #ifdef NETWORK_XBEE 100 | #define NETWORK_CONFIG XBeeConfig 101 | #endif 102 | 103 | #ifdef NETWORK_UDP 104 | #define NETWORK_CONFIG UdpConfig 105 | #endif 106 | 107 | #ifdef NETWORK_XXXXX 108 | #define NETWORK_CONFIG XXXXXConfig 109 | #endif 110 | 111 | #endif /* DEFINES_H_ */ 112 | -------------------------------------------------------------------------------- /Gateway/src/lib/TCPStack.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Socket.cpp 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | 36 | #include "Defines.h" 37 | #include "TCPStack.h" 38 | #include 39 | #include 40 | #include 41 | #include 42 | #include 43 | #include 44 | #include 45 | 46 | using namespace std; 47 | extern char* currentDateTime(); 48 | 49 | /*======================================== 50 | Class TCPStack 51 | =======================================*/ 52 | TCPStack::TCPStack(){ 53 | _addrinfo = 0; 54 | _disconReq = false; 55 | _sockfd = -1; 56 | } 57 | 58 | TCPStack::~TCPStack(){ 59 | if(_addrinfo){ 60 | freeaddrinfo(_addrinfo); 61 | } 62 | } 63 | 64 | bool TCPStack::isValid(){ 65 | if(_sockfd > 0){ 66 | if(_disconReq){ 67 | close(); 68 | _sem.post(); 69 | }else{ 70 | return true; 71 | } 72 | } 73 | return false; 74 | } 75 | 76 | void TCPStack::disconnect(){ 77 | if ( _sockfd > 0 ){ 78 | _disconReq = true; 79 | _sem.wait(); 80 | } 81 | } 82 | 83 | void TCPStack::close(){ 84 | if(_sockfd > 0){ 85 | ::close(_sockfd); 86 | _sockfd = -1; 87 | _disconReq = false; 88 | if(_addrinfo){ 89 | freeaddrinfo(_addrinfo); 90 | _addrinfo = 0; 91 | } 92 | } 93 | } 94 | 95 | bool TCPStack::bind ( const char* service ){ 96 | if(isValid()){ 97 | return false; 98 | } 99 | addrinfo hints; 100 | memset(&hints, 0, sizeof(addrinfo)); 101 | hints.ai_family = AF_INET; 102 | hints.ai_socktype = SOCK_STREAM; 103 | hints.ai_flags = AI_PASSIVE; 104 | 105 | if (_addrinfo){ 106 | freeaddrinfo(_addrinfo); 107 | } 108 | int err = getaddrinfo(0, service, &hints, &_addrinfo); 109 | if (err) { 110 | LOGWRITE("\n%s \x1b[0m\x1b[31merror:\x1b[0m\x1b[37mgetaddrinfo(): %s\n", currentDateTime(),gai_strerror(err)); 111 | return false; 112 | } 113 | 114 | _sockfd = socket(_addrinfo->ai_family, _addrinfo->ai_socktype, _addrinfo->ai_protocol); 115 | if (_sockfd < 0){ 116 | return false; 117 | } 118 | int on = 1; 119 | if ( setsockopt ( _sockfd, SOL_SOCKET, SO_REUSEADDR, ( const char* ) &on, sizeof ( on ) ) == -1 ){ 120 | return false; 121 | } 122 | 123 | if( ::bind ( _sockfd, _addrinfo->ai_addr, _addrinfo->ai_addrlen ) <0){ 124 | return false; 125 | } 126 | return true; 127 | } 128 | 129 | bool TCPStack::listen() { 130 | if ( !isValid() ){ 131 | return false; 132 | } 133 | int listen_return = ::listen ( _sockfd, SOCKET_MAXCONNECTIONS ); 134 | if ( listen_return == -1 ){ 135 | return false; 136 | } 137 | return true; 138 | } 139 | 140 | 141 | bool TCPStack::accept ( TCPStack& new_socket ){ 142 | sockaddr_storage sa; 143 | socklen_t len = sizeof ( sa ); 144 | new_socket._sockfd = ::accept ( _sockfd, (struct sockaddr*) &sa, &len ); 145 | if ( new_socket._sockfd <= 0 ){ 146 | return false; 147 | }else{ 148 | return true; 149 | } 150 | } 151 | 152 | int TCPStack::send (const uint8_t* buf, uint16_t length ){ 153 | return ::send ( _sockfd, buf, length, MSG_NOSIGNAL ); 154 | } 155 | 156 | int TCPStack::recv ( uint8_t* buf, uint16_t len ){ 157 | return ::recv ( _sockfd, buf, len, 0 ); 158 | } 159 | 160 | 161 | bool TCPStack::connect ( const char* host, const char* service ){ 162 | if(isValid()){ 163 | return false; 164 | } 165 | addrinfo hints; 166 | memset(&hints, 0, sizeof(addrinfo)); 167 | hints.ai_family = AF_INET; 168 | hints.ai_socktype = SOCK_STREAM; 169 | if (_addrinfo){ 170 | freeaddrinfo(_addrinfo); 171 | } 172 | 173 | int err = getaddrinfo(host, service, &hints, &_addrinfo); 174 | if (err) { 175 | LOGWRITE("\n%s \x1b[0m\x1b[31merror:\x1b[0m\x1b[37mgetaddrinfo(): %s\n", currentDateTime(),gai_strerror(err)); 176 | return false; 177 | } 178 | 179 | int sockfd = socket(_addrinfo->ai_family, _addrinfo->ai_socktype, _addrinfo->ai_protocol); 180 | 181 | if (sockfd < 0){ 182 | return false; 183 | } 184 | int on = 1; 185 | 186 | if ( setsockopt (sockfd, SOL_SOCKET, SO_REUSEADDR, ( const char* ) &on, sizeof ( on ) ) == -1 ){ 187 | return false; 188 | } 189 | 190 | if( ::connect (sockfd, _addrinfo->ai_addr, _addrinfo->ai_addrlen ) <0){ 191 | //perror("TCPStack connect"); 192 | ::close(sockfd); 193 | return false; 194 | } 195 | 196 | _sockfd = sockfd; 197 | return true; 198 | } 199 | 200 | void TCPStack::setNonBlocking ( const bool b ){ 201 | int opts; 202 | 203 | opts = fcntl ( _sockfd, F_GETFL ); 204 | 205 | if ( opts < 0 ){ 206 | return; 207 | } 208 | 209 | if ( b ){ 210 | opts = ( opts | O_NONBLOCK ); 211 | }else{ 212 | opts = ( opts & ~O_NONBLOCK ); 213 | } 214 | fcntl ( _sockfd, F_SETFL,opts ); 215 | } 216 | -------------------------------------------------------------------------------- /Gateway/src/lib/TCPStack.h: -------------------------------------------------------------------------------- 1 | /* 2 | * TCPStack.h 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | 36 | #ifndef TCPSTACK_H 37 | #define TCPSTACK_H 38 | 39 | 40 | #include 41 | #include 42 | #include 43 | #include 44 | #include 45 | #include 46 | #include 47 | #include "Defines.h" 48 | #include "Messages.h" 49 | 50 | #define SOCKET_MAXCONNECTIONS 5 51 | #define SOCKET_MAXBUFFER_LENGTH 1280 // buffer size 52 | 53 | using namespace std; 54 | 55 | /*======================================== 56 | Class TCPStack 57 | =======================================*/ 58 | class TCPStack{ 59 | public: 60 | TCPStack(); 61 | virtual ~TCPStack(); 62 | void disconnect(); 63 | 64 | // Server initialization 65 | bool bind( const char* service ); 66 | bool listen(); 67 | bool accept( TCPStack& ); 68 | 69 | // Client initialization 70 | bool connect( const char* host, const char* service ); 71 | 72 | int send( const uint8_t* buf, uint16_t length ); 73 | int recv ( uint8_t* buf, uint16_t len ); 74 | void close(); 75 | 76 | void setNonBlocking( const bool ); 77 | 78 | bool isValid(); 79 | int getSock(){return _sockfd;} 80 | private: 81 | int _sockfd; 82 | addrinfo* _addrinfo; 83 | Semaphore _sem; 84 | bool _disconReq; 85 | 86 | }; 87 | 88 | 89 | 90 | #endif /* TCPSTACK_H */ 91 | -------------------------------------------------------------------------------- /Gateway/src/lib/TLSStack.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * TLSStack.cpp 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | 36 | #include "Defines.h" 37 | #include "TLSStack.h" 38 | #include 39 | #include 40 | #include 41 | #include 42 | 43 | using namespace std; 44 | 45 | int TLSStack::_numOfInstance = 0; 46 | SSL_CTX* TLSStack::_ctx = 0; 47 | SSL_SESSION* TLSStack::_session = 0; 48 | 49 | /*======================================== 50 | Class TLSStack 51 | =======================================*/ 52 | TLSStack::TLSStack(){ 53 | TLSStack(true); 54 | } 55 | 56 | TLSStack::TLSStack(bool secure):TCPStack(){ 57 | char error[256]; 58 | if(secure){ 59 | _numOfInstance++; 60 | if(_ctx == 0){ 61 | SSL_load_error_strings(); 62 | SSL_library_init(); 63 | _ctx = SSL_CTX_new(TLSv1_2_client_method()); 64 | if(_ctx == 0){ 65 | ERR_error_string_n(ERR_get_error(), error, sizeof(error)); 66 | LOGWRITE("SSL_CTX_new() %s\n",error); 67 | THROW_EXCEPTION(ExFatal, ERRNO_SYS_01, "can't create SSL context."); 68 | } 69 | if(!SSL_CTX_load_verify_locations(_ctx, 0,TLS_CA_DIR)){ 70 | ERR_error_string_n(ERR_get_error(), error, sizeof(error)); 71 | LOGWRITE("SSL_CTX_load_verify_locations() %s\n",error); 72 | THROW_EXCEPTION(ExFatal, ERRNO_SYS_01, "can't load CA_LIST."); 73 | } 74 | } 75 | } 76 | _ssl = 0; 77 | _disconReq = false; 78 | _secureFlg = secure; 79 | _busy = false; 80 | } 81 | 82 | TLSStack::~TLSStack(){ 83 | if(_secureFlg){ 84 | _numOfInstance--; 85 | } 86 | if(_ssl){ 87 | SSL_free(_ssl); 88 | } 89 | if(_session && _numOfInstance == 0){ 90 | SSL_SESSION_free(_session); 91 | _session = 0; 92 | } 93 | if(_ctx && _numOfInstance == 0){ 94 | SSL_CTX_free(_ctx); 95 | _ctx = 0; 96 | ERR_free_strings(); 97 | } 98 | } 99 | 100 | bool TLSStack::connect ( const char* host, const char* service ){ 101 | char errmsg[256]; 102 | int rc = 0; 103 | char peer_CN[256]; 104 | SSL_SESSION* sess = 0; 105 | X509* peer; 106 | 107 | if(isValid()){ 108 | return false; 109 | } 110 | if(!TCPStack::connect(host, service)){ 111 | return false; 112 | } 113 | if(!_secureFlg){ 114 | return true; 115 | } 116 | 117 | SSL* ssl = SSL_new(_ctx); 118 | if(ssl == 0){ 119 | ERR_error_string_n(ERR_get_error(), errmsg, sizeof(errmsg)); 120 | LOGWRITE("SSL_new() %s\n",errmsg); 121 | return false; 122 | } 123 | 124 | rc = SSL_set_fd(ssl, TCPStack::getSock()); 125 | if(rc == 0){ 126 | SSL_free(ssl); 127 | return false; 128 | } 129 | 130 | if(_session){ 131 | rc = SSL_set_session(ssl, sess); 132 | }else{ 133 | rc = SSL_connect(ssl); 134 | } 135 | if(rc != 1){ 136 | ERR_error_string_n(ERR_get_error(), errmsg, sizeof(errmsg)); 137 | LOGWRITE("SSL_connect() %s\n",errmsg); 138 | SSL_free(ssl); 139 | return false; 140 | } 141 | 142 | if(SSL_get_verify_result(ssl) != X509_V_OK){ 143 | LOGWRITE("SSL_get_verify_result() error: Certificate doesn't verify.\n"); 144 | SSL_free(ssl); 145 | return false; 146 | } 147 | 148 | peer = SSL_get_peer_certificate(ssl); 149 | X509_NAME_get_text_by_NID(X509_get_subject_name(peer), NID_commonName, peer_CN, 256); 150 | if(strcasecmp(peer_CN, host)){ 151 | LOGWRITE("SSL_get_peer_certificate() error: Broker dosen't much host name.\n"); 152 | SSL_free(ssl); 153 | return false; 154 | } 155 | if(_session == 0){ 156 | _session = sess; 157 | } 158 | _ssl = ssl; 159 | return true; 160 | } 161 | 162 | 163 | int TLSStack::send (const uint8_t* buf, uint16_t length ){ 164 | char errmsg[256]; 165 | fd_set rset; 166 | fd_set wset; 167 | bool writeBlockedOnRead = false; 168 | int bpos = 0; 169 | 170 | if(_secureFlg){ 171 | _mutex.lock(); 172 | _busy = true; 173 | 174 | while(true){ 175 | FD_ZERO(&rset); 176 | FD_ZERO(&wset); 177 | FD_SET(getSock(), &rset); 178 | FD_SET(getSock(), &wset); 179 | 180 | int activity = select( getSock() + 1 , &rset , &wset , 0 , 0); 181 | if (activity > 0){ 182 | if(FD_ISSET(getSock(),&wset) || 183 | (writeBlockedOnRead && FD_ISSET(getSock(),&rset))){ 184 | 185 | writeBlockedOnRead = false; 186 | int r = SSL_write(_ssl, buf + bpos, length); 187 | 188 | switch(SSL_get_error(_ssl, r)){ 189 | case SSL_ERROR_NONE: 190 | length -= r; 191 | bpos += r; 192 | if( length == 0){ 193 | _busy = false; 194 | _mutex.unlock(); 195 | return bpos; 196 | } 197 | break; 198 | case SSL_ERROR_WANT_WRITE: 199 | break; 200 | case SSL_ERROR_WANT_READ: 201 | writeBlockedOnRead = true; 202 | break; 203 | default: 204 | ERR_error_string_n(ERR_get_error(), errmsg, sizeof(errmsg)); 205 | LOGWRITE("TLSStack::send() default %s\n",errmsg); 206 | _busy = false; 207 | _mutex.unlock(); 208 | return -1; 209 | } 210 | } 211 | } 212 | } 213 | }else{ 214 | return TCPStack::send (buf, length); 215 | } 216 | } 217 | 218 | 219 | int TLSStack::recv ( uint8_t* buf, uint16_t len ){ 220 | char errmsg[256]; 221 | bool writeBlockedOnRead = false; 222 | bool readBlockedOnWrite = false; 223 | bool readBlocked = false; 224 | int rlen = 0; 225 | int bpos = 0; 226 | fd_set rset; 227 | fd_set wset; 228 | 229 | 230 | if(_secureFlg){ 231 | if(_busy){ 232 | return 0; 233 | } 234 | _mutex.lock(); 235 | _busy = true; 236 | 237 | loop: 238 | do{ 239 | readBlockedOnWrite = false; 240 | readBlocked = false; 241 | 242 | rlen = SSL_read(_ssl, buf + bpos, len - bpos); 243 | 244 | switch (SSL_get_error(_ssl, rlen)){ 245 | case SSL_ERROR_NONE: 246 | _busy = false; 247 | _mutex.unlock(); 248 | return rlen + bpos; 249 | break; 250 | case SSL_ERROR_ZERO_RETURN: 251 | SSL_shutdown(_ssl); 252 | _ssl = 0; 253 | TCPStack::close(); 254 | _busy = false; 255 | _mutex.unlock(); 256 | return -1; 257 | break; 258 | case SSL_ERROR_WANT_READ: 259 | readBlocked = true; 260 | break; 261 | case SSL_ERROR_WANT_WRITE: 262 | readBlockedOnWrite = true; 263 | break; 264 | default: 265 | ERR_error_string_n(ERR_get_error(), errmsg, sizeof(errmsg)); 266 | LOGWRITE("TLSStack::recv() default %s\n", errmsg); 267 | _busy = false; 268 | _mutex.unlock(); 269 | return -1; 270 | } 271 | }while(SSL_pending(_ssl) && !readBlocked); 272 | 273 | bpos += rlen; 274 | while(true){ 275 | FD_ZERO(&rset); 276 | FD_ZERO(&wset); 277 | FD_SET(getSock(), &rset); 278 | FD_SET(getSock(), &wset); 279 | 280 | int activity = select( getSock() + 1 , &rset , &wset , 0 , 0); 281 | if (activity > 0){ 282 | if((FD_ISSET(getSock(),&rset) && !writeBlockedOnRead) || 283 | (readBlockedOnWrite && FD_ISSET(getSock(),&wset))){ 284 | goto loop; 285 | } 286 | }else{ 287 | ERR_error_string_n(ERR_get_error(), errmsg, sizeof(errmsg)); 288 | LOGWRITE("TLSStack::recv() select %s\n",errmsg); 289 | _busy = false; 290 | _mutex.unlock(); 291 | return -1; 292 | } 293 | } 294 | } 295 | return TCPStack::recv (buf, len); 296 | } 297 | 298 | 299 | bool TLSStack::isValid(){ 300 | if(!_secureFlg){ 301 | return TCPStack::isValid(); 302 | } 303 | if(_ssl){ 304 | if(_disconReq){ 305 | SSL_shutdown(_ssl); 306 | _ssl = 0; 307 | TCPStack::close(); 308 | _disconReq = false; 309 | }else{ 310 | return true; 311 | } 312 | } 313 | return false; 314 | } 315 | 316 | void TLSStack::disconnect(){ 317 | if (_ssl){ 318 | _disconReq = true; 319 | TCPStack::disconnect(); 320 | }else{ 321 | TCPStack::disconnect(); 322 | } 323 | } 324 | 325 | 326 | int TLSStack::getSock(){ 327 | return TCPStack::getSock(); 328 | } 329 | 330 | SSL* TLSStack::getSSL(){ 331 | if(_secureFlg){ 332 | return _ssl; 333 | }else{ 334 | return 0; 335 | } 336 | } 337 | 338 | bool TLSStack::isSecure(){ 339 | return _secureFlg; 340 | } 341 | -------------------------------------------------------------------------------- /Gateway/src/lib/TLSStack.h: -------------------------------------------------------------------------------- 1 | /* 2 | * TLSStack.h 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | 36 | #ifndef TLSSTACK_H 37 | #define TLSSTACK_H 38 | 39 | #include 40 | #include 41 | #include 42 | #include 43 | #include "Defines.h" 44 | #include "Messages.h" 45 | #include "TCPStack.h" 46 | 47 | #define TLS_CA_DIR "/etc/ssl/certs" 48 | 49 | using namespace std; 50 | 51 | /*======================================== 52 | Class TLSStack 53 | =======================================*/ 54 | class TLSStack:public TCPStack{ 55 | public: 56 | TLSStack(); 57 | TLSStack(bool secure); 58 | virtual ~TLSStack(); 59 | 60 | bool connect( const char* host, const char* service ); 61 | void disconnect(); 62 | int send( const uint8_t* buf, uint16_t length ); 63 | int recv ( uint8_t* buf, uint16_t len ); 64 | 65 | bool isValid(); 66 | bool isSecure(); 67 | int getSock(); 68 | SSL* getSSL(); 69 | private: 70 | static SSL_CTX* _ctx; 71 | static int _numOfInstance; 72 | static SSL_SESSION* _session; 73 | 74 | SSL* _ssl; 75 | bool _secureFlg; 76 | bool _disconReq; 77 | Mutex _mutex; 78 | bool _busy; 79 | }; 80 | 81 | 82 | 83 | #endif /* TLSSTACK_H */ 84 | -------------------------------------------------------------------------------- /Gateway/src/lib/Topics.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Topics.cpp 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | 36 | #include "Topics.h" 37 | #include "Messages.h" 38 | #include 39 | 40 | extern uint16_t getUint16(uint8_t* pos); 41 | 42 | /*===================================== 43 | Class Topic 44 | ======================================*/ 45 | Topic::Topic(){ 46 | _topicId = 0; 47 | } 48 | 49 | 50 | Topic::Topic(string topic){ 51 | _topicId = 0; 52 | _topicStr = topic; 53 | } 54 | 55 | 56 | Topic::~Topic(){ 57 | 58 | } 59 | 60 | uint16_t Topic::getTopicId(){ 61 | return _topicId; 62 | } 63 | 64 | string* Topic::getTopicName(){ 65 | return &_topicStr; 66 | } 67 | 68 | uint8_t Topic::getTopicLength(){ 69 | return (uint8_t)_topicStr.size(); 70 | } 71 | 72 | void Topic::setTopicId(uint16_t id){ 73 | _topicId = id; 74 | } 75 | 76 | 77 | void Topic::setTopicName(string topic){ 78 | _topicStr = topic; 79 | } 80 | 81 | 82 | uint8_t Topic::isWildCard(uint8_t* pos){ 83 | unsigned int p = _topicStr.find("MQTTSN_TOPIC_SINGLE_WILDCARD", 0); 84 | if( p != string::npos){ 85 | *pos = p; 86 | return MQTTSN_TOPIC_SINGLE_WILDCARD; 87 | }else{ 88 | p = _topicStr.find("MQTTSN_TOPIC_MULTI_WILDCARD", 0); 89 | if( p != string::npos){ 90 | *pos = p; 91 | return MQTTSN_TOPIC_MULTI_WILDCARD; 92 | } 93 | } 94 | *pos = 0; 95 | return 0; 96 | } 97 | 98 | bool Topic::isMatch(Topic* topic){ 99 | uint8_t pos; 100 | uint8_t pos1; 101 | 102 | if (topic->isWildCard(&pos) == MQTTSN_TOPIC_SINGLE_WILDCARD && 103 | (_topicStr.compare(0, (unsigned int)pos, (const string)*(topic->getTopicName()), 0, (unsigned int)pos) == 0 )){ 104 | pos1 = pos + 2; 105 | pos = _topicStr.find("/", ++pos); 106 | 107 | if(pos == string::npos ){ 108 | return true; 109 | }else{ 110 | if(_topicStr.substr(pos) == topic->getTopicName()->substr(pos1)){ 111 | return true; 112 | }else{ 113 | return false; 114 | } 115 | } 116 | 117 | }else if(topic->isWildCard(&pos) == MQTTSN_TOPIC_MULTI_WILDCARD && 118 | (_topicStr.compare(0, (unsigned int)pos, (const string)*(topic->getTopicName()), 0, (unsigned int)pos) == 0 )){ 119 | return true; 120 | } 121 | return false; 122 | } 123 | 124 | /*===================================== 125 | Class Topics 126 | ======================================*/ 127 | Topics::Topics(){ 128 | Topic* tp = new Topic(string(MQTTSN_TOPIC_PREDEFINED_TIME)); 129 | tp->setTopicId(MQTTSN_TOPICID_PREDEFINED_TIME); 130 | _topics.push_back(tp); 131 | _cnt = 1; 132 | _nextTopicId = MQTTSN_TOPICID_NORMAL; 133 | } 134 | 135 | Topics::~Topics() { 136 | for (uint8_t i = 0; i < _topics.size(); i++) { 137 | if(_topics[i]){ 138 | delete _topics[i]; 139 | } 140 | } 141 | } 142 | 143 | 144 | uint16_t Topics::getTopicId(string* topic){ 145 | Topic *p = getTopic(topic); 146 | if ( p != 0) { 147 | return p->getTopicId(); 148 | } 149 | return 0; 150 | } 151 | 152 | 153 | Topic* Topics::getTopic(string* topic) { 154 | for (uint8_t i = 0; i < _cnt; i++) { 155 | if(_topics[i]){ 156 | if( *topic == *(_topics[i]->getTopicName())){ 157 | return _topics[i]; 158 | } 159 | } 160 | } 161 | return 0; 162 | } 163 | 164 | Topic* Topics::getTopic(uint16_t id) { 165 | for (uint8_t i = 0; i < _cnt; i++) { 166 | if(_topics[i]){ 167 | if ( _topics[i]->getTopicId() == id) { 168 | return _topics[i]; 169 | } 170 | } 171 | } 172 | return 0; 173 | } 174 | 175 | 176 | uint16_t Topics::createTopic(string* topic){ 177 | if (!getTopic(topic)){ 178 | if ( _cnt < MAX_TOPIC_COUNT){ 179 | Topic* tp = new Topic(); 180 | tp->setTopicName(*topic); 181 | if(tp->getTopicLength() == 2){ 182 | uint16_t id = getUint16((uint8_t*)tp->getTopicName()); 183 | tp->setTopicId(id); 184 | }else{ 185 | tp->setTopicId(getNextTopicId()); 186 | } 187 | _topics.push_back(tp); 188 | _cnt++; 189 | return _nextTopicId; 190 | }else{ 191 | return 0; 192 | } 193 | }else{ 194 | return getTopicId(topic); 195 | } 196 | } 197 | 198 | uint16_t Topics::getNextTopicId(){ 199 | if(++_nextTopicId < MQTTSN_TOPICID_NORMAL){ 200 | _nextTopicId = MQTTSN_TOPICID_NORMAL; 201 | } 202 | return _nextTopicId; 203 | } 204 | 205 | Topic* Topics::match(string* topic){ 206 | uint8_t pos; 207 | 208 | for ( uint8_t i = 0; i< _cnt; i++){ 209 | if(_topics[i]){ 210 | if ( _topics[i]->isWildCard(&pos)){ 211 | if (getTopic(topic)->isMatch(_topics[i])){ 212 | return _topics[i]; 213 | } 214 | } 215 | } 216 | } 217 | return 0; 218 | } 219 | 220 | 221 | -------------------------------------------------------------------------------- /Gateway/src/lib/Topics.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Topics.h 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | 36 | #ifndef TOPICS_H_ 37 | #define TOPICS_H_ 38 | 39 | #include "ProcessFramework.h" 40 | #include "Messages.h" 41 | #include 42 | 43 | #define MQTTSN_TOPIC_MULTI_WILDCARD '#' 44 | #define MQTTSN_TOPIC_SINGLE_WILDCARD '+' 45 | 46 | #define MQTTSN_TOPICID_NORMAL 256 47 | #define MQTTSN_TOPICID_PREDEFINED_TIME 0x0001 48 | #define MQTTSN_TOPIC_PREDEFINED_TIME ("$GW/01") 49 | 50 | #define MAX_TOPIC_COUNT 50 // Number of Topic Par ClientNode 51 | 52 | /*===================================== 53 | Class Topic 54 | ======================================*/ 55 | 56 | class Topic { 57 | public: 58 | Topic(); 59 | Topic(string topic); 60 | ~Topic(); 61 | uint16_t getTopicId(); 62 | uint8_t getTopicLength(); 63 | string* getTopicName(); 64 | void setTopicId(uint16_t id); 65 | void setTopicName(string topic); 66 | 67 | uint8_t isWildCard(uint8_t* pos); 68 | bool isMatch(Topic* wildCard); 69 | private: 70 | uint16_t _topicId; 71 | string _topicStr; 72 | }; 73 | 74 | /*===================================== 75 | Class Topics 76 | ======================================*/ 77 | class Topics { 78 | public: 79 | Topics(); 80 | ~Topics(); 81 | uint16_t createTopic(string* topic); 82 | uint16_t getTopicId(string* topic); 83 | uint16_t getNextTopicId(); 84 | Topic* getTopic(string* topic); 85 | Topic* getTopic(uint16_t topicId); 86 | Topic* match(string* topic); 87 | bool deleteTopic(string* topic); 88 | 89 | private: 90 | uint16_t _nextTopicId; 91 | uint8_t _cnt; 92 | vector _topics; 93 | 94 | }; 95 | 96 | #endif /* TOPICS_H_ */ 97 | -------------------------------------------------------------------------------- /Gateway/src/lib/UDPStack.h: -------------------------------------------------------------------------------- 1 | /* 2 | * UDPStack.h 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | 36 | #ifndef UDPSTACK_H_ 37 | #define UDPSTACK_H_ 38 | 39 | #include "Defines.h" 40 | #ifdef NETWORK_UDP 41 | 42 | #include "ProcessFramework.h" 43 | #include 44 | #include 45 | #include 46 | #include 47 | #include 48 | #include 49 | #include 50 | #include 51 | #include 52 | 53 | /* 54 | * MQTTS Client's state 55 | */ 56 | #define MQTTS_DEVICE_DISCONNECTED 0 57 | #define MQTTS_DEVICE_ACTIVE 1 58 | #define MQTTS_DEVICE_ASLEEP 2 59 | #define MQTTS_DEVICE_AWAKE 3 60 | #define MQTTS_DEVICE_LOST 4 61 | 62 | #define MQTTSN_MAX_FRAME_SIZE 1024 63 | 64 | using namespace std; 65 | 66 | namespace tomyGateway{ 67 | /*============================================ 68 | NWAddress64 69 | =============================================*/ 70 | class NWAddress64 { 71 | public: 72 | NWAddress64(uint32_t msb, uint32_t lsb); 73 | NWAddress64(void); 74 | uint32_t getMsb(); 75 | uint32_t getLsb(); 76 | void setMsb(uint32_t msb); 77 | void setLsb(uint32_t lsb); 78 | bool operator==(NWAddress64&); 79 | private: 80 | uint32_t _msb; 81 | uint32_t _lsb; 82 | }; 83 | 84 | /*============================================ 85 | NWResponse 86 | =============================================*/ 87 | 88 | class NWResponse { 89 | public: 90 | NWResponse(); 91 | uint8_t getMsgType(); 92 | uint8_t getFrameLength(); 93 | uint8_t getPayload(uint8_t index); 94 | uint8_t* getPayloadPtr(); 95 | uint8_t* getBody(); 96 | uint16_t getBodyLength(); 97 | uint8_t getPayloadLength(); 98 | uint16_t getClientAddress16(); 99 | NWAddress64* getClientAddress64(); 100 | 101 | void setLength(uint16_t len); 102 | void setMsgType(uint8_t type); 103 | void setClientAddress64(uint32_t msb, uint32_t ipAddress); 104 | void setClientAddress16(uint16_t portNo); 105 | private: 106 | NWAddress64 _addr64; 107 | uint16_t _addr16; 108 | uint16_t _len; 109 | uint8_t _type; 110 | uint8_t _frameDataPtr[MQTTSN_MAX_FRAME_SIZE]; 111 | }; 112 | 113 | 114 | /*======================================== 115 | Class UpdPort 116 | =======================================*/ 117 | class UDPPort{ 118 | public: 119 | UDPPort(); 120 | virtual ~UDPPort(); 121 | 122 | int open(UdpConfig config); 123 | 124 | int unicast(const uint8_t* buf, uint32_t length, uint32_t ipaddress, uint16_t port ); 125 | int multicast( const uint8_t* buf, uint32_t length ); 126 | int recv(uint8_t* buf, uint16_t len, uint32_t* ipaddress, uint16_t* port ); 127 | 128 | private: 129 | void close(); 130 | void setNonBlocking( const bool ); 131 | int recvfrom (int sockfd, uint8_t* buf, uint16_t len, uint8_t flags, uint32_t* ipaddress, uint16_t* port ); 132 | 133 | int _sockfdUnicast; 134 | int _sockfdMulticast; 135 | 136 | uint16_t _gPortNo; 137 | uint32_t _gIpAddr; 138 | bool _disconReq; 139 | 140 | }; 141 | 142 | /*=========================================== 143 | Class Network 144 | ============================================*/ 145 | class Network:public UDPPort{ 146 | public: 147 | Network(); 148 | ~Network(); 149 | 150 | void unicast(NWAddress64* addr64, uint16_t addr16, uint8_t* payload, uint16_t payloadLength); 151 | void broadcast(uint8_t* payload, uint16_t payloadLength); 152 | bool getResponse(NWResponse* response); 153 | int initialize(UdpConfig config); 154 | 155 | private: 156 | 157 | }; 158 | 159 | 160 | } /* end of namespace */ 161 | 162 | #endif /* NETWORK_UDP */ 163 | #endif /* UDPSTACK_H_ */ 164 | -------------------------------------------------------------------------------- /Gateway/src/lib/XXXXXStack.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * XXXXXStack.cpp 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | 36 | #include "Defines.h" 37 | 38 | #ifdef NETWORK_XXXXX 39 | 40 | #include 41 | #include 42 | #include 43 | #include 44 | #include 45 | #include 46 | #include 47 | #include 48 | #include 49 | #include 50 | #include 51 | #include 52 | #include "ProcessFramework.h" 53 | #include "XXXXXStack.h" 54 | 55 | using namespace std; 56 | using namespace tomyGateway; 57 | 58 | extern uint16_t getUint16(uint8_t* pos); 59 | extern uint32_t getUint32(uint8_t* pos); 60 | extern void setUint16(uint8_t* pos, uint16_t val); 61 | extern void setUint32(uint8_t* pos, uint32_t val); 62 | 63 | /*========================================= 64 | Class Network 65 | =========================================*/ 66 | Network::Network(){ 67 | } 68 | 69 | Network::~Network(){ 70 | 71 | } 72 | 73 | void Network::unicast(NWAddress64* addr64, uint16_t addr16, uint8_t* payload, uint16_t payloadLength){ 74 | XXXXXPort::unicast( ); 75 | } 76 | 77 | void Network::broadcast(uint8_t* payload, uint16_t payloadLength){ 78 | XXXXXPort::multicast( ); 79 | } 80 | 81 | bool Network::getResponse(NWResponse* response){ 82 | 83 | } 84 | 85 | int Network::initialize(XXXXXConfig config){ 86 | return XXXXXPort::initialize(config); 87 | } 88 | 89 | 90 | /*========================================= 91 | Class XXXXXPort 92 | =========================================*/ 93 | 94 | XXXXXPort::XXXXXPort(){ 95 | 96 | 97 | } 98 | 99 | XXXXXPort::~XXXXXPort(){ 100 | close(); 101 | } 102 | 103 | void XXXXXPort::close(){ 104 | 105 | } 106 | 107 | int XXXXXPort::initialize(){ 108 | return initialize(_config); 109 | } 110 | 111 | int XXXXXPort::initialize(UdpConfig config){ 112 | 113 | _config.param1 = config.param1; 114 | _config.param2 = config.param2; 115 | _config.param3 = config.param3; 116 | 117 | 118 | } 119 | 120 | 121 | int XXXXXPort::unicast( ){ 122 | 123 | } 124 | 125 | int XXXXXPort::multicast(){ 126 | 127 | } 128 | 129 | int XXXXXPort::recv(){ 130 | 131 | } 132 | 133 | 134 | /*========================================= 135 | Class NLLongAddress 136 | =========================================*/ 137 | NWAddress64::NWAddress64(){ 138 | _msb = _lsb = 0; 139 | } 140 | 141 | NWAddress64::NWAddress64(uint32_t msb, uint32_t lsb){ 142 | _msb = msb; 143 | _lsb = lsb; 144 | } 145 | 146 | uint32_t NWAddress64::getMsb(){ 147 | return _msb; 148 | } 149 | 150 | uint32_t NWAddress64::getLsb(){ 151 | return _lsb; 152 | } 153 | 154 | void NWAddress64::setMsb(uint32_t msb){ 155 | _msb = msb; 156 | } 157 | 158 | void NWAddress64::setLsb(uint32_t lsb){ 159 | _lsb = lsb; 160 | } 161 | 162 | bool NWAddress64::operator==(NWAddress64& addr){ 163 | if(_msb == addr.getMsb() && _lsb == addr.getLsb()){ 164 | return true; 165 | }else{ 166 | return false; 167 | } 168 | } 169 | 170 | /*========================================= 171 | Class ZBResponse 172 | =========================================*/ 173 | NWResponse::NWResponse(){ 174 | _addr16 = 0; 175 | memset( _frameDataPtr, 0, MQTTSN_MAX_FRAME_SIZE); 176 | } 177 | 178 | uint8_t NWResponse::getFrameLength(){ 179 | return _len; 180 | } 181 | 182 | void NWResponse::setLength(uint16_t len){ 183 | _len = len; 184 | } 185 | 186 | NWAddress64* NWResponse::getClientAddress64(){ 187 | return &_addr64; 188 | } 189 | 190 | uint16_t NWResponse::getClientAddress16(){ 191 | return _addr16; 192 | } 193 | 194 | void NWResponse::setClientAddress64(uint32_t msb, uint32_t lsb){ 195 | _addr64.setMsb(msb); 196 | _addr64.setLsb(lsb); 197 | } 198 | 199 | void NWResponse::setClientAddress16(uint16_t addr16){ 200 | _addr16 = addr16; 201 | } 202 | 203 | void NWResponse::setMsgType(uint8_t type){ 204 | _type = type; 205 | } 206 | 207 | 208 | uint8_t NWResponse::getMsgType(){ 209 | if(_len > 255){ 210 | return _frameDataPtr[3]; 211 | }else{ 212 | return _frameDataPtr[1]; 213 | } 214 | } 215 | 216 | uint8_t* NWResponse::getBody(){ 217 | if(_len > 255){ 218 | return _frameDataPtr + 4; 219 | }else{ 220 | return _frameDataPtr + 2; 221 | } 222 | } 223 | 224 | uint16_t NWResponse::getBodyLength(){ 225 | if(_len > 255){ 226 | return getPayloadLength() - 4; 227 | }else{ 228 | return getPayloadLength() - 2; 229 | } 230 | } 231 | 232 | uint8_t NWResponse::getPayload(uint8_t index){ 233 | return _frameDataPtr[index + 2]; 234 | 235 | } 236 | 237 | uint8_t* NWResponse::getPayloadPtr(){ 238 | 239 | return _frameDataPtr; 240 | 241 | } 242 | 243 | uint8_t NWResponse::getPayloadLength(){ 244 | 245 | return _len; 246 | } 247 | 248 | #endif /* NETWORK_XXXXX */ 249 | -------------------------------------------------------------------------------- /Gateway/src/lib/XXXXXStack.h: -------------------------------------------------------------------------------- 1 | /* 2 | * UDPStack.h 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | 36 | #ifndef XXXXXSTACK_H_ 37 | #define XXXXXSTACK_H_ 38 | 39 | #include "Defines.h" 40 | #ifdef NETWORK_XXXXX 41 | 42 | #include "ProcessFramework.h" 43 | #include 44 | #include 45 | #include 46 | #include 47 | #include 48 | #include 49 | #include 50 | #include 51 | #include 52 | 53 | /* 54 | * MQTTS Client's state 55 | */ 56 | #define MQTTS_DEVICE_DISCONNECTED 0 57 | #define MQTTS_DEVICE_ACTIVE 1 58 | #define MQTTS_DEVICE_ASLEEP 2 59 | #define MQTTS_DEVICE_AWAKE 3 60 | #define MQTTS_DEVICE_LOST 4 61 | 62 | #define MQTTSN_MAX_FRAME_SIZE 1024 63 | 64 | using namespace std; 65 | 66 | namespace tomyGateway{ 67 | /*============================================ 68 | NWAddress64 69 | =============================================*/ 70 | class NWAddress64 { 71 | public: 72 | NWAddress64(uint32_t msb, uint32_t lsb); 73 | NWAddress64(void); 74 | uint32_t getMsb(); 75 | uint32_t getLsb(); 76 | void setMsb(uint32_t msb); 77 | void setLsb(uint32_t lsb); 78 | bool operator==(NWAddress64&); 79 | private: 80 | uint32_t _msb; 81 | uint32_t _lsb; 82 | }; 83 | 84 | /*============================================ 85 | NWResponse 86 | =============================================*/ 87 | 88 | class NWResponse { 89 | public: 90 | NWResponse(); 91 | uint8_t getMsgType(); 92 | uint8_t getFrameLength(); 93 | uint8_t getPayload(uint8_t index); 94 | uint8_t* getPayloadPtr(); 95 | uint8_t* getBody(); 96 | uint16_t getBodyLength(); 97 | uint8_t getPayloadLength(); 98 | uint16_t getClientAddress16(); 99 | NWAddress64* getClientAddress64(); 100 | 101 | void setLength(uint16_t len); 102 | void setMsgType(uint8_t type); 103 | void setClientAddress64(uint32_t msb, uint32_t ipAddress); 104 | void setClientAddress16(uint16_t portNo); 105 | private: 106 | NWAddress64 _addr64; 107 | uint16_t _addr16; 108 | uint16_t _len; 109 | uint8_t _type; 110 | uint8_t _frameDataPtr[MQTTSN_MAX_FRAME_SIZE]; 111 | }; 112 | 113 | 114 | /*======================================== 115 | Class XXXXXPort 116 | =======================================*/ 117 | class XXXXXPort{ 118 | public: 119 | XXXXXPort(); 120 | virtual ~XXXXXPort(); 121 | 122 | int initialize(XXXXXConfig config); 123 | int initialize(); 124 | 125 | int unicast( ); 126 | int multicast( ); 127 | int recv( ); 128 | 129 | private: 130 | void close(); 131 | 132 | XXXXXConfig _config; 133 | 134 | }; 135 | 136 | /*=========================================== 137 | Class Network 138 | ============================================*/ 139 | class Network:public XXXXXPort{ 140 | public: 141 | Network(); 142 | ~Network(); 143 | 144 | void unicast(NWAddress64* addr64, uint16_t addr16, uint8_t* payload, uint16_t payloadLength); 145 | void broadcast(uint8_t* payload, uint16_t payloadLength); 146 | bool getResponse(NWResponse* response); 147 | int initialize(XXXXXConfig config); 148 | 149 | private: 150 | 151 | }; 152 | 153 | 154 | } /* end of namespace */ 155 | 156 | #endif /* NETWORK_UDP */ 157 | #endif /* UDPSTACK_H_ */ 158 | -------------------------------------------------------------------------------- /Gateway/src/lib/ZBStack.h: -------------------------------------------------------------------------------- 1 | /* 2 | * ZBStack.h 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | 36 | #ifndef ZBSTACK_H_ 37 | #define ZBSTACK_H_ 38 | 39 | #include "Defines.h" 40 | #ifdef NETWORK_XBEE 41 | 42 | #include 43 | #include 44 | #include "ProcessFramework.h" 45 | 46 | 47 | #define START_BYTE 0x7e 48 | #define ESCAPE 0x7d 49 | #define XON 0x11 50 | #define XOFF 0x13 51 | 52 | #define MAX_FRAME_DATA_SIZE 128 53 | 54 | #define XB_BROADCAST_ADDRESS32 0x0000ffff 55 | #define XB_BROADCAST_ADDRESS16 0xfffe 56 | 57 | #define DEFAULT_FRAME_ID 1 58 | 59 | #define XB_PACKET_ACKNOWLEGED 0x01 60 | #define XB_BROADCAST_PACKET 0x02 61 | #define XB_BROADCAST_RADIUS_MAX_HOPS 0 62 | 63 | #define API_ID_INDEX 3 64 | #define PACKET_OVERHEAD_LENGTH 6 65 | #define ZB_TX_API_LENGTH 12 66 | #define ZB_PAYLOAD_OFFSET 11 67 | 68 | /** 69 | * API ID Constant 70 | */ 71 | #define XB_TX_REQUEST 0x10 72 | #define XB_RX_RESPONSE 0x90 73 | 74 | /** 75 | * TX STATUS 76 | */ 77 | #define SUCCESS 0x0 78 | 79 | #define NO_ERROR 0 80 | #define CHECKSUM_FAILURE 1 81 | #define PACKET_EXCEEDS_BYTE_ARRAY_LENGTH 2 82 | #define UNEXPECTED_START_BYTE 3 83 | 84 | 85 | #define NW_TX_UNICAST 0 86 | #define NW_TX_BROADCAST 8 87 | 88 | #define NW_MAX_NODEID 24 89 | 90 | /* 91 | * MQTTS Client's state 92 | */ 93 | #define MQTTS_DEVICE_DISCONNECTED 0 94 | #define MQTTS_DEVICE_ACTIVE 1 95 | #define MQTTS_DEVICE_ASLEEP 2 96 | #define MQTTS_DEVICE_AWAKE 3 97 | #define MQTTS_DEVICE_LOST 4 98 | 99 | namespace tomyGateway{ 100 | 101 | /*============================================ 102 | NWAddress64 103 | =============================================*/ 104 | class NWAddress64 { 105 | public: 106 | NWAddress64(uint32_t msb, uint32_t lsb); 107 | NWAddress64(); 108 | uint32_t getMsb(); 109 | uint32_t getLsb(); 110 | void setMsb(uint32_t msb); 111 | void setLsb(uint32_t lsb); 112 | bool operator==(NWAddress64&); 113 | private: 114 | uint32_t _msb; 115 | uint32_t _lsb; 116 | }; 117 | 118 | /*============================================ 119 | NWResponse 120 | =============================================*/ 121 | class NWResponse { 122 | public: 123 | NWResponse(); 124 | ~NWResponse(); 125 | uint8_t getMsbLength(); 126 | uint8_t getLsbLength(); 127 | uint8_t getChecksum(); 128 | uint8_t getFrameDataLength(); 129 | uint8_t getOption(); 130 | uint8_t getType(); 131 | uint8_t getPayload(int index); 132 | uint8_t getPayloadLength(); 133 | uint8_t getPayloadOffset(); 134 | uint8_t getApiId(); 135 | uint8_t getMsgType(); 136 | uint8_t getErrorCode(); 137 | uint8_t* getFrameData(); 138 | uint8_t* getPayloadPtr(); 139 | uint16_t getPacketLength(); 140 | uint16_t getClientAddress16(); 141 | NWAddress64* getClientAddress64(); 142 | 143 | bool isBroadcast(); 144 | bool isAvailable(); 145 | bool isError(); 146 | 147 | void setApiId(uint8_t apiId); 148 | void setMsbLength(uint8_t msbLength); 149 | void setLsbLength(uint8_t lsbLength); 150 | void setChecksum(uint8_t checksum); 151 | void setFrameData(uint8_t *frameDataPtr); 152 | void setFrameDataLength(uint8_t frameLength); 153 | void setAvailable(bool complete); 154 | void setErrorCode(uint8_t errorCode); 155 | 156 | void reset(); 157 | void absorb(NWResponse* resp); 158 | protected: 159 | uint8_t *_frameDataPtr; 160 | private: 161 | uint32_t getRemoteAddressMsb(); 162 | uint32_t getRemoteAddressLsb(); 163 | 164 | uint8_t _apiId; 165 | uint8_t _msbLength; 166 | uint8_t _lsbLength; 167 | uint8_t _checksum; 168 | uint8_t _frameLength; 169 | uint8_t _errorCode; 170 | bool _complete; 171 | NWAddress64 _addr64; 172 | }; 173 | 174 | /*============================================ 175 | Class NWRequest 176 | =============================================*/ 177 | 178 | class NWRequest{ 179 | public: 180 | NWRequest(); 181 | NWRequest(NWAddress64 &addr64, uint8_t *payload, uint8_t payLoadLength); 182 | NWRequest(NWAddress64 &addr64, uint16_t addr16, uint8_t broadcastRadius, 183 | uint8_t option, uint8_t *payload, uint8_t payloadLength); 184 | ~NWRequest(); 185 | uint8_t* getPayloadPtr(); 186 | uint8_t getBroadcastRadius(); 187 | uint8_t getOption(); 188 | uint8_t getPayloadLength(); 189 | uint8_t getApiId(); 190 | uint8_t getFrameData(uint8_t pos); 191 | uint8_t getFrameDataLength(); 192 | uint16_t getAddress16(); 193 | NWAddress64& getAddress64(); 194 | 195 | void setApiId(uint8_t apiId); 196 | void setClientAddress64(NWAddress64* addr64); 197 | void setClientAddress16(uint16_t addr16); 198 | void setBroadcastRadius(uint8_t broadcastRadius); 199 | void setOption(uint8_t option); 200 | void setPayload(uint8_t *payload); 201 | void setPayloadLength(uint8_t payLoadLength); 202 | 203 | private: 204 | uint8_t _apiId; 205 | uint8_t _broadcastRadius; 206 | uint8_t _option; 207 | uint8_t _payloadLength; 208 | uint8_t* _payloadPtr; 209 | uint16_t _addr16; 210 | NWAddress64 _addr64; 211 | }; 212 | 213 | /*=========================================== 214 | SerialPort 215 | ============================================*/ 216 | #include 217 | class SerialPort{ 218 | public: 219 | SerialPort(); 220 | ~SerialPort(); 221 | int open(XBeeConfig config); 222 | bool send(unsigned char b); 223 | bool recv(unsigned char* b); 224 | void flush(); 225 | 226 | private: 227 | int open(const char* devName, unsigned int boaurate, bool parity, unsigned int stopbit, unsigned int flg); 228 | 229 | int _fd; // file descriptor 230 | struct termios _tio; 231 | }; 232 | 233 | 234 | /*============================================ 235 | XBee 236 | ============================================*/ 237 | 238 | class XBee { 239 | public: 240 | XBee(); 241 | ~XBee(); 242 | 243 | protected: 244 | int initialize(XBeeConfig config); 245 | bool receiveResponse(NWResponse* response); 246 | void sendRequest(NWRequest& request); 247 | private: 248 | void readPacket(void); 249 | bool read(uint8_t* buff); 250 | bool write(uint8_t val); 251 | void sendByte(uint8_t, bool escape); 252 | void resetResponse(); 253 | void flush(); 254 | 255 | SerialPort *_serialPort; 256 | NWResponse _response; 257 | bool _escape; 258 | uint8_t _pos; 259 | uint8_t _checksumTotal; 260 | uint8_t _bd; 261 | }; 262 | 263 | /*=========================================== 264 | Class NetworkStack 265 | ============================================*/ 266 | class Network : public XBee{ 267 | public: 268 | Network(); 269 | ~Network(); 270 | void unicast(NWAddress64* addr64, uint16_t addr16, 271 | uint8_t* payload, uint16_t payloadLength); 272 | void broadcast(uint8_t* payloadLength, uint16_t bodyLenght); 273 | bool getResponse(NWResponse* response); 274 | int initialize(NETWORK_CONFIG config); 275 | 276 | private: 277 | NWRequest _txRequest; 278 | }; 279 | 280 | } 281 | 282 | #endif /* NETWORK_XBEE */ 283 | #endif /* ZBSTACK_H_ */ 284 | -------------------------------------------------------------------------------- /LogMonitor/Makefile: -------------------------------------------------------------------------------- 1 | PROGNAME := LogMonitor 2 | SRCDIR := src 3 | SUBDIR := src/lib 4 | 5 | SRCS := $(SRCDIR)/LogMonitorApp.cpp \ 6 | $(SRCDIR)/LogMonitor.cpp \ 7 | $(SUBDIR)/ProcessFramework.cpp 8 | 9 | CXX := g++ 10 | CPPFLAGS += 11 | DEFS := 12 | LDFLAGS += 13 | LIBS += 14 | LDADD := -lpthread -lrt 15 | 16 | CXXFLAGS := -Wall -O3 17 | 18 | OUTDIR := Build 19 | 20 | PROG := $(OUTDIR)/$(PROGNAME) 21 | OBJS := $(SRCS:%.cpp=$(OUTDIR)/%.o) 22 | DEPS := $(SRCS:%.cpp=$(OUTDIR)/%.d) 23 | 24 | .PHONY: install clean distclean 25 | 26 | all: $(PROG) 27 | 28 | -include $(DEPS) 29 | 30 | $(PROG): $(OBJS) 31 | $(CXX) $(LDFLAGS) -o $@ $^ $(LIBS) $(LDADD) 32 | 33 | $(OUTDIR)/%.o:%.cpp 34 | @if [ ! -e `dirname $@` ]; then mkdir -p `dirname $@`; fi 35 | $(CXX) $(CXXFLAGS) $(CPPFLAGS) $(DEFS) -o $@ -c -MMD -MP -MF $(@:%.o=%.d) $< 36 | 37 | clean: 38 | rm -rf $(OUTDIR) 39 | 40 | install: 41 | cp -p $(PROG) ../../ 42 | -------------------------------------------------------------------------------- /LogMonitor/src/LogMonitor.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * LogMonitor.cpp 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | #ifndef LOGMONITOR_H_ 36 | #define LOGMONITOR_H_ 37 | 38 | #include "lib/ProcessFramework.h" 39 | 40 | using namespace std; 41 | 42 | class LogMonitor:public Process{ 43 | public: 44 | LogMonitor(); 45 | ~LogMonitor(); 46 | void initialize(int argc, char** argv); 47 | void run(); 48 | }; 49 | 50 | 51 | LogMonitor::LogMonitor(){ 52 | theProcess = this; 53 | } 54 | 55 | LogMonitor::~LogMonitor(){ 56 | 57 | } 58 | 59 | void LogMonitor::initialize(int argc, char** argv){ 60 | Process::initialize(0, NULL); 61 | } 62 | 63 | void LogMonitor::run(){ 64 | while(true){ 65 | const char* data = getLog(); 66 | printf("%s", data); 67 | if(int rc = checkSignal()){ 68 | printf("\n\n\n"); 69 | THROW_EXCEPTION(ExInfo, rc, " Terminated normally\n"); 70 | } 71 | } 72 | } 73 | 74 | 75 | #endif /* LOGMONITOR_H_ */ 76 | 77 | 78 | 79 | 80 | -------------------------------------------------------------------------------- /LogMonitor/src/LogMonitor.h: -------------------------------------------------------------------------------- 1 | /* 2 | * LogMonitor.h 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | #ifndef LOGMONITOR_H_ 36 | #define LOGMONITOR_H_ 37 | 38 | #include "lib/ProcessFramework.h" 39 | 40 | using namespace std; 41 | 42 | class LogMonitor:public Process{ 43 | public: 44 | LogMonitor(); 45 | ~LogMonitor(); 46 | void initialize(int argc, char** argv); 47 | void run(); 48 | }; 49 | 50 | 51 | #endif /* LOGMONITOR_H_ */ 52 | -------------------------------------------------------------------------------- /LogMonitor/src/LogMonitorApp.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * LogMonitorApp.cpp 3 | * 4 | * The BSD License 5 | * 6 | * Copyright (c) 2014, tomoaki@tomy-tech.com 7 | * All rights reserved. 8 | * 9 | * Redistribution and use in source and binary forms, with or without modification, 10 | * are permitted provided that the following conditions are met: 11 | * 12 | * 1. Redistributions of source code must retain the above copyright notice, 13 | * this list of conditions and the following disclaimer. 14 | * 15 | * 2. Redistributions in binary form must reproduce the above copyright notice, 16 | * this list of conditions and the following disclaimer in the documentation 17 | * and/or other materials provided with the distribution. 18 | * 19 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 20 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 21 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 22 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 23 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 24 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 25 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 26 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 27 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 28 | * THE POSSIBILITY OF SUCH DAMAGE. 29 | * 30 | * Created on: 2014/06/01 31 | * Modified: 32 | * Author: Tomoaki YAMAGUCHI 33 | * Version: 0.0.0 34 | */ 35 | #include "lib/ProcessFramework.h" 36 | #include "LogMonitor.h" 37 | 38 | /************************************** 39 | * LogMonitor Application 40 | **************************************/ 41 | const char* theCmdlineParameter = ""; 42 | 43 | LogMonitor lp = LogMonitor(); 44 | 45 | 46 | -------------------------------------------------------------------------------- /LogMonitor/src/lib/Defines.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Defines.h 3 | * The BSD License 4 | * 5 | * Copyright (c) 2014, tomoaki@tomy-tech.com 6 | * All rights reserved. 7 | * 8 | * Redistribution and use in source and binary forms, with or without modification, 9 | * are permitted provided that the following conditions are met: 10 | * 11 | * 1. Redistributions of source code must retain the above copyright notice, 12 | * this list of conditions and the following disclaimer. 13 | * 14 | * 2. Redistributions in binary form must reproduce the above copyright notice, 15 | * this list of conditions and the following disclaimer in the documentation 16 | * and/or other materials provided with the distribution. 17 | * 18 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND 19 | * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED 20 | * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. 21 | * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, 22 | * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, 23 | * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, 24 | * OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 25 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 26 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF 27 | * THE POSSIBILITY OF SUCH DAMAGE. 28 | * 29 | * Created on: 2014/06/01 30 | * Modified: 31 | * Author: Tomoaki YAMAGUCHI 32 | * Version: 0.0.0 33 | */ 34 | #ifndef DEFINES_H_ 35 | #define DEFINES_H_ 36 | 37 | /*================================= 38 | * CPU TYPE 39 | ==================================*/ 40 | #define CPU_LITTLEENDIANN 41 | //#define CPU_BIGENDIANN 42 | 43 | /*================================= 44 | * Data Type 45 | ==================================*/ 46 | typedef unsigned char uint8_t; 47 | typedef unsigned short uint16_t; 48 | typedef unsigned int uint32_t; 49 | 50 | #endif /* DEFINES_H_ */ 51 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | MQTT-SN over UDP and XBee 2 | ====== 3 | ***Updated Gateway has been contributed to paho.*** 4 | ***Latest Gateway can connect to AWS IoT.*** 5 | https://github.com/eclipse/paho.mqtt-sn.embedded-c/tree/gateway 6 | 7 | * MQTT-SN Gateway over XBee or UDP (running on linux) 8 | * MQTT-SN Client over XBee (running on linux, Arduino and mbed) 9 | * MQTT-SN Client over UDP (running on linux and Arduino) 10 | 11 | AsyncMQTT-SN is available. https://github.com/ty4tw/AsyncMQTT-SN 12 | 13 | 14 | Supported functions 15 | ------------------- 16 | 17 | * QOS Level 0 and 1 18 | * SEARCHGW, GWINFO 19 | * CONNECT, WILLTOPICREQ, WILLTOPIC, WILLMSGREQ, WILLMSG 20 | * PINGREQ, PINGRESP 21 | * CONNACK, REGISTER, REGACK, SUBACK, PUBACK, UNSUBACK 22 | * SUBSCRIBE, PUBLISH, UNSUBSCRIBE, DISCONNECT 23 | 24 | Implemented control flows: 25 | Application program executes PUBLISH() function, 26 | Protocol flow as berrow is conducted automaticaly. 27 | 28 | 29 | Client Gateway Broker 30 | | | | 31 | PUBLISH() -->| --- SERCHGW ----> | | 32 | | <-- GWINFO ----- | | 33 | | --- CONNECT ----> | | 34 | | <--WILLTOPICREQ-- | | 35 | | --- WILLTOPIC --> | | 36 | | <-- WILLMSGREQ -- | | 37 | | --- WILLMSG ----> | ---- CONNECT ----> |(accepted) 38 | | <-- CONNACK ----- | <--- CONNACK ----- | 39 | | --- PUBLISH ----> | | 40 | | <-- PUBACK ----- | (invalid TopicId) | 41 | | --- REGISTER ---> | | 42 | | <-- REGACK ----- | | 43 | | --- PUBLISH ----> | ---- PUBLISH ----> |(accepted) 44 | | <-- PUBACK ----- | <---- PUBACK ----- | 45 | | | | 46 | // // // 47 | | | | 48 | SUBSCRIBE() -->| --- SUBSCRIBE --> | ---- SUBSCRIBE --> | 49 | [set Callback] | <-- SUBACK ------ | <--- SUBACK ------ | 50 | | | | 51 | // // // 52 | | | | 53 | | <-- REGISTER ---- | <--- PUBLISH ----- |<-- PUBLISH 54 | [exec Callback] | <-- PUBLISH ---- | | 55 | | --- PUBACK ---> | ---- PUBACK ----> |--> PUBACK 56 | | | | 57 | 58 | License 59 | ------------------- 60 | This source code is available under the BSD license 61 | 62 | 63 | --------------------------------------------------------------------------------