void LogType::setUdpRemoteEndpoint() { __udp_remote_endpoint = new boost::asio::ip::udp::endpoint( boost::asio::ip::udp::endpoint( boost::asio::ip::address::from_string(getIpAddress()), getRemotePort())); }
/*! * When the program is closed this will save all * the changes made in the parameters in the configurations.ini file */ Cparameter::~Cparameter(void) { /* WORK SEQUENCE * opens the ini file * Gets the current values if changed in the process by some other functions * simply overwrites all the values when the destructor is called */ QSettings get(QDir::currentPath()+ "/" + "configurations.ini", QSettings::IniFormat); get.beginGroup("Parameters"); QString name = getLogFileName(); //qDebug() << name ; get.setValue("LogFileName", name); QString path = getLogFileDirectory(); get.setValue("LogFileDirectory", path); QString ip = getIpAddress(); get.setValue("IpAddress", ip); int port = getPort(); get.setValue("Port", port); QString resolution = getResolution(); get.setValue("Resolution", resolution); int frames = getFrames(); get.setValue("Frames", frames); float HorizontalFcl = settings->value("HorizontalFocalLength").toFloat(); }
/** * Runs the camera application. * * @param argc Unused. * @param argv Unsued. * @return Never returns, calls exit(0). */ int main(int argc, char **argv) { std::cout << "Starting Camera Application" << std::endl; char *ip = getIpAddress(); if (ip == 0) { std::cout << "No ip address found. Terminating" << std::endl; exit(1); } else { // Replace . with _ for (int i = 0; ip[i] != 0; i++) { if (ip[i] == '.') ip[i] = '_'; } } // Create node name. char nodeName[80]; strcpy(nodeName, "Camera_Application_"); strcat(nodeName, ip); free(ip); ros::init(argc, argv, nodeName); if (ros::console::set_logger_level(ROSCONSOLE_DEFAULT_NAME, ros::console::levels::Debug)) ros::console::notifyLoggerLevelsChanged(); Freenect::Freenect freenect; CvKinect &device = freenect.createDevice<CvKinect>(0); CvImageProcessor *analyzer = new CvImageProcessor(&device, 0, false, false); // CvImageProcessor* analyzer = new CvImageProcessor(&device, 0); // Do ROS stuff. Communicator comm(&device, analyzer); analyzer->setDataReceiver(&comm); // Wait one second to give Kinect time to initialize. usleep(1000000); analyzer->start(); ROS_INFO("Initialized Kinect."); ros::spin(); ROS_INFO("Shutting down."); analyzer->stop(); ros::shutdown(); std::cout << "ros::shutdown() sent" << std::endl; // Wait for ros to shutdown. while (ros::ok()) { usleep(10000); } std::cout << "Camera Application successfully terminated" << std::endl; // Fix for some threads not terminated, probably caused by libfreenect. exit(0); }
/* ** THIS METHOD INITIALIZES INFORMATION ABOUT THE RHINO BOARD */ void initializeMethod(RhinoT *rhinoDevicePtr, RegisterT *rhinoRegistersPtr) { int i; network_infoT *rhino_info, rhino_infoObj; rhino_info = &rhino_infoObj; printf("GETTING INTO THE INIT METHOD\n"); rhinoDevicePtr->nameNumber = RHINOID; rhino_info = getIpAddress(RHINOID); printf("THE MAC ADDRESS OF THIS RHINO IS: [%s]\n", rhino_info->macAddress); printf("THE IP ADDRESS OF THIS RHINO IS: [%s]\n", rhino_info->ipAddress); strncpy(rhinoDevicePtr->ipAddress, rhino_info->ipAddress , sizeof(rhinoDevicePtr->ipAddress)-1); //rhinoDevicePtr->ipAddress[16] = getIpAddress(); rhinoDevicePtr->ipAddress[16] ='\0'; rhinoDevicePtr->busyBit = FPGA_UNPROGRAMMED; //rhinoDevicePtr->registersAccessible = NULL; rhinoRegistersPtr->readWriteBit = 0; rhinoRegistersPtr->rhinoNameNumber = 0; rhinoRegistersPtr->size = 0; memset(&rhinoRegistersPtr->regName[0], 0, sizeof(rhinoRegistersPtr->regName)); //memset(&rhinoDevicePtr->ipAddress[0], 0, sizeof(rhinoDevicePtr->ipAddress)); //printf("THE RHINO REGISTER NAME IS: [%s]\n",rhinoRegistersPtr->regName); }
bool LogType::validate() { writeInfo ( "config FILE = %s", getConfigFile().c_str()); // check if config file exists if( !fileExists(getConfigFile()) ) { writeError ("Can't find config FILE = %s", getConfigFile().c_str()); return false; } // check if config file can read if( !fileReadable(getConfigFile()) ) { writeError ("Can't read from config FILE = %s", getConfigFile().c_str()); return false; } // check if config file exists if( !iniParse(getConfigFile()) ) { writeError ("Can't parse config FILE = %s", getConfigFile().c_str()); return false; } bool result = parseStorageType() && parseIpAddress() && parseRemotePort() && parseSourcePort() && parseUdpBufferSize(); if (result) { __udp_socket = new boost::asio::ip::udp::socket( __io_service, boost::asio::ip::udp::endpoint( boost::asio::ip::address::from_string(getIpAddress()), getSourcePort())); __udp_remote_endpoint = new boost::asio::ip::udp::endpoint( boost::asio::ip::udp::endpoint( boost::asio::ip::address::from_string(getIpAddress()), getRemotePort())); } return result; }
bool TcpDataTransport::connect() { if (!d_socket) { boost::asio::ip::tcp::endpoint endpoint(boost::asio::ip::address::from_string(getIpAddress()), getPort()); d_socket.reset(new boost::asio::ip::tcp::socket(ios)); try { d_socket->connect(endpoint); INFO_("Connected to %s on port %d.", getIpAddress().c_str(), getPort()); } catch(boost::system::system_error& ex) { ERROR_("Cannot establish connection: %s", ex.what()); d_socket.reset(); } } return bool(d_socket); }
void LogType::setUdpSocket() { __udp_socket = new boost::asio::ip::udp::socket( __io_service, boost::asio::ip::udp::endpoint( boost::asio::ip::address::from_string(getIpAddress()), getSourcePort())); if (__udp_socket != NULL) { boost::asio::socket_base::receive_buffer_size option(getUdpBufferSize()); __udp_socket->set_option(option); } }
bool LogType::parseIpAddress() { setIpAddress ( iniGetValue( ini::SECTION, ini::VAR_SWA_IP, ini::settings::ipAddress ) ); if (iniGetError()) { writeError( "Can't get 'IP Address'" ); return false; } if( getIpAddress().empty() ) { writeError( "'IP Address' invalid" ); return false; } writeInfo ( "IP Address = %s", getIpAddress().c_str()); return true; }
foreach (Sliver *sliver, slivers) { sliver->status = Sliver::STATUS_OFFLINE; sliverHash[sliver->name] = sliver; if (relayEnabled()) { installProgram(sliver); addSliverConnection(sliver); } else { if (sliver->IPv6.isEmpty()) { qDebug() << "No ip, getting address"; getIpAddress(sliver); installProgram(sliver); } else { addSliverConnection(sliver); QTimer *timer = new QTimer(this); //if there's a specified IP address, give the connection some time before running the script setting things up. connect(timer, &QTimer::timeout, [timer, sliver, this]() { qDebug() << "Checking connection status"; if (sliver->status == sliver->STATUS_OFFLINE) { qDebug() << "Still offline, reinstalling"; installProgram(sliver); } timer->stop(); timer->deleteLater(); }); timer->start(3000); } } QTimer *timer = new QTimer(this); //Will try to connect as long as the sliver is not connected connect(timer, &QTimer::timeout, [timer, sliver, this]() { if (sliver->status != sliver->STATUS_CONNECTED) { qDebug() << "Retryign connection"; addSliverConnection(sliver); } else { timer->stop(); timer->deleteLater(); } static int time = 0; time+=3; //if (time > 35) { // shutDownNodeprogs(QList<Sliver*>() << sliver); // installProgram(sliver); // time = 0; // } }); timer->start(3000); }
bool UdpDataTransport::connect() { if (!d_socket) { boost::asio::ip::udp::endpoint endpoint(boost::asio::ip::address::from_string(getIpAddress()), getPort()); d_socket.reset(new boost::asio::ip::udp::socket(ios)); try { d_socket->connect(endpoint); } catch(boost::system::system_error&) { d_socket.reset(); } } return bool(d_socket); }
Logger *LoggerManager::CreateLoggerInstance() { if (loggerInstance == NULL) { switch(loggerStyle) { case LoggerManager::DEFAULT: loggerInstance = new LoggerDefault(getLoggerLvl()); break; case LoggerManager::LOGFILE: loggerInstance = new LoggerLogFile(getLogfileName(), getWritemode(), getLoggerLvl()); break; case LoggerManager::COLOR: loggerInstance = new LoggerColor(getLoggerLvl(), colors); break; case LoggerManager::NETWORKSTREAM: loggerInstance = new LoggerNetworkStream(getProtocol(), getIpAddress(), getPortNumber(), getLoggerLvl()); break; } } return loggerInstance; }
std::string ClientInfo::getClientsByFileName(std::string fileName){ std::string message = fileName + "|"; for(auto iter = clients.begin(); iter != clients.end(); iter++) { // This flag is used to add the ipaddress if the filename being added is the // first file for the client being searched. bool firstFileAdded = true; bool wasUpdated = false; for(auto clientFile = iter->fileNames.begin(); clientFile != iter->fileNames.end(); clientFile++) { if (fileName.compare(*clientFile) == 0) { message += iter->getIpAddress(); message += " "; } } } if (message.back() == ' ') { message.pop_back(); } message += "\n"; return message; }
int configureNet(Serial *serial, const char *apnHost, const char *apnUser, const char *apnPass) { if (!sendCommandOK(serial, "AT+CIPMUX=0\r")) return -1; //TODO enable for SIM900 if (!sendCommandOK(serial, "AT+CIPMODE=1\r")) return -1; //if (!sendCommand("AT+CIPCCFG=3,2,256,1\r")) return -1; flushModem(serial); putsCell(serial, "AT+CSTT=\""); putsCell(serial, apnHost); putsCell(serial, "\",\""); putsCell(serial, apnUser); putsCell(serial, "\",\""); putsCell(serial, apnPass); putsCell(serial, "\"\r"); if (!waitCommandResponse(serial, "OK", READ_TIMEOUT)) { return -2; } // if (!sendCommand("AT+CIPHEAD=1\r")) return -2; if (sendCommandWait(serial, "AT+CIICR\r", "OK", CONNECT_TIMEOUT) != 1) { return -3; } if (getIpAddress(serial) !=0 ) { return -4; } // Configure DNS to use Google DNS const char dnsCmd[] = "AT+CDNSCFG=\"8.8.8.8\",\"8.8.4.4\"\r"; if (sendCommandWait(serial, dnsCmd, "OK", READ_TIMEOUT) != 1) { return -5; } return 0; }
//***************************************************************************** // // Method: TcpSocket // // Purpose: // // Returns: // // nothing // // Arguments: // // const std::string & host - name of host publishing service // const std::string & service - name of the published service // //***************************************************************************** TcpSocket::TcpSocket ( const std::string & host, // Host running service const std::string & service, // Required service const bool pBlocking, // Blocking socket? unsigned long connectTimeout, // How long in milliseconds for non-blocking connects to timeout and throw failure exception? unsigned long connectionTestTimeout, // How long in milliseconds for connectionTest selects to timeout and throw failure exception? unsigned long readingTimeout) // How long in milliseconds for readong selects to timeout and throw failure exception? : socketId( -1 ), isBlocking( pBlocking ), m_isDisconnected( true ) { m_connectTimeout.tv_sec = connectTimeout / 1000; m_connectTimeout.tv_usec = 1000 * (connectTimeout % 1000); m_connectionTestTimeout.tv_sec = connectionTestTimeout / 1000; m_connectionTestTimeout.tv_usec = 1000 * (connectionTestTimeout % 1000); m_readingTimeout.tv_sec = readingTimeout / 1000; m_readingTimeout.tv_usec = 1000 * (readingTimeout % 1000); // // MS Visual C++ has its own exception code that we must capture. // try { #if defined( WIN32 ) // // It is necessary to initialise winsock before using any of its // features, so we will do that here. Of course this is only // necessary under "brain dead" operating systems. // int lvError = WSAStartup( MAKEWORD( 2, 2 ), & winsockData ); if (0 != lvError) { std::ostringstream streamErrInfo; std::string strErrorInfo; streamErrInfo << "Couldn't initialise Windows sockets"; strErrorInfo = streamErrInfo.str(); throw std::exception(strErrorInfo.c_str()); } #endif // !WIN32 // // Get the host details. // struct in_addr lvHostAddress; getIpAddress( & lvHostAddress, host ); // // Get the service details. // struct servent lvService; getServicePort( & lvService, service ); serviceName = service; // // Create the socket. // socketId = socket( AF_INET, SOCK_STREAM, 0 ); if ( 0 > socketId ) { std::ostringstream streamErrInfo; std::string strErrorInfo; streamErrInfo << "Unable to create socket " <<host<<":"<<service<<". Reason: "<< strerror( errno ); strErrorInfo = streamErrInfo.str(); throw std::exception(strErrorInfo.c_str()); } // // Set up socket name for future connection. // memset( & socketHandle, 0, sizeof( socketHandle ) ); socketHandle.sin_family = AF_INET; socketHandle.sin_port = lvService.s_port; socketHandle.sin_addr = lvHostAddress; // // Set the blocking/non-blocking flags. In the Windows world we // force the socket into the correct blocking/non-blocking mode as // it seems to default to non-blocking. In the UNIX world the // socket is blocking and we switch it when necessary. // #if !defined( WIN32 ) if ( false == pBlocking ) { fcntl( socketId, F_SETFL, O_NONBLOCK ); } #else // defined( WIN32 ) const unsigned int lvNonBlocking = pBlocking ? 0 : 1; ioctlsocket( socketId, FIONBIO, ( unsigned long * )& lvNonBlocking ); #endif // defined( WIN32 ) // // Don't allow the socket to linger on close. // struct linger lvLingerOpts; lvLingerOpts.l_onoff = 0; lvLingerOpts.l_linger = 0; setsockopt( socketId, 0, SO_LINGER, ( char * ) & lvLingerOpts, sizeof( lvLingerOpts ) ); //LOG (SourceInfo, TA_Base_Core::DebugUtil::GenericLog, // TA_Base_Core::DebugUtil::DebugDebug, // "Created socket to host %s on service port %s", host.c_str(), service.c_str() ); std::stringstream ss; ss << "Created socket to host " << host << " on service port " << service; _LOG(SourceFLInfo, DebugDebug, "%s", ss.str().c_str()); } // // Windows exceptions. // catch ( unsigned int ) { std::ostringstream streamErrInfo; std::string strErrorInfo; streamErrInfo << "Unknown Microsoft exception caught"; strErrorInfo = streamErrInfo.str(); throw std::exception(strErrorInfo.c_str()); } }
void ethIfInitialize(Properties* properties) { UInt32 nameLen; ethIf.ifCount = 1; strcpy(ethIf.devList[0].description, langTextNone()); memcpy(ethIf.devList[0].macAddress, InvalidMac, 6); if (!properties->ports.Eth.disabled) { if (loadPacketLibrary()) { pcapPacketGetAdapterNames(NULL, &nameLen); if (nameLen > 0) { char* nameStr = malloc(nameLen); if (pcapPacketGetAdapterNames(nameStr, &nameLen)) { char* devName; for (devName = nameStr; *devName; devName += strlen(devName) + 1) { if (!getMacAddress(devName, ethIf.devList[ethIf.ifCount].macAddress)) { continue; } sprintf(ethIf.devList[ethIf.ifCount].description, "[%s] - %s", mactos(ethIf.devList[ethIf.ifCount].macAddress), iptos(getIpAddress(devName))); strcpy(ethIf.devList[ethIf.ifCount].devName, devName); if (++ethIf.ifCount == 32) { break; } } } free(nameStr); } } } ethIf.currIf = properties->ports.Eth.ethIndex; if (ethIf.currIf < 0 || ethIf.currIf >= ethIf.ifCount) { ethIf.currIf = 0; } parseMac(ethIf.defaultMac, properties->ports.Eth.macAddress); }
void handleClient(char *buffer, int sock, int msgSize, struct sockaddr_in addr) { Packet *recvPacket = Packet::deserialize(buffer); //Clear the buffer because we no longer need it. memset(buffer, 0, strlen(buffer)); char *action = recvPacket->getAction(); if (strcmp(action, UPDATE) == 0) { printf("Got UPDATE\n"); // TODO: Implement data table logic char* Files = recvPacket->getMessage(); bool updated = false; for(auto iter = ClientInfo::getClients().begin(); iter != ClientInfo::getClients().end(); iter++) { if (strcmp(recvPacket->getHostName(), iter->getHostName()) == 0 && strcmp(recvPacket->getIpAddress(), iter->getIpAddress()) == 0) { iter->formatFilesList(Files); updated = true; break; } } if (!updated) { ClientInfo *clientInfo = new ClientInfo::ClientInfo(recvPacket->getHostName(), recvPacket->getIpAddress()); clientInfo->formatFilesList(Files); ClientInfo::addClient(clientInfo); } Packet *sendPacket = new Packet::Packet(ACK, ACK); if (sendto(sock, sendPacket->serialize(), strlen(sendPacket->serialize()), 0, (struct sockaddr *) &addr, sizeof(addr)) != strlen(sendPacket->serialize())) exitWithError("sendto() sent a different number of bytes than expected"); } else if (strcmp(action, QUERY) == 0) { printf("Got QUERY\n"); // TODO: Implement logic to find all clients with requested file(s) std::vector<std::string> filesVector = split(recvPacket->getMessage(), '\n'); std::string packetMessage = ""; for(auto iter = filesVector.begin(); iter != filesVector.end(); iter++) { // Search through every client looking for the file packetMessage = packetMessage + ClientInfo::getClientsByFileName(*iter); } std::cout << "Message: " << packetMessage << std::endl; Packet *sendPacket = new Packet::Packet(QUERYRESULT, packetMessage.c_str()); if (sendto(sock, sendPacket->serialize(), strlen(sendPacket->serialize()), 0, (struct sockaddr *) &addr, sizeof(addr)) != strlen(sendPacket->serialize())) exitWithError("sendto() sent a different number of bytes than expected"); } else if (strcmp(action, EXIT) == 0) { printf("Got EXIT\n"); // TODO: Handle client wanting to exit and delete it from data table char* exitingHost = recvPacket->getHostName(); char* exitingIP = recvPacket->getIpAddress(); ClientInfo::removeClient(exitingHost, exitingIP); Packet *sendPacket = new Packet::Packet(ACK, "Client has been disconnected"); if (sendto(sock, sendPacket->serialize(), strlen(sendPacket->serialize()), 0, (struct sockaddr *) &addr, sizeof(addr)) != strlen(sendPacket->serialize())) exitWithError("sendto() sent a different number of bytes than expected"); } else { /* Send received datagram back to the client */ // TODO: If a non-valid action is recieved, should the packet be ignored? printf("%s\n", "Client sent invalid action. Ignoring..."); } }
std::string DynomiteConfig::generateConfigFile() { std::string localIp = getIpAddress(); LOG( INFO ) << "Get local ip address [" << localIp << "]."; std::string filename = getRandomTempFile(); LOG( INFO ) << "Generate temporary configuration at [" << filename << "]."; int token = std::rand(); LOG( INFO ) << "Generate dynomite token [" << token << "]."; std::string serviceName = getClusterName(); LOG( INFO ) << "Get dynomite service name [" << serviceName << "]."; int port = getDynomitePort(); LOG( INFO ) << "Get dynomite port [" << port << "]."; consul_datacenter dc; int ret = client->getDefaultDatacenter( dc ); if( ret != 0 ) { LOG( ERROR ) << "Error in getting data center information from consul:" << ret; exit( ret ); } std::stringstream ss; ss << localIp << ":" << port << ":default-rack-" << toLowerCase( dc.name ) << ":" << dc.name << ":" << token; std::string tagId = ss.str(); LOG( INFO ) << "Generate tag id [" << tagId << "]."; consul_service dynomiteService; dynomiteService.service_id = serviceName + "_" + localIp; dynomiteService.service_name = serviceName; dynomiteService.service_address = localIp; dynomiteService.service_port = port; std::vector<consul_service> services; client->getService( serviceName, services ); std::string seed = ""; if( !services.empty() ) { std::vector<consul_service>::iterator it = std::find_if( services.begin(), services.end(), []( consul_service cs ) -> bool { return cs.tags.find( "seed" ) != cs.tags.end(); } ); if( it != services.end() ){ std::set<std::string>::iterator tagIt = std::find_if( it->tags.begin(), it->tags.end(), []( std::string tag ) -> bool { return tag != "seed"; } ); seed = *tagIt; } } std::ofstream ofstream; ofstream.open( filename ); ofstream << getClusterName() << ":" << std::endl; ofstream << " datacenter: " << dc.name << std::endl; ofstream << " rack: default-rack-" << toLowerCase( dc.name ) << std::endl; ofstream << " dyn_listen: 0.0.0.0:" << port << std::endl; ofstream << " listen: 0.0.0.0:" << ( port + 1 ) << std::endl; ofstream << " servers:" << std::endl; ofstream << " - 127.0.0.1:6379:1" << std::endl; ofstream << " tokens: '" << token << "'" << std::endl; ofstream << " redis: true" << std::endl; ofstream << " secure_server_option: datacenter" << std::endl; ofstream << " pem_key_file: /var/dynomite/dynomite.pem" << std::endl; if( seed.empty() ) { LOG( INFO ) << "No seed server, start as seed server."; dynomiteService.tags.insert( "seed" ); dynomiteService.tags.insert( tagId ); } else { LOG( INFO ) << "Find seed [" << seed << "]"; ofstream << " dyn_seeds:" << std::endl; ofstream << " - " << seed << std::endl; dynomiteService.tags.insert( tagId ); } ofstream.close(); ret = client->registerService( dynomiteService ); if( ret != 0 ){ LOG( ERROR ) << "Error to register dynomite service, return " << ret; exit( ret ); } return filename; }