#include <winsock2.h>
#include <ws2tcpip.h>
#include <tchar.h>
#include "KeepAlive.h"
#include "ECTrainer.h"
// コンストラクタ
KeepAlive::KeepAlive(ECTrainer* pEct)
: BaseProcess(pEct)
, _sent(false)
, _socket(NULL) {
_socketAddrLen = sizeof(_socketAddr);
memset((char*)&_socketAddr, 0, _socketAddrLen);
}
// 初期化
bool KeepAlive::Init() {
#if defined(EYEDEVICE_GLASS2)
// Initialize winsock
WSADATA wsa;
if (WSAStartup(MAKEWORD(2, 2), &wsa) != 0) {
std::cerr << "Initialising Winsock Failed with error Code : " << WSAGetLastError() << std::endl;
return false;
}
// Create socket
if ((_socket = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)) == SOCKET_ERROR) {
std::cerr << "Creating socket failed with error code : " << WSAGetLastError() << std::endl;
return false;
}
// setup address structure
_socketAddr.sin_family = AF_INET;
_socketAddr.sin_port = htons(PORT);
InetPton(_socketAddr.sin_family, _T(ADDR), &_socketAddr.sin_addr.S_un.S_addr);
#endif
return true;
}
// メインループ
bool KeepAlive::MainLoop() {
#if defined(EYEDEVICE_GLASS2)
const std::string KA_DATA_MSG = "{\"type\": \"live.data.unicast\", \"key\": \"some_GUID\", \"op\": \"start\"}";
char message[SOCKET_BUF_LEN];
strcpy_s(message, SOCKET_BUF_LEN, KA_DATA_MSG.c_str());
int count = 0;
while (_pEct->IsAppRun()) {
Sleep(100);
if (++count < KEEP_ALIVE_WAIT_COUNT) continue;
count = 0;
if (sendto(_socket, message, (int)strlen(message), 0,
(struct sockaddr*)&_socketAddr, _socketAddrLen) == SOCKET_ERROR) {
std::cerr << "Keep Alive Data Sent Error" << std::endl;
} else {
_sent = true;
}
}
#endif
return true;
}