Minor fixes in LifxLightBulb driver (not fully tested yet)
[iot2.git] / iotjava / iotruntime / cpp / IoTUDP.hpp
1 #ifndef _IOTUDP_HPP__
2 #define _IOTUDP_HPP__
3 #include <iostream>
4
5 #include "IoTDeviceAddress.hpp"
6
7 using namespace std;
8
9 // IoTUDP class for iotruntime
10 // Implemented based on IoTUDP.java that is used to wrap communication socket for UDP
11 //
12 // @author      Rahmadi Trimananda <rahmadi.trimananda @ uci.edu>
13 // @version     1.0
14 // @since       2017-01-09
15
16 class IoTUDP
17 {
18         // IoTUDP class properties
19         private:
20                 string strHostAddress;
21                 int iSrcPort;
22                 int iDstPort;
23                 UDPSocket *socket;
24                 bool didClose;
25
26         public:
27
28                 // Constructor
29                 IoTUDP(IoTDeviceAddress iotDevAdd) {
30
31                         strHostAddress = iotDevAdd.getAddress();
32                         iSrcPort = iotDevAdd.getSourcePortNumber();
33                         iDstPort = iotDevAdd.getDestinationPortNumber();
34
35                         socket = new UDPSocket(iSrcPort);
36                         if (socket == NULL) {
37                                 perror("IoTUDP: UDP socket isn't initialized!");
38                         }
39                         didClose = false;
40                 }
41
42
43                 ~IoTUDP() {
44                         // Clean up
45                         if (socket != NULL) {
46                 
47                                 delete socket;
48                                 socket = NULL;          
49                         }
50                 }
51
52
53                 // Send data packet
54                 void sendData(const void* buffer, int bufferLen) {
55
56                         unsigned short destinationPort = (unsigned short) iDstPort;             
57                         socket->sendTo(buffer, bufferLen, strHostAddress, destinationPort);
58                 }
59
60
61                 // Receive data packet
62                 int receiveData(void* buffer, int iMaxDataLength) {
63
64                         unsigned short destinationPort = (unsigned short) iDstPort;
65                         return socket->recvFrom(buffer, iMaxDataLength, strHostAddress, destinationPort);
66                 }
67 };
68 #endif