void MappingManager::close(Mapper& mapper) {
	if(mapper.hasRules()) {
		bool ret = mapper.init() && mapper.close();
		mapper.uninit();
		if (ret)
			log(STRING_F(MAPPER_REMOVING_SUCCESS, deviceString(mapper) % mapper.getName()), LogMessage::SEV_INFO);
		else
			log(STRING_F(MAPPER_REMOVING_FAILED, deviceString(mapper) % mapper.getName()), LogMessage::SEV_WARNING);
	}
}
string MappingManager::getStatus() const {
	if(working.get()) {
		auto& mapper = *working;
		return STRING_F(MAPPER_CREATING_SUCCESS, deviceString(mapper) % mapper.getName());
	}
	return STRING(MAPPER_CREATING_FAILED);
}
示例#3
0
vector<string> DeviceManager::GetDevices()
{
    // A vector that will hold all devices
    vector<string> devices;
    
    // Will contain the name of the current device
    const char *device;
    
    // Handle to the current device
    int deviceHandle = -1;
    
    // Get the first device
    deviceHandle = bdev_enum(deviceHandle, &device);
        
    // Make sure we found a device
    while(deviceHandle >= 0) {
        
        // Create a new string containing the device name
        string deviceString(device);
        
        // Add the device to our vector
        devices.push_back(deviceString);
        
        // Get the next device
        deviceHandle = bdev_enum(deviceHandle, &device);
    }
        
    return devices;
}
示例#4
0
// ######################################################################
void SerialPort::connect() {
  // Check to see if we have a hardcoded device name. If so, then let's just
  // go ahead and enable that port. If
  printf("INFO: Looking Device Name [%s]\n", itsDevName.c_str());
  if (itsDevName != "") {
    printf("INFO: Opening %s\n", itsDevName.c_str());
    enablePort(itsDevName);
  } else if (itsDevName == "search") {
    printf("INFO: Searching for devices\n");
    itsCmdDevName = "";

    DIR *directory_p;
    struct dirent *entry_p;

    // Open the device directory to search for devices whose names match the
    // search prefix
    directory_p = ::opendir("/dev");
    if (directory_p == NULL)
      printf("FATAL ERROR: Could Not Open /dev Directory!\n");

    // Iterate through the directory entries
    while ((entry_p = ::readdir(directory_p))) {
      std::string entryName(entry_p->d_name);
      if (entryName.find(itsSearchPrefix.c_str()) !=
          std::string::npos) {  // If the directory entry name matches our
                                // search prefix, then let's try configuring a
                                // serial
        // port on that device, sending it an identity request command (0x00),
        // and comparing the result
        // with our required device description

        enablePort("/dev/" + entryName);
        unsigned char cmd[1] = {0};

        write(cmd, 1);
        std::vector<unsigned char> deviceStringVec = readFrame(cmd[0], 255);

        std::string deviceString(deviceStringVec.begin(),
                                 deviceStringVec.end());
        printf("INFO: %s : %s", entryName.c_str(), deviceString.c_str());

        if (deviceString == itsDeviceDescription) {
          itsCmdDevName = "/dev/" + entryName;
          break;
        }
      }
    }
    (void)::closedir(directory_p);
    if (itsCmdDevName == "") {
      printf(
          "FATAL ERROR: Could Not Find Serial Device Matching Descriptor "
          "(%s)\n",
          itsDeviceDescription.c_str());
    }
  } else {
    printf("INFO: Opening from cmd line %s\n", itsCmdDevName.c_str());
    enablePort(itsCmdDevName);
  }
}
string MappingManager::getStatus() const {
	if(working.get()) {
		auto& mapper = *working;
		return str(boost::format("Successfully created port mappings on the %1% device with the %2% interface") %
			deviceString(mapper) % mapper.getName());
	}
	return "Failed to create port mappings";
}
示例#6
0
std::string VideoV4lSource::deviceStr() const
{
    gchar *device_cstr;
    g_object_get(G_OBJECT(source_), "device", &device_cstr, NULL);    // get actual used device

    std::string deviceString(device_cstr); // stay safe from memory leaks
    g_free(device_cstr);
    return deviceString;
}
示例#7
0
/*
================
idCommonLocal::LaunchExternalTitle

Launches an external title  ( Doom 1, or 2 ) based on title index. 
for PS3, a device number is sent in, for the game to register as a local 
user by default, when title initializes.
================
*/
void idCommonLocal::LaunchExternalTitle( int titleIndex, int device, const lobbyConnectInfo_t * const connectInfo ) {

	idStr deviceString( device );

	// We want to pass in the current executable, so that the launching title knows which title to return to.
	// as of right now, this feature is TBD. 
	const char * currentExecutablePath = "ImNotSureYet";
	idStr launchingExecutablePath;

	idCmdArgs cmdArgs;
	cmdArgs.AppendArg( currentExecutablePath );
	
	if ( titleIndex == LAUNCH_TITLE_DOOM ) {
			launchingExecutablePath.Format("%s%s", Sys_DefaultBasePath(), LAUNCH_TITLE_DOOM_EXECUTABLE );
		cmdArgs.AppendArg( "d1bfg" );
	} else if ( titleIndex == LAUNCH_TITLE_DOOM2 ) {
		launchingExecutablePath.Format("%s%s", Sys_DefaultBasePath(), LAUNCH_TITLE_DOOM2_EXECUTABLE );
		cmdArgs.AppendArg( "d2bfg" );

	} else {

		idLib::Warning("Unhandled Launch Title %d \n", titleIndex );
	}

	cmdArgs.AppendArg( deviceString.c_str() );

	// Add an argument so that the new process knows whether or not to read exitspawn data.
	if ( connectInfo != NULL ) {
		cmdArgs.AppendArg( "exitspawnInvite" );
	}

	// Add arguments so that the new process will know which command line to invoke to relaunch this process
	// if necessary.

	const int launchDataSize = ( connectInfo == NULL ) ? 0 : sizeof( *connectInfo );

	Sys_Launch(  launchingExecutablePath.c_str() , cmdArgs, const_cast< lobbyConnectInfo_t * const >( connectInfo ), launchDataSize );
}
int MappingManager::run() {
	ScopedFunctor([this] { busy.clear(); });

	// cache ports
	auto
		conn_port = ConnectionManager::getInstance()->getPort(),
		secure_port = ConnectionManager::getInstance()->getSecurePort(),
		search_port = SearchManager::getInstance()->getPort();

	if(renewal) {
		Mapper& mapper = *working;

		ScopedFunctor([&mapper] { mapper.uninit(); });
		if(!mapper.init()) {
			// can't renew; try again later.
			renewLater(mapper);
			return 0;
		}

		auto addRule = [this, &mapper](const string& port, Mapper::Protocol protocol, const string& description) {
			// just launch renewal requests - don't bother with possible failures.
			if(!port.empty()) {
				mapper.open(port, protocol, STRING_F(MAPPER_X_PORT_X,
					description % port % Mapper::protocols[protocol]));
			}
		};

		addRule(conn_port, Mapper::PROTOCOL_TCP, "Transfer");
		addRule(secure_port, Mapper::PROTOCOL_TCP, "Encrypted transfer");
		addRule(search_port, Mapper::PROTOCOL_UDP, "Search");

		renewLater(mapper);
		return 0;
	}

	// move the preferred mapper to the top of the stack.
	const auto& mapperName = SETTING(MAPPER);
	for(auto i = mappers.begin(); i != mappers.end(); ++i) {
		if(i->first == mapperName) {
			if(i != mappers.begin()) {
				auto mapper = *i;
				mappers.erase(i);
				mappers.insert(mappers.begin(), mapper);
			}
			break;
		}
	}

	for(auto& i: mappers) {
		auto setting = v6 ? SettingsManager::BIND_ADDRESS6 : SettingsManager::BIND_ADDRESS;
		unique_ptr<Mapper> pMapper(i.second((SettingsManager::getInstance()->isDefault(setting) ? Util::emptyString : SettingsManager::getInstance()->get(setting)), v6));
		Mapper& mapper = *pMapper;

		ScopedFunctor([&mapper] { mapper.uninit(); });
		if(!mapper.init()) {
			log(STRING_F(MAPPER_INIT_FAILED, mapper.getName()), LogMessage::SEV_WARNING);
			continue;
		}

		auto addRule = [this, &mapper](const string& port, Mapper::Protocol protocol, const string& description) -> bool {
			if (!port.empty() && !mapper.open(port, protocol, STRING_F(MAPPER_X_PORT_X, APPNAME % description % port % Mapper::protocols[protocol]))) {
				this->log(STRING_F(MAPPER_INTERFACE_FAILED, description % port % Mapper::protocols[protocol] % mapper.getName()), LogMessage::SEV_WARNING);
				mapper.close();
				return false;
			}
			return true;
		};

		if(!(addRule(conn_port, Mapper::PROTOCOL_TCP, STRING(TRANSFER)) &&
			addRule(secure_port, Mapper::PROTOCOL_TCP, STRING(ENCRYPTED_TRANSFER)) &&
			addRule(search_port, Mapper::PROTOCOL_UDP, STRING(SEARCH))))
			continue;

		log(STRING_F(MAPPER_CREATING_SUCCESS_LONG, conn_port % secure_port % search_port % deviceString(mapper) % mapper.getName()), LogMessage::SEV_INFO);

		working = move(pMapper);

		if ((!v6 && !CONNSETTING(NO_IP_OVERRIDE)) || (v6 && !CONNSETTING(NO_IP_OVERRIDE6))) {
			setting = v6 ? SettingsManager::EXTERNAL_IP6 : SettingsManager::EXTERNAL_IP;
			string externalIP = mapper.getExternalIP();
			if(!externalIP.empty()) {
				ConnectivityManager::getInstance()->set(setting, externalIP);
			} else {
				// no cleanup because the mappings work and hubs will likely provide the correct IP.
				log(STRING(MAPPER_IP_FAILED), LogMessage::SEV_WARNING);
			}
		}

		ConnectivityManager::getInstance()->mappingFinished(mapper.getName(), v6);

		renewLater(mapper);
		break;
	}

	if(!getOpened()) {
		log(STRING(MAPPER_CREATING_FAILED), LogMessage::SEV_ERROR);
		ConnectivityManager::getInstance()->mappingFinished(Util::emptyString, v6);
	}

	return 0;
}
示例#9
0
/*
 * Capture Factory constructor.
 * Arguments can be
 * 	- [-d | --device] <device number> : camera number
 * 	- [-f | --file] <filename> : video file name
 * 	- [-m | --mirror] : flip image horizontally
 * 	- [-g | --gray] : convert to gray level
 * 	- [-s | --size] <width>x<height>: preferred width and height
 * @param argList program the argument list provided as a list of
 * strings
 */
CaptureFactory::CaptureFactory(const QStringList & argList) :
	capture(NULL),
	deviceNumber(0),
	liveVideo(true),
	flippedVideo(false),
	grayVideo(false),
	skipImages(false),
	preferredWidth(0),
	preferredHeight(0),
	videoPath()
{
	// C++ Like iterator
	// for (QStringList::const_iterator it = argList.begin(); it != argList.end(); ++it)
	// Java like iterator (because we use hasNext multiple times)
	for (QListIterator<QString> it(argList); it.hasNext(); )
	{
		QString currentArg(it.next());

		if (currentArg == "-d" || currentArg =="--device")
		{
			// Next argument should be device number integer
			if (it.hasNext())
			{
				QString deviceString(it.next());
				bool convertOk;
				deviceNumber = deviceString.toInt(&convertOk,10);
				if (!convertOk || deviceNumber < 0)
				{
					qWarning("Warning: Invalid device number %d",deviceNumber);
					deviceNumber = 0;
				}
				liveVideo = true;
			}
			else
			{
				qWarning("Warning: device tag found with no following device number");
			}
		}
		else if (currentArg == "-v" || currentArg == "--video")
		{
			// Next argument should be a path name to video file or URL
			if (it.hasNext())
			{
				videoPath = it.next();
				liveVideo = false;
			}
			else
			{
				qWarning("file tag found with no following filename");
			}
		}
		else if (currentArg == "-m" || currentArg == "--mirror")
		{
			flippedVideo = true;
		}
		else if (currentArg == "-g" || currentArg == "--gray")
		{
			grayVideo = true;
		}
		else if (currentArg == "-k" || currentArg == "--skip")
		{
			skipImages = true;
		}
		else if (currentArg == "-s" || currentArg == "--size")
		{
			if (it.hasNext())
			{
				// search for <width>x<height>
				QString sizeString = it.next();
				int xIndex = sizeString.indexOf(QChar('x'), 0,
					Qt::CaseInsensitive);
				if (xIndex != -1)
				{
					QString widthString = sizeString.left(xIndex);
					preferredWidth = widthString.toUInt();
					qDebug("preferred width is %d", preferredWidth);

					QString heightString = sizeString.remove(0, xIndex+1);
					preferredHeight = heightString.toUInt();
					qDebug("preferred height is %d", preferredHeight);
				}
				else
				{
					qWarning("invalid <width>x<height>");
				}
			}
			else
			{
				qWarning("size not found after --size");
			}
		}
	}
}
int MappingManager::run() {
	ScopedFunctor([this] { busy.clear(); });

	// cache ports
	auto
		conn_port = ConnectionManager::getInstance()->getPort(),
		secure_port = ConnectionManager::getInstance()->getSecurePort(),
		search_port = SearchManager::getInstance()->getPort();

	if(renewal) {
		Mapper& mapper = *working;

		ScopedFunctor([&mapper] { mapper.uninit(); });
		if(!mapper.init()) {
			// can't renew; try again later.
			renewLater(mapper);
			return 0;
		}

		auto addRule = [this, &mapper](const string& port, Mapper::Protocol protocol, const string& description) {
			// just launch renewal requests - don't bother with possible failures.
			if(!port.empty()) {
				mapper.open(port, protocol, str(boost::format("%1% %2% port (%3% %4%)") %
					description % port % Mapper::protocols[protocol]));
			}
		};

		addRule(conn_port, Mapper::PROTOCOL_TCP, "Transfer");
		addRule(secure_port, Mapper::PROTOCOL_TCP, "Encrypted transfer");
		addRule(search_port, Mapper::PROTOCOL_UDP, "Search");

		renewLater(mapper);
		return 0;
	}

	// move the preferred mapper to the top of the stack.
	const auto& setting = SETTING(MAPPER);
	for(auto i = mappers.begin(); i != mappers.end(); ++i) {
		if(i->first == setting) {
			if(i != mappers.begin()) {
				auto mapper = *i;
				mappers.erase(i);
				mappers.insert(mappers.begin(), mapper);
			}
			break;
		}
	}

	for(auto i = mappers.begin(); i != mappers.end(); ++i) {
		unique_ptr<Mapper> pMapper(i->second(AirUtil::getLocalIp()));
		Mapper& mapper = *pMapper;

		ScopedFunctor([&mapper] { mapper.uninit(); });
		if(!mapper.init()) {
			log(str(boost::format("Failed to initalize the %1% interface") % mapper.getName()), LogManager::LOG_WARNING);
			continue;
		}

		auto addRule = [this, &mapper](const string& port, Mapper::Protocol protocol, const string& description) -> bool {
			if(!port.empty() && !mapper.open(port, protocol, str(boost::format("%1% %2% port (%3% %4%)") %
				APPNAME % description % port % Mapper::protocols[protocol])))
			{
				this->log(str(boost::format("Failed to map the %1% port (%2% %3%) with the %4% interface") %
					description % port % Mapper::protocols[protocol] % mapper.getName()), LogManager::LOG_WARNING);
				mapper.close();
				return false;
			}
			return true;
		};

		if(!(addRule(conn_port, Mapper::PROTOCOL_TCP, "Transfer") &&
			addRule(secure_port, Mapper::PROTOCOL_TCP, "Encrypted transfer") &&
			addRule(search_port, Mapper::PROTOCOL_UDP, "Search")))
			continue;

		log(str(boost::format("Successfully created port mappings (Transfers: %1%, Encrypted transfers: %2%, Search: %3%) on the %4% device with the %5% interface") %
			conn_port % secure_port % search_port % deviceString(mapper) % mapper.getName()), LogManager::LOG_INFO);

		working = move(pMapper);

		if(!CONNSETTING(NO_IP_OVERRIDE)) {
			string externalIP = mapper.getExternalIP();
			if(!externalIP.empty()) {
				ConnectivityManager::getInstance()->set(SettingsManager::EXTERNAL_IP, externalIP);
			} else {
				// no cleanup because the mappings work and hubs will likely provide the correct IP.
				log("Failed to get external IP", LogManager::LOG_WARNING);
			}
		}

		ConnectivityManager::getInstance()->mappingFinished(mapper.getName());

		renewLater(mapper);
		break;
	}

	if(!getOpened()) {
		log(str(boost::format("Failed to create port mappings")), LogManager::LOG_ERROR);
		ConnectivityManager::getInstance()->mappingFinished(Util::emptyString);
	}

	return 0;
}
void MappingManager::close(Mapper& mapper) {
	if(mapper.hasRules()) {
		bool ret = mapper.init() && mapper.close();
		mapper.uninit();
		if (ret)
			log(str(boost::format("Successfully removed port mappings from the %1% device with the %2% interface") % deviceString(mapper) % mapper.getName()), LogManager::LOG_INFO);
		else
			log(str(boost::format("Failed to remove port mappings from the %1% device with the %2% interface") % deviceString(mapper) % mapper.getName()), LogManager::LOG_WARNING);
	}
}
示例#12
0
bool NeoMultiplexerPlugin::detect( QSerialIODevice *device )
{
    qLog(Hardware) << __PRETTY_FUNCTION__;

    // Power on modem via sysfs
    QFile f("/sys/bus/platform/devices/neo1973-pm-gsm.0/power_on");
    if(f.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
        f.write("0");
        f.close();
    }
    if(f.open(QIODevice::WriteOnly | QIODevice::Text | QIODevice::Truncate)) {
        f.write("1");
        f.close();
    } else {
        qWarning() << "Modem power on failed "<< f.errorString();
    }
    
    // The FIC needs a special line discipline set on the device.
    QSerialPort *port = qobject_cast<QSerialPort *>( device );
    if (port) {
        int discipline = N_TIHTC;
        ::ioctl(port->fd(), TIOCSETD, &discipline);
    }
    device->discard();
    int rc;

    struct termios t;
    rc = tcgetattr(port->fd(), &t);
    t.c_cflag |= CRTSCTS;
    rc = tcsetattr(port->fd(), TCSANOW, &t);

    QValueSpaceItem deviceString("/Hardware/Neo/Device");
    if ( deviceString.value().toString() == "GTA02") {
        qLog(Hardware) << __PRETTY_FUNCTION__ << "is gta02";
        muxEnabled = true;
    } else {
        qLog(Hardware) << __PRETTY_FUNCTION__ << "is gta01";
        muxEnabled = false;
    }

    QSettings cfg("Trolltech", "Modem");
    QString multiplexing = cfg.value("Multiplexing/Active", "yes").toString();
    muxEnabled &= (multiplexing != "no");
    qLog(Mux) << "Neo multiplexing " << (muxEnabled ? "enabled" : "disabled")
              << multiplexing;

    // Make the modem talk to us. It can be a bit rough to get
    // it initialized... So we will empty the current buffer
    // and then send ^Z\r\n and wait for an OK or AT from the modem. This is
    // mostly based on ideas from ogsmd

    device->readAll();
    int attempts = 0;
    for (; attempts < 2; ++attempts) {
        if (QSerialIODeviceMultiplexer::chat(device, QChar(0x1a))) {
            qLog(Modem) << "Attempts needed to initialize the modem" << attempts;
            break;
        }
    }

    if (attempts == 2) {
        qWarning() << "Initializing the modem failed.";
        abort();
    }

    // disable echoing of commands
    QSerialIODeviceMultiplexer::chat(device, "ATE0");
    device->readAll();

    if (muxEnabled) {
        // Issue the AT+CMUX command to determine if this device
        // uses GSM 07.10-style multiplexing.
        return QGsm0710Multiplexer::cmuxChat( device, NEO_FRAME_SIZE, true );
    }
    return true;
}