virtual ::grpc::Status GetContract(::grpc::ServerContext* context, const BfGetContractReq* request, ::grpc::ServerWriter<BfContractData>* writer) override { BfDebug("%s on thread:%d", __FUNCTION__, ::GetCurrentThreadId()); QString clientId = getClientId(context); BfDebug("clientId=%s", qPrintable(clientId)); if (request->symbol() == "*" && request->exchange() == "*") { QStringList ids = g_sm->gatewayMgr()->getIds(); //g_sm->gatewayMgr()->getIdsAll(); for (int index = 0; index < ids.length(); index++) { QString symbol = ids.at(index); void* contract = g_sm->gatewayMgr()->getContract(symbol); BfContractData bfItem; CtpUtils::translateContract(contract, &bfItem); writer->Write(bfItem); } } else { QString symbol = request->symbol().c_str(); void* contract = g_sm->gatewayMgr()->getContract(symbol); BfContractData bfItem; CtpUtils::translateContract(contract, &bfItem); writer->Write(bfItem); } return grpc::Status::OK; }
void jus::Service::onClientData(jus::Buffer& _value) { uint32_t tmpID = _value.getTransactionId(); uint32_t clientId = _value.getClientId();; auto it = m_callMultiData.begin(); while (it != m_callMultiData.end()) { if ( it->getTransactionId() == tmpID && it->getClientId() == clientId) { JUS_WARNING("Append data ... " << tmpID); it->appendData(_value); if (it->isFinished() == true) { JUS_WARNING("CALL Function ..."); callBinary(tmpID, it->getRaw()); it = m_callMultiData.erase(it); } return; } ++it; } jus::FutureCall futCall(clientId, tmpID, _value); if (futCall.isFinished() == true) { JUS_INFO("Call Binary .."); callBinary(tmpID, futCall.getRaw()); } else { m_callMultiData.push_back(futCall); } }
//----------------------------------------------------------------------------------------- // Constructors //----------------------------------------------------------------------------------------- SocketClient::SocketClient( int server_port, int client_port, char *ip, float interval, Logger *log ) : BaseSocket( server_port, client_port, ip, log) { client_id = -1; req_id = 0; timer = new FdTimer( getClientId(), interval , log ); }
virtual ::grpc::Status QueryOrders(::grpc::ServerContext* context, const BfVoid* request, BfVoid* response) override { BfDebug("%s on thread:%d", __FUNCTION__, ::GetCurrentThreadId()); QString clientId = getClientId(context); BfDebug("clientId=%s", qPrintable(clientId)); QMetaObject::invokeMethod(g_sm->gatewayMgr(), "queryOrders", Qt::QueuedConnection); return grpc::Status::OK; }
void UserWin::addContact() { bool ok = false; QString contact = QInputDialog::getText(this, "Ajout", "Indiquez l'ID du contact à ajouter:", QLineEdit::Normal, QString(), &ok); if (ok && !contact.isEmpty() && contact != getClientId()) this->sendDataTcp(ASKTOADD, this->getClientId().toStdString(), contact.toStdString()); else QMessageBox::warning(this, "Ajout de Contact", "Votre demande a échouée.", QMessageBox::Close); }
void Player::toPacket(sf::Packet* packet) { // Extract player info *packet << getClientId(); *packet << getUserName(); *packet << getPing(); // Extract ship info ship.toPacket(packet); }
std::string Player::toString() { std::stringstream tmp; tmp << getUserName() << "[" << getClientId() << "] : "; tmp << "Ping: " << getPing() << " "; tmp << "Ship info: " << ship.toString(); return tmp.str(); }
virtual ::grpc::Status DisconnectPush(::grpc::ServerContext* context, const BfVoid* request, BfVoid* response) override { BfDebug("%s on thread:%d", __FUNCTION__, ::GetCurrentThreadId()); QString clientId = getClientId(context); BfDebug("(%s)->Disconnect", qPrintable(clientId)); // NOTE(hege):关闭stream QMetaObject::invokeMethod(g_sm->pushService(), "disconnectClient", Qt::QueuedConnection, Q_ARG(QString, clientId)); return grpc::Status::OK; }
int main() { char sendLine[MAX_MESSAGE_LENGTH]; bzero(&serverAddress, sizeof(serverAddress)); serverAddress.sin_family = AF_INET; serverAddress.sin_port = htons(SERVER_PORT); serverAddress.sin_addr.s_addr = htonl(INADDR_ANY); if ((sockfd = socket(PF_INET, SOCK_DGRAM, 0)) < 0) { perror(NULL); exit(1); } else { printf("Sock fd:%d\n", sockfd); } if (bind(sockfd, (struct sockaddr*) &serverAddress, sizeof(serverAddress)) < 0) { perror(NULL); close(sockfd); exit(1); } while (1) { clilen = sizeof(clientAddress); if ((n = recvfrom(sockfd, sendLine, MAX_MESSAGE_LENGTH - 1, 0, (struct sockaddr*)&clientAddress, &clilen)) < 0) { perror(NULL); close(sockfd); exit(1); } if (firstMessageFrom(clientAddress)) { addNewClient(clientAddress, sendLine); } else { int clientId = getClientId(clientAddress); sendToChat(sendLine, clientId); } printf("receive %s from %s\n", sendLine, clients[getClientId(clientAddress)].clientNick); } return 0; }
void Item::setOtbId(uint16 id) { if(!g_things.isValidOtbId(id)) id = 0; auto itemType = g_things.getItemType(id); m_serverId = id; id = itemType->getClientId(); if(!g_things.isValidDatId(id, ThingCategoryItem)) id = 0; m_clientId = id; }
virtual ::grpc::Status SendOrder(::grpc::ServerContext* context, const BfSendOrderReq* request, BfSendOrderResp* response) override { BfDebug("%s on thread:%d", __FUNCTION__, ::GetCurrentThreadId()); QString clientId = getClientId(context); BfDebug("clientId=%s", qPrintable(clientId)); QString bfOrderId = g_sm->gatewayMgr()->genOrderId(); response->set_bforderid(bfOrderId.toStdString()); QMetaObject::invokeMethod(g_sm->gatewayMgr(), "sendOrderWithId", Qt::QueuedConnection, Q_ARG(QString, bfOrderId), Q_ARG(BfSendOrderReq, *request)); return grpc::Status::OK; }
virtual ::grpc::Status GetContract(::grpc::ServerContext* context, const BfGetContractReq* request, ::grpc::ServerWriter<BfContractData>* writer) override { BfLog("%s on thread:%d", __FUNCTION__, ::GetCurrentThreadId()); QString clientId = getClientId(context); BfLog("clientId=%s", qPrintable(clientId)); QList<BfContractData> resps; g_sm->dbService()->getContract(*request, resps); for (auto resp : resps) { writer->Write(resp); } return grpc::Status::OK; }
void Client::parseTransmit() { qDebug() << "parseTransmit():"; if ( !(this->status_ == ST_ADMIN || this->status_ == ST_CLIENT)) { qDebug() << "cmd not allowed"; this->disconnectFromHost(); return; } if (buf_.size()<9) // TODO: remove magic number return; // not all data avaliable qDebug() << "buf size" << buf_.size(); qDebug() << "packet len" << getPacketLength(buf_); if (buf_.size()<getPacketLength(buf_)+9) // TODO: remove magic number return; // not all data avaliable qint16 clientId=getClientId(buf_); QByteArray cmd=getPacketData(buf_); QByteArray response; response.append(CSPYP1_PROTOCOL_ID); response.append(CSPYP1_PROTOCOL_VERSION); response.append(CMD1_TRANSMIT); response.append(toBytes(getId())); response.append(toBytes(cmd.size())); response.append(cmd); auto destClient = getServer()->searchClient(clientId); qDebug() << "Client to ID:" << clientId; if (destClient != getServer()->clientEnd()) { qDebug() << "transmiting data.."; destClient.value()->send(response); } buf_=buf_.right(buf_.size() - (getPacketLength(buf_) + 9)); if (buf_.size() > 0) onDataReceived(); // If something in buffer - parse again }
api_return HubApi::handleConnect(ApiRequest& aRequest) { const auto& reqJson = aRequest.getRequestBody(); auto address = JsonUtil::getField<string>("hub_url", reqJson, false); RecentHubEntryPtr r = new RecentHubEntry(address); auto client = ClientManager::getInstance()->createClient(r, SETTING(DEFAULT_SP)); if (!client) { aRequest.setResponseErrorStr("Hub exists"); return websocketpp::http::status_code::bad_request; } aRequest.setResponseBody({ { "id", client->getClientId() } }); return websocketpp::http::status_code::ok; }
int startServer(){ /* server start */ AllGameInfo agi; char clientMsg[MAX_MESSAGE+1]; char *cmd[20]; int n; ServerMessage sm; int clientId; /* 1 or 2 */ int fd; int res; #if defined TEST #endif /* Create fifo file */ if((mkfifo(FIFO_SERVER, 0777)) < 0) printf("Cannot create fifoServe : %s\n", FIFO_SERVER); /* iit all info */ initAllGameInfo(&agi); while(1){ /* receive client msg */ receiveClientMsg(FIFO_SERVER, clientMsg); n = splitStrByChar(clientMsg, cmd, ' '); if(n < 1 || n > 3){ printf("******************************\n"); printf("%s clientMsg error: %s %s %s\n", cmd[0], cmd[0], cmd[1], cmd[2]); printf("******************************\n"); } if(n >= 3){ if(!strcmp(cmd[2],"TJ")) strcpy(cmd[2],"XT"); if(!strcmp(cmd[2],"WJ")) strcpy(cmd[2],"XW"); } clientId = getClientId(cmd[0]); updateAllGameInfo(&agi, cmd); printf("gameInfoToServerMessage for %d\n", clientId); sendMessageToClient(agi, clientId); } #if defined TEST #endif return 0; }
int ScripMasterDataRequest::serialize(char *buf) { int bytes = 0; UNSIGNED_INTEGER tmp = 0; UNSIGNED_SHORT tmpShort = 0; UNSIGNED_CHARACTER tmpChar = 0; UNSIGNED_LONG tmpLong = 0; bytes = sizeof(UNSIGNED_SHORT); // Leave 2 bytes for packet size // Put category of command SERIALIZE_8(tmpChar, (UNSIGNED_CHARACTER)(CMD::CommandCategory_SEND_SCRIP_MASTER_DATA), buf, bytes); //Command Category // Put fields of this class SERIALIZE_8(tmpChar, getScripMasterDataRequestType(), buf, bytes); SERIALIZE_32(tmp, getClientId(), buf, bytes); SERIALIZE_64(tmpLong, getRecordNumber(), buf, bytes); SERIALIZE_64(tmpLong, getSecurityId(), buf, bytes); SERIALIZE_64(tmpLong, getSymbolId(), buf, bytes); SERIALIZE_16(tmpShort, getExchangeId(), buf, bytes); memcpy(buf + bytes, getSymbol(), SYMBOL_SIZE); bytes += SYMBOL_SIZE; memcpy(buf + bytes, getSeries(), SERIES_SIZE); bytes += SERIES_SIZE; memcpy(buf + bytes, getMarketName(), SERIES_SIZE); bytes += MARKET_NAME_SIZE; SERIALIZE_8(tmpChar, getOptionType(), buf, bytes); SERIALIZE_8(tmpChar, getOptionMode(), buf, bytes); SERIALIZE_8(tmpChar, getSecurityType(), buf, bytes); SERIALIZE_64(tmpLong, getStrikePrice(), buf, bytes); SERIALIZE_32(tmp, getExpiryYearMon(), buf, bytes); SERIALIZE_32(tmp, getExpiryDate(), buf, bytes); SERIALIZE_32(tmp, getNumberOfRecords(), buf, bytes); memcpy(buf + bytes, getSymbolAlias(), SYMBOL_ALIAS_SIZE); bytes += SYMBOL_ALIAS_SIZE; UNSIGNED_SHORT dummyBytes = 0; // Put size as the first field after deducting 2 bytes reserved for size SERIALIZE_16(tmpShort, (UNSIGNED_SHORT)(bytes-sizeof(UNSIGNED_SHORT)), buf, dummyBytes); return bytes; }
void acceptConnection() { int clientId; TCPsocket incomming; while (true) { incomming = SDLNet_TCP_Accept(TCPsock); if (incomming !=0x0) { if ((clientId = getClientId())<0) {printf("Too many users! \n");} else { clients[clientId].socket = incomming; clients[clientId].id = clientId; clients[clientId].active = true; clients[clientId].ip = SDLNet_TCP_GetPeerAddress(incomming)->host; SDL_DetachThread(SDL_CreateThread(Lobby, "lobbyThread", &clientId)); incomming = NULL; } } if(ClientsAreReady()) { printf("starting in 3...\n"); Broadcast("$4starting in 3..."); SDL_Delay(1000); if(ClientsAreReady()) { printf("starting in 2...\n"); Broadcast("$4starting in 2..."); SDL_Delay(1000); if(ClientsAreReady()) { printf("starting in 1...\n"); Broadcast("$4starting in 1..."); SDL_Delay(1000); printf("!GO\n"); Broadcast("!GO"); break; } } } incomming = NULL; SDL_Delay(1000); } }
void Client::parseSetInfo() { qDebug() << "SetInfo received!"; if (this->status_!=ST_ADMIN) { qDebug() << "cmd not allowed"; this->disconnectFromHost(); return; } if (buf_.size()< CMD1_SETINFO_SIZE) // TODO: remove magic number return; // not all data avaliable qint16 clientId=getClientId(buf_); QString caption=getClientCaption(buf_); getServer()->setClientCaption(clientId,caption); buf_ = buf_.right(buf_.size() - CMD1_SETINFO_SIZE); if (buf_.size() > 0) onDataReceived(); // If something in buffer - parse again }
void ScripMasterDataRequest::dump() { std::cout << "ScripMasterDataRequest dump : " << std::endl; std::cout << getScripMasterDataRequestType() << std::endl; std::cout << getClientId() << std::endl; std::cout << getRecordNumber() << std::endl; std::cout << getSecurityId() << std::endl; std::cout << getSymbolId() << std::endl; std::cout << getExchangeId() << std::endl; std::cout << getSymbol() << std::endl; std::cout << getSeries() << std::endl; std::cout << getMarketName() << std::endl; std::cout << getOptionType() << std::endl; std::cout << getOptionMode() << std::endl; std::cout << getSecurityType() << std::endl; std::cout << getStrikePrice() << std::endl; std::cout << getExpiryYearMon() << std::endl; std::cout << getExpiryDate() << std::endl; std::cout << getNumberOfRecords() << std::endl; std::cout << getSymbolAlias() << std::endl; std::cout << "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx\n" << std::endl; }
std::string VKBase::parseHTML() { std::string cookiestring = ""; _curl = curl_easy_init(); CURLcode result; std::string buffer = ""; // for response std::string url = ""; // for url char errorBuffer[CURL_ERROR_SIZE]; if(!_curl) { printf("%s\n", "ERROR: curl_easy_init()"); exit(0); } std::string scopes = ""; std::vector<std::string> vscopes = getScopes(); std::for_each(vscopes.begin(), vscopes.end(), [&scopes](std::string scope){ scopes += scope+"&"; }); url = "https://oauth.vk.com/authorize?client_id="; url += getClientId(); url += "&scope="+scopes+"redirect_uri=http://api.vkontakte.ru/blank.html&display=mobile&v=5.24&response_type=token&revoke=1"; curl_easy_setopt(_curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(_curl, CURLOPT_FOLLOWLOCATION, 1L); curl_easy_setopt(_curl, CURLOPT_NOSIGNAL, 1); curl_easy_setopt(_curl, CURLOPT_HEADER, 1); curl_easy_setopt(_curl, CURLOPT_SSL_VERIFYPEER, 0L); curl_easy_setopt(_curl, CURLOPT_SSL_VERIFYHOST, 0L); curl_easy_setopt(_curl, CURLOPT_COOKIEFILE, cookiestring.c_str()); curl_easy_setopt(_curl, CURLOPT_PORT, 443); curl_easy_setopt(_curl, CURLOPT_WRITEFUNCTION, &VKBase::writer); curl_easy_setopt(_curl, CURLOPT_WRITEDATA, &buffer); curl_easy_setopt(_curl, CURLOPT_ERRORBUFFER, errorBuffer); result = curl_easy_perform(_curl); curlCheckError(_curl, result, errorBuffer); buffer.clear(); Authorization(); // grant access url = "https://login.vk.com/?act=grant_access&client_id="+getClientId(); url += "&settings=8&redirect_uri=http%3A%2F%2Fapi.vkontakte.ru%2Fblank.html&response_type=token&direct_hash=85bc6b0b250f6f44d1&token_type=0&v=5.24"; url += "&state=&display=mobile"; url += "&ip_h="+_ip_h; url += "&hash="+_hash; url += "&https=1"; curl_easy_setopt(_curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(_curl, CURLOPT_WRITEDATA, &buffer); result = curl_easy_perform(_curl); curlCheckError(_curl, result, errorBuffer); url = "https://api.vk.com/method/"+getMethod()+"?&access_token="+parseAccessTokenFromHeaders(buffer); buffer.clear(); curl_easy_setopt(_curl, CURLOPT_URL, url.c_str()); curl_easy_setopt(_curl, CURLOPT_HEADER, 0); result = curl_easy_perform(_curl); curlCheckError(_curl, result, errorBuffer); Json::Value root; Json::Reader reader; bool bjsonparse = reader.parse(buffer, root); if(bjsonparse && root["error"].get("error_code", 0).asInt()) { err.b = true; err.msg = root["error"].get("error_msg", "false").asString(); }else{ err.b = false; err.msg = ""; } return buffer; }
virtual ::grpc::Status Ping(::grpc::ServerContext* context, const BfPingData* request, BfPingData* response) override { QString clientId = getClientId(context); response->set_message(request->message()); return grpc::Status::OK; }
int WebSocketTcpServer::__callback_websocket__(struct lws *wsi, enum lws_callback_reasons reason, void *user, void *in, size_t len) { if ( nullptr == m_context ) return 0; WebSocketTcpServer *server = static_cast<WebSocketTcpServer*>(lws_context_user(m_context)); if ( server->m_run_thread == false ) return 0; switch ( reason ) { case LWS_CALLBACK_WSI_CREATE: break; case LWS_CALLBACK_ESTABLISHED: { LOG_DEBUG("LWS_CALLBACK_ESTABLISHED \n"); string protocol = server->__getProtocolFromHeader__(wsi); LOG_DEBUG("user : %s \n", protocol.data()); int client_fd = lws_get_socket_fd(wsi); struct sockaddr_in clientaddr; socklen_t peeraddrlen = sizeof(clientaddr); if ( 0 > getpeername(client_fd, (struct sockaddr*)&clientaddr, &peeraddrlen) ) { perror("getpeername error "); } size_t client_id = server->addClientInfo(ClientInfoPtr( new WebSocketTcpClientInfo(client_fd, &clientaddr, wsi, protocol))); NOTIFY_CLIENT_CONNECTED(server->m_server_id, client_id); } break; case LWS_CALLBACK_RECEIVE: LOG_DEBUG("LWS_CALLBACK_RECEIVE \n"); { LOG_DEBUG("received data: %s\n", (char *) in); int client_fd = lws_get_socket_fd(wsi); auto client = static_pointer_cast<WebSocketTcpClientInfo>(server->findClientInfo(client_fd)); NOTIFY_SERVER_RECEIVED_FROM_PROTOCOL( server->m_server_id, client->getClientId(), (char*)in, len, client->getProtocol()); } break; case LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION: LOG_DEBUG("LWS_CALLBACK_FILTER_PROTOCOL_CONNECTION \n"); break; case LWS_CALLBACK_WS_PEER_INITIATED_CLOSE: LOG_DEBUG("LWS_CALLBACK_WS_PEER_INITIATED_CLOSE \n"); break; case LWS_CALLBACK_CLOSED: LOG_DEBUG("LWS_CALLBACK_CLOSED \n"); { int client_fd = lws_get_socket_fd(wsi); size_t client_id = server->removeClientInfo(client_fd); NOTIFY_CLIENT_DISCONNECTED(server->m_server_id, client_id); } break; case LWS_CALLBACK_PROTOCOL_INIT: LOG_DEBUG("LWS_CALLBACK_PROTOCOL_INIT \n"); break; case LWS_CALLBACK_PROTOCOL_DESTROY: LOG_DEBUG("LWS_CALLBACK_PROTOCOL_DESTROY \n"); break; case LWS_CALLBACK_GET_THREAD_ID: /* to be silent */ break; case LWS_CALLBACK_DEL_POLL_FD: LOG_DEBUG("LWS_CALLBACK_DEL_POLL_FD \n"); { int client_fd = lws_get_socket_fd(wsi); size_t client_id = server->removeClientInfo(client_fd); NOTIFY_CLIENT_DISCONNECTED(server->m_server_id, client_id); } break; default: LOG_WARNING("Unhandled callback reason [%d] \n", reason); break; } return 0; }
int playerPutPoker(AllGameInfo *agi, char *cmd[]){ /* player put poker */ char *p,*q,*s; char buf[10]; char errorStr[MAX_MESSAGE+1]; int clientId; int num,otherNum; char *pokerName; pokerName = cmd[2]; /* 在这个函数里不知道怎么会把agi->errorStr改变 */ clientId = getClientId(cmd[0]); num = clientId - 1; /* 检测是否轮到 clientId 出牌 */ if(agi->playerStat[num] != 1){ errorNo = CLIENT_PLA_TURN_ERROR; strcpy(agi->errorStr[num], "没有轮到你出牌"); return -1; } /* 检测clientId 有没有 pokerName */ s = strstr(agi->playerCurPokerString[num], pokerName); if(s == NULL){ errorNo = CLIENT_POK_NON_ERROR; sprintf(errorStr, "你没有‘%2s’牌",pokerName); strcpy(agi->errorStr[num], errorStr); return -1; } /* 储存要出的牌 */ q = buf; p = s; while(*p != ' '){ *q++ = *p++; } *q++ = ' '; /* 保持序列的一致性:t1 t3 d3 */ *q = '\0'; otherNum = getOtherId(clientId) - 1; /* 出过两张牌后,清空 */ if(clearCard == 2){ clearCard =0; memset(agi->playerPuttingPokerName[otherNum], 0, 6); } if(!strcmp(agi->playerPuttingPokerName[otherNum], "")){ /* 对方没出牌 */ strcpy(agi->playerPuttingPokerName[num], buf); strcat(agi->playerPuttingPokerName[num], "1"); clearCard++; }else{ /* 对方已出牌 */ strcpy(agi->playerPuttingPokerName[num], buf); strcat(agi->playerPuttingPokerName[num], "2"); clearCard++; } /* 比较牌的大小 */ if(clearCard == 2){ comparePutingCard(agi); } /* 删除打出的牌 */ while(*s){ /* 可能有问题,证明没问题 */ *s = *(s+3); s++; } /* 将删除的牌加入出过的牌中 */ strcat(agi->playerPuttedPokerString[num],buf); /* 改变玩家状态 */ if(clearCard != 2){ changePlayerStat(agi->playerStat); } if(clearCard == 2) pkResult(agi); strcpy(agi->errorStr[num], ""); return 0; }
int main(int argc, char **argv) { InitDHT(1); char* json; int lckStatus; int res; int sleepTimeout; struct config configstr; char *passwd; char *username; char msproxyUrl[MAXBUF]; //setup the syslog logging setlogmask(LOG_UPTO(LOGLEVEL)); openlog("iot", LOG_PID | LOG_CONS, LOG_USER); syslog(LOG_INFO, "**** IoT Raspberry Pi Sample has started ****"); // register the signal handler for USR1-user defined signal 1 if (signal(SIGUSR1, sig_handler) == SIG_ERR) syslog(LOG_CRIT, "Not able to register the signal handler\n"); if (signal(SIGINT, sig_handler) == SIG_ERR) syslog(LOG_CRIT, "Not able to register the signal handler\n"); //read the config file, to decide whether to goto quickstart or registered mode of operation isRegistered = get_config(configFile, &configstr); if (isRegistered) { syslog(LOG_INFO, "Running in Registered mode\n"); sprintf(msproxyUrl, "ssl://%s.messaging.internetofthings.ibmcloud.com:8883", configstr.org); if(strcmp(configstr.authmethod ,"token") != 0) { syslog(LOG_ERR, "Detected that auth-method is not token. Currently other authentication mechanisms are not supported, IoT process will exit."); syslog(LOG_INFO, "**** IoT Raspberry Pi Sample has ended ****"); closelog(); exit(1); } else { username = "******"; passwd = configstr.authtoken; } } else { syslog(LOG_INFO, "Running in Quickstart mode\n"); strcpy(msproxyUrl,"tcp://quickstart.messaging.internetofthings.ibmcloud.com:1883"); } // read the events char* mac_address = getmac("eth0"); getClientId(&configstr, mac_address); //the timeout between the connection retry int connDelayTimeout = 1; // default sleep for 1 sec int retryAttempt = 0; // initialize the MQTT connection init_mqtt_connection(&client, msproxyUrl, isRegistered, clientId, username, passwd); // Wait till we get a successful connection to IoT MQTT server while (!MQTTAsync_isConnected(client)) { connDelayTimeout = 1; // add extra delay(3,60,600) only when reconnecting if (connected == -1) { connDelayTimeout = reconnect_delay(++retryAttempt); //Try to reconnect after the retry delay syslog(LOG_ERR, "Failed connection attempt #%d. Will try to reconnect " "in %d seconds\n", retryAttempt, connDelayTimeout); connected = 0; init_mqtt_connection(&client, msproxyUrl, isRegistered, clientId, username, passwd); } fflush(stdout); sleep(connDelayTimeout); } // resetting the counters connDelayTimeout = 1; retryAttempt = 0; // count for the sine wave int count = 1; sleepTimeout = EVENTS_INTERVAL; //subscribe for commands - only on registered mode if (isRegistered) { subscribe(&client, subscribeTopic); } while (1) { JsonMessage json_message = { DEVICE_NAME, getCPUTemp(), sineVal( MIN_VALUE, MAX_VALUE, 16, count), GetCPULoad() , getHumidity(), getTemp()}; json = generateJSON(json_message); res = publishMQTTMessage(&client, publishTopic, json); syslog(LOG_DEBUG, "Posted the message with result code = %d\n", res); if (res == -3) { //update the connected to connection failed connected = -1; while (!MQTTAsync_isConnected(client)) { if (connected == -1) { connDelayTimeout = reconnect_delay(++retryAttempt); //Try to reconnect after the retry delay syslog(LOG_ERR, "Failed connection attempt #%d. " "Will try to reconnect in %d " "seconds\n", retryAttempt, connDelayTimeout); sleep(connDelayTimeout); connected = 0; reconnect(&client, isRegistered, username,passwd); } fflush(stdout); sleep(1); } // resetting the counters connDelayTimeout = 1; retryAttempt = 0; } fflush(stdout); free(json); count++; sleep(sleepTimeout); } return 0; }